@magic6/dsh-compaction-policy-engine 0.0.0-stage → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,1384 @@
1
+ /**
2
+ * dsh-compaction-policy-engine — a configurable policy layer over the official
3
+ * compaction engine.
4
+ *
5
+ * `@deepseek-ai/dsh-compaction-basic` already implements the compaction semantics
6
+ * (region selection, tool-pairing balance, summary framing, the durable
7
+ * transaction); what it lacks is a configuration surface. This plugin adds
8
+ * exactly that and nothing else: it *replaces* the `compaction-basic` row (one
9
+ * implementation per `ctx.compaction`) by subclassing `BasicCompactionEngine` and
10
+ * overriding its two documented hooks — `compactIfNeeded` (whether, and at what
11
+ * threshold) and `summarize` (which model) — plus `compactNow`, for manual
12
+ * compaction that survives its caller (see that method).
13
+ *
14
+ * Thresholds and retention are ratios of the adapter-declared context window, so
15
+ * they keep their meaning when a window changes; a layer may instead state
16
+ * `thresholdTokens`/`retainTokens` for a fixed working tail, which the engine
17
+ * resolves through the window before handing the parent its ratio form.
18
+ *
19
+ * @module dsh-compaction-policy-engine
20
+ */
21
+
22
+ import z from '@deepseek-ai/schemastery';
23
+ import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic';
24
+ import {
25
+ CompactionConfigError,
26
+ THINKING_OFF,
27
+ overlayDocument,
28
+ pickThinkingOff,
29
+ resolveConfig,
30
+ resolvePolicy,
31
+ resolveSummarizationEffort,
32
+ toBasicConfig,
33
+ } from './policy.js';
34
+ import { SETTINGS_NS, installSettings, plainConfig, settingsSchema } from './settings.js';
35
+ import { patchFilePaths, settingsFilePath, watchPatchFile, watchSettingsFile } from './settings-file.js';
36
+
37
+ export { CompactionConfigError } from './policy.js';
38
+ export {
39
+ AUTO,
40
+ DEFAULT_THRESHOLD_RATIO,
41
+ MIN_COMPACT_GAP_TOKENS,
42
+ THINKING_OFF,
43
+ overlayDocument,
44
+ pickThinkingOff,
45
+ resolveConfig,
46
+ resolvePolicy,
47
+ resolveSummarizationEffort,
48
+ toBasicConfig,
49
+ } from './policy.js';
50
+ export { SETTINGS_NS, plainConfig, settingsSchema } from './settings.js';
51
+
52
+ // The two range re-pricing helpers are exported because the manual-retention
53
+ // contract rests on them: a test can drive them directly and assert the shape of
54
+ // the measurement the parent's selector will consume, which is the only way to
55
+ // notice an upstream change to that selector before it silently degrades manual
56
+ // compactions back to one node. They are pure, so exporting them widens nothing.
57
+ export { reframeMeasurement, retainKeepIndex, reportUnstatedThreshold };
58
+
59
+ /**
60
+ * A one-line description of a failed summarization attempt.
61
+ *
62
+ * A failure arrives in three shapes — an `LlmError`-carrying `finish` reason, a
63
+ * thrown error from a middleware or consumer, and a bare object — and the operator
64
+ * reading the log needs the same thing from all three: what went wrong and, when
65
+ * the adapter said so, which code. Naming the code matters because the retry-worthy
66
+ * failures (`RATE_LIMITED`, `QUOTA_EXCEEDED`) and the permanent ones
67
+ * (`INVALID_CREDENTIAL`, `UNSUPPORTED_CONTENT`) look identical in a bare message.
68
+ *
69
+ * @param failure - the failure reason, thrown error, or fallback object.
70
+ * @returns a single-line description.
71
+ */
72
+ function failureMessage(failure) {
73
+ const message = typeof failure?.message === 'string' && failure.message.length > 0 ? failure.message : String(failure);
74
+ const code = failure?.code;
75
+ return code === undefined ? message : `${code}: ${message}`;
76
+ }
77
+
78
+ /**
79
+ * Render one policy field for a log line, in whichever unit the layer stated:
80
+ * `200000` and `0.2` are the same policy on a 1M window and different ones on a
81
+ * 256k window, so the unit is always explicit.
82
+ */
83
+ function declaredText(ratio, tokens) {
84
+ if (tokens !== undefined) return `${tokens}tok`;
85
+ return ratio ?? 'unset';
86
+ }
87
+
88
+ /**
89
+ * Re-pricing constants for the manual-compaction range shadow.
90
+ *
91
+ * `TAIL_DISCOUNT` is subtracted from every node above the keep index, so the
92
+ * official selector's `accumulated >= retainTokens` check (which the caller has
93
+ * fixed at `0`) fails while it walks the tail. The keep index gets the same
94
+ * amount back plus `KEEP_MARGIN`, which makes the accumulated sum telescope
95
+ * back to exactly the real tail total plus a margin. The magnitudes are set
96
+ * against the cancellation: `accumulated` walks through values of order
97
+ * `TAIL_DISCOUNT × nodeCount`, so float error grows with session length (about
98
+ * 1e4 for a 10k-event session) and `KEEP_MARGIN` stays three orders above it.
99
+ * A smaller margin would let a short tail fall through the check and compact
100
+ * the very context the operator asked to keep.
101
+ */
102
+ const TAIL_DISCOUNT = 1e12;
103
+ const KEEP_MARGIN = 1e9;
104
+
105
+ /**
106
+ * Re-price a real measurement so the parent's `retainTokens: 0` range selector
107
+ * stops at `keepFromIdx`.
108
+ *
109
+ * This is the manual-compaction fix. The parent's `compactNow` states `0` as its
110
+ * retention — a forced reduction keeps almost nothing, its "one useful
111
+ * reduction" semantic — so a manual compaction kept a single surface node while
112
+ * an automatic one kept the operator's whole tail. The transaction that would
113
+ * take a real retention is private to the upstream package, so the retention
114
+ * cannot be passed in; it has to change what the parent's selector sees.
115
+ *
116
+ * @param measurement - real unified measurement from the conversation meter.
117
+ * @param keepFromIdx - index to retain from (inclusive), or undefined when the
118
+ * real selector would return null (every node is then discounted, so the
119
+ * parent's loop runs off the end and it returns null as well).
120
+ * @returns a measurement holding the same nodes in the same order, re-priced.
121
+ */
122
+ function reframeMeasurement(measurement, keepFromIdx) {
123
+ const nodes = measurement.nodes;
124
+ return {
125
+ ...measurement,
126
+ nodes: nodes.map((node, index) => {
127
+ if (keepFromIdx === undefined) return { ...node, tokens: node.tokens - TAIL_DISCOUNT };
128
+ if (index === keepFromIdx) {
129
+ return { ...node, tokens: node.tokens + TAIL_DISCOUNT * (nodes.length - 1 - keepFromIdx) + KEEP_MARGIN };
130
+ }
131
+ if (index > keepFromIdx) return { ...node, tokens: node.tokens - TAIL_DISCOUNT };
132
+ return { ...node };
133
+ }),
134
+ };
135
+ }
136
+
137
+ /**
138
+ * The index the parent's private range selector would stop at for a real
139
+ * retention budget, replicating its index loop exactly.
140
+ *
141
+ * Everything the parent does after the loop — stepping past a system head,
142
+ * backing off across a tool-call/result pair — is left to it: the shadowed
143
+ * measurement only has to break the loop on the same index, after which the
144
+ * parent applies exactly the validation and pairing it always did. So a policy
145
+ * the real selector rejects (a retention larger than the tail, a range that
146
+ * would split a tool pair) is rejected here too, by the same code.
147
+ *
148
+ * @param measurement - real unified measurement from the conversation meter.
149
+ * @param retainTokens - minimum recent tail budget retained verbatim, in tokens.
150
+ * @returns the index to retain from (inclusive), or undefined when no index
151
+ * satisfies the budget.
152
+ */
153
+ function retainKeepIndex(measurement, retainTokens) {
154
+ const nodes = measurement.nodes;
155
+ if (nodes.length === 0) return undefined;
156
+ let accumulated = 0;
157
+ let keepFromIdx = nodes.length;
158
+ for (let index = nodes.length - 1; index >= 0; index -= 1) {
159
+ accumulated += nodes[index].tokens;
160
+ keepFromIdx = index;
161
+ if (accumulated >= retainTokens) break;
162
+ }
163
+ // The parent's post-loop guard rejects a keep index of zero for every possible
164
+ // `firstIdx`, so this is the "no useful range" answer rather than a real index.
165
+ return keepFromIdx > 0 ? keepFromIdx : undefined;
166
+ }
167
+
168
+ /**
169
+ * Parent-config fields that must be finite after a policy is applied. A
170
+ * non-finite threshold turns every gate comparison false, which *disables* the
171
+ * gate rather than raising it — a failure that looks like "compaction is far too
172
+ * eager". Checked in `applyPolicy` so it cannot pass silently.
173
+ */
174
+ const FIELD_CHECKED_AFTER_APPLY = ['headroomTokens', 'thresholdRatio'];
175
+
176
+ /**
177
+ * Load-time schema for this plugin's own policy document.
178
+ *
179
+ * Declaring it is not cosmetic: a subclass inherits the parent's static `Config`,
180
+ * and the loader validates an entry against it *before* the constructor runs —
181
+ * so omitting it made the loader stamp the parent-only `modelPolicies: []` into
182
+ * this plugin's config, which this plugin's resolver then rejected: a hard load
183
+ * failure. Shape and type only; cross-field rules live in `resolveConfig`.
184
+ */
185
+ const ratioSchema = z.number().description('a fraction of the context window, greater than 0 and less than 1');
186
+
187
+ /**
188
+ * Fields shared by the global default and every override layer.
189
+ *
190
+ * Written out longhand for each layer rather than shared through a spread,
191
+ * because this schemastery version has no `extend`/`merge` for object schemas —
192
+ * the same reason the parent engine repeats its own policy fields.
193
+ */
194
+ const layerFields = {
195
+ threshold: ratioSchema.description('compact once the session reaches this fraction of the context window'),
196
+ thresholdTokens: z
197
+ .number()
198
+ .step(1)
199
+ .min(1)
200
+ .description('compact once the session reaches this many tokens; needs a route that declares a window'),
201
+ retain: ratioSchema.description('verbatim tail to keep, as a fraction of the context window; must be below the threshold'),
202
+ retainTokens: z
203
+ .number()
204
+ .step(1)
205
+ .min(1)
206
+ .description('verbatim tail to keep, in tokens; must be below the threshold'),
207
+ summarizationModel: z
208
+ .string()
209
+ .description('"auto" to reuse the conversation\'s own routed model, or an explicit "provider/model"'),
210
+ summarizationFallback: z
211
+ .array(z.string())
212
+ .description('ordered "provider/model" routes tried when the primary summarization route fails; strongest free first, paid last'),
213
+ headroomTokens: z
214
+ .number()
215
+ .step(1)
216
+ .min(0)
217
+ .description('tokens kept free below the threshold so a summary has room to be smaller than the region it replaces'),
218
+ maxTokens: z.number().step(1).min(1).description('cap on the generated summary length'),
219
+ compactionRetries: z.number().step(1).min(0).description('retries when a summarization attempt fails'),
220
+ maxOverflowRetries: z.number().step(1).min(0).description('retries when the request itself overflowed the context window'),
221
+ };
222
+
223
+ /** The global default layer. */
224
+ const layer = z.object(layerFields);
225
+
226
+ /** One exact-target override: the same fields plus the route it applies to. */
227
+ const modelLayer = z.object({
228
+ provider: z.string().required(),
229
+ model: z.string().required(),
230
+ ...layerFields,
231
+ });
232
+
233
+ /**
234
+ * The routed (provider, model) of a conversation: the latest durable request
235
+ * wins (that is what is actually in use), falling back to the agent's options.
236
+ */
237
+ function conversationTarget(agent) {
238
+ const routed = agent.session.requestHeader()?.config;
239
+ if (routed !== undefined && routed.provider.length > 0 && routed.model.length > 0) {
240
+ return { provider: routed.provider, model: routed.model };
241
+ }
242
+ const { provider, model } = agent.options;
243
+ if (provider !== undefined && provider.length > 0 && model !== undefined && model.length > 0) {
244
+ return { provider, model };
245
+ }
246
+ return undefined;
247
+ }
248
+
249
+ /**
250
+ * The message list the last routed request actually sent: the system head plus
251
+ * every surface node's projected message, in surface order.
252
+ *
253
+ * Why the summary call must replay all of it rather than only the shadowed
254
+ * region (measured against a local inference engine): that engine
255
+ * resumes only from a stored state that is an exact token-prefix of the new
256
+ * prompt, and it keeps at most `--prompt-cache` (6) checkpoints, taken at
257
+ * assistant-turn boundaries and every `--prompt-cache-every` (16384) fresh
258
+ * tokens. Those six slots hold the *recent* turn boundaries, so the shadowed
259
+ * region's own checkpoints are long evicted: a region-only replay matches
260
+ * nothing but the pinned system-prompt root and re-reads the whole region.
261
+ * Measured: a 403,413-token prompt read over 311 s, then killed by provider-d's
262
+ * 300 s idle watchdog, because a prefill emits no tokens and a slow engine
263
+ * therefore looks idle. Appending the instruction after the FULL conversation
264
+ * instead makes the call an exact extension of the live state, so the engine
265
+ * resumes at the live end and prefills only the instruction.
266
+ *
267
+ * The trade-off is deliberate: the summary now condenses the whole
268
+ * conversation, so the checkpoint and the verbatim-retained tail overlap. That
269
+ * costs the tail's tokens once per compaction, against re-reading the entire
270
+ * context on every one.
271
+ *
272
+ * @param session - the session whose surface to project.
273
+ * @returns the projected messages, or `undefined` when the surface is unreadable.
274
+ */
275
+ function fullConversationMessages(session) {
276
+ const nodes = session?.surface?.nodes;
277
+ if (!Array.isArray(nodes) || nodes.length === 0) return undefined;
278
+ const messages = [];
279
+ for (const seq of nodes) {
280
+ const event = session.eventAt?.(seq);
281
+ if (event === undefined || event === null) continue;
282
+ const message = session.deriveEventMessage?.(event);
283
+ if (message === null || message === undefined) continue;
284
+ messages.push(message);
285
+ }
286
+ return messages.length === 0 ? undefined : messages;
287
+ }
288
+
289
+ /**
290
+ * The summary request's message list: the full conversation when the session
291
+ * can project it, otherwise the caller's own region-only input unchanged.
292
+ */
293
+ function summarizationInput(input, agent) {
294
+ const messages = fullConversationMessages(agent?.session);
295
+ return messages === undefined ? input : { ...input, messages };
296
+ }
297
+
298
+ /**
299
+ * Say once when the pressure gate falls back to the engine's constructor baseline
300
+ * because no layer states a threshold for this target.
301
+ *
302
+ * Silence is the whole bug: the settings card renders the document it holds, so an
303
+ * operator is shown 42% while compaction fires at 80% and cannot tell a mis-set
304
+ * field from a policy that never reached the resolver.
305
+ *
306
+ * @param engine - the engine holding the applied config and the file origin.
307
+ * @param target - routed provider and model, or `undefined` when none is routed.
308
+ * @param policy - the resolved policy, or `undefined` when no target was routed.
309
+ */
310
+ function reportUnstatedThreshold(engine, target, policy) {
311
+ if (policy !== undefined && (policy.thresholdRatio !== undefined || policy.thresholdTokens !== undefined)) return;
312
+ const key = target === undefined ? 'no-routed-target' : `${target.provider}/${target.model}`;
313
+ engine._reportedUnstatedThreshold ??= new Set();
314
+ if (engine._reportedUnstatedThreshold.has(key)) return;
315
+ engine._reportedUnstatedThreshold.add(key);
316
+ process.stderr.write(
317
+ `[compaction] NO THRESHOLD fiber=${engine.ctx.fiber?.name} target=${key} source=${engine._fileOrigin} ` +
318
+ `thresholdRatio=${engine.config.thresholdRatio} retainRatio=${engine.config.retainRatio}: no layer states a ` +
319
+ `threshold for this target, so the pressure gate runs on the engine baseline and fires at ` +
320
+ `${Math.round(engine.config.thresholdRatio * 100)}% of the window instead of the configured value. ` +
321
+ 'Check that this target\'s provider has a row in the policy document, and that the profile patch ' +
322
+ 'layer reached this engine (source=cordis.patch.yml).\n',
323
+ );
324
+ }
325
+
326
+ /**
327
+ * A signal that never aborts, for one manual compaction: durable work must not
328
+ * die with the caller's UI request, and the agent's own maintenance signal still
329
+ * cancels it inside the parent (`AbortSignal.any`). Fresh per call, because
330
+ * `AbortSignal.any` attaches a listener to every source it is given.
331
+ */
332
+ function detachedSignal() {
333
+ return new AbortController().signal;
334
+ }
335
+
336
+ /**
337
+ * Whether one parent failure is the agent loop's "already has active work" gate.
338
+ * `compactNow` rewrites every *synchronous* `runMaintenance` failure into
339
+ * `ManualCompactionError('busy', …)`, so the cause it attaches is the only way to
340
+ * tell a closing gate from a real compaction lock.
341
+ */
342
+ export function isMaintenanceGateError(error) {
343
+ return error?.code === 'busy' && String(error?.cause?.message ?? '').includes('already has active work');
344
+ }
345
+
346
+ /**
347
+ * Wait, bounded, for the agent's current activity to finish.
348
+ *
349
+ * The gate closes one or more microtasks *after* the previous command reported
350
+ * failure (measured: 4ms, against a retry 6–8ms later), so waiting on
351
+ * `agent.whenIdle()` closes exactly that window. The timeout bounds the wait and
352
+ * the caller's signal ends it early; the promise always resolves.
353
+ */
354
+ export function waitForAgentIdle(agent, signal, timeoutMs) {
355
+ return new Promise((resolve) => {
356
+ let settled = false;
357
+ const finish = () => {
358
+ if (settled) return;
359
+ settled = true;
360
+ clearTimeout(timer);
361
+ signal?.removeEventListener?.('abort', finish);
362
+ resolve();
363
+ };
364
+ const timer = setTimeout(finish, timeoutMs);
365
+ if (signal?.aborted === true) {
366
+ finish();
367
+ return;
368
+ }
369
+ signal?.addEventListener?.('abort', finish, { once: true });
370
+ Promise.resolve(agent?.whenIdle?.()).then(finish, finish);
371
+ });
372
+ }
373
+
374
+ /**
375
+ * The stable name of the one prompt section this plugin registers. Registered
376
+ * from the host-plane companion (global scope, so every preset carries it), and
377
+ * shadowable per agent by the same name.
378
+ */
379
+ export const CONTEXT_POLICY_SECTION = 'compaction:context-policy';
380
+
381
+ /**
382
+ * The one behavioral rule compaction owes the model.
383
+ *
384
+ * Measured 2026-10-04 in two long sessions: the model announced its context was
385
+ * nearly exhausted — and deferred work on that basis — while still far below the
386
+ * gate, and first said so *before* any compaction had fired. It cannot measure
387
+ * its own context, nothing reports one to it, and once said the claim is repeated
388
+ * (52 and 49 times). Compaction is automatic; the model's job is to keep working.
389
+ */
390
+ export const CONTEXT_POLICY_TEXT =
391
+ 'Context management is automatic and is not your responsibility: the harness measures this conversation and ' +
392
+ 'compacts it at a configured threshold. You cannot measure your own context usage, so never estimate it. ' +
393
+ 'Never stop, shorten, defer, or hand off work because you believe your context is nearly full, and never cite ' +
394
+ 'a context limit as a reason to change plans or to ask the user to start a new session — keep working until the ' +
395
+ 'user stops you or the task is complete.';
396
+
397
+ /**
398
+ * Placement of that section: directly after the deployment persona prefix, well
399
+ * before the plan/team policies, so it reads as a standing rule rather than as
400
+ * tool documentation.
401
+ */
402
+ const CONTEXT_POLICY_ORDER = 100;
403
+
404
+ /**
405
+ * Compaction engine with a three-layer policy table.
406
+ *
407
+ * Policy is resolved per routed target rather than once at construction, because
408
+ * one session can change models mid-conversation and each model may carry its
409
+ * own threshold and summarization route.
410
+ */
411
+ export class CompactionControlEngine extends BasicCompactionEngine {
412
+ /**
413
+ * This plugin's config schema. Must be declared explicitly: statics are
414
+ * inherited, so omitting it would make the loader validate this plugin's
415
+ * document against the *parent's* schema (see the schema's own comment).
416
+ */
417
+ static Config = z.object({
418
+ // 根字段判活(`.volatile()`):dsh-settings 只把带 volatile 字段的 entry
419
+ // 供到设置平面(volatileForm),而 schemastery 不允许"字典里再嵌 volatile
420
+ // 字段"($.providers.*.threshold ... without an enclosing volatile field),
421
+ // 所以只能标在这四个固定路径上。标了之后本插件读自己的配置必须先
422
+ // plainConfig() 解单元格。
423
+ default: layer.volatile(),
424
+ providers: z.dict(layer).volatile(),
425
+ models: z.array(modelLayer).volatile(),
426
+ auto: z.boolean().volatile(),
427
+ });
428
+
429
+ /**
430
+ * The operator's policy document, validated at load time and kept separately
431
+ * from the parent's already-resolved config so the parent can be fed a
432
+ * per-target configuration on each call.
433
+ */
434
+ controlConfig;
435
+
436
+ /**
437
+ * The composition document, kept unresolved-of-the-user: every later read of
438
+ * `settings.yaml` is overlaid on *this*, so a layer the file does not restate
439
+ * (a `models[]` row the profile shipped, a `providers{}` entry) survives the
440
+ * user's first edit instead of being silently dropped.
441
+ */
442
+ baseConfig;
443
+
444
+ /**
445
+ * The latest `compaction-control:` section read from `settings.yaml`, or
446
+ * undefined when that file is absent or silent. A dsh with the profile
447
+ * importer renames the file away at boot, so this normally stays undefined
448
+ * and the patch layer below is what carries the operator's numbers.
449
+ */
450
+ _fileSection;
451
+
452
+ /**
453
+ * The latest `config:` mapping read from the profile's `cordis.patch.yml`
454
+ * for this plugin's loader entry. Outranks `_fileSection` because dsh applies
455
+ * the patch layer last; a running server does not re-read it on its own, so
456
+ * this watcher is the only thing that makes a patch edit take effect live.
457
+ */
458
+ _patchEntry;
459
+
460
+ /** Which source the live policy came from, for the `source=` diagnostic. */
461
+ _fileOrigin;
462
+
463
+ /** Resolved policy per `provider/model` *and* window, so a hot path does not re-merge layers. */
464
+ policyCache = new Map();
465
+
466
+ /** Warning texts already printed, so an unworkable policy is stated once. */
467
+ reportedWarnings = new Set();
468
+
469
+ /** Live settings document, or undefined when no settings provider is mounted. */
470
+ settingsState;
471
+
472
+ /**
473
+ * @param ctx - context providing the LLM, token-meter, and session services.
474
+ * @param config - the operator's policy document, used as the composition default.
475
+ */
476
+ constructor(ctx, config = {}) {
477
+ // Resolve first: a malformed policy must fail here, with this plugin's own
478
+ // diagnostics, rather than at the first compaction.
479
+ const controlConfig = resolveConfig(plainConfig(config));
480
+ // Seed the parent with the global default layer, so inherited code paths that
481
+ // read `this.config` without a routed request already see the right numbers.
482
+ const baseline = resolvePolicy(controlConfig, { provider: '', model: '' });
483
+ super(ctx, { ...toBasicConfig(baseline), auto: controlConfig.auto });
484
+ // Keep the parent's *own* resolved shape (`headroomTokens` above all, which it
485
+ // defaults to 65536): every later `applyPolicy` rebuild starts from it, because
486
+ // `toBasicConfig` names only the fields this plugin owns.
487
+ this._parentDefaults = { ...this.config };
488
+ this.controlConfig = controlConfig;
489
+ this.baseConfig = controlConfig;
490
+
491
+ // Publish the user-facing settings section, based on this plugin's own config,
492
+ // so a profile ships a working policy the user tunes from the settings page.
493
+ // With no settings provider the section is never published at all.
494
+ this.settingsState = installSettings(ctx, SETTINGS_NS, settingsSchema, controlConfig, () => {
495
+ // The document changed (possibly an external file edit): drop every cached
496
+ // policy, or the cache would pin it for the life of the process.
497
+ this.reloadPolicy();
498
+ });
499
+
500
+ // Read the same section straight from `settings.yaml` as well.
501
+ //
502
+ // The injected path above is canonical, but it does not reach a preset-plane
503
+ // engine on this deployment: gate lines carried the composition's 0.8 while
504
+ // the file said 0.2, with no change notification. This reader gives the engine
505
+ // the one source both realms share and a person actually edits.
506
+ this._settingsFileWatcher = watchSettingsFile({
507
+ file: settingsFilePath(),
508
+ fallbackSection: controlConfig,
509
+ onSection: (section, origin) => {
510
+ this._fileSection = section;
511
+ this._fileOrigin = origin;
512
+ this.reloadPolicy();
513
+ },
514
+ onError: (error) => {
515
+ this.ctx.logger?.warn?.(`compaction-control: settings.yaml unreadable (${error.message}); keeping the last good policy`);
516
+ },
517
+ });
518
+ ctx.effect(() => () => this._settingsFileWatcher?.());
519
+
520
+ // Read the profile patch layer too: in a dsh that ships the profile
521
+ // importer, `settings.yaml` is renamed away at boot and the patch file is
522
+ // the layer a person actually edits. Nothing in dsh watches it — its own
523
+ // header says a restart is required — so without this poll an edit to the
524
+ // chain or the threshold reaches a running engine only on restart.
525
+ //
526
+ // The patch layer outranks `settings.yaml` because it is the layer dsh
527
+ // applies last, so it is allowed to override the section read above.
528
+ this._patchFileWatcher = watchPatchFile({
529
+ files: patchFilePaths(),
530
+ onConfig: (config) => {
531
+ // `reloadPolicy` derives `source=` from which layers are present, so
532
+ // this callback only records the value.
533
+ this._patchEntry = config;
534
+ this.reloadPolicy();
535
+ },
536
+ onError: (error) => {
537
+ this.ctx.logger?.warn?.(`compaction-control: profile patch unreadable (${error.message}); keeping the last good policy`);
538
+ },
539
+ });
540
+ ctx.effect(() => () => this._patchFileWatcher?.());
541
+
542
+ // One line per process, on stderr, unconditionally: "the policy is not being
543
+ // applied" and "this plugin never mounted" are otherwise indistinguishable
544
+ // from outside (the card renders either way, and a disabled or auto:false
545
+ // engine prints no gate diagnostic at all). The fiber name says *which* mount
546
+ // this is — a host-plane and a preset-realm engine print the same numbers.
547
+ process.stderr.write(
548
+ `[compaction] engine up: fiber=${this.ctx.fiber?.name} ` +
549
+ `threshold=${declaredText(this.controlConfig.default.threshold, this.controlConfig.default.thresholdTokens)} ` +
550
+ `retain=${declaredText(this.controlConfig.default.retain, this.controlConfig.default.retainTokens)} auto=${controlConfig.auto} ` +
551
+ `thinking=${THINKING_OFF} source=${this._fileOrigin}\n`,
552
+ );
553
+ }
554
+
555
+ /**
556
+ * Re-resolve the operator's document and drop cached policies.
557
+ *
558
+ * A malformed document is reported and the previous policy kept: a bad edit must
559
+ * not take the running session's compaction down, and silently reverting to
560
+ * built-in defaults would be worse than either.
561
+ */
562
+ reloadPolicy() {
563
+ // Precedence, lowest first: the composition config, then the injected
564
+ // settings service or `settings.yaml`, then the profile patch layer. Each
565
+ // later source is *overlaid* rather than replacing the document, so the
566
+ // layers the profile declared but the operator did not restate (per-model
567
+ // rows above all) survive a save — replacing them silently dropped them.
568
+ //
569
+ // The patch layer is applied last because dsh applies it last: it is the
570
+ // final word on this entry's config, and a running server that never
571
+ // re-reads it is exactly how an edit went unnoticed until restart.
572
+ let document = this.baseConfig;
573
+ let origin = 'composition';
574
+ if (this._fileSection !== undefined) {
575
+ document = overlayDocument(document, this._fileSection);
576
+ origin = 'settings.yaml';
577
+ } else if (this.settingsState !== undefined) {
578
+ const current = this.settingsState.current();
579
+ if (current !== undefined) {
580
+ document = current;
581
+ origin = 'settings-service';
582
+ }
583
+ }
584
+ if (this._patchEntry !== undefined) {
585
+ document = overlayDocument(document, this._patchEntry);
586
+ origin = 'cordis.patch.yml';
587
+ }
588
+ this._fileOrigin = origin;
589
+ try {
590
+ this.controlConfig = resolveConfig(plainConfig(document));
591
+ } catch (error) {
592
+ this.ctx.logger?.warn?.(`compaction-control: ignoring invalid settings (${error.message})`);
593
+ return false;
594
+ }
595
+ this.policyCache.clear();
596
+ this.reportedWarnings.clear();
597
+ // One line per accepted change: the settings path is live, so this record is
598
+ // the only way to tell "the watcher fired and the document was accepted" from
599
+ // "the edit never arrived".
600
+ this.ctx.logger?.info?.(
601
+ `compaction-control: policy reloaded (default.threshold=${declaredText(this.controlConfig.default.threshold, this.controlConfig.default.thresholdTokens)} ` +
602
+ `default.retain=${declaredText(this.controlConfig.default.retain, this.controlConfig.default.retainTokens)} auto=${this.controlConfig.auto} ` +
603
+ `routes=${Object.keys(this.controlConfig.providers).join(',') || '-'} ` +
604
+ `models=${this.controlConfig.models.length} source=${this._fileOrigin})`,
605
+ );
606
+ return true;
607
+ }
608
+
609
+ /**
610
+ * Resolve (and cache) the effective policy for one routed target.
611
+ *
612
+ * Keyed by the window as well as the target: an absolute token budget resolves to
613
+ * different ratios on two windows, so a target-only key would pin whichever
614
+ * window was seen first.
615
+ */
616
+ policyFor(target, contextWindow) {
617
+ const key = `${target.provider}\u0000${target.model}\u0000${contextWindow ?? ''}`;
618
+ const cached = this.policyCache.get(key);
619
+ if (cached !== undefined) return cached;
620
+ const policy = resolvePolicy(this.controlConfig, target, contextWindow);
621
+ this.policyCache.set(key, policy);
622
+ return policy;
623
+ }
624
+
625
+ /**
626
+ * The route's declared context window, when it declares a usable one.
627
+ *
628
+ * Not cached: it is one adapter-local read per step, and caching would only add
629
+ * staleness. Absence is a normal answer — a ratio-only policy never consults it.
630
+ */
631
+ async contextWindowOf(target, signal) {
632
+ if (target === undefined) return undefined;
633
+ try {
634
+ const info = await this.ctx.llm.resolveModelInfo(target.provider, target.model, signal);
635
+ const window = info?.context?.contextWindow;
636
+ return typeof window === 'number' && Number.isFinite(window) && window > 0 ? window : undefined;
637
+ } catch {
638
+ return undefined;
639
+ }
640
+ }
641
+
642
+ /**
643
+ * Apply the operator's policy for one target to the parent's config.
644
+ *
645
+ * Rebuilt rather than patched (a patch would leave a previous target's fields
646
+ * behind) and seeded from the parent's own resolved defaults, because
647
+ * `toBasicConfig` names only this plugin's fields — dropping `headroomTokens`
648
+ * made the parent's threshold NaN and silently disabled the gate. This plugin's
649
+ * vocabulary is `threshold`/`retain`; the parent's is
650
+ * `thresholdRatio`/`retainRatio`; `toBasicConfig` translates.
651
+ *
652
+ * @param target - routed provider and model.
653
+ * @param contextWindow - the route's declared window, when the caller has it.
654
+ * @returns the target's policy.
655
+ */
656
+ applyPolicy(target, contextWindow) {
657
+ const policy = this.policyFor(target, contextWindow);
658
+ // Refuse an absolute budget this route cannot convert, rather than silently
659
+ // replacing it with the engine default: the alternative is a policy that reads
660
+ // as applied while the gate runs on a number nobody wrote.
661
+ if (policy.deferred.length > 0) {
662
+ throw new CompactionConfigError(
663
+ `${policy.deferred.join(' and ')} for ${target.provider}/${target.model} cannot be honored: ` +
664
+ 'this route declares no context window to convert from. State the budget as a ratio, or fix the route\'s declared window.',
665
+ );
666
+ }
667
+ const owned = toBasicConfig(policy);
668
+ // Seed the rebuild from the parent's own resolved defaults: `toBasicConfig`
669
+ // names only this plugin's fields, so building from it drops `headroomTokens`
670
+ // — and the parent then computes `Math.min(window * ratio, NaN)` → **NaN**,
671
+ // which makes every gate comparison false. Compaction then fires on *every*
672
+ // step and the retry loop can never succeed (the 2026-10-03 runaway, context
673
+ // compacted repeatedly down to a few hundred tokens).
674
+ const next = { ...this._parentDefaults, ...owned, auto: this.controlConfig.auto };
675
+ // Retention is a mutually exclusive pair; leaving the inherited sibling in
676
+ // place makes the parent reject the whole config.
677
+ if (owned.retainTokens === undefined) delete next.retainTokens;
678
+ else delete next.retainRatio;
679
+ this.config = this.constructor.resolvedConfigFor(next);
680
+ // Fail loud rather than gate-off: a non-finite threshold is not a "no
681
+ // compaction needed" answer, and ignoring it is precisely the runaway above.
682
+ // Throwing is safe — the parent's `agent/pre-step` logs it and continues.
683
+ for (const field of FIELD_CHECKED_AFTER_APPLY) {
684
+ if (Number.isFinite(this.config[field])) continue;
685
+ throw new CompactionConfigError(
686
+ `compaction-control: the parent engine's "${field}" is ${this.config[field]} after applying the policy for ` +
687
+ `${target.provider}/${target.model}; a non-finite threshold silently disables the pressure gate. ` +
688
+ 'This means the parent schema no longer fills its own defaults — report it with this message.',
689
+ );
690
+ }
691
+ // The parent needs exactly one retention unit; checked post-resolution, so an
692
+ // absolute `retainTokens` policy is accepted and one that lost both is not.
693
+ const retention = [this.config.retainRatio, this.config.retainTokens].filter((value) => Number.isFinite(value));
694
+ if (retention.length !== 1) {
695
+ throw new CompactionConfigError(
696
+ `compaction-control: the parent engine holds ${retention.length} usable retention values ` +
697
+ `(retainRatio=${this.config.retainRatio}, retainTokens=${this.config.retainTokens}) after applying the policy for ` +
698
+ `${target.provider}/${target.model}; exactly one finite value is required.`,
699
+ );
700
+ }
701
+ this.reportWarnings(policy);
702
+ return policy;
703
+ }
704
+
705
+ /**
706
+ * Say once per distinct message what is wrong with a policy's numbers: a warning
707
+ * that repeats hundreds of times an hour is a warning nobody reads.
708
+ */
709
+ reportWarnings(policy) {
710
+ for (const warning of policy.warnings) {
711
+ if (this.reportedWarnings.has(warning)) continue;
712
+ this.reportedWarnings.add(warning);
713
+ process.stderr.write(
714
+ `[compaction] WARNING fiber=${this.ctx.fiber?.name} target=${policy.target.provider}/${policy.target.model} ${warning}\n`,
715
+ );
716
+ }
717
+ }
718
+
719
+ /**
720
+ * Validate a config in the parent's vocabulary against the parent's schema, which
721
+ * is the authoritative statement of its shape — no duplicated copy to drift from.
722
+ */
723
+ static resolvedConfigFor(config) {
724
+ return BasicCompactionEngine.Config(config);
725
+ }
726
+
727
+ /**
728
+ * Consider automatic compaction under the operator's policy for this target;
729
+ * region selection, tool-result pruning, retries, and the durable transaction all
730
+ * remain the parent's.
731
+ */
732
+ async compactIfNeeded(agent, trigger, signal) {
733
+ const target = conversationTarget(agent);
734
+ let thresholdTokens;
735
+ let result;
736
+ try {
737
+ // Needed twice (absolute-budget conversion and the diagnostic), so resolved
738
+ // once. Not a failure condition: a ratio-only policy never consults it.
739
+ const window = await this.contextWindowOf(target, signal);
740
+ // Apply the policy *before* the diagnostic, so the numbers it prints are
741
+ // the ones the gate will compare; reading `this.config` first would report
742
+ // the constructor baseline and misreport every override as ineffective.
743
+ const policy = target === undefined ? undefined : this.applyPolicy(target, window);
744
+ // The gate's number comes from the *policy*, not from `this.config`.
745
+ // `this.config` is only right here because `applyPolicy` happens to have
746
+ // rewritten it, and when `target` is undefined it still holds the engine's
747
+ // constructor baseline (0.8/0.16 on this deployment). Gating on that number
748
+ // is silent and wrong: the settings card reads 42% while compaction fires at
749
+ // 80%, which is indistinguishable from "my setting never applied".
750
+ const ratio = policy?.thresholdRatio ?? this.config.thresholdRatio;
751
+ thresholdTokens =
752
+ policy?.thresholdTokens ??
753
+ (window === undefined ? undefined : Math.floor(window * ratio));
754
+ reportUnstatedThreshold(this, target, policy);
755
+ if (process.env.DSH_COMPACT_DEBUG) {
756
+ let measured = 'unavailable';
757
+ try {
758
+ measured = this.ctx.tokenMeter.measure(agent.session).totalTokens;
759
+ } catch (error) {
760
+ measured = `error(${error.message})`;
761
+ }
762
+ // The verdict, not just the inputs: `gate` is the comparison the parent is
763
+ // about to make, so "compaction never fired" is answerable from one line.
764
+ const gate =
765
+ thresholdTokens === undefined || typeof measured !== 'number'
766
+ ? 'unknown'
767
+ : measured >= thresholdTokens
768
+ ? 'FIRE'
769
+ : 'wait';
770
+ // `declared.*` is the document as written, in its own unit, beside the
771
+ // numbers the parent compares.
772
+ process.stderr.write(
773
+ `[compact-debug] fiber=${this.ctx.fiber?.name} trigger=${trigger} target=${target === undefined ? 'UNDEFINED' : `${target.provider}/${target.model}`} ` +
774
+ `declared.threshold=${declaredText(
775
+ this.controlConfig.default.threshold,
776
+ this.controlConfig.default.thresholdTokens,
777
+ )} ` +
778
+ `declared.retain=${declaredText(
779
+ this.controlConfig.default.retain,
780
+ this.controlConfig.default.retainTokens,
781
+ )} ` +
782
+ `thresholdRatio=${this.config.thresholdRatio} retainRatio=${this.config.retainRatio} ` +
783
+ `retainTokens=${this.config.retainTokens} headroomTokens=${this.config.headroomTokens} window=${window ?? 'unresolved'} ` +
784
+ `thresholdTokens=${thresholdTokens ?? 'unknown'} measured=${measured} gate=${gate} ` +
785
+ `source=${this._fileOrigin}\n`,
786
+ );
787
+ }
788
+ result = await super.compactIfNeeded(agent, trigger, signal);
789
+ } catch (error) {
790
+ // The parent's own log line does not reach this deployment's log destination,
791
+ // and a summary that fails on every step leaves the conversation growing with
792
+ // no visible cause — so state it on stderr too, once per trigger.
793
+ if (this._reportedFailures.get(trigger) !== String(error?.message ?? error)) {
794
+ this._reportedFailures.set(trigger, String(error?.message ?? error));
795
+ process.stderr.write(
796
+ `[compaction] FAILED fiber=${this.ctx.fiber?.name} trigger=${trigger} target=${target === undefined ? 'UNDEFINED' : `${target.provider}/${target.model}`} error=${String(error?.message ?? error)}\n`,
797
+ );
798
+ }
799
+ throw error;
800
+ }
801
+ if (result !== null) {
802
+ process.stderr.write(
803
+ `[compaction] FIRED fiber=${this.ctx.fiber?.name} trigger=${trigger} source=${this._fileOrigin} thresholdRatio=${this.config.thresholdRatio} thresholdTokens=${thresholdTokens ?? 'unknown'} shadowed=${result.shadowedSeqs.length} seqs=${result.shadowedRange.start}-${result.shadowedRange.end} tokens=~${result.shadowedTokenCount}\n`,
804
+ );
805
+ }
806
+ return result;
807
+ }
808
+
809
+ /**
810
+ * How long a manual compaction waits for the agent's previous activity to release
811
+ * its gate before reporting it stuck. Overridable so a test need not wait the
812
+ * production timeout to pin the failure branch.
813
+ */
814
+ static MANUAL_GATE_WAIT_MS = 10_000;
815
+
816
+ /**
817
+ * Run one manual compaction that outlives the caller's own cancellation.
818
+ *
819
+ * Two inherited defects are fixed here, both measured 2026-10-04 (two sessions,
820
+ * each: the first attempt aborted ~4s in, the second reported "busy"):
821
+ *
822
+ * 1. The transaction was composed with the **UI request's** signal, which
823
+ * `dsh-commands` also races the handler against — so a dropped request
824
+ * killed a 20–40s durable compaction while the command had already settled
825
+ * as "This operation was aborted". The parent now receives a never-aborting
826
+ * signal; only the agent's maintenance signal cancels (Stop still works).
827
+ * 2. The parent `return`s `runMaintenance(…)` without `await`, so async
828
+ * failures escape its `catch`, and that `catch` rewrites any synchronous
829
+ * failure into `busy`. Awaiting it lets the real cause through, and a gate
830
+ * that is merely still closing is waited out once instead of being reported
831
+ * as an active compaction that does not exist.
832
+ *
833
+ * @param agent - idle agent whose next-turn admission this call reserves.
834
+ * @param signal - the caller's cancellation signal (the UI request).
835
+ * @param sourceCommandId - initiating command identity for presentation correlation.
836
+ * @returns the committed result, or `null` when no safe useful range exists.
837
+ */
838
+ async compactNow(agent, signal, sourceCommandId) {
839
+ // The request signal governs only the decision to *start*: a caller that
840
+ // already gave up must not open a transaction nobody is waiting for.
841
+ signal?.throwIfAborted?.();
842
+ // A running turn is not a closing gate; waiting for it would stall the
843
+ // command for the length of the turn and then still refuse. Say so at once.
844
+ if (agent?.status === 'running') {
845
+ throw new Error(
846
+ 'manual compaction needs an idle agent: this session is running a turn. ' +
847
+ 'Stop it or wait for the turn to finish, then retry /compact.',
848
+ );
849
+ }
850
+ // A manual compaction shall honour the same policy as an automatic one. It did
851
+ // not: the parent's `compactNow` hard-codes a zero retention (its forced
852
+ // reduction semantic), so `/compact` collapsed the history onto a single
853
+ // surface node while the pressure gate kept the operator's whole tail. That is
854
+ // not a size difference, it is a different policy, and it is the reason a user
855
+ // could not trust a manual compaction to leave the session usable.
856
+ //
857
+ // The policy cannot be passed to the parent — the transaction that would take
858
+ // a retention is private to the upstream package — so it is applied by
859
+ // changing what the parent's range selector sees (see `reframeMeasurement`).
860
+ const retainTokens = this.retainTokensForManual(agent);
861
+
862
+ const waitMs = this.constructor.MANUAL_GATE_WAIT_MS;
863
+ for (let attempt = 0; ; attempt += 1) {
864
+ try {
865
+ if (retainTokens === undefined) {
866
+ return await super.compactNow(agent, detachedSignal(), sourceCommandId);
867
+ }
868
+ return this.compactNowWithRetention(agent, detachedSignal(), sourceCommandId, retainTokens);
869
+ } catch (error) {
870
+ if (!isMaintenanceGateError(error)) throw error;
871
+ // A closing gate is waited out exactly once. Any second refusal is a
872
+ // genuinely busy agent, and the message must say that rather than
873
+ // claim an active compaction that does not exist.
874
+ if (attempt > 0) {
875
+ throw new Error(
876
+ `manual compaction could not start: the agent is still finishing its previous activity ` +
877
+ `after waiting ${waitMs}ms. The compaction lock itself is free — retry /compact now.`,
878
+ { cause: error },
879
+ );
880
+ }
881
+ await waitForAgentIdle(agent, signal, waitMs);
882
+ // The wait may have been cut short by the caller giving up.
883
+ signal?.throwIfAborted?.();
884
+ }
885
+ }
886
+ }
887
+
888
+ /**
889
+ * The context window a routed target was last resolved against, read from the
890
+ * policy cache without a model round-trip.
891
+ *
892
+ * `policyFor` keys on the window as well as the target — an absolute budget
893
+ * resolves to different ratios on two windows — so the window the pressure gate
894
+ * used is recoverable from the cache it already wrote. That is what lets the
895
+ * manual path stay synchronous: `resolveModelInfo` is the only other source and
896
+ * it is a promise, which `compactNow` cannot await without breaking the contract
897
+ * its callers rely on (the parent's transaction body runs to its first await
898
+ * before the caller gets to inspect it — the wrapper tests pin exactly that).
899
+ *
900
+ * @param target - routed provider and model.
901
+ * @returns the last window used, or undefined when the gate never ran for it.
902
+ */
903
+ cachedWindowOf(target) {
904
+ const prefix = `${target.provider}\u0000${target.model}\u0000`;
905
+ for (const key of this.policyCache.keys()) {
906
+ if (!key.startsWith(prefix)) continue;
907
+ const window = Number(key.slice(prefix.length));
908
+ if (Number.isFinite(window) && window > 0) return window;
909
+ }
910
+ return undefined;
911
+ }
912
+
913
+ /**
914
+ * The retention the operator's policy asks a manual compaction to keep, in
915
+ * tokens, read from the state the pressure gate already resolved.
916
+ *
917
+ * Deliberately synchronous and deliberately `undefined` — not a default, not a
918
+ * guess — when the policy cannot be resolved for this route (no routed target,
919
+ * no cached window, or a retention that resolves to nothing). A manual
920
+ * compaction then keeps the parent's own forced-reduction semantics rather than
921
+ * inventing a number: silently guessing a retention is how a compaction ends up
922
+ * keeping context the operator never asked for.
923
+ *
924
+ * @param agent - idle agent whose session is about to be compacted.
925
+ * @returns the retention in tokens, or undefined.
926
+ */
927
+ retainTokensForManual(agent) {
928
+ // `conversationTarget` dereferences the agent's session and options, and a
929
+ // manual compaction can arrive from a caller that supplies neither — a test
930
+ // double, or an agent whose session is not up yet. No policy can be honoured
931
+ // for such a caller, so the parent's own forced-reduction semantics apply:
932
+ // that is the behaviour this method existed to refine, not a new failure.
933
+ if (agent?.session === undefined || agent?.options === undefined) return undefined;
934
+ const target = conversationTarget(agent);
935
+ if (target === undefined) return undefined;
936
+ const window = this.cachedWindowOf(target);
937
+ if (!Number.isFinite(window)) return undefined;
938
+ // The parent resolves a ratio against the message budget — the window less
939
+ // what the route reserves for its own completion — and manual compaction must
940
+ // use the same number or the two paths disagree about what "keep the tail"
941
+ // means. The reserve is the latest routed request's configured maxTokens, the
942
+ // same value the parent's own `reservedCompletionTokens` prefers.
943
+ const reserved = agent.session.requestHeader?.()?.config?.maxTokens ?? this.config.maxTokens ?? 0;
944
+ const messageBudget = window - reserved;
945
+ const tokens = this.config.retainTokens;
946
+ const retain = tokens === undefined || !Number.isFinite(tokens) ? Math.floor(messageBudget * this.config.retainRatio) : tokens;
947
+ if (!Number.isFinite(retain) || retain <= 0) return undefined;
948
+ return retain;
949
+ }
950
+
951
+ /**
952
+ * Run the parent's manual compaction with its range selector held to the
953
+ * operator's retention.
954
+ *
955
+ * The shadow is a receiver, never a mutation: `ctx.extend()` returns a context
956
+ * that prototypally inherits this one with `tokenMeter` shadowed, and the
957
+ * parent runs against that receiver. Writing the live context instead is what
958
+ * Cordis rejects outright — a service property belongs to the fiber that
959
+ * provided it, so the assignment throws "cannot set property in multiple
960
+ * fibers" — and the failure is realm-dependent, which is the worst shape for a
961
+ * bug to take. Nothing is shared, so concurrent compactions in one realm cannot
962
+ * leak one conversation's re-pricing into another's.
963
+ *
964
+ * @param agent - idle agent whose session is compacted.
965
+ * @param signal - cancellation scoped to this compaction.
966
+ * @param sourceCommandId - command identity for presentation correlation.
967
+ * @param retainTokens - the retention the policy asked for, in tokens.
968
+ * @returns the committed result, or `null` when no safe useful range exists.
969
+ */
970
+ async compactNowWithRetention(agent, signal, sourceCommandId, retainTokens) {
971
+ const meter = this.ctx.tokenMeter;
972
+ const measured = meter.measure(agent.session);
973
+ const keepFromIdx = retainKeepIndex(measured, retainTokens);
974
+ if (process.env.DSH_COMPACT_DEBUG) {
975
+ process.stderr.write(
976
+ `[compact-debug] fiber=${this.ctx.fiber?.name} trigger=manual-target target=${agent.session.id} ` +
977
+ `retained=${retainTokens} keepFromIdx=${keepFromIdx ?? 'none'} nodes=${measured.nodes.length} ` +
978
+ `measured=${measured.totalTokens}\n`,
979
+ );
980
+ }
981
+ // Nothing to hold: the selection already returns null on its own, and
982
+ // shadowing a meter for a call the parent will refuse is pure risk.
983
+ if (keepFromIdx === undefined) return super.compactNow(agent, signal, sourceCommandId);
984
+ const shadow = Object.create(meter);
985
+ Object.defineProperty(shadow, 'measure', {
986
+ value: (session) => reframeMeasurement(meter.measure(session), keepFromIdx),
987
+ });
988
+ const receiver = Object.create(this);
989
+ // `defineProperty`, not assignment: when a method is entered through
990
+ // `ctx.compaction.<method>()` cordis rebinds `this` to a traceable shadow
991
+ // proxy in which `ctx` is read-only by design, and `receiver.ctx = …`
992
+ // walks that chain and trips its `set` trap
993
+ // (`'set' on proxy: trap returned falsish for property 'ctx'`). The
994
+ // automatic path enters with `this` still the real engine, which is why
995
+ // only the manual `/compact` route failed.
996
+ Object.defineProperty(receiver, 'ctx', {
997
+ value: this.ctx.extend({ tokenMeter: shadow }),
998
+ writable: true,
999
+ configurable: true,
1000
+ });
1001
+ // The parent prices the compaction through `regionDependencies().meter`, and
1002
+ // the re-priced nodes would charge a summary for megabytes of context that
1003
+ // were never in it. Pricing therefore runs against the real meter while only
1004
+ // the range selector sees the reframed one. `call(this)` rather than a
1005
+ // closure over `receiver`: a plain closure would recurse into this override.
1006
+ receiver.regionDependencies = () => ({
1007
+ ...BasicCompactionEngine.prototype.regionDependencies.call(this),
1008
+ meter,
1009
+ });
1010
+ return BasicCompactionEngine.prototype.compactNow.call(receiver, agent, signal, sourceCommandId);
1011
+ }
1012
+
1013
+ /** Last failure reported per trigger, so a repeating failure is stated once. */
1014
+ _reportedFailures = new Map();
1015
+
1016
+ /** Targets already warned about gating on the engine baseline. */
1017
+ _reportedUnstatedThreshold = new Set();
1018
+
1019
+ /**
1020
+ * Routes already told what their summarization thinking control is, so the
1021
+ * diagnostic is stated once per provider/model per process rather than once
1022
+ * per compaction — a route that cannot be told not to think is a property of
1023
+ * the route, not of the call, and repeating it per step would bury the one
1024
+ * line that explains a slow summary under thousands of gate lines.
1025
+ */
1026
+ _reportedThinkingControl = new Map();
1027
+
1028
+ /**
1029
+ * Summarize through the operator's chosen model, or through the conversation's
1030
+ * own when the policy says `auto` — handing the parent an empty target makes it
1031
+ * fall back to the latest routed request, which preserves the provider's warm
1032
+ * prefix cache.
1033
+ *
1034
+ * The message list is rewritten to the whole conversation first (see
1035
+ * `summarizationInput`): upstream replays only the shadowed region, and a local
1036
+ * engine whose checkpoints for that region have been evicted can only answer
1037
+ * that by re-reading all of it. On `auto` the target is therefore the very
1038
+ * route whose live state this request now extends.
1039
+ */
1040
+ async summarize(input, agent, signal) {
1041
+ const effective = summarizationInput(input, agent);
1042
+ const target = conversationTarget(agent);
1043
+ // The window goes with the policy for the same reason it does in the gate:
1044
+ // an absolute retention has to be converted before the parent can compare
1045
+ // it, and a document stated in tokens must not resolve two different ways
1046
+ // on the two paths that apply it.
1047
+ const policy = target === undefined ? undefined : this.applyPolicy(target, await this.contextWindowOf(target, signal));
1048
+ const effort = await this.resolveEffort(target, signal);
1049
+ // The diagnostic, not the decision: `effort` below is exactly what it was
1050
+ // before this line existed, and the seam is still installed on the same
1051
+ // condition. What changes is that a route which will think by default now
1052
+ // says so once, instead of costing reasoning tokens in silence.
1053
+ this.logThinkingControl(target, await this.thinkingControlOf(target, signal));
1054
+ const fallback = policy?.summarizationFallback ?? [];
1055
+ // `effort` decides whether this call needs the seam at all: with no declared
1056
+ // "do not think" level and no chain there is nothing to give the seam. It is
1057
+ // not handed to it — the attempt re-resolves the level against whichever route
1058
+ // serves it, because a chain's later routes do not have to accept the primary's,
1059
+ // and naming an undeclared id is a hard rejection.
1060
+ //
1061
+ // A route with no declared thinking level and no fallback chain needs no seam
1062
+ // at all: `super.summarize` is the parent's own call with the parent's own
1063
+ // context, and shadowing it would add a hand-off for nothing.
1064
+ if (effort === undefined && fallback.length === 0) return super.summarize(effective, agent, signal);
1065
+ // The parent assembles the whole summary request and calls `ctx.llm.stream`
1066
+ // itself, and the package exports only the engine class — so there is no
1067
+ // request option to hand the effort or the fallback to. The seam therefore
1068
+ // has to be the context, and the only safe direction is *outward*:
1069
+ // `ctx.extend()` returns a new context that prototypally inherits this one
1070
+ // with `llm` shadowed by a thin forwarder, and the parent runs against that
1071
+ // receiver.
1072
+ //
1073
+ // Writing the live context instead (`ctx.llm = …`) is what shipped first,
1074
+ // and Cordis rejects it — a service property belongs to the fiber that
1075
+ // provided it, so the assignment throws `cannot set property "llm" in
1076
+ // multiple fibers`. On this deployment that failure was realm-dependent:
1077
+ // the host-plane engine shares the provider fiber and could assign, the
1078
+ // preset-plane engine could not, which is why a manual compaction (served
1079
+ // by the former) completed while every automatic one (dispatched to the
1080
+ // latter) aborted right after the gate fired.
1081
+ //
1082
+ // Nothing is shared or mutated here, so concurrent compactions in one realm
1083
+ // cannot leak one conversation's effort — or one conversation's fallback
1084
+ // attempt — into another's summary.
1085
+ const llm = this.ctx.llm;
1086
+ const shadow = Object.create(llm);
1087
+ Object.defineProperty(shadow, 'stream', {
1088
+ value: (options) => this.streamWithFallback(llm, options, { fallback, signal }),
1089
+ });
1090
+ const receiver = Object.create(this);
1091
+ // `defineProperty`, not assignment — see `compactNowWithRetention` above for
1092
+ // why an assignment here trips cordis's read-only `ctx` shadow.
1093
+ Object.defineProperty(receiver, 'ctx', {
1094
+ value: this.ctx.extend({ llm: shadow }),
1095
+ writable: true,
1096
+ configurable: true,
1097
+ });
1098
+ return BasicCompactionEngine.prototype.summarize.call(receiver, effective, agent, signal);
1099
+ }
1100
+
1101
+ /**
1102
+ * The parent's summarization stream, with the reasoning effort applied and the
1103
+ * configured fallback chain attempted in order.
1104
+ *
1105
+ * The chain exists because the harness has none. `dsh-llm-retry` retries the
1106
+ * *same* provider/model with backoff, keyed by `retryStateKey(provider,
1107
+ * policyKey)`; nothing anywhere in the official packages walks to a different
1108
+ * model on failure. And a summarization call is exactly where that hurts: the
1109
+ * summary is the one request the harness cannot proceed without, so a free
1110
+ * route that is rate-limited or briefly down stops the conversation instead of
1111
+ * degrading to the next route.
1112
+ *
1113
+ * The parent consumes this stream incrementally
1114
+ * (`for await (const chunk of ctx.llm.stream(options))`), so an attempt cannot
1115
+ * be yielded as it arrives: a failure is only known once the stream ends, and
1116
+ * by then the parent has already fed the assembler. Each attempt is therefore
1117
+ * buffered whole, and only a complete, text-bearing attempt is released. A
1118
+ * failed attempt contributes nothing to the parent — not its deltas, not its
1119
+ * usage — so its cost is the operator's bill, never a corrupted summary.
1120
+ *
1121
+ * `options` is rewritten in place on success, because the parent reads
1122
+ * `options.provider`/`options.model` **after** the stream to record the
1123
+ * `compaction/summary` row. Without that rewrite the durable record would name
1124
+ * the primary route while a fallback did the work — and that record is the only
1125
+ * evidence an operator has of which model summarized what.
1126
+ *
1127
+ * @param llm - the real llm service, captured before the context was shadowed.
1128
+ * @param options - the parent's assembled request.
1129
+ * @param attempt - the ordered fallback routes and the call's abort signal.
1130
+ * @returns an async generator of chunks from the first attempt that succeeds.
1131
+ */
1132
+ async *streamWithFallback(llm, options, attempt) {
1133
+ const { fallback, signal } = attempt;
1134
+ const primary = { provider: options.provider, model: options.model };
1135
+ const routes = [primary, ...fallback];
1136
+ const reasons = [];
1137
+ for (const [index, route] of routes.entries()) {
1138
+ const chunks = [];
1139
+ let failure;
1140
+ let sawText = false;
1141
+ // The effort is per route, not per call: a level the primary offers is not
1142
+ // one a fallback route has to accept, and naming an undeclared id is a hard
1143
+ // rejection rather than a drop to the adapter default. Resolve it against
1144
+ // whatever route serves the attempt, and send none at all when that route
1145
+ // offers nothing or its levels cannot be read — a guess is not safer here,
1146
+ // because a wrong guess is refused outright and burns the attempt.
1147
+ const routeEffort = await this.resolveEffort(route, signal, llm);
1148
+ // Per route, for the same reason the effort is: a fallback route that
1149
+ // cannot be told not to think is a different route's problem, and the
1150
+ // chain is walked one route at a time.
1151
+ this.logThinkingControl(route, await this.thinkingControlOf(route, signal, llm));
1152
+ try {
1153
+ for await (const chunk of llm.stream({
1154
+ ...options,
1155
+ provider: route.provider,
1156
+ model: route.model,
1157
+ ...(routeEffort === undefined ? {} : { reasoningEffort: routeEffort }),
1158
+ })) {
1159
+ // A terminal `error`/`aborted` finish is how `LlmRuntime` reports an
1160
+ // adapter, dispatch, or iteration failure — it does not throw — so the
1161
+ // stream ending cleanly is not evidence that the attempt worked.
1162
+ // `max-tokens` is the third terminal kind and it is not a success:
1163
+ // the output was cut at the cap, so the summary is incomplete. Yielding
1164
+ // it as text let a truncated checkpoint through as a "successful"
1165
+ // summary and the parent only noticed once it assembled it.
1166
+ const kind = chunk.type === 'finish' ? chunk.reason?.kind : undefined;
1167
+ if (kind === 'error' || kind === 'aborted' || kind === 'max-tokens') {
1168
+ failure = chunk.reason.failure ?? { message: `summarization cut at the token cap (finish ${kind})` };
1169
+ break;
1170
+ }
1171
+ chunks.push(chunk);
1172
+ if (chunk.type === 'text-delta' && chunk.text.trim().length > 0) sawText = true;
1173
+ else if (chunk.type === 'block-end' && chunk.block?.type === 'text' && chunk.block.text.trim().length > 0) sawText = true;
1174
+ }
1175
+ } catch (error) {
1176
+ // Middleware, nested-call, and consumer failures *do* throw. Both shapes
1177
+ // mean the same thing here: this route produced no usable summary.
1178
+ failure = error;
1179
+ }
1180
+ // Aborting is the operator stopping the work, not a route failing; walking
1181
+ // to the next route would spend money on a request nobody is waiting for.
1182
+ if (signal?.aborted) throw signal.reason ?? new Error('summarization aborted');
1183
+ // An attempt that ends without text produced no summary even when it did not
1184
+ // "fail": the parent rejects an empty summary, and re-sending the prompt is
1185
+ // cheaper than reporting a compaction that cannot be committed.
1186
+ if (failure === undefined && sawText) {
1187
+ options.provider = route.provider;
1188
+ options.model = route.model;
1189
+ if (index > 0) {
1190
+ this.ctx.logger?.info?.(
1191
+ `compaction-control: summarization fell back to ${route.provider}/${route.model} ` +
1192
+ `(route ${index + 1} of ${routes.length}) after ${primary.provider}/${primary.model} failed: ` +
1193
+ `${failureMessage(failure ?? { message: 'no summary text' })}`,
1194
+ );
1195
+ }
1196
+ yield* chunks;
1197
+ return;
1198
+ }
1199
+ const reason = failureMessage(failure ?? { message: 'the route produced no summary text' });
1200
+ reasons.push(`${route.provider}/${route.model}: ${reason}`);
1201
+ this.ctx.logger?.warn?.(
1202
+ `compaction-control: summarization attempt ${index + 1}/${routes.length} on ` +
1203
+ `${route.provider}/${route.model} failed: ${reason}`,
1204
+ );
1205
+ }
1206
+ // Every route failed. The parent needs a terminal outcome, and its own
1207
+ // contract is the `finish` chunk — throwing instead would surface as an
1208
+ // unhandled stream error rather than the lawful "summarization failed".
1209
+ // The message carries each route's own reason: the parent's caller reports
1210
+ // only one line for the whole compaction, and without these an operator has
1211
+ // no way to tell a rate-limited free route from a truncated one.
1212
+ yield {
1213
+ type: 'finish',
1214
+ reason: { kind: 'error', failure: { message: `all ${routes.length} summarization routes failed (${reasons.join('; ')})`, code: 'FALLBACK_EXHAUSTED' } },
1215
+ };
1216
+ }
1217
+
1218
+ /**
1219
+ * The reasoning effort the summarization call should carry: summarizing is
1220
+ * mechanical compression, so it runs at the route's own "do not think" level. The
1221
+ * level id is adapter-owned, so it is matched against what the route declares
1222
+ * (an undeclared id is a hard rejection), and a route with no such level gets no
1223
+ * effort field at all.
1224
+ *
1225
+ * `service` is the llm service to read the levels through; the fallback executor
1226
+ * passes the one it streams on, because that is the route that has to accept the
1227
+ * level, and it may not be the context's own service.
1228
+ */
1229
+ async resolveEffort(target, signal, service) {
1230
+ if (target === undefined) return undefined;
1231
+ try {
1232
+ const info = await (service ?? this.ctx.llm).resolveModelInfo(target.provider, target.model, signal);
1233
+ return pickThinkingOff(info.reasoning?.efforts);
1234
+ } catch (error) {
1235
+ this.ctx.logger?.warn?.(
1236
+ `compaction-control: could not resolve thinking levels for ${target.provider}/${target.model} (${error.message}); summarizing with the adapter default`,
1237
+ );
1238
+ return undefined;
1239
+ }
1240
+ }
1241
+
1242
+ /**
1243
+ * The route's declared thinking capability, read once for the diagnostic.
1244
+ *
1245
+ * Separate from `resolveEffort` so the diagnostic cannot change what is sent:
1246
+ * this only reads, and its answer is logged, never returned into a request. A
1247
+ * lookup failure is `unknown` here, and the existing "could not resolve
1248
+ * thinking levels" warning in `resolveEffort` stays the only thing said about
1249
+ * it.
1250
+ *
1251
+ * @param target - routed provider and model; undefined (the `auto` case) is
1252
+ * skipped by the caller, because there is no route to name.
1253
+ * @param signal - the call's abort signal.
1254
+ * @param service - the llm service to read through; defaults to the context's.
1255
+ * @returns the resolved control, or undefined when there is no route.
1256
+ */
1257
+ async thinkingControlOf(target, signal, service) {
1258
+ if (target === undefined) return undefined;
1259
+ try {
1260
+ const info = await (service ?? this.ctx.llm).resolveModelInfo(target.provider, target.model, signal);
1261
+ return resolveSummarizationEffort(info);
1262
+ } catch {
1263
+ return undefined;
1264
+ }
1265
+ }
1266
+
1267
+ /**
1268
+ * Say once per provider/model what the summarization call will do about
1269
+ * thinking, and warn when it will think.
1270
+ *
1271
+ * The warning is the point. A route with no off level — whether it declares
1272
+ * levels but none of them is an off switch, or declares no reasoning at all —
1273
+ * is one the provider-d adapter treats as non-reasoning: it skips every
1274
+ * thinking-control branch, off included, and the provider then thinks at its
1275
+ * own default inside the summarization `maxTokens`. That used to be completely
1276
+ * silent, and a silent route that burns the cap is indistinguishable from a
1277
+ * merely slow one.
1278
+ *
1279
+ * @param target - routed provider and model. Undefined means `auto`, where
1280
+ * the route is the conversation's own and is named by the gate's own lines.
1281
+ * @param control - the resolved control; undefined means "could not be read",
1282
+ * which `resolveEffort` has already reported.
1283
+ */
1284
+ logThinkingControl(target, control) {
1285
+ if (target === undefined || control === undefined) return;
1286
+ const key = `${target.provider}/${target.model}`;
1287
+ if (this._reportedThinkingControl.has(key)) return;
1288
+ this._reportedThinkingControl.set(key, control.control);
1289
+ const offered = control.offered.length === 0 ? 'none' : control.offered.join(', ');
1290
+ if (control.control === 'off') {
1291
+ this.ctx.logger?.info?.(
1292
+ `compaction-control: summarization thinking control for ${key}: ${control.effort} (off level; offered: ${offered})`,
1293
+ );
1294
+ return;
1295
+ }
1296
+ // `no-off-level` and `no-reasoning` are the two ways a route ends up
1297
+ // thinking by default; `unknown` means its declaration could not be read at
1298
+ // all, which is the same risk with less certainty.
1299
+ const reason =
1300
+ control.control === 'no-off-level'
1301
+ ? `it declares ${control.offered.length} level(s) (${offered}) and none of them is an off switch`
1302
+ : control.control === 'no-reasoning'
1303
+ ? 'it declares no reasoning capability, so the adapter sends no thinking control at all'
1304
+ : 'its declared thinking levels could not be read';
1305
+ this.ctx.logger?.warn?.(
1306
+ `compaction-control: summarization route ${key} cannot be told not to think: ${reason}; ` +
1307
+ 'the provider will think at its own default inside the summarization maxTokens',
1308
+ );
1309
+ }
1310
+ }
1311
+
1312
+ /**
1313
+ * Host-plane companion: publishes the settings section and the standing
1314
+ * "compaction is automatic" prompt rule.
1315
+ *
1316
+ * Why a second entry exists: the engine cannot live on the host plane (it would
1317
+ * not supersede the preset one — both would listen on the bubbling
1318
+ * `agent/pre-step` and the lower threshold would win), yet the browser bundle is
1319
+ * discovered from **enabled host-plane loader entries**, and a row that exists
1320
+ * only inside a preset is invisible to that scan. So the engine owns the seam and
1321
+ * the policy, and this row publishes the settings section, registers
1322
+ * {@link CONTEXT_POLICY_SECTION}, and anchors `dsh-client-modules`.
1323
+ *
1324
+ * It claims no service, and both publications are optional: with no `settings`
1325
+ * provider or no `systemPrompt` service the corresponding one is simply never
1326
+ * published. The prompt rule is registered here rather than from the engine row
1327
+ * because the engine is mounted once per realm — and can be mounted twice.
1328
+ */
1329
+ export class CompactionControlSettings {
1330
+ /**
1331
+ * Accepts the same policy document as the engine, because it is the same
1332
+ * document: this row is normally the composition base the settings section
1333
+ * overrides. Declaring the schema keeps a malformed host config a load-time
1334
+ * failure rather than a surprise at first compaction.
1335
+ */
1336
+ static Config = z.object({
1337
+ // 根字段判活(`.volatile()`):dsh-settings 只把带 volatile 字段的 entry
1338
+ // 供到设置平面(volatileForm),而 schemastery 不允许"字典里再嵌 volatile
1339
+ // 字段"($.providers.*.threshold ... without an enclosing volatile field),
1340
+ // 所以只能标在这四个固定路径上。标了之后本插件读自己的配置必须先
1341
+ // plainConfig() 解单元格。
1342
+ default: layer.volatile(),
1343
+ providers: z.dict(layer).volatile(),
1344
+ models: z.array(modelLayer).volatile(),
1345
+ auto: z.boolean().volatile(),
1346
+ });
1347
+
1348
+ /** Live settings document, exposed for tests and diagnostics. */
1349
+ settingsState;
1350
+
1351
+ /**
1352
+ * @param ctx - context that may provide the `settings` service.
1353
+ * @param config - the composition default policy document.
1354
+ */
1355
+ constructor(ctx, config = {}) {
1356
+ // Validated for the same reason the engine validates: a bad document
1357
+ // should fail where it was written, naming the field.
1358
+ const base = resolveConfig(plainConfig(config));
1359
+ this.settingsState = installSettings(ctx, SETTINGS_NS, settingsSchema, base, () => {});
1360
+ // Publish the standing rule that compaction is automatic. This row is the
1361
+ // right owner because it is the only one mounted unconditionally on the host
1362
+ // plane — its scope is global, so no preset has to restate the rule — and
1363
+ // because a compaction plugin is what makes the rule true. Degradation is
1364
+ // the same as the settings section: a profile with no system-prompt service
1365
+ // simply never publishes it.
1366
+ ctx.inject(['systemPrompt'], (promptCtx) => {
1367
+ promptCtx.systemPrompt.section({
1368
+ name: CONTEXT_POLICY_SECTION,
1369
+ order: CONTEXT_POLICY_ORDER,
1370
+ text: CONTEXT_POLICY_TEXT,
1371
+ });
1372
+ });
1373
+ }
1374
+
1375
+ /**
1376
+ * The effective policy document, as the settings page sees it.
1377
+ * @returns the merged document.
1378
+ */
1379
+ currentPolicy() {
1380
+ return this.settingsState.current();
1381
+ }
1382
+ }
1383
+
1384
+ export default CompactionControlEngine;