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.
@@ -1,10 +1,15 @@
1
1
  import assert from 'node:assert/strict'
2
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'
3
+ import { homedir, tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
2
5
  import test from 'node:test'
3
6
 
4
7
  import { apply, internals, name, inject, Config, CONTEXT_NAME, VARIABLE_NAME } from '../lib/index.js'
5
8
 
6
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
7
10
 
11
+ const { resolveFoldMode, handoffTrigger, handoffRoot, handoffPathFor, handoffPrepMessage, handoffActivationMessage, handoffReapable, sweepHandoffs, handoffFileChars, safeSegment, sessionIdOf, isDelegate, samePath, HANDOFF_TOOL_NAME, HANDOFF_MIN_CHARS, HANDOFF_MAX_AGE_MS, HANDOFF_STATE_FILE } = internals
12
+
8
13
  /** A 1M window reserving the DeepSeek adapter's default 256K completion tokens. */
9
14
  const WINDOW = 1000000
10
15
  const MAX_TOKENS = 256000
@@ -12,10 +17,21 @@ const MAX_TOKENS = 256000
12
17
  const THRESHOLD = 678464
13
18
 
14
19
  /** Minimal ctx capturing what the plugin registers. */
15
- function stubContext({ used, meter, projections, compaction, commands, logs } = {}) {
16
- const registered = { variable: undefined, context: undefined, listeners: {}, injections: [] }
20
+ function stubContext({ used, meter, projections, compaction, commands, logs, tools } = {}) {
21
+ const registered = { variable: undefined, context: undefined, listeners: {}, injections: [], tools: [], effects: [], timers: [] }
17
22
  const tokenMeter = meter === undefined ? { measure: () => ({ totalTokens: used }) } : meter
18
- const services = { tokenMeter, compaction, sessionProjections: projections, commands }
23
+ // A host always mounts the tools service, so the stub does too: without it the
24
+ // handoff tool cannot register and every log assertion would see that warning.
25
+ const toolsService =
26
+ tools === undefined
27
+ ? {
28
+ register: (definition) => {
29
+ registered.tools.push(definition)
30
+ return () => {}
31
+ },
32
+ }
33
+ : tools
34
+ const services = { tokenMeter, compaction, sessionProjections: projections, commands, tools: toolsService }
19
35
  const ctx = {
20
36
  logger:
21
37
  logs === undefined
@@ -50,8 +66,27 @@ function stubContext({ used, meter, projections, compaction, commands, logs } =
50
66
  registered.context = contribution
51
67
  },
52
68
  },
69
+ // Two capabilities now share `agent/status` (the idle fold and the handoff
70
+ // fold), and a host runs every listener. Composing here keeps every existing
71
+ // assertion working — `listeners[event](payload)` still fires all of them.
53
72
  on: (event, listener) => {
54
- registered.listeners[event] = listener
73
+ const previous = registered.listeners[event]
74
+ registered.listeners[event] =
75
+ previous === undefined
76
+ ? listener
77
+ : (...args) => {
78
+ previous(...args)
79
+ listener(...args)
80
+ }
81
+ },
82
+ effect: (callback, label) => {
83
+ registered.effects.push(label)
84
+ const dispose = callback()
85
+ return typeof dispose === 'function' ? dispose : () => {}
86
+ },
87
+ setInterval: (callback, ms) => {
88
+ registered.timers.push({ callback, ms })
89
+ return () => {}
55
90
  },
56
91
  }
57
92
  return { ctx, registered }
@@ -927,21 +962,30 @@ test('the idle fold fires at the turn boundary once the room runs out', async ()
927
962
  await tick()
928
963
  assert.equal(calls.length, 1, 'a calm session must not fold')
929
964
 
930
- // Off by default: the listener exists (so the switch is live) but never folds.
965
+ // Default mode is `idle`: a config nobody touched folds at the turn boundary,
966
+ // which is the behaviour this plugin always had behind `foldAtIdle: true`.
967
+ const byDefault = stubContext({ used: 640000, compaction })
968
+ apply(byDefault.ctx, {})
969
+ assert.equal(typeof byDefault.registered.listeners['agent/status'], 'function')
970
+ byDefault.registered.listeners['agent/status']({ agent: { session }, status: 'idle' })
971
+ await tick()
972
+ assert.equal(calls.length, 2, 'the default mode folds at the turn boundary')
973
+
974
+ // Explicitly off: the listener exists (so the switch is live) but never folds.
931
975
  const off = stubContext({ used: 640000, compaction })
932
- apply(off.ctx, {})
976
+ apply(off.ctx, { foldMode: 'off' })
933
977
  assert.equal(typeof off.registered.listeners['agent/status'], 'function')
934
978
  off.registered.listeners['agent/status']({ agent: { session }, status: 'idle' })
935
979
  await tick()
936
- assert.equal(calls.length, 1, 'the default configuration must not fold anything')
980
+ assert.equal(calls.length, 2, 'an explicit off must not fold anything')
937
981
 
938
982
  // The pure decision, including the band where the fold must not fire.
939
983
  const options = resolveOptions({ foldAtIdle: true })
940
984
  assert.equal(shouldFoldAtIdle({ used: 640000, threshold: THRESHOLD, window: WINDOW }, options).fold, true)
941
985
  assert.equal(shouldFoldAtIdle({ used: 620000, threshold: THRESHOLD, window: WINDOW }, options).fold, false)
942
986
  assert.equal(shouldFoldAtIdle({ used: 640000, threshold: undefined, window: WINDOW }, options).fold, false)
943
- assert.equal(shouldFoldAtIdle({ used: 640000, threshold: THRESHOLD, window: WINDOW }, resolveOptions({})).fold, false)
944
- assert.equal(DEFAULT_OPTIONS.foldAtIdle, false, 'the fold is a policy decision, so it ships off')
987
+ assert.equal(shouldFoldAtIdle({ used: 640000, threshold: THRESHOLD, window: WINDOW }, resolveOptions({ foldMode: 'off' })).fold, false)
988
+ assert.equal(DEFAULT_OPTIONS.foldMode, 'idle', 'the automatic idle fold is the default')
945
989
  })
946
990
 
947
991
  test('an idle fold never breaks a turn', async () => {
@@ -1153,3 +1197,592 @@ test('a diagnostic string from the property read never shadows a working service
1153
1197
  await tick()
1154
1198
  assert.equal(calls.length, 1, 'the reachable service must win over the diagnostic string')
1155
1199
  })
1200
+
1201
+ // ---------------------------------------------------------------------------
1202
+ // Capability 3: foldMode 'handoff'
1203
+ //
1204
+ // The state machine has more ways to stop than to proceed, so every stop is
1205
+ // asserted with the same weight as the happy path: a fold that silently does not
1206
+ // happen is the failure this mode exists to remove, and one that happens when it
1207
+ // should not is worse.
1208
+ // ---------------------------------------------------------------------------
1209
+
1210
+ /** A root-session fixture carrying the header the handoff state keys on. */
1211
+ function handoffSession(id = 'session-handoff-1', { depth = 0 } = {}) {
1212
+ return {
1213
+ id,
1214
+ header: { id, delegationDepth: depth },
1215
+ requestContext: () => ({ contextWindow: WINDOW }),
1216
+ requestHeader: () => ({ config: { maxTokens: MAX_TOKENS } }),
1217
+ }
1218
+ }
1219
+
1220
+ /** A live-agent fixture recording what the plugin injects and activates. */
1221
+ function handoffAgent(session) {
1222
+ const agent = {
1223
+ status: 'running',
1224
+ session,
1225
+ injected: [],
1226
+ followed: [],
1227
+ inject: (message) => agent.injected.push(message),
1228
+ followup: (message) => agent.followed.push(message),
1229
+ }
1230
+ return agent
1231
+ }
1232
+
1233
+ /** A token meter a test can move between steps. */
1234
+ function movableMeter(used) {
1235
+ const box = { used }
1236
+ return { box, meter: { measure: () => ({ totalTokens: box.used }) } }
1237
+ }
1238
+
1239
+ /** Fire the composed `agent/request` waterfall at one step. */
1240
+ function requestStep(registered, agent, turn, step = 1) {
1241
+ const listener = registered.listeners['agent/request']
1242
+ assert.equal(typeof listener, 'function', 'handoff mode must subscribe to agent/request')
1243
+ return listener({ agent, turn, step, signal: {} }, () => Promise.resolve({}))
1244
+ }
1245
+
1246
+ /** Fire the composed `agent/status` listeners at an idle boundary and settle them. */
1247
+ async function idleBoundary(registered, agent) {
1248
+ registered.listeners['agent/status']({ agent, status: 'idle' })
1249
+ await tick()
1250
+ await tick()
1251
+ }
1252
+
1253
+ /** A scratch handoff root that the test removes afterwards. */
1254
+ function scratchRoot(t) {
1255
+ const root = mkdtempSync(join(tmpdir(), 'ct-handoff-'))
1256
+ t.after(() => rmSync(root, { recursive: true, force: true }))
1257
+ return root
1258
+ }
1259
+
1260
+ test('foldMode: absent means idle, an explicit opt-out or mode wins', () => {
1261
+ assert.equal(DEFAULT_OPTIONS.foldMode, 'idle', 'the automatic idle fold is the default')
1262
+ assert.equal(resolveOptions({}).foldMode, 'idle')
1263
+ assert.equal(resolveOptions({ foldAtIdle: true }).foldMode, 'idle', 'the legacy switch means the same thing as the default')
1264
+ assert.equal(resolveOptions({ foldAtIdle: false }).foldMode, 'off', 'an explicit opt-out is honoured')
1265
+ assert.equal(resolveOptions({ foldAtIdle: true, foldMode: 'off' }).foldMode, 'off', 'an explicit mode beats the alias')
1266
+ assert.equal(resolveOptions({ foldAtIdle: false, foldMode: 'handoff' }).foldMode, 'handoff')
1267
+ assert.equal(resolveOptions({ foldMode: 'nonsense' }).foldMode, 'idle', 'an unknown value degrades to the default')
1268
+
1269
+ // The schema is the first line of defence, and the mode is decided by the
1270
+ // RESOLVED value, not by key presence: `.volatile()` materializes the key as a
1271
+ // reference cell even when the user never set it, so presence proves nothing.
1272
+ // What must hold is that a config the user never touched resolves to `idle`,
1273
+ // an explicit `foldAtIdle: false` still opts out, through the real schema.
1274
+ assert.throws(() => Config({ foldMode: 'nonsense' }))
1275
+ assert.equal(resolveOptions(Config({})).foldMode, 'idle')
1276
+ assert.equal(resolveOptions(Config({ foldAtIdle: false })).foldMode, 'off')
1277
+ assert.equal(resolveOptions(Config({ foldAtIdle: true })).foldMode, 'idle')
1278
+ assert.equal(resolveOptions(Config({ foldMode: 'off' })).foldMode, 'off')
1279
+ assert.equal(resolveOptions(Config({ foldMode: 'handoff' })).foldMode, 'handoff')
1280
+
1281
+ // One gate decides both spellings, so handoff mode can never also idle-fold.
1282
+ assert.equal(shouldFoldAtIdle({ used: 640000, threshold: THRESHOLD, window: WINDOW }, resolveOptions({ foldMode: 'handoff' })).fold, false)
1283
+ assert.equal(shouldFoldAtIdle({ used: 640000, threshold: THRESHOLD, window: WINDOW }, resolveOptions({ foldMode: 'idle' })).fold, true)
1284
+ })
1285
+
1286
+ test('handoff notes live under $DSH_HOME, one directory per session, never the workspace', () => {
1287
+ const env = { DSH_HOME: join(tmpdir(), 'ct-home') }
1288
+ const base = resolveOptions({ foldMode: 'handoff' })
1289
+ assert.equal(handoffRoot(base, env), join(env.DSH_HOME, 'handoffs'))
1290
+ assert.equal(handoffRoot(resolveOptions({ foldMode: 'handoff', handoffDir: 'notes-test' }), env), join(env.DSH_HOME, 'notes-test'))
1291
+ const absolute = join(tmpdir(), 'ct-absolute')
1292
+ assert.equal(handoffRoot(resolveOptions({ foldMode: 'handoff', handoffDir: absolute }), env), absolute)
1293
+ // No DSH_HOME in the environment → ~/.dsh, which is still not the workspace.
1294
+ assert.equal(handoffRoot(base, {}), join(homedir(), '.dsh', 'handoffs'))
1295
+
1296
+ const root = join(tmpdir(), 'ct-h')
1297
+ assert.equal(handoffPathFor(root, 'session-abc', 1), join(root, 'session-abc', '001.handoff.md'))
1298
+ assert.ok(handoffPathFor(root, 'session-abc', 42).endsWith('042.handoff.md'))
1299
+
1300
+ // A session id cannot climb out of its own directory, and an empty one is named.
1301
+ const segment = safeSegment('../../etc/passwd')
1302
+ assert.equal(/[\\/]/.test(segment), false)
1303
+ assert.equal(segment.startsWith('.'), false)
1304
+ assert.equal(safeSegment(''), 'unknown-session')
1305
+
1306
+ // The identity comes from the header first, which is the id the store uses.
1307
+ assert.equal(sessionIdOf({ id: 'from-body', header: { id: 'from-header' } }), 'from-header')
1308
+ assert.equal(sessionIdOf({ id: 'from-body' }), 'from-body')
1309
+ assert.equal(sessionIdOf({}), '')
1310
+ })
1311
+
1312
+ test('the prep point is a fraction of the fold point, and only handoff mode prepares', () => {
1313
+ const options = resolveOptions({ foldMode: 'handoff' })
1314
+ const point = Math.round(THRESHOLD * 0.85)
1315
+ assert.equal(handoffTrigger({ used: 580000, threshold: THRESHOLD, window: WINDOW }, options).point, point)
1316
+ assert.equal(handoffTrigger({ used: point, threshold: THRESHOLD, window: WINDOW }, options).prepare, true)
1317
+ assert.equal(handoffTrigger({ used: point - 1, threshold: THRESHOLD, window: WINDOW }, options).prepare, false)
1318
+ assert.equal(handoffTrigger({ used: 1e6 }, options).prepare, false, 'no fold point, no prep')
1319
+ assert.equal(handoffTrigger({ used: 1e6, threshold: THRESHOLD }, resolveOptions({})).prepare, false)
1320
+ assert.equal(handoffTrigger({ used: 1e6, threshold: THRESHOLD }, resolveOptions({ foldAtIdle: true })).prepare, false, 'idle mode must not prepare')
1321
+
1322
+ // The configured fraction is honoured and clamped to the documented range.
1323
+ const at = (value) => handoffTrigger({ used: 1, threshold: THRESHOLD }, resolveOptions({ foldMode: 'handoff', handoffAt: value })).point
1324
+ assert.equal(at(0.85), point)
1325
+ assert.equal(at(0.1), Math.round(THRESHOLD * 0.5))
1326
+ assert.equal(at(0.99), Math.round(THRESHOLD * 0.95))
1327
+
1328
+ // Both messages name the note and the temporary-file warning; the prepare line
1329
+ // also says where in the fold the session is standing.
1330
+ const path = handoffPathFor(join(tmpdir(), 'h'), 'session-abc', 3)
1331
+ const trigger = handoffTrigger({ used: 600000, threshold: THRESHOLD, window: WINDOW }, options)
1332
+ const zhOptions = resolveOptions({ foldMode: 'handoff', language: 'zh' })
1333
+ const zhPrep = handoffPrepMessage({ path, trigger, recycled: 2, options: zhOptions })
1334
+ assert.ok(zhPrep.includes(path))
1335
+ assert.match(zhPrep, new RegExp(`${Math.round((600000 / THRESHOLD) * 100)}%`))
1336
+ assert.match(zhPrep, /临时文件/)
1337
+ assert.match(zhPrep, /handoff_ready/)
1338
+ assert.match(zhPrep, /2/)
1339
+ const enOptions = resolveOptions({ foldMode: 'handoff' })
1340
+ const enPrep = handoffPrepMessage({ path, trigger, recycled: 0, options: enOptions })
1341
+ assert.ok(enPrep.includes(path))
1342
+ assert.match(enPrep, /temporary file/)
1343
+ const enActivation = handoffActivationMessage({ path, foldNo: 1, options: enOptions })
1344
+ assert.ok(enActivation.includes(path))
1345
+ assert.match(enActivation, /only auto-activated turn/)
1346
+ })
1347
+
1348
+ test('handoff mode folds at the round end and activates exactly one turn', async (t) => {
1349
+ const root = scratchRoot(t)
1350
+ const { box, meter } = movableMeter(500000)
1351
+ const folds = []
1352
+ const logs = []
1353
+ const session = handoffSession('session-happy')
1354
+ const agent = handoffAgent(session)
1355
+ const { ctx, registered } = stubContext({
1356
+ meter,
1357
+ logs,
1358
+ compaction: {
1359
+ compactNow: (...args) => {
1360
+ folds.push(args)
1361
+ return Promise.resolve({ shadowedSeqs: [1], shadowedTokenCount: 10, summarySeq: 2 })
1362
+ },
1363
+ },
1364
+ })
1365
+ apply(ctx, { foldMode: 'handoff', handoffDir: root, language: 'zh' })
1366
+
1367
+ // Below the prep point: no reminder, no tool call, nothing.
1368
+ await requestStep(registered, agent, 1)
1369
+ assert.equal(agent.injected.length, 0)
1370
+
1371
+ // Crossing it injects one reminder naming the exact path.
1372
+ box.used = 600000
1373
+ 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
1377
+ 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')
1380
+
1381
+ // One per turn, even though the waterfall runs on every step.
1382
+ await requestStep(registered, agent, 2, 2)
1383
+ await requestStep(registered, agent, 2, 3)
1384
+ assert.equal(agent.injected.length, 1)
1385
+
1386
+ // The tool refuses a note that does not exist yet.
1387
+ const tool = registered.tools.find((definition) => definition.name === HANDOFF_TOOL_NAME)
1388
+ assert.ok(tool !== undefined, 'handoff mode must register handoff_ready')
1389
+ assert.equal(tool.output.render([], 'x')[0].text, 'x')
1390
+ assert.match(tool.execute({}, { agent }), /还没有文件/)
1391
+
1392
+ // Write the note, register it.
1393
+ mkdirSync(join(root, 'session-happy'), { recursive: true })
1394
+ writeFileSync(notePath, `# 交接档\n${'x'.repeat(400)}`, 'utf8')
1395
+ const registeredText = tool.execute({ path: notePath }, { agent })
1396
+ assert.match(registeredText, /✓ 交接档已登记/)
1397
+ assert.ok(registeredText.includes(notePath))
1398
+
1399
+ // The round ends: fold once, activate once.
1400
+ await idleBoundary(registered, agent)
1401
+ assert.equal(folds.length, 1, 'the round end must fold')
1402
+ assert.ok(folds[0][1] !== undefined, 'compactNow must receive an abort signal')
1403
+ assert.equal(agent.followed.length, 1, 'exactly one activation turn')
1404
+ const activation = agent.followed[0].content[0].text
1405
+ assert.ok(activation.includes(notePath))
1406
+ assert.match(activation, /唯一一次自动激活/)
1407
+ assert.equal(agent.followed[0].source.kind, 'user')
1408
+
1409
+ // A second idle boundary activates nothing more, and the fold is not repeated.
1410
+ // A real fold drops the reading below the prep point, which is what keeps the
1411
+ // reminder (and its wake) out of the activation round.
1412
+ box.used = 100000
1413
+ await idleBoundary(registered, agent)
1414
+ assert.equal(agent.followed.length, 1)
1415
+ assert.equal(folds.length, 1)
1416
+
1417
+ // The state is durable, and it says exactly what happened.
1418
+ const state = JSON.parse(readFileSync(join(root, 'session-happy', HANDOFF_STATE_FILE), 'utf8'))
1419
+ assert.equal(state.foldNo, 1)
1420
+ assert.equal(state.ready, null)
1421
+ assert.equal(state.pending.foldNo, 1)
1422
+ assert.ok(state.pending.deliveredAt > 0)
1423
+ })
1424
+
1425
+ test('a round that ends past the prep point wakes one reminder turn, bounded by the budget', async (t) => {
1426
+ const root = scratchRoot(t)
1427
+ const { box, meter } = movableMeter(600000)
1428
+ const folds = []
1429
+ const logs = []
1430
+ const agent = handoffAgent(handoffSession('session-nonote'))
1431
+ const { ctx, registered } = stubContext({
1432
+ meter,
1433
+ logs,
1434
+ compaction: { compactNow: (...args) => (folds.push(args), Promise.resolve({ shadowedSeqs: [1] })) },
1435
+ })
1436
+ apply(ctx, { foldMode: 'handoff', handoffDir: root })
1437
+
1438
+ // The mid-round reminder is queued for the next request; the model ends the
1439
+ // round without writing a note.
1440
+ await requestStep(registered, agent, 1)
1441
+ assert.equal(agent.injected.length, 1)
1442
+ await idleBoundary(registered, agent)
1443
+ assert.equal(folds.length, 0, 'handoff mode must not fold behind the model\'s back')
1444
+ assert.equal(agent.followed.length, 1, 'an unread reminder must wake the round instead of waiting for a human')
1445
+ assert.ok(agent.followed[0].content[0].text.includes(handoffPathFor(root, 'session-nonote', 1)))
1446
+ assert.ok(
1447
+ logs.some(([, message]) => String(message).includes('woke the round')),
1448
+ 'the wake must be logged',
1449
+ )
1450
+
1451
+ // A second idle event of the same round must not add a second wake.
1452
+ await idleBoundary(registered, agent)
1453
+ assert.equal(agent.followed.length, 1)
1454
+
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.
1457
+ await requestStep(registered, agent, 2)
1458
+ assert.equal(agent.injected.length, 1, 'no duplicate reminder in the wake round')
1459
+ await requestStep(registered, agent, 2, 2)
1460
+ assert.equal(agent.injected.length, 1, 'and none on a later step of the same wake round')
1461
+
1462
+ // Still no note: the budget allows one more wake, then it stops.
1463
+ await idleBoundary(registered, agent)
1464
+ assert.equal(agent.followed.length, 2)
1465
+ await requestStep(registered, agent, 3)
1466
+ await idleBoundary(registered, agent)
1467
+ assert.equal(agent.followed.length, 2, 'the reminder budget must cap the wakes')
1468
+ assert.equal(folds.length, 0)
1469
+ assert.ok(logs.some(([, message]) => String(message).includes('budget spent')))
1470
+ })
1471
+
1472
+ test('a failed fold keeps the note and activates nothing', async (t) => {
1473
+ const root = scratchRoot(t)
1474
+ const { box, meter } = movableMeter(600000)
1475
+ const logs = []
1476
+ const agent = handoffAgent(handoffSession('session-fail'))
1477
+ const { ctx, registered } = stubContext({
1478
+ meter,
1479
+ logs,
1480
+ compaction: { compactNow: () => Promise.reject(new Error('engine busy')) },
1481
+ })
1482
+ apply(ctx, { foldMode: 'handoff', handoffDir: root })
1483
+ const notePath = handoffPathFor(root, 'session-fail', 1)
1484
+ mkdirSync(join(root, 'session-fail'), { recursive: true })
1485
+ writeFileSync(notePath, `# note\n${'x'.repeat(400)}`, 'utf8')
1486
+ const tool = registered.tools.find((definition) => definition.name === HANDOFF_TOOL_NAME)
1487
+ assert.match(tool.execute({}, { agent }), /✓/)
1488
+
1489
+ await idleBoundary(registered, agent)
1490
+ assert.equal(agent.followed.length, 0, 'a fold that threw must not activate a turn')
1491
+ assert.ok(logs.some(([, message]) => String(message).includes('handoff fold failed')))
1492
+ const state = JSON.parse(readFileSync(join(root, 'session-fail', HANDOFF_STATE_FILE), 'utf8'))
1493
+ assert.equal(state.foldNo, 0, 'a failed fold does not count')
1494
+ assert.equal(state.ready.path, notePath, 'the note stays for the next attempt')
1495
+ assert.equal(state.pending, null)
1496
+ })
1497
+
1498
+ test('an activation that cannot be sent survives a restart and is delivered once', async (t) => {
1499
+ const root = scratchRoot(t)
1500
+ const { box, meter } = movableMeter(600000)
1501
+ const logs = []
1502
+ const agent = handoffAgent(handoffSession('session-restart'))
1503
+ let refuses = true
1504
+ agent.followup = (message) => {
1505
+ if (refuses) throw new Error('agent gone')
1506
+ agent.followed.push(message)
1507
+ }
1508
+ const compaction = { compactNow: () => Promise.resolve({ shadowedSeqs: [1] }) }
1509
+ const first = stubContext({ meter, logs, compaction })
1510
+ apply(first.ctx, { foldMode: 'handoff', handoffDir: root })
1511
+ const notePath = handoffPathFor(root, 'session-restart', 1)
1512
+ mkdirSync(join(root, 'session-restart'), { recursive: true })
1513
+ writeFileSync(notePath, `# note\n${'x'.repeat(400)}`, 'utf8')
1514
+ first.registered.tools.find((definition) => definition.name === HANDOFF_TOOL_NAME).execute({}, { agent })
1515
+
1516
+ await idleBoundary(first.registered, agent)
1517
+ assert.equal(agent.followed.length, 0)
1518
+ assert.ok(logs.some(([, message]) => String(message).includes('could not activate the post-fold turn')))
1519
+ const afterFold = JSON.parse(readFileSync(join(root, 'session-restart', HANDOFF_STATE_FILE), 'utf8'))
1520
+ assert.equal(afterFold.foldNo, 1, 'the fold itself succeeded')
1521
+ assert.equal(afterFold.pending.deliveredAt, null)
1522
+ assert.equal(afterFold.pending.attempts, 1, 'the attempt is durable before it is sent')
1523
+
1524
+ // A fresh apply() is what a restart looks like: nothing in memory survives.
1525
+ refuses = false
1526
+ const second = stubContext({ meter, compaction })
1527
+ apply(second.ctx, { foldMode: 'handoff', handoffDir: root })
1528
+ await idleBoundary(second.registered, agent)
1529
+ assert.equal(agent.followed.length, 1, 'the pending activation must be delivered after a restart')
1530
+ // The fold dropped the reading: no reminder wake may follow the activation.
1531
+ box.used = 100000
1532
+ await idleBoundary(second.registered, agent)
1533
+ assert.equal(agent.followed.length, 1, 'and only once')
1534
+ })
1535
+
1536
+ test('the activation cap gives up instead of looping', async (t) => {
1537
+ const root = scratchRoot(t)
1538
+ const { box, meter } = movableMeter(600000)
1539
+ const logs = []
1540
+ const agent = handoffAgent(handoffSession('session-cap'))
1541
+ const dir = join(root, 'session-cap')
1542
+ mkdirSync(dir, { recursive: true })
1543
+ writeFileSync(
1544
+ join(dir, HANDOFF_STATE_FILE),
1545
+ JSON.stringify({
1546
+ version: 1,
1547
+ sessionId: 'session-cap',
1548
+ foldNo: 1,
1549
+ pending: { path: join(dir, '001.handoff.md'), foldNo: 1, attempts: 2, deliveredAt: null },
1550
+ }),
1551
+ 'utf8',
1552
+ )
1553
+ const { ctx, registered } = stubContext({ meter, logs, compaction: { compactNow: () => Promise.resolve({}) } })
1554
+ apply(ctx, { foldMode: 'handoff', handoffDir: root })
1555
+ await idleBoundary(registered, agent)
1556
+ assert.equal(agent.followed.length, 0, 'the cap must stop the retry loop')
1557
+ // `logLine` hands the host a printf-style template, so the count lives in the
1558
+ // arguments, not in the message text.
1559
+ assert.ok(
1560
+ logs.some(([, message, , , attempts]) => String(message).includes('leaving the session to the human') && attempts === 2),
1561
+ 'the give-up must be logged with the attempt count',
1562
+ )
1563
+ })
1564
+
1565
+ test('a delegated session is never prepared, registered, or folded', async (t) => {
1566
+ const root = scratchRoot(t)
1567
+ const { box, meter } = movableMeter(600000)
1568
+ const folds = []
1569
+ const logs = []
1570
+ const agent = handoffAgent(handoffSession('session-child', { depth: 2 }))
1571
+ const { ctx, registered } = stubContext({
1572
+ meter,
1573
+ logs,
1574
+ compaction: { compactNow: (...args) => (folds.push(args), Promise.resolve({})) },
1575
+ })
1576
+ apply(ctx, { foldMode: 'handoff', handoffDir: root })
1577
+
1578
+ await requestStep(registered, agent, 1)
1579
+ assert.equal(agent.injected.length, 0, 'a delegate must not be reminded')
1580
+ const notePath = handoffPathFor(root, 'session-child', 1)
1581
+ mkdirSync(join(root, 'session-child'), { recursive: true })
1582
+ writeFileSync(notePath, `# note\n${'x'.repeat(400)}`, 'utf8')
1583
+ const tool = registered.tools.find((definition) => definition.name === HANDOFF_TOOL_NAME)
1584
+ assert.match(tool.execute({}, { agent }), /delegated session/)
1585
+ await idleBoundary(registered, agent)
1586
+ assert.equal(folds.length, 0)
1587
+ assert.equal(isDelegate(handoffSession('root', { depth: 0 })), false)
1588
+ })
1589
+
1590
+ test('the activation target survives the prep that hands out the next note', async (t) => {
1591
+ const root = scratchRoot(t)
1592
+ const dir = join(root, 'session-gc')
1593
+ mkdirSync(dir, { recursive: true })
1594
+ // 现场复刻(2026-11-16 实机演练):fold #1 的激活档 001.handoff.md 与更早的草稿同在一个
1595
+ // 目录里,准备轮为 fold #2 发提醒。旧实现把 001 一起回收 —— 实测激活 18:39:58.877,
1596
+ // 回收 18:40:03.431,激活轮第一条 read 18:40:04.983 得到 FS_NOT_FOUND。这里钉住:
1597
+ // 激活目标必须留下,只有更早的草稿被回收。
1598
+ writeFileSync(join(dir, '001.handoff.md'), 'activation target', 'utf8')
1599
+ writeFileSync(join(dir, '001.drill.md'), 'older draft', 'utf8')
1600
+ writeFileSync(
1601
+ join(dir, HANDOFF_STATE_FILE),
1602
+ JSON.stringify({
1603
+ version: 1,
1604
+ sessionId: 'session-gc',
1605
+ foldNo: 1,
1606
+ pending: { path: join(dir, '001.handoff.md'), foldNo: 1, attempts: 1, deliveredAt: 1 },
1607
+ }),
1608
+ 'utf8',
1609
+ )
1610
+ const { box, meter } = movableMeter(600000)
1611
+ const agent = handoffAgent(handoffSession('session-gc'))
1612
+ const { ctx, registered } = stubContext({ meter, compaction: { compactNow: () => Promise.resolve({}) } })
1613
+ apply(ctx, { foldMode: 'handoff', handoffDir: root })
1614
+
1615
+ 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)))
1618
+ assert.equal(existsSync(join(dir, '001.handoff.md')), true, 'the note the delivered activation points at is still there')
1619
+ assert.equal(existsSync(join(dir, '001.drill.md')), false, 'the older draft is recycled')
1620
+ assert.equal(
1621
+ handoffReapable(root, 'session-gc', [handoffPathFor(root, 'session-gc', 2), handoffPathFor(root, 'session-gc', 1)]).length,
1622
+ 0,
1623
+ 'recycling is idempotent',
1624
+ )
1625
+ })
1626
+
1627
+ test('the note of the last fold is kept even when no activation record is left', async (t) => {
1628
+ const root = scratchRoot(t)
1629
+ const dir = join(root, 'session-gc')
1630
+ mkdirSync(dir, { recursive: true })
1631
+ // 不变量与持久化记录解耦:只要目录里还有 fold N 的档,准备轮 N+1 就不能删它 ——
1632
+ // 哪怕 pending 已经不在了(旧版状态文件、或将来清空 pending 的版本)。
1633
+ writeFileSync(join(dir, '001.handoff.md'), 'last fold', 'utf8')
1634
+ writeFileSync(join(dir, HANDOFF_STATE_FILE), JSON.stringify({ version: 1, sessionId: 'session-gc', foldNo: 1 }), 'utf8')
1635
+ const { box, meter } = movableMeter(600000)
1636
+ const agent = handoffAgent(handoffSession('session-gc'))
1637
+ const { ctx, registered } = stubContext({ meter, compaction: { compactNow: () => Promise.resolve({}) } })
1638
+ apply(ctx, { foldMode: 'handoff', handoffDir: root })
1639
+
1640
+ await requestStep(registered, agent, 1)
1641
+ assert.equal(existsSync(join(dir, '001.handoff.md')), true, 'the newest note is not recyclable while it is still the activation target')
1642
+ })
1643
+
1644
+ test('the note of an older fold is recycled once a newer fold exists', async (t) => {
1645
+ const root = scratchRoot(t)
1646
+ const dir = join(root, 'session-gc')
1647
+ mkdirSync(dir, { recursive: true })
1648
+ writeFileSync(join(dir, '001.handoff.md'), 'fold 1', 'utf8')
1649
+ writeFileSync(join(dir, '002.handoff.md'), 'fold 2', 'utf8')
1650
+ writeFileSync(
1651
+ join(dir, HANDOFF_STATE_FILE),
1652
+ JSON.stringify({ version: 1, sessionId: 'session-gc', foldNo: 2, pending: { path: join(dir, '002.handoff.md'), foldNo: 2, attempts: 1, deliveredAt: 1 } }),
1653
+ 'utf8',
1654
+ )
1655
+ const { box, meter } = movableMeter(600000)
1656
+ const agent = handoffAgent(handoffSession('session-gc'))
1657
+ const { ctx, registered } = stubContext({ meter, compaction: { compactNow: () => Promise.resolve({}) } })
1658
+ apply(ctx, { foldMode: 'handoff', handoffDir: root })
1659
+
1660
+ await requestStep(registered, agent, 1)
1661
+ assert.deepEqual(readdirSync(dir).sort(), [HANDOFF_STATE_FILE, '002.handoff.md'].sort(), 'only the previous fold is kept')
1662
+ })
1663
+
1664
+ test('the backstop sweep recycles notes older than a week but never a pending one', (t) => {
1665
+ const root = scratchRoot(t)
1666
+ const dir = join(root, 'session-old')
1667
+ mkdirSync(dir, { recursive: true })
1668
+ const stale = join(dir, '001.handoff.md')
1669
+ const fresh = join(dir, '002.handoff.md')
1670
+ writeFileSync(stale, 'x'.repeat(300), 'utf8')
1671
+ writeFileSync(fresh, 'y'.repeat(300), 'utf8')
1672
+ const old = new Date(Date.now() - HANDOFF_MAX_AGE_MS - 86400000)
1673
+ utimesSync(stale, old, old)
1674
+
1675
+ const writeState = (pending) =>
1676
+ writeFileSync(join(dir, HANDOFF_STATE_FILE), JSON.stringify({ version: 1, sessionId: 'session-old', foldNo: 1, pending }), 'utf8')
1677
+
1678
+ // A queued activation still points at the stale note: it must survive.
1679
+ writeState({ path: stale, foldNo: 1, attempts: 0, deliveredAt: null })
1680
+ assert.equal(sweepHandoffs(root, Date.now(), HANDOFF_MAX_AGE_MS), 0)
1681
+ assert.equal(existsSync(stale), true)
1682
+
1683
+ // Delivered: the stale note is fair game, the fresh one is not.
1684
+ writeState({ path: stale, foldNo: 1, attempts: 1, deliveredAt: Date.now() })
1685
+ assert.equal(sweepHandoffs(root, Date.now(), HANDOFF_MAX_AGE_MS), 1)
1686
+ assert.equal(existsSync(stale), false)
1687
+ assert.equal(existsSync(fresh), true)
1688
+
1689
+ // A directory is only pruned when nothing in it — notes or state — has been
1690
+ // touched for the same week: pruning takes the state file with it, and that file
1691
+ // is where a pending activation lives. A unit test caught the hard version of
1692
+ // this by losing its own fixture at load.
1693
+ unlinkSync(fresh)
1694
+ assert.equal(sweepHandoffs(root, Date.now(), HANDOFF_MAX_AGE_MS), 0)
1695
+ assert.equal(existsSync(dir), true, 'a fresh state file keeps its directory alive')
1696
+ const staleState = new Date(Date.now() - HANDOFF_MAX_AGE_MS - 86400000)
1697
+ utimesSync(join(dir, HANDOFF_STATE_FILE), staleState, staleState)
1698
+ assert.equal(sweepHandoffs(root, Date.now(), HANDOFF_MAX_AGE_MS), 0)
1699
+ assert.equal(existsSync(dir), false, 'a directory nobody has touched for the sweep window goes away')
1700
+ })
1701
+
1702
+ test('handoff_ready refuses everything it cannot honour', async (t) => {
1703
+ const root = scratchRoot(t)
1704
+ const agent = handoffAgent(handoffSession('session-refuse'))
1705
+ const toolFor = (config) => {
1706
+ const { ctx, registered } = stubContext({ used: 600000, compaction: { compactNow: () => Promise.resolve({}) } })
1707
+ apply(ctx, { handoffDir: root, ...config })
1708
+ return registered.tools.find((definition) => definition.name === HANDOFF_TOOL_NAME)
1709
+ }
1710
+
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/)
1714
+
1715
+ const tool = toolFor({ foldMode: 'handoff' })
1716
+ const notePath = handoffPathFor(root, 'session-refuse', 1)
1717
+ assert.match(tool.execute({}, { agent }), /there is no handoff note at/)
1718
+ assert.match(tool.execute({ path: join(root, 'elsewhere', 'note.md') }, { agent }), /not the one this session owns/)
1719
+
1720
+ mkdirSync(join(root, 'session-refuse'), { recursive: true })
1721
+ writeFileSync(notePath, 'too short', 'utf8')
1722
+ assert.match(tool.execute({}, { agent }), new RegExp(`only ${'too short'.length} characters`))
1723
+ assert.equal(handoffFileChars(notePath), 'too short'.length)
1724
+ assert.equal(handoffFileChars(join(root, 'missing.md')), null)
1725
+
1726
+ // The one accepted shape registers the note and says what happens next.
1727
+ writeFileSync(notePath, `# note\n${'x'.repeat(HANDOFF_MIN_CHARS)}`, 'utf8')
1728
+ const ok = tool.execute({}, { agent })
1729
+ assert.match(ok, /✓ handoff registered/)
1730
+ assert.match(ok, /End this round now/)
1731
+ const state = JSON.parse(readFileSync(join(root, 'session-refuse', HANDOFF_STATE_FILE), 'utf8'))
1732
+ assert.equal(state.ready.path, notePath)
1733
+ assert.ok(state.ready.chars >= HANDOFF_MIN_CHARS)
1734
+ // Registering twice is not a way to queue two folds.
1735
+ assert.match(tool.execute({}, { agent }), /already queued|✓/)
1736
+ })
1737
+
1738
+ test('a note registered early waits, and a reading that collapsed releases it', async (t) => {
1739
+ const root = scratchRoot(t)
1740
+ const { box, meter } = movableMeter(600000)
1741
+ const folds = []
1742
+ const logs = []
1743
+ const agent = handoffAgent(handoffSession('session-early'))
1744
+ const { ctx, registered } = stubContext({
1745
+ meter,
1746
+ logs,
1747
+ compaction: { compactNow: (...args) => (folds.push(args), Promise.resolve({})) },
1748
+ })
1749
+ apply(ctx, { foldMode: 'handoff', handoffDir: root })
1750
+ const notePath = handoffPathFor(root, 'session-early', 1)
1751
+ mkdirSync(join(root, 'session-early'), { recursive: true })
1752
+ writeFileSync(notePath, `# note\n${'x'.repeat(400)}`, 'utf8')
1753
+ const tool = registered.tools.find((definition) => definition.name === HANDOFF_TOOL_NAME)
1754
+ assert.match(tool.execute({}, { agent }), /✓/)
1755
+
1756
+ // A reading that is merely below the prep point keeps the note for the next end.
1757
+ box.used = 500000
1758
+ await idleBoundary(registered, agent)
1759
+ assert.equal(folds.length, 0)
1760
+ assert.ok(logs.some(([, message]) => String(message).includes('below the prep point')))
1761
+
1762
+ // A reading far below it means somebody else folded: the note was not used.
1763
+ box.used = 200000
1764
+ await idleBoundary(registered, agent)
1765
+ assert.equal(folds.length, 0)
1766
+ assert.ok(logs.some(([, message]) => String(message).includes('folded by something else')))
1767
+ const state = JSON.parse(readFileSync(join(root, 'session-early', HANDOFF_STATE_FILE), 'utf8'))
1768
+ assert.equal(state.ready, null, 'the unused note is released, and the next cycle re-preps')
1769
+ assert.equal(state.foldNo, 0)
1770
+ })
1771
+
1772
+ test('prep reminders are one per turn and capped per cycle', async (t) => {
1773
+ const root = scratchRoot(t)
1774
+ const { box, meter } = movableMeter(600000)
1775
+ const logs = []
1776
+ const agent = handoffAgent(handoffSession('session-budget'))
1777
+ const { ctx, registered } = stubContext({ meter, logs, compaction: { compactNow: () => Promise.resolve({}) } })
1778
+ apply(ctx, { foldMode: 'handoff', handoffDir: root, handoffReminders: 2 })
1779
+
1780
+ await requestStep(registered, agent, 1, 1)
1781
+ await requestStep(registered, agent, 1, 2)
1782
+ assert.equal(agent.injected.length, 1, 'one per turn')
1783
+ await requestStep(registered, agent, 2, 1)
1784
+ assert.equal(agent.injected.length, 2, 'a new turn gets one more')
1785
+ await requestStep(registered, agent, 3, 1)
1786
+ assert.equal(agent.injected.length, 2, 'the budget stops the nagging')
1787
+ assert.ok(logs.some(([, message]) => String(message).includes('reminder budget spent')))
1788
+ })