dsh-context-truth 0.1.3 → 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/CHANGELOG.md +233 -0
- package/README-en.md +94 -7
- package/README.md +163 -7
- package/lib/client.js +154 -0
- package/lib/index.js +1839 -46
- package/package.json +14 -1
- package/test/client.test.js +59 -0
- package/test/index.test.js +1352 -26
package/test/index.test.js
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
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
|
-
import { apply, internals, name, inject, CONTEXT_NAME, VARIABLE_NAME } from '../lib/index.js'
|
|
7
|
+
import { apply, internals, name, inject, Config, CONTEXT_NAME, VARIABLE_NAME } from '../lib/index.js'
|
|
5
8
|
|
|
6
|
-
const { resolveOptions, readOccupancy, settleBand, quantize, quantizeHeadroom, headroomDisplayStep, render, patchCompactionInstruction, patchCompactionRequest, isCompactionRequest, isTaggedCompactionRequest, messageText, DEFAULT_OPTIONS, DEFAULT_COMPACTION_RULES } = internals
|
|
9
|
+
const { resolveOptions, readOccupancy, settleBand, quantize, quantizeHeadroom, headroomDisplayStep, render, patchCompactionInstruction, patchCompactionRequest, isCompactionRequest, isTaggedCompactionRequest, messageText, DEFAULT_OPTIONS, DEFAULT_COMPACTION_RULES, PACE_LADDER, median, nextPaceState, samplePace, paceSteps, paceRung, settlePace, paceSentence, tightClause, foldClause, shouldFoldAtIdle, backendIdentity } = internals
|
|
10
|
+
|
|
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
|
|
7
12
|
|
|
8
13
|
/** A 1M window reserving the DeepSeek adapter's default 256K completion tokens. */
|
|
9
14
|
const WINDOW = 1000000
|
|
@@ -12,15 +17,46 @@ 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 } = {}) {
|
|
16
|
-
const registered = { variable: undefined, context: undefined, listeners: {} }
|
|
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
|
|
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 }
|
|
18
35
|
const ctx = {
|
|
19
|
-
logger:
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
36
|
+
logger:
|
|
37
|
+
logs === undefined
|
|
38
|
+
? undefined
|
|
39
|
+
: {
|
|
40
|
+
info: (...args) => logs.push(['info', ...args]),
|
|
41
|
+
warn: (...args) => logs.push(['warn', ...args]),
|
|
42
|
+
},
|
|
43
|
+
get: (key) => services[key],
|
|
44
|
+
// Mirrors cordis: the callback runs with a child context exposing exactly the
|
|
45
|
+
// requested services, and does not run at all when one of them is absent. The
|
|
46
|
+
// child's properties are live, so a test that replaces `ctx.get` is followed —
|
|
47
|
+
// which is also what the plugin relies on (it resolves per use, never once).
|
|
48
|
+
inject: (names, callback) => {
|
|
49
|
+
registered.injections.push(names)
|
|
50
|
+
const child = { logger: ctx.logger, get: ctx.get, on: ctx.on, systemPrompt: ctx.systemPrompt }
|
|
51
|
+
let ready = true
|
|
52
|
+
for (const name of names) {
|
|
53
|
+
if (ctx.get(name) === undefined) {
|
|
54
|
+
ready = false
|
|
55
|
+
continue
|
|
56
|
+
}
|
|
57
|
+
Object.defineProperty(child, name, { configurable: true, get: () => ctx.get(name) })
|
|
58
|
+
}
|
|
59
|
+
if (ready) callback(child)
|
|
24
60
|
},
|
|
25
61
|
systemPrompt: {
|
|
26
62
|
variable: (variableName, provider) => {
|
|
@@ -30,8 +66,27 @@ function stubContext({ used, meter, projections } = {}) {
|
|
|
30
66
|
registered.context = contribution
|
|
31
67
|
},
|
|
32
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.
|
|
33
72
|
on: (event, listener) => {
|
|
34
|
-
registered.listeners[event]
|
|
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 () => {}
|
|
35
90
|
},
|
|
36
91
|
}
|
|
37
92
|
return { ctx, registered }
|
|
@@ -73,7 +128,10 @@ function compactionRequest() {
|
|
|
73
128
|
|
|
74
129
|
test('exports the cordis plugin shape', () => {
|
|
75
130
|
assert.equal(name, 'context-truth')
|
|
76
|
-
|
|
131
|
+
// A sibling entry's service is reachable only through cordis injection, and both
|
|
132
|
+
// services are declared here: `ctx.get` and `ctx.inject(name, cb)` each came back
|
|
133
|
+
// empty in a live deployment, while `/compact` (declaring its injections) works.
|
|
134
|
+
assert.deepEqual(inject, ['systemPrompt', 'tokenMeter'])
|
|
77
135
|
assert.equal(typeof apply, 'function')
|
|
78
136
|
})
|
|
79
137
|
|
|
@@ -155,16 +213,31 @@ test('the displayed headroom never promises more room than the session has', ()
|
|
|
155
213
|
}
|
|
156
214
|
// The step coarsens as the room grows, which is what keeps re-injection rare.
|
|
157
215
|
assert.equal(quantizeHeadroom(THRESHOLD - 172437, WINDOW, options), 500000)
|
|
158
|
-
assert.equal(quantizeHeadroom(THRESHOLD - 610000, WINDOW, options),
|
|
216
|
+
assert.equal(quantizeHeadroom(THRESHOLD - 610000, WINDOW, options), 60000)
|
|
217
|
+
// And it stays coarse near the point: the floor is 10% of the window quantum,
|
|
218
|
+
// because within a few tens of thousands of tokens the pace estimate is the
|
|
219
|
+
// useful signal, and a 2K step re-injected the line on nearly every step.
|
|
220
|
+
for (const headroom of [68464, 28464, 18464, 8464]) {
|
|
221
|
+
assert.equal(headroomDisplayStep(headroom, WINDOW, options), 10000)
|
|
222
|
+
}
|
|
159
223
|
})
|
|
160
224
|
|
|
161
|
-
test('the tight band
|
|
225
|
+
test('the tight band names the small headroom and asks for nothing', () => {
|
|
162
226
|
const { ctx, registered } = stubContext({ used: 610000 })
|
|
163
227
|
apply(ctx, {})
|
|
164
228
|
const line = lineFor(registered, stubSession())
|
|
165
|
-
assert.match(line, /
|
|
229
|
+
assert.match(line, /About 60K tokens of headroom remain/)
|
|
166
230
|
assert.doesNotMatch(line, /Context is NOT scarce/)
|
|
167
|
-
|
|
231
|
+
// The default tight line carries no advice: no fold notice, no hand-off order.
|
|
232
|
+
assert.doesNotMatch(line, /folded into an LLM-written summary/)
|
|
233
|
+
assert.doesNotMatch(line, /hand off/)
|
|
234
|
+
assert.doesNotMatch(line, /finish the current step/)
|
|
235
|
+
// ...and it says plainly that this is telemetry the model must not act on.
|
|
236
|
+
assert.match(line, /Background telemetry from the host/)
|
|
237
|
+
assert.match(line, /take no action about compaction/)
|
|
238
|
+
// The measured figure is not an allowance: a live model counted it down on its
|
|
239
|
+
// own (30K -> 28K -> 16K -> 10K -> 7K -> 5K) while the host kept reporting 10K.
|
|
240
|
+
assert.match(line, /do not estimate or count it down yourself/)
|
|
168
241
|
})
|
|
169
242
|
|
|
170
243
|
test('over the compaction point the line stops promising headroom', () => {
|
|
@@ -172,6 +245,9 @@ test('over the compaction point the line stops promising headroom', () => {
|
|
|
172
245
|
apply(ctx, {})
|
|
173
246
|
const line = lineFor(registered, stubSession())
|
|
174
247
|
assert.match(line, /At or past the automatic compaction point/)
|
|
248
|
+
// "About 0 tokens of headroom remain" is noise; the point itself says it.
|
|
249
|
+
assert.doesNotMatch(line, /0 tokens of headroom/)
|
|
250
|
+
assert.doesNotMatch(line, /more step/)
|
|
175
251
|
})
|
|
176
252
|
|
|
177
253
|
test('a broken meter degrades to the fallback text instead of throwing', () => {
|
|
@@ -215,12 +291,15 @@ test('language and switches are honoured', () => {
|
|
|
215
291
|
assert.doesNotMatch(rendered, /作废/)
|
|
216
292
|
})
|
|
217
293
|
|
|
218
|
-
test('disabled mounts
|
|
294
|
+
test('disabled mounts no line, and leaves the other capabilities alone', () => {
|
|
219
295
|
const { ctx, registered } = stubContext({ used: 1000 })
|
|
220
296
|
apply(ctx, { enabled: false, patchCompactionPrompt: false })
|
|
221
297
|
assert.equal(registered.variable, undefined)
|
|
222
298
|
assert.equal(registered.context, undefined)
|
|
223
|
-
|
|
299
|
+
// The listeners are installed unconditionally so a settings toggle can switch
|
|
300
|
+
// them on without a reload; a disabled one no-ops per event instead.
|
|
301
|
+
assert.equal(typeof registered.listeners['llm/stream'], 'function')
|
|
302
|
+
assert.equal(typeof registered.listeners['agent/status'], 'function')
|
|
224
303
|
})
|
|
225
304
|
|
|
226
305
|
test('a second mount in the same scope stays inert instead of failing', () => {
|
|
@@ -326,8 +405,13 @@ test('the rules can be replaced or switched off', () => {
|
|
|
326
405
|
|
|
327
406
|
const { ctx, registered } = stubContext({ used: 1000 })
|
|
328
407
|
apply(ctx, { patchCompactionPrompt: false })
|
|
329
|
-
assert.equal(registered.listeners['llm/stream'], undefined)
|
|
330
408
|
assert.ok(registered.variable, 'the measured line stays installed')
|
|
409
|
+
// Installed but gated per request, so the settings switch is live: the request
|
|
410
|
+
// passes through byte-identical while the capability is off.
|
|
411
|
+
const off = compactionRequest()
|
|
412
|
+
const before = JSON.stringify(off)
|
|
413
|
+
registered.listeners['llm/stream'](off, () => 'stream')
|
|
414
|
+
assert.equal(JSON.stringify(off), before)
|
|
331
415
|
})
|
|
332
416
|
|
|
333
417
|
test('a request that merely quotes the directive is not a compaction call', () => {
|
|
@@ -428,12 +512,13 @@ test('an empty session still reads a true zero, and Chinese floors the same way'
|
|
|
428
512
|
assert.match(lineFor(zh.registered, stubSession()), /已用 不足 50K \/ 1\.00M(不足 5%)/)
|
|
429
513
|
})
|
|
430
514
|
|
|
431
|
-
test('a floored headroom names its own step instead of claiming
|
|
515
|
+
test('a floored headroom names its own step instead of claiming zero', () => {
|
|
432
516
|
const options = resolveOptions({})
|
|
433
|
-
//
|
|
434
|
-
assert.equal(headroomDisplayStep(
|
|
435
|
-
assert.equal(quantizeHeadroom(
|
|
436
|
-
|
|
517
|
+
// A reading between one and two steps floors to one full step...
|
|
518
|
+
assert.equal(headroomDisplayStep(15000, WINDOW, options), 10000)
|
|
519
|
+
assert.equal(quantizeHeadroom(15000, WINDOW, options), 10000)
|
|
520
|
+
// ...and a reading inside one step floors to zero, which renders as the step.
|
|
521
|
+
assert.equal(quantizeHeadroom(2464, WINDOW, options), 0)
|
|
437
522
|
const rendered = render(
|
|
438
523
|
'tight',
|
|
439
524
|
{
|
|
@@ -444,13 +529,96 @@ test('a floored headroom names its own step instead of claiming less than 1K', (
|
|
|
444
529
|
threshold: THRESHOLD,
|
|
445
530
|
percent: 65,
|
|
446
531
|
headroom: 0,
|
|
447
|
-
headroomRaw:
|
|
448
|
-
headroomStep:
|
|
532
|
+
headroomRaw: 2464,
|
|
533
|
+
headroomStep: 10000,
|
|
449
534
|
},
|
|
450
535
|
options,
|
|
451
536
|
)
|
|
452
|
-
assert.match(rendered, /Under
|
|
537
|
+
assert.match(rendered, /Under 10K tokens of headroom remain before it\./)
|
|
453
538
|
assert.doesNotMatch(rendered, /less than 1K/)
|
|
539
|
+
assert.doesNotMatch(rendered, /0 tokens of headroom/)
|
|
540
|
+
})
|
|
541
|
+
|
|
542
|
+
test('the small bands define what the fold is, without ordering anything', () => {
|
|
543
|
+
const options = resolveOptions({})
|
|
544
|
+
const reading = {
|
|
545
|
+
quantized: 650000,
|
|
546
|
+
step: 50000,
|
|
547
|
+
used: 652000,
|
|
548
|
+
window: WINDOW,
|
|
549
|
+
threshold: THRESHOLD,
|
|
550
|
+
percent: 65,
|
|
551
|
+
headroom: 20000,
|
|
552
|
+
headroomRaw: 26464,
|
|
553
|
+
headroomStep: 10000,
|
|
554
|
+
steps: 5,
|
|
555
|
+
}
|
|
556
|
+
// A live model read `Under 10K ... remain before it` as "context left" and
|
|
557
|
+
// answered "Very low context. I must do this in as few commands as possible."
|
|
558
|
+
const tight = render('tight', reading, options)
|
|
559
|
+
assert.match(tight, /The fold is routine, not the end of the window/)
|
|
560
|
+
assert.match(tight, /work continues after it/)
|
|
561
|
+
// A definition, not an instruction: nothing to do, nowhere to go.
|
|
562
|
+
assert.doesNotMatch(tight, /hand off|must |should |wrap up/)
|
|
563
|
+
|
|
564
|
+
// The band that already expects a fold gets only the half that defuses "exhausted".
|
|
565
|
+
const critical = render('critical', { ...reading, headroom: 0, headroomRaw: 0, steps: 0 }, options)
|
|
566
|
+
assert.match(critical, /The window is not exhausted — work continues after the fold\./)
|
|
567
|
+
assert.doesNotMatch(critical, /fold is routine/)
|
|
568
|
+
|
|
569
|
+
// Neither calm band needs the definition: the fold is not the subject there.
|
|
570
|
+
assert.doesNotMatch(render('ample', reading, options), /not the end of the window/)
|
|
571
|
+
assert.doesNotMatch(render('moderate', reading, options), /not the end of the window/)
|
|
572
|
+
assert.doesNotMatch(render('tight', reading, { ...options, foldClause: false }), /fold is routine/)
|
|
573
|
+
|
|
574
|
+
assert.equal(DEFAULT_OPTIONS.foldClause, true)
|
|
575
|
+
assert.equal(resolveOptions({ foldClause: false }).foldClause, false)
|
|
576
|
+
assert.equal(foldClause(false, options, true), ' The window is not exhausted — work continues after the fold.')
|
|
577
|
+
assert.equal(foldClause(false, { ...options, foldClause: false }), '')
|
|
578
|
+
assert.match(render('tight', reading, { ...options, language: 'zh' }), /折叠是例行操作,不是窗口的终点/)
|
|
579
|
+
})
|
|
580
|
+
|
|
581
|
+
test('the line answers "how much context is left" with the free window', () => {
|
|
582
|
+
// The headroom figure answers "how far to the fold"; a live model answered the
|
|
583
|
+
// other question with it and announced "Very low context" while 350K of the
|
|
584
|
+
// window was free. Both figures now ride the line, and neither is removed.
|
|
585
|
+
const tight = stubContext({ used: 652000 })
|
|
586
|
+
apply(tight.ctx, {})
|
|
587
|
+
const line = lineFor(tight.registered, stubSession())
|
|
588
|
+
assert.match(line, /About 300K of the window is still free\./)
|
|
589
|
+
assert.match(line, /About 20K tokens of headroom remain before it\./)
|
|
590
|
+
|
|
591
|
+
// It rides every band: this is the anti-invention anchor, not a pressure warning.
|
|
592
|
+
const calm = stubContext({ used: 300000 })
|
|
593
|
+
apply(calm.ctx, {})
|
|
594
|
+
assert.match(lineFor(calm.registered, stubSession()), /About 700K of the window is still free\./)
|
|
595
|
+
|
|
596
|
+
// A remainder inside one display step says so instead of rendering a zero.
|
|
597
|
+
const tiny = stubContext({ used: 980000 })
|
|
598
|
+
apply(tiny.ctx, {})
|
|
599
|
+
assert.match(lineFor(tiny.registered, stubSession()), /Under 50K of the window is still free\./)
|
|
600
|
+
|
|
601
|
+
// Quantized onto the same step as `used`, so it adds no re-injection of its own.
|
|
602
|
+
const freeOf = (used) => {
|
|
603
|
+
const stub = stubContext({ used })
|
|
604
|
+
apply(stub.ctx, {})
|
|
605
|
+
return /About \d+K of the window is still free\./.exec(lineFor(stub.registered, stubSession()))[0]
|
|
606
|
+
}
|
|
607
|
+
assert.equal(freeOf(652000), freeOf(654000))
|
|
608
|
+
|
|
609
|
+
const off = stubContext({ used: 652000 })
|
|
610
|
+
apply(off.ctx, { freeClause: false })
|
|
611
|
+
assert.doesNotMatch(lineFor(off.registered, stubSession()), /still free/)
|
|
612
|
+
assert.equal(DEFAULT_OPTIONS.freeClause, true)
|
|
613
|
+
assert.equal(resolveOptions({ freeClause: false }).freeClause, false)
|
|
614
|
+
assert.match(
|
|
615
|
+
render(
|
|
616
|
+
'tight',
|
|
617
|
+
{ quantized: 650000, step: 50000, used: 652000, window: WINDOW, threshold: THRESHOLD, percent: 65, free: 300000, freeRaw: 348000 },
|
|
618
|
+
{ ...resolveOptions({}), language: 'zh' },
|
|
619
|
+
),
|
|
620
|
+
/窗口还有约 300K 未使用。/,
|
|
621
|
+
)
|
|
454
622
|
})
|
|
455
623
|
|
|
456
624
|
test('the first rule forbids quoting a budget claim and embeds none itself', () => {
|
|
@@ -460,3 +628,1161 @@ test('the first rule forbids quoting a budget claim and embeds none itself', ()
|
|
|
460
628
|
assert.equal(rule.includes('"'), false, 'the rule must not hand the model a quotable false claim')
|
|
461
629
|
assert.match(DEFAULT_COMPACTION_RULES[1], /whose only justification was context pressure/)
|
|
462
630
|
})
|
|
631
|
+
|
|
632
|
+
// --- pace estimate ---------------------------------------------------------
|
|
633
|
+
|
|
634
|
+
/** Readings one step apart, each adding `step` tokens on top of `start`. */
|
|
635
|
+
function growth({ start, step, count, turn = 1 }) {
|
|
636
|
+
return Array.from({ length: count }, (_, index) => ({ turn, step: index + 1, used: start + index * step }))
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/** Drive the pure reducer over a sequence of step-boundary readings. */
|
|
640
|
+
function paceOver(readings, options = resolveOptions({})) {
|
|
641
|
+
let result = nextPaceState(undefined, readings[0], options)
|
|
642
|
+
for (const reading of readings.slice(1)) result = nextPaceState(result.state, reading, options)
|
|
643
|
+
return result
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
test('the pace estimate needs real step boundaries and enough samples', () => {
|
|
647
|
+
const options = resolveOptions({})
|
|
648
|
+
const anchor = nextPaceState(undefined, { turn: 1, step: 1, used: 100000 }, options)
|
|
649
|
+
assert.equal(anchor.perStep, undefined, 'the first reading can only anchor')
|
|
650
|
+
assert.equal(anchor.samples, 0)
|
|
651
|
+
|
|
652
|
+
const two = paceOver(growth({ start: 100000, step: 20000, count: 3 }), options)
|
|
653
|
+
assert.equal(two.perStep, undefined, 'two deltas are still below paceMinSamples')
|
|
654
|
+
assert.equal(two.samples, 2)
|
|
655
|
+
|
|
656
|
+
const three = paceOver(growth({ start: 100000, step: 20000, count: 4 }), options)
|
|
657
|
+
assert.equal(three.perStep, 20000)
|
|
658
|
+
assert.equal(three.samples, 3)
|
|
659
|
+
})
|
|
660
|
+
|
|
661
|
+
test('a re-assembly inside one step is not mistaken for work', () => {
|
|
662
|
+
const options = resolveOptions({})
|
|
663
|
+
const settled = paceOver(growth({ start: 100000, step: 20000, count: 4 }), options)
|
|
664
|
+
assert.equal(settled.perStep, 20000)
|
|
665
|
+
|
|
666
|
+
// Same step assembled again, with the reading moved by a tool result.
|
|
667
|
+
const again = nextPaceState(settled.state, { turn: 1, step: 4, used: 900000 }, options)
|
|
668
|
+
assert.equal(again.perStep, 20000, 'the estimate must not move inside a step')
|
|
669
|
+
assert.equal(again.state.used, 160000, 'the sampled reading must not move inside a step')
|
|
670
|
+
})
|
|
671
|
+
|
|
672
|
+
test('a fold re-base drops the pace history instead of poisoning it', () => {
|
|
673
|
+
const options = resolveOptions({})
|
|
674
|
+
const before = paceOver(growth({ start: 600000, step: 20000, count: 4 }), options)
|
|
675
|
+
assert.equal(before.perStep, 20000)
|
|
676
|
+
|
|
677
|
+
// The meter re-bases when a fold lands: the next reading is far below the last.
|
|
678
|
+
const folded = nextPaceState(before.state, { turn: 1, step: 5, used: 24000 }, options)
|
|
679
|
+
assert.equal(folded.perStep, undefined, 'the estimate must disappear until it is re-earned')
|
|
680
|
+
assert.equal(folded.samples, 0, 'pre-fold deltas must not survive the fold')
|
|
681
|
+
|
|
682
|
+
const rebuilt = paceOver(
|
|
683
|
+
[
|
|
684
|
+
{ turn: 1, step: 5, used: 24000 },
|
|
685
|
+
{ turn: 1, step: 6, used: 44000 },
|
|
686
|
+
{ turn: 1, step: 7, used: 64000 },
|
|
687
|
+
{ turn: 1, step: 8, used: 84000 },
|
|
688
|
+
],
|
|
689
|
+
options,
|
|
690
|
+
)
|
|
691
|
+
assert.equal(rebuilt.perStep, 20000, 'post-fold steps rebuild the estimate from scratch')
|
|
692
|
+
})
|
|
693
|
+
|
|
694
|
+
test('one large tool dump does not move the estimate', () => {
|
|
695
|
+
const options = resolveOptions({})
|
|
696
|
+
const steady = paceOver(growth({ start: 0, step: 10000, count: 7 }), options)
|
|
697
|
+
assert.equal(steady.perStep, 10000)
|
|
698
|
+
assert.equal(steady.samples, 6)
|
|
699
|
+
|
|
700
|
+
const spiked = nextPaceState(steady.state, { turn: 1, step: 8, used: steady.state.used + 90000 }, options)
|
|
701
|
+
assert.equal(spiked.perStep, 10000, 'the median absorbs a single 90K step')
|
|
702
|
+
assert.equal(spiked.samples, 7)
|
|
703
|
+
|
|
704
|
+
const long = paceOver(growth({ start: 0, step: 10000, count: 20 }), options)
|
|
705
|
+
assert.equal(long.samples, options.paceSamples, 'the ring buffer stays bounded')
|
|
706
|
+
})
|
|
707
|
+
|
|
708
|
+
test('a step that added nothing says nothing about pace', () => {
|
|
709
|
+
const options = resolveOptions({})
|
|
710
|
+
const steady = paceOver(growth({ start: 100000, step: 20000, count: 4 }), options)
|
|
711
|
+
const flat = nextPaceState(steady.state, { turn: 1, step: 5, used: steady.state.used }, options)
|
|
712
|
+
assert.equal(flat.perStep, 20000)
|
|
713
|
+
assert.equal(flat.samples, 3, 'a zero delta is neither work nor a re-base')
|
|
714
|
+
})
|
|
715
|
+
|
|
716
|
+
test('samplePace keeps per-session state and honours the switch', () => {
|
|
717
|
+
const options = resolveOptions({})
|
|
718
|
+
const store = new Map()
|
|
719
|
+
const session = {}
|
|
720
|
+
const assembly = { agent: { phase: { turn: 1, step: 1 } } }
|
|
721
|
+
assert.equal(samplePace(store, session, assembly, 100000, options), undefined)
|
|
722
|
+
assert.equal(store.get(session).used, 100000)
|
|
723
|
+
assert.equal(samplePace(store, session, assembly, 100000, { ...options, paceEstimate: false }), undefined)
|
|
724
|
+
assert.equal(samplePace(store, session, { agent: {} }, 100000, options), undefined, 'no counter, no state move')
|
|
725
|
+
const other = {}
|
|
726
|
+
assert.equal(samplePace(store, other, { agent: {} }, 100000, options), undefined)
|
|
727
|
+
assert.equal(store.get(other), undefined, 'a session without a counter stores nothing')
|
|
728
|
+
})
|
|
729
|
+
|
|
730
|
+
test('the step count floors and refuses nonsense', () => {
|
|
731
|
+
assert.equal(paceSteps(78464, 20000), 3)
|
|
732
|
+
assert.equal(paceSteps(19999, 20000), 0)
|
|
733
|
+
assert.equal(paceSteps(undefined, 20000), undefined)
|
|
734
|
+
assert.equal(paceSteps(1000, 0), undefined)
|
|
735
|
+
assert.equal(paceSteps(1000, -5), undefined)
|
|
736
|
+
})
|
|
737
|
+
|
|
738
|
+
test('the estimate rides only on the two bands that ask about headroom', () => {
|
|
739
|
+
const options = resolveOptions({})
|
|
740
|
+
const reading = {
|
|
741
|
+
quantized: 300000,
|
|
742
|
+
step: 50000,
|
|
743
|
+
used: 300000,
|
|
744
|
+
window: WINDOW,
|
|
745
|
+
threshold: THRESHOLD,
|
|
746
|
+
percent: 30,
|
|
747
|
+
headroom: 378000,
|
|
748
|
+
headroomRaw: 378464,
|
|
749
|
+
headroomStep: 50000,
|
|
750
|
+
steps: 6,
|
|
751
|
+
}
|
|
752
|
+
assert.doesNotMatch(render('ample', reading, options), /more step/)
|
|
753
|
+
assert.doesNotMatch(render('moderate', reading, options), /more step/)
|
|
754
|
+
assert.match(render('tight', reading, options), /roughly 5 more steps/)
|
|
755
|
+
assert.match(render('critical', reading, options), /roughly 5 more steps/)
|
|
756
|
+
})
|
|
757
|
+
|
|
758
|
+
test('the rungs are coarse and round down, and a lone step reads as one step', () => {
|
|
759
|
+
assert.equal(paceSentence(0, false), '')
|
|
760
|
+
assert.equal(paceSentence(1, false), " At this session's recent rate that is roughly 1 more step.")
|
|
761
|
+
assert.equal(paceSentence(2, false), " At this session's recent rate that is roughly 2 more steps.")
|
|
762
|
+
assert.equal(paceSentence(6, false), " At this session's recent rate that is roughly 5 more steps.")
|
|
763
|
+
assert.equal(paceSentence(19, false), " At this session's recent rate that is roughly 13 more steps.")
|
|
764
|
+
assert.equal(paceSentence(20, false), " At this session's recent rate that is roughly 20+ more steps.")
|
|
765
|
+
assert.equal(paceSentence(40, false), " At this session's recent rate that is roughly 20+ more steps.")
|
|
766
|
+
assert.equal(paceSentence(3, true), ' 按本会话近期节奏,这点余量约合 3 步。')
|
|
767
|
+
assert.deepEqual(PACE_LADDER, [1, 2, 3, 5, 8, 13, 20])
|
|
768
|
+
assert.equal(median([]), undefined)
|
|
769
|
+
assert.equal(median([5, 1, 3]), 3)
|
|
770
|
+
assert.equal(median([4, 1, 3, 2]), 2.5)
|
|
771
|
+
})
|
|
772
|
+
|
|
773
|
+
test('a straddling estimate no longer flips the published rung', () => {
|
|
774
|
+
const options = resolveOptions({})
|
|
775
|
+
// The raw step counts behind the five commits observed in one live session:
|
|
776
|
+
// they straddled the old 21/34 boundary and flipped the line four times.
|
|
777
|
+
const rendered = []
|
|
778
|
+
let state
|
|
779
|
+
for (const steps of [38, 23, 35, 24, 34]) {
|
|
780
|
+
const settled = settlePace(steps, state, options)
|
|
781
|
+
state = settled.state
|
|
782
|
+
rendered.push(settled.steps)
|
|
783
|
+
}
|
|
784
|
+
assert.deepEqual(rendered, [20, 20, 20, 20, 20])
|
|
785
|
+
assert.equal(new Set(rendered).size, 1, 'one rung means no pace-driven snapshot churn')
|
|
786
|
+
})
|
|
787
|
+
|
|
788
|
+
test('the rung drops at once and rises only past the margin', () => {
|
|
789
|
+
const options = resolveOptions({})
|
|
790
|
+
const first = settlePace(38, undefined, options)
|
|
791
|
+
assert.equal(first.steps, 20)
|
|
792
|
+
assert.equal(settlePace(38, first.state, options).steps, 20)
|
|
793
|
+
|
|
794
|
+
// Less room is never held back: a drop publishes immediately.
|
|
795
|
+
const down = settlePace(9, first.state, options)
|
|
796
|
+
assert.equal(down.steps, 8)
|
|
797
|
+
|
|
798
|
+
// Upward needs 20 * 1.25 = 25 to be promised again.
|
|
799
|
+
assert.equal(settlePace(24, down.state, options).steps, 8, 'a straddling estimate holds')
|
|
800
|
+
const up = settlePace(25, down.state, options)
|
|
801
|
+
assert.equal(up.steps, 20, 'a sustained change is still published — the rule cannot freeze')
|
|
802
|
+
assert.equal(settlePace(15, up.state, options).steps, 13)
|
|
803
|
+
assert.equal(settlePace(undefined, up.state, options).steps, undefined)
|
|
804
|
+
assert.equal(settlePace(0, up.state, options).steps, undefined)
|
|
805
|
+
|
|
806
|
+
assert.equal(paceRung(0), undefined)
|
|
807
|
+
assert.equal(paceRung(1), 0)
|
|
808
|
+
assert.equal(paceRung(19), 5)
|
|
809
|
+
assert.equal(paceRung(20), 6)
|
|
810
|
+
assert.equal(paceRung(9999), 6)
|
|
811
|
+
assert.equal(DEFAULT_OPTIONS.paceMargin, 0.25)
|
|
812
|
+
assert.equal(resolveOptions({ paceMargin: 0 }).paceMargin, 0)
|
|
813
|
+
// A wider margin needs a louder signal before promising more room.
|
|
814
|
+
assert.equal(settlePace(26, down.state, resolveOptions({ paceMargin: 0.5 })).steps, 8)
|
|
815
|
+
})
|
|
816
|
+
|
|
817
|
+
test('with no estimate the published line is unchanged', () => {
|
|
818
|
+
const session = stubSession()
|
|
819
|
+
const lineAt = (config, withPhase) => {
|
|
820
|
+
let used = 0
|
|
821
|
+
const meter = { measure: () => ({ totalTokens: used }) }
|
|
822
|
+
const { ctx, registered } = stubContext({ meter })
|
|
823
|
+
apply(ctx, config)
|
|
824
|
+
let line = ''
|
|
825
|
+
for (let step = 1; step <= 7; step += 1) {
|
|
826
|
+
used = 480000 + (step - 1) * 20000
|
|
827
|
+
const agent = withPhase ? { session, phase: { turn: 1, step } } : { session }
|
|
828
|
+
line = registered.variable.provider({ agent })
|
|
829
|
+
}
|
|
830
|
+
return line
|
|
831
|
+
}
|
|
832
|
+
const none = lineAt({}, false)
|
|
833
|
+
assert.match(none, /600K \/ 1\.00M tokens used \(60%\)/)
|
|
834
|
+
assert.doesNotMatch(none, /more step/)
|
|
835
|
+
assert.equal(lineAt({ paceEstimate: false }, true), none, 'the switch off must render the old line byte for byte')
|
|
836
|
+
assert.equal(lineAt({ paceEstimate: true }, true).includes('more steps'), true)
|
|
837
|
+
})
|
|
838
|
+
|
|
839
|
+
test('the tight band asks for nothing by default and offers both older wordings', () => {
|
|
840
|
+
const options = resolveOptions({})
|
|
841
|
+
const reading = {
|
|
842
|
+
quantized: 600000,
|
|
843
|
+
step: 50000,
|
|
844
|
+
used: 600000,
|
|
845
|
+
window: WINDOW,
|
|
846
|
+
threshold: THRESHOLD,
|
|
847
|
+
percent: 60,
|
|
848
|
+
headroom: 70000,
|
|
849
|
+
headroomRaw: 78464,
|
|
850
|
+
headroomStep: 10000,
|
|
851
|
+
steps: 3,
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
// Default: the numbers are the message. A fold notice here made a live model
|
|
855
|
+
// narrate compaction every step or two, so it is gone by default.
|
|
856
|
+
const none = render('tight', reading, options)
|
|
857
|
+
assert.equal(tightClause(false, options), '')
|
|
858
|
+
assert.doesNotMatch(none, /folded into an LLM-written summary/)
|
|
859
|
+
assert.doesNotMatch(none, /hand off/)
|
|
860
|
+
assert.doesNotMatch(none, /finish the current step/)
|
|
861
|
+
assert.doesNotMatch(none, /genuinely small/)
|
|
862
|
+
// The facts that make the decision possible are all still there.
|
|
863
|
+
assert.match(none, /Automatic compaction fires at 678K/)
|
|
864
|
+
assert.match(none, /About 70K tokens of headroom remain before it\./)
|
|
865
|
+
assert.match(none, /roughly 3 more steps/)
|
|
866
|
+
assert.match(none, /Background telemetry from the host/)
|
|
867
|
+
|
|
868
|
+
const inform = render('tight', reading, { ...options, tightAdvice: 'inform' })
|
|
869
|
+
assert.match(inform, /At that point the older turns are folded into an LLM-written summary/)
|
|
870
|
+
assert.match(inform, /keep nothing critical only in the conversation/)
|
|
871
|
+
assert.doesNotMatch(inform, /hand off/)
|
|
872
|
+
|
|
873
|
+
const stop = render('tight', reading, { ...options, tightAdvice: 'stop' })
|
|
874
|
+
assert.match(stop, /Headroom is genuinely small — finish the current step, land durable state, then hand off\./)
|
|
875
|
+
|
|
876
|
+
const zh = render('tight', reading, { ...options, language: 'zh' })
|
|
877
|
+
assert.doesNotMatch(zh, /会被折成一段 LLM 摘要/)
|
|
878
|
+
assert.doesNotMatch(zh, /再考虑交接/)
|
|
879
|
+
assert.doesNotMatch(zh, /余量确实不多了/)
|
|
880
|
+
assert.match(zh, /本行是宿主的后台遥测/)
|
|
881
|
+
assert.match(zh, /不要自行倒计时/)
|
|
882
|
+
assert.match(render('tight', reading, { ...options, language: 'zh', tightAdvice: 'inform' }), /会被折成一段 LLM 摘要/)
|
|
883
|
+
assert.match(render('tight', reading, { ...options, language: 'zh', tightAdvice: 'stop' }), /再考虑交接/)
|
|
884
|
+
|
|
885
|
+
// `critical` states the fact that a fold is at hand, and keeps doing so.
|
|
886
|
+
assert.match(render('critical', reading, options), /At or past the automatic compaction point/)
|
|
887
|
+
|
|
888
|
+
assert.equal(resolveOptions({ tightAdvice: 'stop' }).tightAdvice, 'stop')
|
|
889
|
+
assert.equal(resolveOptions({ tightAdvice: 'inform' }).tightAdvice, 'inform')
|
|
890
|
+
assert.equal(resolveOptions({ tightAdvice: 'nonsense' }).tightAdvice, 'none')
|
|
891
|
+
assert.equal(DEFAULT_OPTIONS.tightAdvice, 'none')
|
|
892
|
+
})
|
|
893
|
+
|
|
894
|
+
test('the registered provider turns a session pace into the rendered clause', () => {
|
|
895
|
+
let used = 0
|
|
896
|
+
const meter = { measure: () => ({ totalTokens: used }) }
|
|
897
|
+
const { ctx, registered } = stubContext({ meter })
|
|
898
|
+
apply(ctx, {})
|
|
899
|
+
const session = stubSession()
|
|
900
|
+
let line = ''
|
|
901
|
+
for (let step = 1; step <= 7; step += 1) {
|
|
902
|
+
used = 480000 + (step - 1) * 20000
|
|
903
|
+
line = registered.variable.provider({ agent: { session, phase: { turn: 1, step } } })
|
|
904
|
+
}
|
|
905
|
+
// 600K of a 678,464 point, growing 20K per step → 78,464 floors to three steps.
|
|
906
|
+
assert.match(line, /Context occupancy \(host-measured\): 600K \/ 1\.00M tokens used \(60%\)/)
|
|
907
|
+
assert.match(line, /About 70K tokens of headroom remain before it\./)
|
|
908
|
+
assert.match(line, /roughly 3 more steps/)
|
|
909
|
+
assert.match(line, /Background telemetry from the host/)
|
|
910
|
+
assert.doesNotMatch(line, /folded into an LLM-written summary/)
|
|
911
|
+
|
|
912
|
+
const zh = stubContext({ meter })
|
|
913
|
+
apply(zh.ctx, { language: 'zh' })
|
|
914
|
+
let zhLine = ''
|
|
915
|
+
for (let step = 1; step <= 7; step += 1) {
|
|
916
|
+
used = 480000 + (step - 1) * 20000
|
|
917
|
+
zhLine = zh.registered.variable.provider({ agent: { session, phase: { turn: 1, step } } })
|
|
918
|
+
}
|
|
919
|
+
assert.match(zhLine, /按本会话近期节奏,这点余量约合 3 步。/)
|
|
920
|
+
})
|
|
921
|
+
|
|
922
|
+
/** Let a listener's microtask chain run before asserting on its effects. */
|
|
923
|
+
const tick = () => new Promise((resolve) => setImmediate(resolve))
|
|
924
|
+
|
|
925
|
+
test('the idle fold fires at the turn boundary once the room runs out', async () => {
|
|
926
|
+
const calls = []
|
|
927
|
+
const compaction = {
|
|
928
|
+
compactNow: (...args) => {
|
|
929
|
+
calls.push(args)
|
|
930
|
+
return Promise.resolve()
|
|
931
|
+
},
|
|
932
|
+
}
|
|
933
|
+
const session = stubSession()
|
|
934
|
+
|
|
935
|
+
// 640K of a 1M window with the point at 678,464 → 38,464 of headroom, inside the
|
|
936
|
+
// 5% (50K) default margin: exactly the state that turns turns into short sprints.
|
|
937
|
+
const near = stubContext({ used: 640000, compaction })
|
|
938
|
+
apply(near.ctx, { foldAtIdle: true })
|
|
939
|
+
const onStatus = near.registered.listeners['agent/status']
|
|
940
|
+
assert.equal(typeof onStatus, 'function', 'foldAtIdle must subscribe to agent/status')
|
|
941
|
+
|
|
942
|
+
// Only the idle boundary folds: a running agent is mid-turn and must be left alone.
|
|
943
|
+
onStatus({ agent: { session }, status: 'running' })
|
|
944
|
+
await tick()
|
|
945
|
+
assert.equal(calls.length, 0)
|
|
946
|
+
|
|
947
|
+
onStatus({ agent: { session }, status: 'idle' })
|
|
948
|
+
await tick()
|
|
949
|
+
assert.equal(calls.length, 1, 'the idle fold must call compaction.compactNow')
|
|
950
|
+
assert.equal(calls[0][0].session, session)
|
|
951
|
+
assert.ok(calls[0][1] !== undefined, 'compactNow must receive an abort signal')
|
|
952
|
+
|
|
953
|
+
// Rate-limited: an in-flight or just-attempted fold is not repeated.
|
|
954
|
+
onStatus({ agent: { session }, status: 'idle' })
|
|
955
|
+
await tick()
|
|
956
|
+
assert.equal(calls.length, 1)
|
|
957
|
+
|
|
958
|
+
// Plenty of room: the trigger stays out of the way entirely.
|
|
959
|
+
const calm = stubContext({ used: 300000, compaction: { compactNow: () => (calls.push(['calm']), Promise.resolve()) } })
|
|
960
|
+
apply(calm.ctx, { foldAtIdle: true })
|
|
961
|
+
calm.registered.listeners['agent/status']({ agent: { session }, status: 'idle' })
|
|
962
|
+
await tick()
|
|
963
|
+
assert.equal(calls.length, 1, 'a calm session must not fold')
|
|
964
|
+
|
|
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.
|
|
975
|
+
const off = stubContext({ used: 640000, compaction })
|
|
976
|
+
apply(off.ctx, { foldMode: 'off' })
|
|
977
|
+
assert.equal(typeof off.registered.listeners['agent/status'], 'function')
|
|
978
|
+
off.registered.listeners['agent/status']({ agent: { session }, status: 'idle' })
|
|
979
|
+
await tick()
|
|
980
|
+
assert.equal(calls.length, 2, 'an explicit off must not fold anything')
|
|
981
|
+
|
|
982
|
+
// The pure decision, including the band where the fold must not fire.
|
|
983
|
+
const options = resolveOptions({ foldAtIdle: true })
|
|
984
|
+
assert.equal(shouldFoldAtIdle({ used: 640000, threshold: THRESHOLD, window: WINDOW }, options).fold, true)
|
|
985
|
+
assert.equal(shouldFoldAtIdle({ used: 620000, threshold: THRESHOLD, window: WINDOW }, options).fold, false)
|
|
986
|
+
assert.equal(shouldFoldAtIdle({ used: 640000, threshold: undefined, window: WINDOW }, options).fold, false)
|
|
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')
|
|
989
|
+
})
|
|
990
|
+
|
|
991
|
+
test('an idle fold never breaks a turn', async () => {
|
|
992
|
+
const logs = []
|
|
993
|
+
const boom = stubContext({
|
|
994
|
+
used: 640000,
|
|
995
|
+
logs,
|
|
996
|
+
compaction: { compactNow: () => Promise.reject(new Error('engine busy')) },
|
|
997
|
+
})
|
|
998
|
+
apply(boom.ctx, { foldAtIdle: true })
|
|
999
|
+
boom.registered.listeners['agent/status']({ agent: { session: stubSession() }, status: 'idle' })
|
|
1000
|
+
await tick()
|
|
1001
|
+
assert.ok(
|
|
1002
|
+
logs.some(([, message]) => String(message).includes('idle fold failed')),
|
|
1003
|
+
'a failed fold must be logged, not thrown',
|
|
1004
|
+
)
|
|
1005
|
+
|
|
1006
|
+
// No compaction service at all: warn once and keep the turn alive.
|
|
1007
|
+
const bare = stubContext({ used: 640000, logs })
|
|
1008
|
+
apply(bare.ctx, { foldAtIdle: true })
|
|
1009
|
+
bare.registered.listeners['agent/status']({ agent: { session: stubSession() }, status: 'idle' })
|
|
1010
|
+
bare.registered.listeners['agent/status']({ agent: { session: stubSession() }, status: 'idle' })
|
|
1011
|
+
await tick()
|
|
1012
|
+
const warns = logs.filter(([, message]) => String(message).includes('nor a reachable compaction service answered'))
|
|
1013
|
+
assert.equal(warns.length, 1, 'the missing-service warning must be one-shot')
|
|
1014
|
+
})
|
|
1015
|
+
|
|
1016
|
+
test('every schema default matches DEFAULT_OPTIONS', () => {
|
|
1017
|
+
// Adding the settings schema silently switched capability 2 off once: the host
|
|
1018
|
+
// materializes a field with no schema default as `[]`, and `[]` means "append
|
|
1019
|
+
// nothing" for the compaction rules. The invariant this guards is that a config
|
|
1020
|
+
// the form never touches behaves exactly like no config at all.
|
|
1021
|
+
const write = Symbol.for('cosmokit.volatile.write')
|
|
1022
|
+
const plain = (value) =>
|
|
1023
|
+
value !== null && typeof value === 'object' && write in value && typeof value.get === 'function'
|
|
1024
|
+
? plain(value.get())
|
|
1025
|
+
: value
|
|
1026
|
+
|
|
1027
|
+
const fromSchema = resolveOptions(Config({}))
|
|
1028
|
+
const fromNothing = resolveOptions({})
|
|
1029
|
+
for (const key of Object.keys(DEFAULT_OPTIONS)) {
|
|
1030
|
+
assert.deepEqual(
|
|
1031
|
+
fromSchema[key],
|
|
1032
|
+
fromNothing[key],
|
|
1033
|
+
`schema default for "${key}" must match DEFAULT_OPTIONS`,
|
|
1034
|
+
)
|
|
1035
|
+
}
|
|
1036
|
+
assert.equal(plain(Config({}).compactionRules).length, DEFAULT_COMPACTION_RULES.length)
|
|
1037
|
+
assert.ok(DEFAULT_COMPACTION_RULES.length > 0, 'the shipped rules must not be empty')
|
|
1038
|
+
})
|
|
1039
|
+
|
|
1040
|
+
test('the idle fold reaches the compaction service wired by inject', async () => {
|
|
1041
|
+
// Two live designs failed to get the service — `ctx.get('compaction')` and
|
|
1042
|
+
// `ctx.inject(['compaction'], cb)` — so it comes from the declared injection and
|
|
1043
|
+
// is read off the context, per use rather than snapshotted.
|
|
1044
|
+
const calls = []
|
|
1045
|
+
const first = { compactNow: (...args) => (calls.push(['first', ...args]), Promise.resolve()) }
|
|
1046
|
+
const stub = stubContext({ used: 640000, compaction: first })
|
|
1047
|
+
stub.ctx.compaction = first
|
|
1048
|
+
stub.ctx.tokenMeter = { measure: () => ({ totalTokens: 640000 }) }
|
|
1049
|
+
apply(stub.ctx, { foldAtIdle: true })
|
|
1050
|
+
|
|
1051
|
+
const second = { compactNow: (...args) => (calls.push(['second', ...args]), Promise.resolve()) }
|
|
1052
|
+
// Resolved per use, so a provider that arrives (or is replaced) after apply is
|
|
1053
|
+
// followed. Both reads are swapped: the stub answers `get` and the property
|
|
1054
|
+
// independently, and the resolution prefers whichever carries `compactNow`.
|
|
1055
|
+
const meter = { measure: () => ({ totalTokens: 640000 }) }
|
|
1056
|
+
stub.ctx.get = (key) => (key === 'compaction' ? second : key === 'tokenMeter' ? meter : undefined)
|
|
1057
|
+
stub.ctx.compaction = second
|
|
1058
|
+
|
|
1059
|
+
stub.registered.listeners['agent/status']({ agent: { session: stubSession() }, status: 'idle' })
|
|
1060
|
+
await tick()
|
|
1061
|
+
assert.equal(calls.length, 1, 'the trigger must reach the wired service')
|
|
1062
|
+
assert.equal(calls[0][0], 'second', 'the service must be resolved per use, not snapshotted')
|
|
1063
|
+
|
|
1064
|
+
// The meter comes from the same wiring, and the reading proves it: 640,000 used
|
|
1065
|
+
// (shown as the 600K display step) is inside the 5% margin of the 678,464 point,
|
|
1066
|
+
// and a missing meter would render "no reading yet" instead.
|
|
1067
|
+
const line = stub.registered.variable.provider({ agent: { session: stubSession() } })
|
|
1068
|
+
assert.match(line, /600K \/ 1\.00M tokens used \(60%\)/)
|
|
1069
|
+
assert.match(line, /About 30K tokens of headroom remain/)
|
|
1070
|
+
})
|
|
1071
|
+
|
|
1072
|
+
test('a live settings change reaches the plugin without a reload', async () => {
|
|
1073
|
+
// The host stores every `.volatile()` field as a reference cell and commits a
|
|
1074
|
+
// settings change into it in place (`loader._commitVolatile`), so options
|
|
1075
|
+
// snapshotted at apply time would silently ignore the toggle. Build the cell
|
|
1076
|
+
// shape the host uses and prove the plugin follows it.
|
|
1077
|
+
const write = Symbol.for('cosmokit.volatile.write')
|
|
1078
|
+
const cell = (initial) => {
|
|
1079
|
+
let current = initial
|
|
1080
|
+
return { get: () => current, [write]: (next) => (current = next) }
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
const freeClause = cell(true)
|
|
1084
|
+
const { ctx, registered } = stubContext({ used: 652000 })
|
|
1085
|
+
apply(ctx, { freeClause })
|
|
1086
|
+
const line = () => registered.variable.provider({ agent: { session: stubSession() } })
|
|
1087
|
+
assert.match(line(), /of the window is still free/)
|
|
1088
|
+
|
|
1089
|
+
freeClause[write](false) // what the settings page does to the running reference
|
|
1090
|
+
assert.doesNotMatch(line(), /still free/)
|
|
1091
|
+
freeClause[write](true)
|
|
1092
|
+
assert.match(line(), /of the window is still free/)
|
|
1093
|
+
|
|
1094
|
+
// And the fold switch follows the same path: flipped at runtime, it arms.
|
|
1095
|
+
const calls = []
|
|
1096
|
+
const foldAtIdle = cell(false)
|
|
1097
|
+
const armed = stubContext({
|
|
1098
|
+
used: 640000,
|
|
1099
|
+
compaction: { compactNow: (...args) => (calls.push(args), Promise.resolve()) },
|
|
1100
|
+
})
|
|
1101
|
+
apply(armed.ctx, { foldAtIdle })
|
|
1102
|
+
const idle = () => armed.registered.listeners['agent/status']({ agent: { session: stubSession() }, status: 'idle' })
|
|
1103
|
+
idle()
|
|
1104
|
+
await tick()
|
|
1105
|
+
assert.equal(calls.length, 0, 'a switched-off fold must not fire')
|
|
1106
|
+
|
|
1107
|
+
foldAtIdle[write](true)
|
|
1108
|
+
idle()
|
|
1109
|
+
await tick()
|
|
1110
|
+
assert.equal(calls.length, 1, 'flipping the switch at runtime must arm the fold')
|
|
1111
|
+
assert.equal(resolveOptions({ freeClause }).freeClause, true, 'resolveOptions must unwrap a reference cell')
|
|
1112
|
+
})
|
|
1113
|
+
|
|
1114
|
+
test('the backend identity names the mounted engine', () => {
|
|
1115
|
+
// Which backend owns the seam decides whether a fold can be requested at all and
|
|
1116
|
+
// whether capability 2 has anything to patch, so the startup line reports it.
|
|
1117
|
+
class CompactionEngine {}
|
|
1118
|
+
class BasicCompactionEngine extends CompactionEngine {}
|
|
1119
|
+
class DcpEngine extends BasicCompactionEngine {}
|
|
1120
|
+
assert.equal(backendIdentity(new DcpEngine()), 'DcpEngine>BasicCompactionEngine>CompactionEngine')
|
|
1121
|
+
assert.equal(backendIdentity(undefined), 'none')
|
|
1122
|
+
assert.equal(backendIdentity('not injected'), 'none', 'cordis answers with a string when unreachable')
|
|
1123
|
+
assert.equal(backendIdentity({}), 'anonymous')
|
|
1124
|
+
assert.equal(backendIdentity(null), 'none')
|
|
1125
|
+
})
|
|
1126
|
+
|
|
1127
|
+
test('the idle fold prefers the realm /compact command and falls back to the service', async () => {
|
|
1128
|
+
// `commands.execute(agent, '/compact', …)` runs the fold through the AGENT's
|
|
1129
|
+
// realm view, so it lands on whichever backend that agent mounts — the only
|
|
1130
|
+
// channel that works on a stock deployment (a profile-scope plugin cannot inject
|
|
1131
|
+
// a preset realm's compaction service: upstream discussion 9425).
|
|
1132
|
+
const called = []
|
|
1133
|
+
const agent = { session: stubSession() }
|
|
1134
|
+
const commands = { execute: (...args) => (called.push(['command', ...args]), Promise.resolve({ kind: 'completed' })) }
|
|
1135
|
+
const service = { compactNow: (...args) => (called.push(['service', ...args]), Promise.resolve()) }
|
|
1136
|
+
|
|
1137
|
+
const viaCommand = stubContext({ used: 640000, compaction: service, commands })
|
|
1138
|
+
viaCommand.ctx.compaction = service
|
|
1139
|
+
viaCommand.ctx.tokenMeter = { measure: () => ({ totalTokens: 640000 }) }
|
|
1140
|
+
apply(viaCommand.ctx, { foldAtIdle: true })
|
|
1141
|
+
viaCommand.registered.listeners['agent/status']({ agent, status: 'idle' })
|
|
1142
|
+
await tick()
|
|
1143
|
+
assert.equal(called.length, 1, 'the command channel must be tried first')
|
|
1144
|
+
assert.equal(called[0][0], 'command')
|
|
1145
|
+
assert.equal(called[0][2], '/compact')
|
|
1146
|
+
assert.deepEqual(called[0][3], [], 'submitted attachments must be an empty list')
|
|
1147
|
+
assert.ok(called[0][4] !== undefined, 'the command must receive an abort signal')
|
|
1148
|
+
|
|
1149
|
+
// A realm that refuses (or mounts no compact) must not silence the fold.
|
|
1150
|
+
called.length = 0
|
|
1151
|
+
const refusing = stubContext({
|
|
1152
|
+
used: 640000,
|
|
1153
|
+
compaction: service,
|
|
1154
|
+
commands: { execute: (...args) => (called.push(['command', ...args]), Promise.reject(new Error('no such command'))) },
|
|
1155
|
+
})
|
|
1156
|
+
refusing.ctx.compaction = service
|
|
1157
|
+
refusing.ctx.tokenMeter = { measure: () => ({ totalTokens: 640000 }) }
|
|
1158
|
+
apply(refusing.ctx, { foldAtIdle: true })
|
|
1159
|
+
refusing.registered.listeners['agent/status']({ agent, status: 'idle' })
|
|
1160
|
+
await tick()
|
|
1161
|
+
assert.deepEqual(called.map((entry) => entry[0]), ['command', 'service'], 'the service must answer when the command cannot')
|
|
1162
|
+
|
|
1163
|
+
// `service` skips the command entirely.
|
|
1164
|
+
called.length = 0
|
|
1165
|
+
const direct = stubContext({ used: 640000, compaction: service, commands })
|
|
1166
|
+
direct.ctx.compaction = service
|
|
1167
|
+
direct.ctx.tokenMeter = { measure: () => ({ totalTokens: 640000 }) }
|
|
1168
|
+
apply(direct.ctx, { foldAtIdle: true, foldAtIdleMethod: 'service' })
|
|
1169
|
+
direct.registered.listeners['agent/status']({ agent, status: 'idle' })
|
|
1170
|
+
await tick()
|
|
1171
|
+
assert.deepEqual(called.map((entry) => entry[0]), ['service'])
|
|
1172
|
+
|
|
1173
|
+
// `command` never touches the service, even when one is reachable.
|
|
1174
|
+
called.length = 0
|
|
1175
|
+
const onlyCommand = stubContext({ used: 640000, compaction: service, commands })
|
|
1176
|
+
onlyCommand.ctx.compaction = service
|
|
1177
|
+
onlyCommand.ctx.tokenMeter = { measure: () => ({ totalTokens: 640000 }) }
|
|
1178
|
+
apply(onlyCommand.ctx, { foldAtIdle: true, foldAtIdleMethod: 'command' })
|
|
1179
|
+
onlyCommand.registered.listeners['agent/status']({ agent, status: 'idle' })
|
|
1180
|
+
await tick()
|
|
1181
|
+
assert.deepEqual(called.map((entry) => entry[0]), ['command'])
|
|
1182
|
+
assert.equal(DEFAULT_OPTIONS.foldAtIdleMethod, 'auto')
|
|
1183
|
+
})
|
|
1184
|
+
|
|
1185
|
+
test('a diagnostic string from the property read never shadows a working service', async () => {
|
|
1186
|
+
// `ctx.compaction` answers with a string when this fiber lacks the service, while
|
|
1187
|
+
// `ctx.get('compaction')` can still resolve it. Treating the string as "found"
|
|
1188
|
+
// skipped the candidate that worked and the fold silently stopped firing.
|
|
1189
|
+
const calls = []
|
|
1190
|
+
const service = { compactNow: (...args) => (calls.push(args), Promise.resolve()) }
|
|
1191
|
+
const stub = stubContext({ used: 640000 })
|
|
1192
|
+
stub.ctx.get = (key) => (key === 'compaction' ? service : key === 'tokenMeter' ? { measure: () => ({ totalTokens: 640000 }) } : undefined)
|
|
1193
|
+
stub.ctx.compaction = 'service "compaction" has not been injected' // the diagnostic string
|
|
1194
|
+
stub.ctx.tokenMeter = { measure: () => ({ totalTokens: 640000 }) }
|
|
1195
|
+
apply(stub.ctx, { foldAtIdle: true, foldAtIdleMethod: 'service' })
|
|
1196
|
+
stub.registered.listeners['agent/status']({ agent: { session: stubSession() }, status: 'idle' })
|
|
1197
|
+
await tick()
|
|
1198
|
+
assert.equal(calls.length, 1, 'the reachable service must win over the diagnostic string')
|
|
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
|
+
})
|