dsh-context-truth 0.2.0 → 0.3.0

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/lib/index.js CHANGED
@@ -11,8 +11,8 @@
11
11
  * "established background", and the false belief survives every later
12
12
  * compaction. The model never gets a correction because no correction exists.
13
13
  *
14
- * TWO CAPABILITIES, ONE BELIEF TO KILL
15
- * ------------------------------------
14
+ * THREE CAPABILITIES, ONE BELIEF TO KILL
15
+ * --------------------------------------
16
16
  * 1. MEASUREMENT IN (default on). One dynamic runtime-context line, refreshed
17
17
  * from the host's own token meter, re-injected only when the reading moves a
18
18
  * display step. It adds no tool, no message, and no per-step noise — one
@@ -20,6 +20,13 @@
20
20
  * 2. CLAIM FILTERING (default on). The compaction summarizer is told not to
21
21
  * record the assistant's own guesses about its remaining budget, so the
22
22
  * false belief stops being re-injected as established background.
23
+ * 3. FOLD POLICY (`foldMode`, default idle). Who folds, and what the model knows
24
+ * before it happens. `idle` keeps the legacy turn-boundary fold; `handoff`
25
+ * asks the model for a handoff note at 85% of the fold point, folds at that
26
+ * round's end, and activates exactly one follow-up turn whose first job is to
27
+ * read the note back. The point of `handoff` is the cost `idle` leaves on the
28
+ * table: a fold the model did not see coming makes it rebuild its own
29
+ * picture from a summary, and long tasks pay for that in repeated work.
23
30
  *
24
31
  * HOW IT PLUGS IN
25
32
  * ---------------
@@ -62,6 +69,11 @@
62
69
  * is accepted. Everything else stays dependency-free ESM, and this file is both
63
70
  * the source and the runtime artifact (`lib/index.js`).
64
71
  */
72
+ import { randomUUID } from 'node:crypto'
73
+ import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
74
+ import { homedir } from 'node:os'
75
+ import { isAbsolute, join, resolve as resolvePath } from 'node:path'
76
+
65
77
  import z from '@deepseek-ai/schemastery'
66
78
 
67
79
  /** Stable cordis plugin name (loader diagnostics, and the runtime-context section name). */
@@ -227,6 +239,41 @@ const DEFAULT_OPTIONS = {
227
239
  foldAtIdleMethod: 'auto',
228
240
  /** Minimum gap between idle-fold attempts, so a failure cannot hammer the engine. */
229
241
  foldAtIdleCooldownMs: 60000,
242
+ /**
243
+ * Which fold policy owns the session. Capability 3, and the only option here
244
+ * that changes *behaviour* rather than reporting.
245
+ *
246
+ * `off` — another plugin (or the host's own pressure trigger) owns it.
247
+ * Folding spends a summarizer call and rewrites the window, so this
248
+ * is the opt-out for deployments that do not want it.
249
+ * `idle` — the legacy turn-boundary fold, and the DEFAULT. Folds when the
250
+ * idle reading is within `foldAtIdleMarginPercent` of the fold point.
251
+ * `handoff` — EXPERIMENTAL. Handoff-first. The model is reminded at `handoffAt` ×
252
+ * the fold point, writes its own handoff note, registers it with
253
+ * `handoff_ready`, and the fold runs at that round's end. Exactly
254
+ * one follow-up turn is activated, and its first instruction is to
255
+ * read that note back before touching the task.
256
+ */
257
+ foldMode: 'idle',
258
+ /**
259
+ * Prep point as a fraction of the FOLD POINT (not of the window): at
260
+ * `handoffAt` × fold point the handoff reminder is injected. 0.85 leaves the
261
+ * model roughly one turn's worth of steps before the host's own pressure fold
262
+ * would take the decision away from it.
263
+ */
264
+ handoffAt: 0.85,
265
+ /**
266
+ * Where handoff notes live. `''` means `$DSH_HOME/handoffs`, and a relative
267
+ * value resolves under `$DSH_HOME`. Never the workspace: a note that lives in
268
+ * the repo becomes project state, and it is recycled.
269
+ */
270
+ handoffDir: '',
271
+ /**
272
+ * How many prep reminders one fold cycle may inject (each lands at most once
273
+ * per turn). After the budget is spent the host's pressure fold takes over,
274
+ * which is the behaviour this mode exists to improve on — so keep it above 1.
275
+ */
276
+ handoffReminders: 3,
230
277
  }
231
278
 
232
279
  /**
@@ -274,10 +321,30 @@ export const Config = z.object({
274
321
  // schema switches capability 2 off. Found live: the running config read
275
322
  // `compactionRules: []` and the summarizer directive went unpatched.
276
323
  compactionRules: z.array(z.string()).default(DEFAULT_COMPACTION_RULES).volatile(),
277
- foldAtIdle: z.boolean().default(false).volatile(),
324
+ /**
325
+ * Legacy switch, read only by `resolveFoldMode`. NO `.default()` on purpose: a
326
+ * materialized `false` would make every untouched config look like an explicit
327
+ * opt-out, and the resolver could no longer tell "never set" (→ `idle`) from
328
+ * "set to false" (→ `off`).
329
+ */
330
+ foldAtIdle: z.boolean().volatile(),
278
331
  foldAtIdleMarginPercent: z.number().min(0.1).max(50).default(5).volatile(),
279
332
  foldAtIdleMethod: z.string().default('auto').volatile(),
280
333
  foldAtIdleCooldownMs: z.number().step(1).min(0).default(60000).volatile(),
334
+ /**
335
+ * NO `.default()` HERE, AND THAT IS LOAD-BEARING. An absent key is the only way
336
+ * this plugin can tell "the user never chose a mode" apart from "the user chose
337
+ * a mode", and that distinction is what makes the compatibility rules safe: a
338
+ * config written before `foldMode` existed resolves to `idle` (folding at the
339
+ * model's own turn boundary is what it already did), a config that explicitly
340
+ * set `foldAtIdle: false` keeps opting out, and a config the settings form has
341
+ * touched stays exactly where it was put. `resolveOptions` is the only reader,
342
+ * so an absent key never reaches runtime.
343
+ */
344
+ foldMode: z.union([z.const('off'), z.const('idle'), z.const('handoff')]).volatile(),
345
+ handoffAt: z.number().min(0.5).max(0.95).default(0.85).volatile(),
346
+ handoffDir: z.string().default('').volatile(),
347
+ handoffReminders: z.number().step(1).min(0).default(3).volatile(),
281
348
  })
282
349
 
283
350
  /** Clamp a numeric option, falling back when it is not a finite number. */
@@ -318,6 +385,26 @@ function plainConfig(config) {
318
385
  return out
319
386
  }
320
387
 
388
+ /**
389
+ * Resolve the fold mode, with `foldAtIdle` as the deprecated spelling of `idle`.
390
+ *
391
+ * `raw` is the validated config, not the merged defaults: the schema leaves
392
+ * `foldMode` defaultless on purpose so that a missing key is observable here.
393
+ *
394
+ * DEFAULT = `idle`: folding at the model's own turn boundary is what this plugin
395
+ * did before `foldMode` existed (behind `foldAtIdle: true`), and a config that
396
+ * never touched either key must keep that behaviour. `foldAtIdle: false` is the
397
+ * explicit opt-out that predates the mode selector, so it still resolves to `off`.
398
+ * An explicit `foldMode` always wins, because the settings form writes one the
399
+ * moment a human picks a mode.
400
+ */
401
+ function resolveFoldMode(raw) {
402
+ const explicit = raw !== null && typeof raw === 'object' ? raw.foldMode : undefined
403
+ if (explicit === 'off' || explicit === 'idle' || explicit === 'handoff') return explicit
404
+ const legacy = raw !== null && typeof raw === 'object' ? raw.foldAtIdle : undefined
405
+ return legacy === false ? 'off' : 'idle'
406
+ }
407
+
321
408
  /** Merge user config over the defaults with light validation. */
322
409
  function resolveOptions(config) {
323
410
  const raw = plainConfig(config)
@@ -361,6 +448,15 @@ function resolveOptions(config) {
361
448
  0,
362
449
  num(merged.foldAtIdleCooldownMs, DEFAULT_OPTIONS.foldAtIdleCooldownMs),
363
450
  ),
451
+ // Already resolved from `raw`, so a legacy `foldAtIdle: true` and an explicit
452
+ // `foldMode` can never disagree downstream.
453
+ foldMode: resolveFoldMode(raw),
454
+ handoffAt: Math.min(0.95, Math.max(0.5, num(merged.handoffAt, DEFAULT_OPTIONS.handoffAt))),
455
+ handoffDir: typeof merged.handoffDir === 'string' ? merged.handoffDir.trim() : '',
456
+ handoffReminders: Math.max(
457
+ 0,
458
+ Math.round(num(merged.handoffReminders, DEFAULT_OPTIONS.handoffReminders)),
459
+ ),
364
460
  }
365
461
  }
366
462
 
@@ -1092,6 +1188,7 @@ export function apply(ctx, config) {
1092
1188
 
1093
1189
  installCompactionPatch(ctx, resolve)
1094
1190
  installIdleFold(ctx, resolve, services)
1191
+ installHandoffFold(ctx, resolve, services)
1095
1192
  }
1096
1193
 
1097
1194
  /** Whether a registration failed because the name is already taken in this layer. */
@@ -1144,7 +1241,10 @@ function logLine(ctx, level, format, ...args) {
1144
1241
  * @returns `{ fold }` plus the numbers behind the decision, for the log line.
1145
1242
  */
1146
1243
  function shouldFoldAtIdle(reading, options) {
1147
- if (options.foldAtIdle !== true) return { fold: false }
1244
+ // The mode is the authority, not the legacy flag: `resolveOptions` has already
1245
+ // mapped `foldAtIdle: true` onto `foldMode: 'idle'`, so a single gate keeps the
1246
+ // two spellings from ever disagreeing (`handoff` mode must not also fold here).
1247
+ if (options.foldMode !== 'idle') return { fold: false }
1148
1248
  const used = reading === null || reading === undefined ? undefined : reading.used
1149
1249
  const threshold = reading === null || reading === undefined ? undefined : reading.threshold
1150
1250
  const window_ = reading === null || reading === undefined ? undefined : reading.window
@@ -1168,7 +1268,7 @@ function installIdleFold(ctx, resolve, services) {
1168
1268
  ctx.on('agent/status', ({ agent, status } = {}) => {
1169
1269
  if (status !== 'idle' || agent === null || agent === undefined) return
1170
1270
  const options = resolve()
1171
- if (options.foldAtIdle !== true) return
1271
+ if (options.foldMode !== 'idle') return
1172
1272
  if (inFlight || Date.now() - attemptedAt < options.foldAtIdleCooldownMs) return
1173
1273
  let decision
1174
1274
  try {
@@ -1185,8 +1285,8 @@ function installIdleFold(ctx, resolve, services) {
1185
1285
  Promise.resolve()
1186
1286
  .then(() => requestFold(ctx, agent, options, services, signal))
1187
1287
  .then(
1188
- (how) => {
1189
- if (how === undefined) {
1288
+ (outcome) => {
1289
+ if (outcome === undefined) {
1190
1290
  if (!warnedNoService) {
1191
1291
  warnedNoService = true
1192
1292
  logLine(
@@ -1200,10 +1300,11 @@ function installIdleFold(ctx, resolve, services) {
1200
1300
  logLine(
1201
1301
  ctx,
1202
1302
  'info',
1203
- 'context-truth: folded at idle via %s (headroom=%s margin=%s)',
1204
- how,
1303
+ 'context-truth: folded at idle via %s (headroom=%s margin=%s folded=%s)',
1304
+ outcome.how,
1205
1305
  decision.headroom,
1206
1306
  decision.margin,
1307
+ outcome.folded,
1207
1308
  )
1208
1309
  },
1209
1310
  (error) =>
@@ -1236,15 +1337,24 @@ function installIdleFold(ctx, resolve, services) {
1236
1337
  * scope — the direct path, and the only one available when the realm registers
1237
1338
  * no `compact` command (e.g. a preset that drops `command-compact`).
1238
1339
  *
1239
- * @returns which channel answered, or `undefined` when neither could be reached.
1340
+ * @returns `{ how, folded }` — which channel answered and whether a summary was
1341
+ * actually committed — or `undefined` when neither channel could be reached.
1342
+ * The two are separate answers on purpose: a `/compact` that finds no compactable
1343
+ * range answers successfully without folding, and capability 3 must not activate
1344
+ * a follow-up turn on the strength of a fold that never happened.
1240
1345
  */
1241
1346
  async function requestFold(ctx, agent, options, services, signal) {
1242
1347
  if (options.foldAtIdleMethod !== 'service') {
1243
1348
  const commands = safeGet(ctx, 'commands')
1244
1349
  if (commands !== undefined && typeof commands.execute === 'function') {
1245
1350
  try {
1246
- await commands.execute(agent, '/compact', [], signal)
1247
- return 'command'
1351
+ const result = await commands.execute(agent, '/compact', [], signal)
1352
+ // `sourceEventSeq` correlates the committed summary with `compaction/summary`
1353
+ // and is absent on the "No compactable history yet" success.
1354
+ return {
1355
+ how: 'command',
1356
+ folded: result !== null && result !== undefined && result.sourceEventSeq !== undefined,
1357
+ }
1248
1358
  } catch (error) {
1249
1359
  // A realm without the command, or a refusal, is not fatal: the service
1250
1360
  // channel below is still worth trying.
@@ -1289,8 +1399,896 @@ async function requestFold(ctx, agent, options, services, signal) {
1289
1399
  (candidate) => isService(candidate) && typeof candidate.compactNow === 'function',
1290
1400
  )
1291
1401
  if (compaction === undefined) return undefined
1292
- await compaction.compactNow(agent, signal)
1293
- return 'service'
1402
+ const result = await compaction.compactNow(agent, signal)
1403
+ // `null` is the engine's documented "no safe useful range" answer.
1404
+ return { how: 'service', folded: result !== null && result !== undefined }
1405
+ }
1406
+
1407
+ // ---------------------------------------------------------------------------
1408
+ // Capability 3 (`foldMode: 'handoff'`): fold behind the model's own handoff note.
1409
+ //
1410
+ // What `idle` mode leaves on the table is not the fold, it is the surprise. The
1411
+ // host folds on pressure, between steps, without telling the model; the model then
1412
+ // rebuilds its picture of a long task from a summary, and the rebuild is where
1413
+ // repeated work comes from (measured over 143 folds: 81 were followed by the model
1414
+ // re-reading files it had written itself before the fold).
1415
+ //
1416
+ // This mode moves the decision to where the model can still act on it:
1417
+ //
1418
+ // 1. PREP at `handoffAt` × the fold point (default 85%) a reminder is
1419
+ // injected into the running turn. The model writes a note to a path
1420
+ // this plugin chose, then calls `handoff_ready`.
1421
+ // 2. FOLD at that round's end (idle), `compactNow` runs — the same engine
1422
+ // `/compact` and the legacy idle fold reach.
1423
+ // 3. ACTIVATE exactly one follow-up turn whose first instruction is to read the
1424
+ // note back before touching the task. One, not a loop: a chain of
1425
+ // self-activated turns is how a plugin takes a session over.
1426
+ //
1427
+ // Everything here is fail-open. A missing service, an unreadable state file, a
1428
+ // full disk, an engine that throws — each is logged and leaves the turn alive. The
1429
+ // worst outcome must be "no fold", never "the session is stuck".
1430
+ // ---------------------------------------------------------------------------
1431
+
1432
+ /** Tool the model calls to register the note it just wrote. */
1433
+ const HANDOFF_TOOL_NAME = 'handoff_ready'
1434
+ /** State file kept beside the notes, one per session directory. */
1435
+ const HANDOFF_STATE_FILE = 'state.json'
1436
+ /** A note shorter than this cannot carry a task across a fold. */
1437
+ const HANDOFF_MIN_CHARS = 200
1438
+ /** Backstop: a note no later cycle referenced again is recycled after a week. */
1439
+ const HANDOFF_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
1440
+ /** How often the backstop sweep runs while the plugin is mounted. */
1441
+ const HANDOFF_SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000
1442
+ /** Activation deliveries attempted per fold before giving up (crash recovery). */
1443
+ const HANDOFF_MAX_ACTIVATION_ATTEMPTS = 2
1444
+
1445
+ /** Path segment that cannot escape its directory; session ids are already safe, but never trust that. */
1446
+ function safeSegment(value) {
1447
+ const text = String(value === null || value === undefined ? '' : value)
1448
+ .replace(/[^A-Za-z0-9._-]+/g, '_')
1449
+ .replace(/^\.+/, '')
1450
+ const trimmed = text.slice(0, 120)
1451
+ return trimmed === '' ? 'unknown-session' : trimmed
1452
+ }
1453
+
1454
+ /** `$DSH_HOME`, or `~/.dsh` when the host exports nothing. `env` is a parameter so this is testable. */
1455
+ function dshHome(env) {
1456
+ const exported = env !== null && typeof env === 'object' ? env.DSH_HOME : undefined
1457
+ if (typeof exported === 'string' && exported.trim() !== '') return exported.trim()
1458
+ return join(homedir(), '.dsh')
1459
+ }
1460
+
1461
+ /**
1462
+ * Root that owns every session's notes. Empty `handoffDir` means
1463
+ * `$DSH_HOME/handoffs`; a relative value resolves under `$DSH_HOME`, so a profile
1464
+ * patch can say `handoffs-test` without hard-coding an absolute path.
1465
+ */
1466
+ function handoffRoot(options, env) {
1467
+ const configured = typeof options.handoffDir === 'string' ? options.handoffDir.trim() : ''
1468
+ const home = dshHome(env === undefined ? process.env : env)
1469
+ if (configured === '') return join(home, 'handoffs')
1470
+ return isAbsolute(configured) ? configured : resolvePath(home, configured)
1471
+ }
1472
+
1473
+ /** `<root>/<sessionId>/<fold#>.handoff.md` — one directory per session, never the workspace. */
1474
+ function handoffPathFor(root, sessionId, foldNo) {
1475
+ const label = String(Math.max(1, Math.round(Number.isFinite(foldNo) ? foldNo : 1))).padStart(3, '0')
1476
+ return join(root, safeSegment(sessionId), `${label}.handoff.md`)
1477
+ }
1478
+
1479
+ /** Session identity, header first: that is the id the store and the UI use. */
1480
+ function sessionIdOf(session) {
1481
+ if (session === null || session === undefined) return ''
1482
+ const header = session.header
1483
+ const candidates = [header === null || header === undefined ? undefined : header.id, session.id]
1484
+ for (const candidate of candidates) {
1485
+ if (typeof candidate === 'string' && candidate.trim() !== '') return candidate.trim()
1486
+ }
1487
+ return ''
1488
+ }
1489
+
1490
+ /**
1491
+ * Whether this session is a delegate of another one.
1492
+ *
1493
+ * Measured on this host: the session header carries no `origin` field, so
1494
+ * `delegationDepth` is the authoritative signal — 0 for a root session, > 0 for
1495
+ * anything a delegation created. Folding a delegate would activate a turn nobody
1496
+ * is watching, so handoff mode stays out of those sessions entirely.
1497
+ */
1498
+ function isDelegate(session) {
1499
+ const header = session === null || session === undefined ? undefined : session.header
1500
+ const depth = header === null || header === undefined ? undefined : header.delegationDepth
1501
+ return Number.isFinite(depth) && depth > 0
1502
+ }
1503
+
1504
+ /** The prep point: `handoffAt` of the FOLD POINT, plus the numbers behind the decision. */
1505
+ function handoffTrigger(reading, options) {
1506
+ if (options.foldMode !== 'handoff') return { prepare: false }
1507
+ const used = reading === null || reading === undefined ? undefined : reading.used
1508
+ const threshold = reading === null || reading === undefined ? undefined : reading.threshold
1509
+ if (!Number.isFinite(used) || !Number.isFinite(threshold) || threshold <= 0) return { prepare: false }
1510
+ const ratio = Math.min(0.95, Math.max(0.5, num(options.handoffAt, DEFAULT_OPTIONS.handoffAt)))
1511
+ const point = Math.round(threshold * ratio)
1512
+ return { prepare: used >= point, point, used, threshold, headroom: Math.round(threshold - used) }
1513
+ }
1514
+
1515
+ /** The reading as a percentage of the fold point, for message text. */
1516
+ function foldPointPercent(used, threshold) {
1517
+ if (!Number.isFinite(used) || !Number.isFinite(threshold) || threshold <= 0) return '?'
1518
+ return String(Math.round((used / threshold) * 100))
1519
+ }
1520
+
1521
+ /** Same file, however it was spelled. Windows compares case-insensitively. */
1522
+ function samePath(left, right) {
1523
+ if (typeof left !== 'string' || typeof right !== 'string') return false
1524
+ if (left === '' || right === '') return false
1525
+ try {
1526
+ const a = resolvePath(left)
1527
+ const b = resolvePath(right)
1528
+ return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b
1529
+ } catch {
1530
+ return false
1531
+ }
1532
+ }
1533
+
1534
+ /** The message shape the agent loop accepts from a plugin (`followup` / `inject`). */
1535
+ function handoffMessage(text) {
1536
+ return { id: randomUUID(), role: 'user', content: [{ type: 'text', text }], source: { kind: 'user' } }
1537
+ }
1538
+
1539
+ /** Prep reminder: what to write, exactly where, and why it is worth the steps. */
1540
+ function handoffPrepMessage({ path, trigger, recycled, options }) {
1541
+ const percent = foldPointPercent(trigger.used, trigger.threshold)
1542
+ const used = formatTokens(trigger.used)
1543
+ const point = formatTokens(trigger.threshold)
1544
+ const recycledNote =
1545
+ recycled > 0
1546
+ ? options.language === 'zh'
1547
+ ? `(按回收策略删掉了上一份 ${recycled} 个档文件。)`
1548
+ : ` (recycled ${recycled} older note file(s) per the recycling rule.)`
1549
+ : ''
1550
+ if (options.language === 'zh') {
1551
+ return [
1552
+ `[交接式折叠 · 准备] 本会话已用到折叠点的 ${percent}%(${used} / ${point})。宿主的自动折叠会在折叠点直接发生,不看你的进度;折叠后你只能靠摘要重建认知,长任务里那正是重复劳动的来源。`,
1553
+ '',
1554
+ '现在写一份交接档给折叠后的你自己,然后继续手头的活(不要为写档中断任务):',
1555
+ `1) 路径必须是这个,不要改:${path}`,
1556
+ '2) 按这几节写,标准是「不看对话历史也能立刻接上」:',
1557
+ ' - 当前目标(一句话)',
1558
+ ' - 已定案(拍过板的决定,注明勿再复议)',
1559
+ ' - 已验证的事实与证据(命令输出、file:line)',
1560
+ ' - 待办(按序,标出下一步的第一个动作)',
1561
+ ' - 关键路径',
1562
+ ' - 坑(试过并失败的路线,避免重试)',
1563
+ '3) 写完调用工具 handoff_ready 登记(它只认上面这个路径)。',
1564
+ `4) 这是临时文件:下一次交接生成时它会被回收${recycledNote}。要长期保留的内容写进项目里,不要留在这里。`,
1565
+ '',
1566
+ '本轮结束时才会折叠,之后会自动开一轮(仅一轮)让你读档接着做。',
1567
+ ].join('\n')
1568
+ }
1569
+ return [
1570
+ `[handoff fold · prepare] This session is at ${percent}% of its fold point (${used} / ${point}). The host's automatic fold happens at the fold point regardless of where you are in your work; after it you would rebuild your picture from a summary, which is where long tasks pay for repeated work.`,
1571
+ '',
1572
+ 'Write a handoff note for the post-fold you, then continue your work (do not interrupt the task to do this):',
1573
+ `1) The path must be exactly this one, do not change it: ${path}`,
1574
+ '2) Use these sections; the bar is "a reader with no conversation history can continue":',
1575
+ ' - current goal (one line)',
1576
+ ' - decisions already made (note that they are settled)',
1577
+ ' - verified facts and their evidence (command output, file:line)',
1578
+ ' - next steps in order, with the very next action marked',
1579
+ ' - key paths',
1580
+ ' - dead ends already tried, so they are not retried',
1581
+ '3) Then call the handoff_ready tool to register it; it only accepts the path above.',
1582
+ `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.`,
1583
+ '',
1584
+ 'The fold runs at the end of this round, and exactly one follow-up turn is activated to read the note back.',
1585
+ ].join('\n')
1586
+ }
1587
+
1588
+ /** Activation message: read the note first, then finish the interrupted work. */
1589
+ function handoffActivationMessage({ path, foldNo, options }) {
1590
+ if (options.language === 'zh') {
1591
+ return [
1592
+ `[交接式折叠 · 激活] 你刚才那一轮被折叠了(本会话第 ${foldNo} 次)。折叠前你自己写了交接档:`,
1593
+ path,
1594
+ '',
1595
+ '这是唯一一次自动激活的轮次,不会连续自动开轮。按顺序做:',
1596
+ '1) 先 read 这个文件,再动手。它是你对折叠前状态的第一手记录,比摘要可靠。',
1597
+ '2) 按「待办」继续,把因折叠被打断的那件事做完。不要重新推导档里已经写明的结论——省掉那段时间正是这套机制的目的。',
1598
+ '3) 这一轮内文件还在:你记得、但档里没写的关键事实,补进去。',
1599
+ '4) 如果档里的描述和你现在看到的实际情况冲突,以实际情况为准,并在最后说明冲突在哪。',
1600
+ '5) 结束时简短交代:从档里接上了什么、这一轮推进了什么。',
1601
+ ].join('\n')
1602
+ }
1603
+ return [
1604
+ `[handoff fold · activate] Your previous round was folded (fold #${foldNo} of this session). Before it happened you wrote yourself a handoff note:`,
1605
+ path,
1606
+ '',
1607
+ 'This is the only auto-activated turn; nothing will auto-activate again until the next fold. In order:',
1608
+ '1) Read that file first, before doing anything else. It is your own first-hand record of the state, more reliable than the summary.',
1609
+ '2) Continue from its "next steps" and finish what the fold interrupted. Do not re-derive conclusions the note already states — not paying that cost is the point of this mechanism.',
1610
+ '3) The file still exists this round: add any key fact you remember that it is missing.',
1611
+ '4) Where the note disagrees with what you observe now, trust the observation and say where they diverged.',
1612
+ '5) End with a short account of what you picked up from the note and what this round advanced.',
1613
+ ].join('\n')
1614
+ }
1615
+
1616
+ /** A fresh state record for one session. */
1617
+ function emptyHandoffState(sessionId) {
1618
+ return { version: 1, sessionId, foldNo: 0, reminders: 0, reminderTurn: null, ready: null, pending: null, wokenAt: null }
1619
+ }
1620
+
1621
+ /** A registered note, or `null` when the record is unusable. */
1622
+ function normalizeReady(value) {
1623
+ if (value === null || typeof value !== 'object') return null
1624
+ if (typeof value.path !== 'string' || value.path === '') return null
1625
+ return {
1626
+ path: value.path,
1627
+ chars: Number.isFinite(value.chars) ? value.chars : 0,
1628
+ at: Number.isFinite(value.at) ? value.at : 0,
1629
+ }
1630
+ }
1631
+
1632
+ /** A queued activation, or `null`. */
1633
+ function normalizePending(value) {
1634
+ if (value === null || typeof value !== 'object') return null
1635
+ if (typeof value.path !== 'string' || value.path === '') return null
1636
+ return {
1637
+ id: typeof value.id === 'string' && value.id !== '' ? value.id : randomUUID(),
1638
+ path: value.path,
1639
+ foldNo: Number.isFinite(value.foldNo) ? Math.round(value.foldNo) : 0,
1640
+ createdAt: Number.isFinite(value.createdAt) ? value.createdAt : 0,
1641
+ attempts: Number.isFinite(value.attempts) && value.attempts >= 0 ? Math.round(value.attempts) : 0,
1642
+ deliveredAt: Number.isFinite(value.deliveredAt) ? value.deliveredAt : null,
1643
+ }
1644
+ }
1645
+
1646
+ /**
1647
+ * Load one session's state, or a fresh record.
1648
+ *
1649
+ * Synchronous on purpose: the prep decision runs inside the `agent/request`
1650
+ * waterfall, where an await would delay the model call, and this is a few hundred
1651
+ * bytes read at most once per turn. A corrupt or unreadable file degrades to "no
1652
+ * state" instead of throwing — the worst case is one duplicate reminder, not a
1653
+ * broken session.
1654
+ */
1655
+ function readHandoffState(dir, sessionId) {
1656
+ try {
1657
+ const parsed = JSON.parse(readFileSync(join(dir, HANDOFF_STATE_FILE), 'utf8'))
1658
+ if (parsed === null || typeof parsed !== 'object') return emptyHandoffState(sessionId)
1659
+ const state = emptyHandoffState(sessionId)
1660
+ if (Number.isFinite(parsed.foldNo) && parsed.foldNo >= 0) state.foldNo = Math.round(parsed.foldNo)
1661
+ if (Number.isFinite(parsed.reminders) && parsed.reminders >= 0) state.reminders = Math.round(parsed.reminders)
1662
+ if (Number.isFinite(parsed.reminderTurn)) state.reminderTurn = Math.round(parsed.reminderTurn)
1663
+ if (Number.isFinite(parsed.wokenAt)) state.wokenAt = Math.round(parsed.wokenAt)
1664
+ state.ready = normalizeReady(parsed.ready)
1665
+ state.pending = normalizePending(parsed.pending)
1666
+ return state
1667
+ } catch {
1668
+ return emptyHandoffState(sessionId)
1669
+ }
1670
+ }
1671
+
1672
+ /** Mirror one session's state to disk. Returns whether it landed. */
1673
+ function writeHandoffState(dir, state) {
1674
+ try {
1675
+ mkdirSync(dir, { recursive: true })
1676
+ writeFileSync(join(dir, HANDOFF_STATE_FILE), `${JSON.stringify(state, null, 2)}\n`, 'utf8')
1677
+ return true
1678
+ } catch {
1679
+ return false
1680
+ }
1681
+ }
1682
+
1683
+ /** Character count of a note, or `null` when the file is missing or not a file. */
1684
+ function handoffFileChars(path) {
1685
+ try {
1686
+ if (!statSync(path).isFile()) return null
1687
+ return readFileSync(path, 'utf8').length
1688
+ } catch {
1689
+ return null
1690
+ }
1691
+ }
1692
+
1693
+ /**
1694
+ * Notes this prep should recycle: everything in the session directory except the
1695
+ * paths it must survive and the state file.
1696
+ *
1697
+ * Decision: recycling happens when the NEXT handoff is handed out, and the next
1698
+ * note's number is always `foldNo + 1`, so the ONLY note that must survive is the
1699
+ * one the last fold activated — `foldNo`'s own note. Keeping it is not a nicety:
1700
+ * the prep for note N+1 runs at the head of the activation turn for note N, so a
1701
+ * recycle that ignored this deleted the activation target 4.5s after it was
1702
+ * activated and the turn's first `read` failed with FS_NOT_FOUND (live drill,
1703
+ * 2026-11-16: activated 18:39:58.877, prep 18:40:03.431, read 18:40:04.983).
1704
+ * The older reasoning — "an undelivered activation is protected upstream" — ✗ was
1705
+ * wrong, because delivery happens before the round starts, not after it ends.
1706
+ */
1707
+ function handoffReapable(root, sessionId, keepPaths) {
1708
+ const dir = join(root, safeSegment(sessionId))
1709
+ let names
1710
+ try {
1711
+ names = readdirSync(dir)
1712
+ } catch {
1713
+ return []
1714
+ }
1715
+ const keep = Array.isArray(keepPaths) ? keepPaths : [keepPaths]
1716
+ const doomed = []
1717
+ for (const entry of names) {
1718
+ if (!entry.toLowerCase().endsWith('.md')) continue
1719
+ const full = join(dir, entry)
1720
+ if (keep.some((keepPath) => samePath(full, keepPath))) continue
1721
+ doomed.push(full)
1722
+ }
1723
+ return doomed
1724
+ }
1725
+
1726
+ /** Delete files, tolerating a locked one (it is swept next pass). */
1727
+ function deleteFiles(files) {
1728
+ let removed = 0
1729
+ for (const file of files) {
1730
+ try {
1731
+ unlinkSync(file)
1732
+ removed += 1
1733
+ } catch {
1734
+ // A locked or already-gone file is not an error worth failing a prep for.
1735
+ }
1736
+ }
1737
+ return removed
1738
+ }
1739
+
1740
+ /**
1741
+ * Backstop sweep: notes older than `maxAgeMs` go, then directories left holding
1742
+ * nothing but their state file. A directory with an undelivered activation is left
1743
+ * alone — its note is about to be read.
1744
+ */
1745
+ function sweepHandoffs(root, nowMs, maxAgeMs) {
1746
+ let removed = 0
1747
+ let entries
1748
+ try {
1749
+ entries = readdirSync(root, { withFileTypes: true })
1750
+ } catch {
1751
+ return 0
1752
+ }
1753
+ for (const entry of entries) {
1754
+ if (entry === null || entry === undefined || !entry.isDirectory()) continue
1755
+ const dir = join(root, entry.name)
1756
+ const state = readHandoffState(dir, entry.name)
1757
+ const spare = state.pending !== null && state.pending.deliveredAt === null ? state.pending.path : null
1758
+ let names
1759
+ try {
1760
+ names = readdirSync(dir)
1761
+ } catch {
1762
+ continue
1763
+ }
1764
+ for (const name of names) {
1765
+ if (!name.toLowerCase().endsWith('.md')) continue
1766
+ const file = join(dir, name)
1767
+ if (spare !== null && samePath(file, spare)) continue
1768
+ let info
1769
+ try {
1770
+ info = statSync(file)
1771
+ } catch {
1772
+ continue
1773
+ }
1774
+ if (nowMs - info.mtimeMs <= maxAgeMs) continue
1775
+ try {
1776
+ unlinkSync(file)
1777
+ removed += 1
1778
+ } catch {
1779
+ // Swept next time.
1780
+ }
1781
+ }
1782
+ try {
1783
+ const left = readdirSync(dir).filter((name) => name !== HANDOFF_STATE_FILE)
1784
+ // Pruning takes the state file with the directory, so it must be as
1785
+ // conservative as the note sweep: only when nothing but the state remains
1786
+ // AND the state itself has not been touched for the same week. Getting this
1787
+ // wrong is not cosmetic — the sweep runs at every plugin load, and the state
1788
+ // it would have deleted is exactly the pending activation that restart
1789
+ // recovery depends on (found by a unit test that lost its fixture).
1790
+ let stateStale = true
1791
+ try {
1792
+ stateStale = nowMs - statSync(join(dir, HANDOFF_STATE_FILE)).mtimeMs > maxAgeMs
1793
+ } catch {
1794
+ stateStale = true
1795
+ }
1796
+ if (left.length === 0 && stateStale) rmSync(dir, { recursive: true, force: true })
1797
+ } catch {
1798
+ // A directory that cannot be pruned now is pruned later.
1799
+ }
1800
+ }
1801
+ return removed
1802
+ }
1803
+
1804
+ /**
1805
+ * Install the handoff fold: prep reminder, `handoff_ready`, the round-end fold, the
1806
+ * single activation turn, and the recycling that keeps the directory bounded.
1807
+ */
1808
+ function installHandoffFold(ctx, resolve, services) {
1809
+ /** Per-session state, hydrated from disk on first use and mirrored back on change. */
1810
+ const states = new Map()
1811
+ /** One-shot log keys: a condition that recurs every step is reported once. */
1812
+ const noted = new Set()
1813
+ /** A fold is an engine call; never run two at once from this closure. */
1814
+ let folding = false
1815
+
1816
+ const dirFor = (options, sessionId) => join(handoffRoot(options), safeSegment(sessionId))
1817
+
1818
+ const messageOf = (error) =>
1819
+ error === null || error === undefined ? 'unknown error' : (error.message ?? String(error))
1820
+
1821
+ function noteOnce(key, level, format, ...args) {
1822
+ if (noted.has(key)) return
1823
+ noted.add(key)
1824
+ logLine(ctx, level, format, ...args)
1825
+ }
1826
+
1827
+ function stateFor(options, sessionId) {
1828
+ const cached = states.get(sessionId)
1829
+ if (cached !== undefined) return cached
1830
+ const loaded = readHandoffState(dirFor(options, sessionId), sessionId)
1831
+ states.set(sessionId, loaded)
1832
+ return loaded
1833
+ }
1834
+
1835
+ function persist(options, sessionId, state) {
1836
+ if (writeHandoffState(dirFor(options, sessionId), state)) return
1837
+ noteOnce(
1838
+ `state-write:${sessionId}`,
1839
+ 'warn',
1840
+ 'context-truth: could not write the handoff state for %s; this fold still works, restart recovery will not',
1841
+ sessionId,
1842
+ )
1843
+ }
1844
+
1845
+ /**
1846
+ * Step 1: remind the model while it can still act. Runs inside the
1847
+ * `agent/request` waterfall, so it stays synchronous and swallows everything —
1848
+ * the return value is the model call's configuration.
1849
+ */
1850
+ function prepare(agent, turn) {
1851
+ const options = resolve()
1852
+ if (options.foldMode !== 'handoff') return
1853
+ const session = agent === null || agent === undefined ? undefined : agent.session
1854
+ if (session === null || session === undefined) return
1855
+ if (isDelegate(session)) return
1856
+ const sessionId = sessionIdOf(session)
1857
+ if (sessionId === '') return
1858
+ const state = stateFor(options, sessionId)
1859
+ // A wake already carries this round's reminder as its first user message; a
1860
+ // second inject would stack two copies of it in the same round.
1861
+ if (state.wokenAt !== null) {
1862
+ state.wokenAt = null
1863
+ // 唤醒轮的第一条消息就是提醒,把它记成“本轮已提醒”,否则同一轮第二个
1864
+ // request 会再注入一条(实机 01:39:07 唤醒 2/3,01:39:17 又注入 3/3)。
1865
+ state.reminderTurn = turn === undefined ? null : turn
1866
+ persist(options, sessionId, state)
1867
+ return
1868
+ }
1869
+ // A queued activation owns the next round: never remind on top of it.
1870
+ if (state.pending !== null && state.pending.deliveredAt === null) return
1871
+ if (state.ready !== null) return
1872
+ if (state.reminders >= options.handoffReminders) {
1873
+ noteOnce(
1874
+ `budget:${sessionId}`,
1875
+ 'info',
1876
+ 'context-truth: handoff reminder budget spent for %s (%s in this cycle); the host pressure fold takes this one',
1877
+ sessionId,
1878
+ options.handoffReminders,
1879
+ )
1880
+ return
1881
+ }
1882
+ if (turn !== undefined && state.reminderTurn === turn) return
1883
+ const reading = readOccupancy(ctx, session, options, services.meter)
1884
+ const trigger = handoffTrigger(reading, options)
1885
+ if (!trigger.prepare) return
1886
+
1887
+ const root = handoffRoot(options)
1888
+ const path = handoffPathFor(root, sessionId, state.foldNo + 1)
1889
+ // 交接档 N 是当前折叠的激活目标,必须活到激活轮读完它;准备轮 N+1 就发生在激活轮
1890
+ // 里,所以这里按编号把它排除掉(✗ 旧实现只排除“未投递的激活”,而投递发生在轮次开始
1891
+ // 之前,等于没排除)。不额外按 pending.path 排除:一次折叠后 pending.foldNo 恒等于
1892
+ // state.foldNo,两者指向同一份文件 —— 两套守卫互为冗余时,变异测试抓不住任何一套
1893
+ // (实测:删掉编号守卫,67/67 仍全绿,因为 pending 守卫替它挡了)。
1894
+ const keep = [path, handoffPathFor(root, sessionId, state.foldNo)]
1895
+ 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
+ }
1904
+ const recycled = deleteFiles(doomed)
1905
+ state.reminders += 1
1906
+ state.reminderTurn = turn === undefined ? null : turn
1907
+ persist(options, sessionId, state)
1908
+ logLine(
1909
+ ctx,
1910
+ 'info',
1911
+ 'context-truth: handoff prep %s/%s for %s (used=%s of the %s fold point, recycled=%s) -> %s',
1912
+ state.reminders,
1913
+ options.handoffReminders,
1914
+ sessionId,
1915
+ trigger.used,
1916
+ trigger.threshold,
1917
+ recycled,
1918
+ path,
1919
+ )
1920
+ }
1921
+
1922
+ /**
1923
+ * Step 1b: wake a round with the reminder.
1924
+ *
1925
+ * `agent.inject` only queues for the next REQUEST of a running round. When the
1926
+ * reminder trips on the model's last step of a round, the message waits for
1927
+ * something to start a new round — observed live: injected 18:48:04.482, read
1928
+ * only after the human's next message. A round end is the one moment a wake is
1929
+ * both safe (nothing is running) and bounded (the same reminder budget).
1930
+ */
1931
+ function remind(agent, options, sessionId, state) {
1932
+ if (state.wokenAt !== null) return
1933
+ const trigger = handoffTrigger(readOccupancy(ctx, agent.session, options, services.meter), options)
1934
+ if (!trigger.prepare) {
1935
+ noteOnce(
1936
+ `no-note:${sessionId}`,
1937
+ 'info',
1938
+ 'context-truth: %s ended a round without handoff_ready and below the prep point; leaving this fold to the host pressure trigger',
1939
+ sessionId,
1940
+ )
1941
+ return
1942
+ }
1943
+ if (state.reminders >= options.handoffReminders) {
1944
+ noteOnce(
1945
+ `budget:${sessionId}`,
1946
+ 'info',
1947
+ 'context-truth: handoff reminder budget spent for %s (%s in this cycle); leaving this fold to the host pressure trigger',
1948
+ sessionId,
1949
+ options.handoffReminders,
1950
+ )
1951
+ return
1952
+ }
1953
+ const root = handoffRoot(options)
1954
+ const path = handoffPathFor(root, sessionId, state.foldNo + 1)
1955
+ const doomed = handoffReapable(root, sessionId, [path, handoffPathFor(root, sessionId, state.foldNo)])
1956
+ try {
1957
+ agent.followup(handoffMessage(handoffPrepMessage({ path, trigger, recycled: doomed.length, options })))
1958
+ } catch (error) {
1959
+ logLine(ctx, 'warn', 'context-truth: could not wake %s with the handoff reminder: %s', sessionId, messageOf(error))
1960
+ return
1961
+ }
1962
+ const recycled = deleteFiles(doomed)
1963
+ state.reminders += 1
1964
+ state.wokenAt = Date.now()
1965
+ state.reminderTurn = null
1966
+ persist(options, sessionId, state)
1967
+ logLine(
1968
+ ctx,
1969
+ 'info',
1970
+ 'context-truth: handoff reminder %s/%s for %s woke the round (used=%s of the %s fold point, recycled=%s) -> %s',
1971
+ state.reminders,
1972
+ options.handoffReminders,
1973
+ sessionId,
1974
+ trigger.used,
1975
+ trigger.threshold,
1976
+ recycled,
1977
+ path,
1978
+ )
1979
+ }
1980
+
1981
+ /** Step 3: deliver the one activation turn, at most twice across restarts. */
1982
+ function deliver(agent, options, sessionId, state) {
1983
+ const pending = state.pending
1984
+ if (pending === null || pending.deliveredAt !== null) return
1985
+ if (pending.attempts >= HANDOFF_MAX_ACTIVATION_ATTEMPTS) {
1986
+ logLine(
1987
+ ctx,
1988
+ 'warn',
1989
+ 'context-truth: activation for fold #%s of %s failed %s times; leaving the session to the human (note: %s)',
1990
+ pending.foldNo,
1991
+ sessionId,
1992
+ pending.attempts,
1993
+ pending.path,
1994
+ )
1995
+ return
1996
+ }
1997
+ // The activation message names a file; a turn whose first step is a read of a
1998
+ // missing file is worse than no activation at all. The recycle rule below no
1999
+ // longer deletes this note, so this is the backstop for the other ways it can
2000
+ // vanish (a human, a sweep, another instance).
2001
+ try {
2002
+ if (!statSync(pending.path).isFile()) throw new Error('not a regular file')
2003
+ } catch (error) {
2004
+ logLine(
2005
+ ctx,
2006
+ 'warn',
2007
+ 'context-truth: the note for fold #%s of %s is gone (%s); releasing the activation instead of pointing a turn at a missing file',
2008
+ pending.foldNo,
2009
+ sessionId,
2010
+ messageOf(error),
2011
+ )
2012
+ state.pending = null
2013
+ persist(options, sessionId, state)
2014
+ return
2015
+ }
2016
+ // Persist the attempt BEFORE sending. A crash between the two can duplicate one
2017
+ // message at worst (bounded by the cap above); it can never loop.
2018
+ pending.attempts += 1
2019
+ persist(options, sessionId, state)
2020
+ try {
2021
+ agent.followup(
2022
+ handoffMessage(handoffActivationMessage({ path: pending.path, foldNo: pending.foldNo, options })),
2023
+ )
2024
+ } catch (error) {
2025
+ logLine(ctx, 'warn', 'context-truth: could not activate the post-fold turn for %s: %s', sessionId, messageOf(error))
2026
+ return
2027
+ }
2028
+ pending.deliveredAt = Date.now()
2029
+ persist(options, sessionId, state)
2030
+ logLine(ctx, 'info', 'context-truth: activated fold #%s of %s -> %s', pending.foldNo, sessionId, pending.path)
2031
+ }
2032
+
2033
+ /** Step 2: at the round's end, fold if the model registered a note. */
2034
+ function foldAtRoundEnd(agent) {
2035
+ const options = resolve()
2036
+ if (options.foldMode !== 'handoff') return
2037
+ const session = agent === null || agent === undefined ? undefined : agent.session
2038
+ if (session === null || session === undefined) return
2039
+ if (isDelegate(session)) return
2040
+ const sessionId = sessionIdOf(session)
2041
+ if (sessionId === '') return
2042
+ const state = stateFor(options, sessionId)
2043
+
2044
+ // An activation that never left the building comes first: the fold already
2045
+ // happened, and the missing piece is the round that was supposed to read it.
2046
+ if (state.pending !== null && state.pending.deliveredAt === null) {
2047
+ deliver(agent, options, sessionId, state)
2048
+ return
2049
+ }
2050
+ if (state.ready === null) {
2051
+ remind(agent, options, sessionId, state)
2052
+ return
2053
+ }
2054
+ if (folding) return
2055
+ const reading = readOccupancy(ctx, session, options, services.meter)
2056
+ const trigger = handoffTrigger(reading, options)
2057
+ if (!trigger.prepare) {
2058
+ // A reading far below the prep point means somebody else folded first (the
2059
+ // host at pressure, or a human running /compact). The note was not used.
2060
+ const foldedElsewhere = Number.isFinite(trigger.point) && trigger.used < trigger.point * 0.75
2061
+ if (foldedElsewhere) {
2062
+ logLine(
2063
+ ctx,
2064
+ 'info',
2065
+ 'context-truth: %s was folded by something else (used=%s, prep point=%s); the note at %s went unused and is released',
2066
+ sessionId,
2067
+ trigger.used,
2068
+ trigger.point,
2069
+ state.ready.path,
2070
+ )
2071
+ state.ready = null
2072
+ state.reminders = 0
2073
+ state.reminderTurn = null
2074
+ state.wokenAt = null
2075
+ persist(options, sessionId, state)
2076
+ return
2077
+ }
2078
+ noteOnce(
2079
+ `below-point:${sessionId}`,
2080
+ 'info',
2081
+ 'context-truth: %s registered a handoff but the reading (%s) is below the prep point (%s); keeping it for the next round end',
2082
+ sessionId,
2083
+ trigger.used,
2084
+ trigger.point,
2085
+ )
2086
+ return
2087
+ }
2088
+
2089
+ const note = state.ready
2090
+ folding = true
2091
+ Promise.resolve()
2092
+ .then(() => requestFold(ctx, agent, options, services, new AbortController().signal))
2093
+ .then(
2094
+ (outcome) => {
2095
+ if (outcome === undefined) {
2096
+ noteOnce(
2097
+ `no-service:${sessionId}`,
2098
+ 'warn',
2099
+ 'context-truth: handoff mode found neither the realm /compact command nor a reachable compaction service (upstream discussion 9425); the note at %s is kept',
2100
+ note.path,
2101
+ )
2102
+ return
2103
+ }
2104
+ if (!outcome.folded) {
2105
+ logLine(
2106
+ ctx,
2107
+ 'info',
2108
+ 'context-truth: the fold reported no compactable range for %s; the note at %s is kept for the next round end',
2109
+ sessionId,
2110
+ note.path,
2111
+ )
2112
+ return
2113
+ }
2114
+ const foldNo = state.foldNo + 1
2115
+ state.foldNo = foldNo
2116
+ state.ready = null
2117
+ state.reminders = 0
2118
+ state.reminderTurn = null
2119
+ state.wokenAt = null
2120
+ // The activation is durable before it is sent, which is the one thing the
2121
+ // reference implementation this was modelled on does not do.
2122
+ state.pending = {
2123
+ id: randomUUID(),
2124
+ path: note.path,
2125
+ foldNo,
2126
+ createdAt: Date.now(),
2127
+ attempts: 0,
2128
+ deliveredAt: null,
2129
+ }
2130
+ persist(options, sessionId, state)
2131
+ logLine(
2132
+ ctx,
2133
+ 'info',
2134
+ 'context-truth: folded %s at the round end via %s (fold #%s, note %s)',
2135
+ sessionId,
2136
+ outcome.how,
2137
+ foldNo,
2138
+ note.path,
2139
+ )
2140
+ deliver(agent, options, sessionId, state)
2141
+ },
2142
+ (error) => logLine(ctx, 'warn', 'context-truth: handoff fold failed: %s', messageOf(error)),
2143
+ )
2144
+ .finally(() => {
2145
+ folding = false
2146
+ })
2147
+ }
2148
+
2149
+ /**
2150
+ * The tool the model calls once the note exists.
2151
+ *
2152
+ * Registered as a plain definition rather than through `defineTool`, because
2153
+ * `@deepseek-ai/dsh-tools` is not resolvable from this package's own directory
2154
+ * (verified here: ERR_MODULE_NOT_FOUND) and a plugin that cannot load is worse
2155
+ * than a plugin that builds a four-field object itself. The registry only
2156
+ * requires `output: { schema, render }`, so this is the whole contract.
2157
+ */
2158
+ function toolDefinition() {
2159
+ return {
2160
+ name: HANDOFF_TOOL_NAME,
2161
+ description:
2162
+ 'Register the handoff note you just wrote to the path context-truth named, so this round is folded and exactly one follow-up turn is activated to read it back. Only meaningful in handoff fold mode, and only for that exact path.',
2163
+ parameters: {
2164
+ type: 'object',
2165
+ properties: {
2166
+ path: {
2167
+ type: 'string',
2168
+ description: 'The handoff path context-truth named. Omit to use the path it chose for this session.',
2169
+ },
2170
+ },
2171
+ },
2172
+ output: {
2173
+ schema: { type: 'string' },
2174
+ render: (_args, value) => [{ type: 'text', text: String(value) }],
2175
+ },
2176
+ execute: (args, exec) => {
2177
+ const options = resolve()
2178
+ const zh = options.language === 'zh'
2179
+ const agent = exec === null || exec === undefined ? undefined : exec.agent
2180
+ const session = agent === null || agent === undefined ? undefined : agent.session
2181
+ if (options.foldMode !== 'handoff') {
2182
+ return zh
2183
+ ? `✗ handoff_ready 只在 handoff 折叠模式下有效(当前:${options.foldMode}),没有登记任何东西。`
2184
+ : `✗ handoff_ready only applies in handoff fold mode (current mode: ${options.foldMode}); nothing was registered.`
2185
+ }
2186
+ if (session === null || session === undefined) {
2187
+ return zh ? '✗ handoff_ready 需要一个活着的会话,没有登记任何东西。' : '✗ handoff_ready needs a live session; nothing was registered.'
2188
+ }
2189
+ if (isDelegate(session)) {
2190
+ return zh
2191
+ ? '✗ 当前是委派会话,交接式折叠只在根会话上生效;没有登记任何东西。'
2192
+ : '✗ this is a delegated session, and handoff folding only applies to a root session; nothing was registered.'
2193
+ }
2194
+ const sessionId = sessionIdOf(session)
2195
+ if (sessionId === '') {
2196
+ return zh ? '✗ 无法识别当前会话,没有登记任何东西。' : '✗ could not identify this session; nothing was registered.'
2197
+ }
2198
+ const state = stateFor(options, sessionId)
2199
+ if (state.pending !== null && state.pending.deliveredAt === null) {
2200
+ return zh
2201
+ ? '✗ 本会话已经排了一次折叠,激活轮还没投递;这次不重复登记。'
2202
+ : '✗ a fold for this session is already queued and not yet activated; nothing was registered.'
2203
+ }
2204
+ const root = handoffRoot(options)
2205
+ const expected = handoffPathFor(root, sessionId, state.foldNo + 1)
2206
+ const given = args !== null && typeof args === 'object' && typeof args.path === 'string' ? args.path.trim() : ''
2207
+ if (given !== '' && !samePath(given, expected)) {
2208
+ return zh
2209
+ ? `✗ 这个路径不属于本会话的交接目录。\n 期望:${expected}\n 收到:${given}\n交接档只能放在插件管理的目录里,不能写进工作区。写到期望路径后再调用。`
2210
+ : `✗ that path is not the one this session owns.\n expected: ${expected}\n given: ${given}\nHandoff notes stay in the plugin's own directory, never in the workspace. Write to the expected path and call again.`
2211
+ }
2212
+ const chars = handoffFileChars(expected)
2213
+ if (chars === null) {
2214
+ return zh
2215
+ ? `✗ 这个路径还没有文件:${expected}\n先把档写到这里(必须是这个路径),再调用 handoff_ready。`
2216
+ : `✗ there is no handoff note at ${expected}\nWrite it there first (that exact path), then call handoff_ready.`
2217
+ }
2218
+ if (chars < HANDOFF_MIN_CHARS) {
2219
+ return zh
2220
+ ? `✗ 交接档只有 ${chars} 字符(最少 ${HANDOFF_MIN_CHARS})。它要能让折叠后的会话不看对话历史就接上:补上目标、已定案、证据、下一步,再调用。`
2221
+ : `✗ the note is only ${chars} characters (minimum ${HANDOFF_MIN_CHARS}). It has to let the folded session continue without this conversation: add the goal, the decisions, the evidence, the next action, then call again.`
2222
+ }
2223
+ state.ready = { path: expected, chars, at: Date.now() }
2224
+ persist(options, sessionId, state)
2225
+ logLine(ctx, 'info', 'context-truth: handoff registered for %s (%s chars) at %s', sessionId, chars, expected)
2226
+ return zh
2227
+ ? `✓ 交接档已登记(${chars} 字符):${expected}\n本轮结束时会执行折叠,然后自动开一轮(仅一轮)让你读档。现在结束本轮:收尾正在写的文件,不要再开新任务。`
2228
+ : `✓ handoff registered (${chars} chars): ${expected}\nThis round is folded when it ends, and exactly one turn is activated to read it back. End this round now: finish the file you are writing, do not start a new task.`
2229
+ },
2230
+ }
2231
+ }
2232
+
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.
2236
+ const tools = safeGet(ctx, 'tools')
2237
+ if (tools === undefined || typeof tools.register !== 'function' || typeof ctx.effect !== 'function') {
2238
+ logLine(
2239
+ ctx,
2240
+ 'warn',
2241
+ 'context-truth: no tools service is reachable from this scope; handoff mode cannot register %s and will stay inert',
2242
+ HANDOFF_TOOL_NAME,
2243
+ )
2244
+ } else {
2245
+ try {
2246
+ ctx.effect(() => tools.register(toolDefinition()), `context-truth: ${HANDOFF_TOOL_NAME}`)
2247
+ } catch (error) {
2248
+ logLine(ctx, 'warn', 'context-truth: could not register %s: %s', HANDOFF_TOOL_NAME, messageOf(error))
2249
+ }
2250
+ }
2251
+
2252
+ // Prep runs inside a waterfall: synchronous, and it must never throw — its return
2253
+ // value is the model call's configuration.
2254
+ ctx.on('agent/request', (payload, next) => {
2255
+ try {
2256
+ prepare(payload === null || payload === undefined ? undefined : payload.agent, payload === null || payload === undefined ? undefined : payload.turn)
2257
+ } catch (error) {
2258
+ noteOnce('prep-error', 'warn', 'context-truth: handoff prep failed: %s', messageOf(error))
2259
+ }
2260
+ return next()
2261
+ })
2262
+
2263
+ // The fold itself is async and runs after the emitting stack unwinds, so the
2264
+ // `followup` that activates the next round never re-enters the agent loop.
2265
+ ctx.on('agent/status', ({ agent, status } = {}) => {
2266
+ if (status !== 'idle' || agent === null || agent === undefined) return
2267
+ Promise.resolve()
2268
+ .then(() => foldAtRoundEnd(agent))
2269
+ .catch((error) => logLine(ctx, 'warn', 'context-truth: handoff fold failed: %s', messageOf(error)))
2270
+ })
2271
+
2272
+ function sweep() {
2273
+ const options = resolve()
2274
+ if (options.foldMode !== 'handoff') return
2275
+ try {
2276
+ const removed = sweepHandoffs(handoffRoot(options), Date.now(), HANDOFF_MAX_AGE_MS)
2277
+ if (removed > 0) {
2278
+ logLine(ctx, 'info', 'context-truth: recycled %s stale handoff note(s) older than %s days', removed, Math.round(HANDOFF_MAX_AGE_MS / 86400000))
2279
+ }
2280
+ } catch (error) {
2281
+ logLine(ctx, 'warn', 'context-truth: handoff sweep failed: %s', messageOf(error))
2282
+ }
2283
+ }
2284
+
2285
+ // Backstop only: the primary recycling happens when the next note is handed out.
2286
+ try {
2287
+ Promise.resolve().then(sweep).catch(() => {})
2288
+ if (typeof ctx.setInterval === 'function') ctx.setInterval(sweep, HANDOFF_SWEEP_INTERVAL_MS)
2289
+ } catch {
2290
+ // A timer is a convenience, never a requirement.
2291
+ }
1294
2292
  }
1295
2293
 
1296
2294
  /** Install the dynamic runtime-context line. */
@@ -1393,15 +2391,34 @@ function installContextLine(ctx, resolve, services) {
1393
2391
  }
1394
2392
  }
1395
2393
 
1396
- ctx.systemPrompt.variable(VARIABLE_NAME, (assembly) => line(assembly))
1397
- ctx.systemPrompt.context({
1398
- name: CONTEXT_NAME,
1399
- // `order` is fixed at registration: the host snapshots the contribution list
1400
- // per assembly, and moving it live would reshuffle the cached prefix for a
1401
- // change nobody asked to see mid-turn.
1402
- order: resolve().order,
1403
- text: `{{${VARIABLE_NAME}}}`,
1404
- })
2394
+ // Bind both registrations to THIS plugin's fiber.
2395
+ //
2396
+ // The service returns a disposer, but it is created through `layers.effect` on
2397
+ // the *service's* context, so ignoring it leaves the variable registered for the
2398
+ // lifetime of the service — i.e. forever. The consequence is not cosmetic: after
2399
+ // one reload the name is taken, every later instance throws "already registered",
2400
+ // and this plugin's `apply` deliberately goes inert on that error, so the plugin
2401
+ // can never be reloaded into a new version again (observed live 2026-11-16: every
2402
+ // reload logged "another instance already owns the context line" while no other
2403
+ // instance existed). `ctx.effect` puts the disposer on our own fiber, which is
2404
+ // what a reload actually disposes.
2405
+ const bind = typeof ctx.effect === 'function' ? (fn, label) => ctx.effect(fn, label) : (fn) => fn()
2406
+ bind(
2407
+ () => ctx.systemPrompt.variable(VARIABLE_NAME, (assembly) => line(assembly)),
2408
+ 'context-truth: runtime-context variable',
2409
+ )
2410
+ bind(
2411
+ () =>
2412
+ ctx.systemPrompt.context({
2413
+ name: CONTEXT_NAME,
2414
+ // `order` is fixed at registration: the host snapshots the contribution list
2415
+ // per assembly, and moving it live would reshuffle the cached prefix for a
2416
+ // change nobody asked to see mid-turn.
2417
+ order: resolve().order,
2418
+ text: `{{${VARIABLE_NAME}}}`,
2419
+ }),
2420
+ 'context-truth: runtime-context section',
2421
+ )
1405
2422
  }
1406
2423
 
1407
2424
  /** Test-only surface: the pure helpers, so the suite can exercise them directly. */
@@ -1429,6 +2446,26 @@ export const internals = {
1429
2446
  tightClause,
1430
2447
  foldClause,
1431
2448
  shouldFoldAtIdle,
2449
+ resolveFoldMode,
2450
+ handoffTrigger,
2451
+ handoffRoot,
2452
+ handoffPathFor,
2453
+ handoffPrepMessage,
2454
+ handoffActivationMessage,
2455
+ handoffReapable,
2456
+ sweepHandoffs,
2457
+ readHandoffState,
2458
+ writeHandoffState,
2459
+ handoffFileChars,
2460
+ emptyHandoffState,
2461
+ safeSegment,
2462
+ sessionIdOf,
2463
+ isDelegate,
2464
+ samePath,
2465
+ HANDOFF_TOOL_NAME,
2466
+ HANDOFF_MIN_CHARS,
2467
+ HANDOFF_MAX_AGE_MS,
2468
+ HANDOFF_STATE_FILE,
1432
2469
  backendIdentity,
1433
2470
  render,
1434
2471
  renderUnknown,