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