dsh-context-compression-improved 0.6.4 → 0.7.0-beta.1

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.
Files changed (75) hide show
  1. package/CHANGELOG.ja.md +51 -0
  2. package/CHANGELOG.ko.md +47 -0
  3. package/CHANGELOG.md +72 -0
  4. package/CHANGELOG.zh.md +47 -0
  5. package/README.ja.md +2 -2
  6. package/README.ko.md +2 -2
  7. package/README.md +6 -3
  8. package/README.zh.md +3 -2
  9. package/eslint.config.js +76 -30
  10. package/package.json +164 -162
  11. package/packages/selector/dsh.plugin.json +16 -16
  12. package/packages/selector/lib/client.js +16 -4
  13. package/packages/selector/lib/index.js +92 -1
  14. package/packages/selector/lib/{advisor-state.js → intent-gate.js} +91 -3
  15. package/packages/selector/lib/profiles.d.ts +9 -0
  16. package/packages/selector/lib/pruner.d.ts +59 -0
  17. package/packages/selector/lib/pruner.js +410 -8
  18. package/packages/selector/package.json +114 -114
  19. package/packages/selector/src/client/decode.ts +6 -2
  20. package/packages/selector/src/client/index.ts +213 -232
  21. package/packages/selector/src/client/scope-face.ts +24 -24
  22. package/packages/selector/src/deepseek-v4-tokenizer.ts +1 -1
  23. package/packages/selector/src/index.ts +418 -412
  24. package/packages/selector/src/preset-overlay.ts +3 -0
  25. package/packages/selector/src/profiles.ts +30 -10
  26. package/packages/selector/src/pruner/content.ts +1 -1
  27. package/packages/selector/src/pruner/state.ts +7 -0
  28. package/packages/selector/src/pruner.ts +253 -10
  29. package/packages/selector/src/runtime/audit.ts +17 -0
  30. package/packages/selector/src/runtime/config.ts +36 -11
  31. package/packages/selector/src/runtime/reducers.ts +1 -1
  32. package/packages/selector/src/runtime/summary-command.ts +133 -0
  33. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +46 -1
  34. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +55 -0
  35. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  36. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  37. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  38. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  39. package/packages/selector/src/runtime/tokenpilot/locator.ts +2 -2
  40. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +4 -1
  41. package/packages/selector/src/runtime/types.ts +12 -0
  42. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
  43. package/packages/selector/tests/built/client-artifact.spec.ts +2 -0
  44. package/packages/selector/tests/code-skeleton.client.spec.ts +94 -93
  45. package/packages/selector/tests/custom-contract.client.spec.ts +3 -2
  46. package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
  47. package/packages/selector/tests/helpers/legacy-namespace.ts +8 -4
  48. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -0
  49. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -0
  50. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -0
  51. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -0
  52. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -0
  53. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -206
  54. package/packages/selector/tests/preset-options-write.client.spec.ts +188 -187
  55. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -206
  56. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  57. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  58. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -233
  59. package/packages/selector/tests/runtime/audit.spec.ts +275 -274
  60. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +3 -3
  61. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +4 -4
  62. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  63. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  64. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2736 -2727
  65. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  66. package/packages/selector/tests/settings-seat.client.spec.ts +165 -165
  67. package/packages/selector/tests/standing-generation.host.spec.ts +704 -704
  68. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +18 -2
  69. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  70. package/pnpm-workspace.yaml +1 -1
  71. package/scripts/packed-components-smoke.mjs +2 -0
  72. package/scripts/packed-install-e2e.mjs +1275 -1273
  73. package/scripts/verify-release.mjs +318 -317
  74. package/tsconfig.tests.json +3 -1
  75. package/vitest.config.ts +14 -0
@@ -575,6 +575,9 @@ function installAgentPresetsDecoration(
575
575
  /** Capture callable methods and whether each was inherited or owned. */
576
576
  function snapshotMethods(presets: OverlayableAgentPresets): MethodSnapshot[] {
577
577
  return (['resolve', 'mount', 'recompose', 'standingKeyFor'] as const).map((name) => {
578
+ // Capture is detached by design: every apply/restore site re-binds via
579
+ // Reflect.apply(..., presets, args), so this read never escapes its `this`.
580
+ // eslint-disable-next-line @typescript-eslint/unbound-method
578
581
  const original = presets[name]
579
582
  if (typeof original !== 'function') {
580
583
  throw new TypeError(`context-compression selector: AgentPresets.${name} is unavailable`)
@@ -108,6 +108,14 @@ export interface CodeSkeletonSettings {
108
108
  enabled: boolean
109
109
  }
110
110
 
111
+ /**
112
+ * Orthogonal turn-tail intent-summary gate, mirrored browser-safe from the
113
+ * runtime: independent of every profile, default off.
114
+ */
115
+ export interface IntentSummarySettings {
116
+ enabled: boolean
117
+ }
118
+
111
119
  /**
112
120
  * Decode the persisted codeSkeleton section with exactly the runtime schema's
113
121
  * strictness: absent means the lossless off default; present values must be a
@@ -119,7 +127,17 @@ export function decodeCodeSkeletonSettings(value: unknown): CodeSkeletonSettings
119
127
  if (!isPlainRecord(value)) return undefined
120
128
  const keys = Object.keys(value)
121
129
  if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
122
- const enabled = (value as Record<string, unknown>).enabled
130
+ const enabled = (value).enabled
131
+ return typeof enabled === 'boolean' ? { enabled } : undefined
132
+ }
133
+
134
+ /** Browser-safe mirror of the runtime intentSummary section (absent inherits off). */
135
+ export function decodeIntentSummarySettings(value: unknown): IntentSummarySettings | undefined {
136
+ if (value === undefined) return { enabled: false }
137
+ if (!isPlainRecord(value)) return undefined
138
+ const keys = Object.keys(value)
139
+ if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
140
+ const enabled = (value).enabled
123
141
  return typeof enabled === 'boolean' ? { enabled } : undefined
124
142
  }
125
143
 
@@ -221,18 +239,18 @@ export function decodePresetOptionsSettings(value: unknown): PresetOptionsSettin
221
239
  if (value.summaryLocator !== undefined) decoded.summaryLocator = value.summaryLocator as boolean
222
240
  if (value.prefixStabilizer !== undefined) decoded.prefixStabilizer = value.prefixStabilizer as boolean
223
241
  if (value.readState !== undefined) decoded.readState = value.readState as boolean
224
- if (estimatorMode !== undefined) decoded.estimatorMode = estimatorMode as '' | 'host' | 'direct'
242
+ if (estimatorMode !== undefined) decoded.estimatorMode = estimatorMode
225
243
  if (value.estimatorProvider !== undefined) decoded.estimatorProvider = value.estimatorProvider as string
226
244
  if (value.estimatorModel !== undefined) decoded.estimatorModel = value.estimatorModel as string
227
245
  if (value.estimatorBaseUrl !== undefined) decoded.estimatorBaseUrl = value.estimatorBaseUrl as string
228
246
  if (value.estimatorApiKey !== undefined) decoded.estimatorApiKey = value.estimatorApiKey as string
229
- if (estimatorTimeoutMs !== undefined) decoded.estimatorTimeoutMs = estimatorTimeoutMs as number
230
- if (advisorMode !== undefined) decoded.advisorMode = advisorMode as '' | 'host' | 'direct'
231
- if (advisorTimeoutMs !== undefined) decoded.advisorTimeoutMs = advisorTimeoutMs as number
232
- if (advisorRefreshTurns !== undefined) decoded.advisorRefreshTurns = advisorRefreshTurns as number
233
- if (advisorScoreThreshold !== undefined) decoded.advisorScoreThreshold = advisorScoreThreshold as number
234
- if (advisorSampleLimit !== undefined) decoded.advisorSampleLimit = advisorSampleLimit as number
235
- if (advisorMinTokens !== undefined) decoded.advisorMinTokens = advisorMinTokens as number
247
+ if (estimatorTimeoutMs !== undefined) decoded.estimatorTimeoutMs = estimatorTimeoutMs
248
+ if (advisorMode !== undefined) decoded.advisorMode = advisorMode
249
+ if (advisorTimeoutMs !== undefined) decoded.advisorTimeoutMs = advisorTimeoutMs
250
+ if (advisorRefreshTurns !== undefined) decoded.advisorRefreshTurns = advisorRefreshTurns
251
+ if (advisorScoreThreshold !== undefined) decoded.advisorScoreThreshold = advisorScoreThreshold
252
+ if (advisorSampleLimit !== undefined) decoded.advisorSampleLimit = advisorSampleLimit
253
+ if (advisorMinTokens !== undefined) decoded.advisorMinTokens = advisorMinTokens
236
254
  return decoded
237
255
  }
238
256
 
@@ -273,7 +291,7 @@ export function decodeAutoCompactSettings(value: unknown): AutoCompactSettings |
273
291
  if (!isPlainRecord(value)) return undefined
274
292
  const keys = Object.keys(value)
275
293
  if (keys.length !== 1 || keys[0] !== 'thresholdPercent') return undefined
276
- const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
294
+ const thresholdPercent = (value).thresholdPercent
277
295
  return isValidAutoCompactThresholdPercent(thresholdPercent)
278
296
  ? { thresholdPercent }
279
297
  : undefined
@@ -289,6 +307,8 @@ export interface ContextCompressionSettings {
289
307
  autoCompact: AutoCompactSettings
290
308
  /** Code-skeleton reducer gate captured independently of `profile`. */
291
309
  codeSkeleton: CodeSkeletonSettings
310
+ /** Turn-tail intent-summary gate captured independently of `profile`. */
311
+ intentSummary: IntentSummarySettings
292
312
  /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
293
313
  presetOptions?: PresetOptionsSettings
294
314
  }
@@ -156,7 +156,7 @@ function nativePruneContent(
156
156
  const headText = points.slice(0, headEnd).join('')
157
157
  const insertion = intersectsRemoved && !markerInserted && typeof marker === 'function'
158
158
  ? marker(1 + newlinesBefore + headText.split('\n').length - 1)
159
- : intersectsRemoved && !markerInserted ? marker : ''
159
+ : intersectsRemoved && !markerInserted && typeof marker === 'string' ? marker : ''
160
160
  if (insertion !== '') markerInserted = true
161
161
  const text = points.slice(0, headEnd).join('') + insertion + points.slice(tailStart).join('')
162
162
  if (text !== '') pruned.push({ ...block, text })
@@ -9,6 +9,7 @@ import type { Session } from '@deepseek-ai/dsh-session'
9
9
  import type { DedupeTable } from '../runtime/tokenpilot/dedup.ts'
10
10
  import type { EstimatorFailures } from '../runtime/tokenpilot/estimator.ts'
11
11
  import type { SideChannel } from '../runtime/tokenpilot/sidechannel.ts'
12
+ import type { PendingIntentFold } from '../runtime/tokenpilot/intent-fold.ts'
12
13
  import type {
13
14
  ContextCompressionSettings,
14
15
  ResolvedConfig,
@@ -47,4 +48,10 @@ export interface PrunerState {
47
48
  readonly estimatorRemainingTurns: WeakMap<Session, number>
48
49
  /** Per-session advisor side channel, constructed once with the advisor overrides. */
49
50
  readonly advisorChannels: WeakMap<Session, SideChannel>
51
+ /** Staged intent fold awaiting the next pressure round (at most one per session). */
52
+ readonly pendingIntentFolds: WeakMap<Session, PendingIntentFold>
53
+ /** Landed intent-fold seqs: fold-once, never reconsidered by any later stage. */
54
+ readonly intentFoldedSeqs: WeakMap<Session, Set<number>>
55
+ /** Live-surface tokens when the last intent fold landed (growth-gate baseline). */
56
+ readonly intentBaselines: WeakMap<Session, number>
50
57
  }
@@ -91,6 +91,12 @@ import {
91
91
  runSessionAdvisorPass,
92
92
  } from './runtime/tokenpilot/advisor.ts'
93
93
  import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
94
+ import { evaluateIntentGate } from './runtime/tokenpilot/intent-gate.ts'
95
+ import { extractErrorLines, maskCandidateForSummary, type IntentRole } from './runtime/tokenpilot/intent-input-mask.ts'
96
+ import { computeIntentRange, INTENT_RANGE_MAX_CANDIDATES } from './runtime/tokenpilot/intent-range.ts'
97
+ import { INTENT_FOLD_MARKER, renderIntentFoldBlock } from './runtime/tokenpilot/intent-fold.ts'
98
+ import { buildIntentSummarySystemPrompt, buildIntentSummaryUserPrompt, parseIntentSummaryAnswer } from './runtime/tokenpilot/advisor-prompt.ts'
99
+ import { getSummaryOverride, observeIntentEnabled, recordIntentFold } from './runtime/tokenpilot/advisor-state.ts'
94
100
 
95
101
  import {
96
102
  DedupeTable,
@@ -247,6 +253,9 @@ export class ToolResultPruner extends Service {
247
253
  turnClocks: new WeakMap(),
248
254
  estimatorRemainingTurns: new WeakMap(),
249
255
  advisorChannels: new WeakMap(),
256
+ pendingIntentFolds: new WeakMap(),
257
+ intentFoldedSeqs: new WeakMap(),
258
+ intentBaselines: new WeakMap(),
250
259
  }
251
260
 
252
261
  ctx.on('session/event', (session, event) => {
@@ -316,6 +325,9 @@ export class ToolResultPruner extends Service {
316
325
  // summaries, scores, and decay figure never touch any decision path.
317
326
  // Strictly fire-and-forget, with its own backoff state.
318
327
  void this.postflightAdvisorPass(agent.session, turn, signal).catch(() => undefined)
328
+ // Turn-tail intent summary: strictly fire-and-forget like the advisor;
329
+ // the growth gate inside decides whether a summary call is even spent.
330
+ void this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => undefined)
319
331
  })
320
332
  }
321
333
 
@@ -736,6 +748,200 @@ export class ToolResultPruner extends Service {
736
748
  }
737
749
  }
738
750
 
751
+ // ─────────── Turn-tail intent summary (host-driven fold, model writes text only) ───────────
752
+
753
+ /**
754
+ * Fire-and-forget postflight: evaluate the growth gate, and only when it
755
+ * passes, select the consumed increment OUTSIDE the protected working set,
756
+ * mask it to semantic-role records, and spend ONE summary-writer call. The
757
+ * verdict stages as a pending fold that the NEXT pressure round lands via
758
+ * the ordinary plan/apply machinery — the synchronous decision path never
759
+ * waits on an LLM.
760
+ */
761
+ private async postflightIntentFoldPass(session: Session, turn: number, signal: AbortSignal): Promise<void> {
762
+ const started = Date.now()
763
+ const sessionId = String(session.id)
764
+ const policy = this.activePolicy(session)
765
+ const settings = this.activeSettings(session)
766
+ const intentEnabled = settings.intentSummary.enabled
767
+ const override = getSummaryOverride(sessionId)
768
+ observeIntentEnabled(sessionId, intentEnabled)
769
+ if (policy === undefined) return
770
+ if (this.state.pendingIntentFolds.has(session)) return
771
+ const advisorState = getAdvisorState(session)
772
+ if (advisorState.inFlight) return
773
+ if (isCoolingDown(advisorState.failures, Date.now())) return
774
+
775
+ const view = measureForCompaction(this.ctx, session)
776
+ // The window is the Auto Compact linkage input: policy.autoCompactTokens
777
+ // == floor(window * threshold/100); invert for the gate floor.
778
+ const thresholdPercent = settings.autoCompact.thresholdPercent
779
+ const contextWindow = policy.autoCompactTokens !== undefined && thresholdPercent > 0
780
+ ? Math.round(policy.autoCompactTokens / (thresholdPercent / 100))
781
+ : undefined
782
+ const gate = evaluateIntentGate({
783
+ enabled: intentEnabled,
784
+ override,
785
+ liveTokens: view.totalTokens,
786
+ contextWindow,
787
+ baselineTokens: this.state.intentBaselines.get(session) ?? 0,
788
+ })
789
+ if (!gate.decision) return
790
+
791
+ const settingsPreset = settings.presetOptions
792
+ if (settingsPreset === undefined) return
793
+ if (settingsPreset.estimatorBaseUrl === undefined || settingsPreset.estimatorBaseUrl.length === 0
794
+ || settingsPreset.estimatorModel === undefined || settingsPreset.estimatorModel.length === 0) {
795
+ emitCompressionAudit(this.ctx.logger, {
796
+ schemaVersion: 1,
797
+ kind: 'intent-summary-outcome',
798
+ sessionId,
799
+ ok: false,
800
+ reason: 'no-direct-endpoint',
801
+ turnIndex: turn,
802
+ latencyMs: Date.now() - started,
803
+ })
804
+ return
805
+ }
806
+
807
+ const candidates = this.snapshot(session, view).filter(candidate => !this.isRecoveryExempt(session, candidate))
808
+ const protectedSeqs = this.protectedHistoryCandidateSeqs(candidates, policy)
809
+ const range = computeIntentRange({
810
+ candidates,
811
+ protectedSeqs,
812
+ foldedSeqs: this.state.intentFoldedSeqs.get(session) ?? new Set<number>(),
813
+ maxCandidates: INTENT_RANGE_MAX_CANDIDATES,
814
+ })
815
+ if (range.seqs.length === 0) return
816
+
817
+ const bySeq = new Map(candidates.map(candidate => [candidate.seq, candidate]))
818
+ const records: { seq: number, role: IntentRole, toolName: string, line: string }[] = []
819
+ const errorLines = new Set<string>()
820
+ for (const seq of range.seqs) {
821
+ const candidate = bySeq.get(seq)
822
+ if (candidate === undefined) continue
823
+ const result = candidate.event.data.message
824
+ const text = onlyTextBlock(result.content)?.text ?? ''
825
+ const masked = maskCandidateForSummary(seq, candidate.call.name, candidate.call.arguments, text)
826
+ records.push({ seq, role: masked.role, toolName: candidate.call.name, line: masked.record })
827
+ for (const line of extractErrorLines(text)) errorLines.add(line)
828
+ }
829
+ if (records.length === 0) return
830
+
831
+ const events = sessionEvents(session)
832
+ const task = collectTaskSemantics(events)
833
+ let channel = this.state.advisorChannels.get(session)
834
+ if (channel === undefined) {
835
+ channel = new SideChannel(this.ctx, settingsPreset, {
836
+ mode: 'direct',
837
+ timeoutMs: 30_000,
838
+ maxTokens: 512,
839
+ })
840
+ this.state.advisorChannels.set(session, channel)
841
+ }
842
+
843
+ const answer = await channel.ask({
844
+ system: buildIntentSummarySystemPrompt(),
845
+ user: buildIntentSummaryUserPrompt(task?.taskText ?? '(no task semantics yet)', records.map(record => record.line), collectTailText(events)),
846
+ signal,
847
+ })
848
+ const summaryCallChars = answer?.length ?? 0
849
+ const parsed = answer === undefined ? undefined : parseIntentSummaryAnswer(answer)
850
+ if (parsed === undefined) {
851
+ const failures = (advisorState.failures?.failures ?? 0) + 1
852
+ advisorState.failures = { failures, cooldownUntil: Date.now() + backoffCooldownMs(failures) }
853
+ emitCompressionAudit(this.ctx.logger, {
854
+ schemaVersion: 1,
855
+ kind: 'intent-summary-outcome',
856
+ sessionId,
857
+ ok: false,
858
+ reason: answer === undefined ? 'ask-failed' : 'parse-failed',
859
+ turnIndex: turn,
860
+ foldedCount: records.length,
861
+ summaryCallChars,
862
+ latencyMs: Date.now() - started,
863
+ })
864
+ return
865
+ }
866
+ this.state.pendingIntentFolds.set(session, {
867
+ createdAt: Date.now(),
868
+ turn,
869
+ startSeq: range.seqs[0]!,
870
+ endSeq: range.seqs[range.seqs.length - 1]!,
871
+ summary: parsed.summary,
872
+ errorLines: [...errorLines],
873
+ records,
874
+ summaryCallChars,
875
+ })
876
+ emitCompressionAudit(this.ctx.logger, {
877
+ schemaVersion: 1,
878
+ kind: 'intent-summary-outcome',
879
+ sessionId,
880
+ ok: true,
881
+ reason: 'staged',
882
+ turnIndex: turn,
883
+ foldedCount: records.length,
884
+ summaryCallChars,
885
+ latencyMs: Date.now() - started,
886
+ })
887
+ }
888
+
889
+ /**
890
+ * Convert a staged pending fold into per-candidate planned replacements
891
+ * (reducer `intent-summary`). Fail-open: a candidate that would grow, is
892
+ * rich-content, or no longer exists keeps its original text. Returns
893
+ * `undefined` when there is nothing (or no longer anything) to fold.
894
+ */
895
+ private applyPendingIntentFold(
896
+ session: Session,
897
+ policy: CompressionPolicy,
898
+ view: CompactionTokenView,
899
+ eligible: readonly SnapshotCandidate[],
900
+ ): { plans: PlannedReplacement[], reclaim: number, foldedSeqs: Set<number>, charsBefore: number, charsAfter: number, turn: number, summaryCallChars: number } | undefined {
901
+ const pending = this.state.pendingIntentFolds.get(session)
902
+ if (pending === undefined) return undefined
903
+ const bySeq = new Map(eligible.map(candidate => [candidate.seq, candidate]))
904
+ const foldable = pending.records
905
+ .map(record => record.seq)
906
+ .filter(seq => bySeq.has(seq))
907
+ .sort((a, b) => a - b)
908
+ if (foldable.length === 0) {
909
+ this.state.pendingIntentFolds.delete(session)
910
+ return undefined
911
+ }
912
+ const plans: PlannedReplacement[] = []
913
+ const foldedSeqs = new Set<number>()
914
+ let reclaim = 0
915
+ let charsBefore = 0
916
+ let charsAfter = 0
917
+ for (const seq of foldable) {
918
+ const candidate = bySeq.get(seq)!
919
+ const result = candidate.event.data.message
920
+ const block = onlyTextBlock(result.content)
921
+ if (block === null) continue
922
+ const text = renderIntentFoldBlock(pending, seq)
923
+ const plan = this.plan(
924
+ candidate,
925
+ [{ ...block, text }],
926
+ rootToolResultSeq(session, candidate.seq),
927
+ 'intent-summary',
928
+ 'pressure',
929
+ 'history',
930
+ policy.historyMode,
931
+ view,
932
+ )
933
+ if (plan === null || plan.charsAfter >= plan.charsBefore) continue
934
+ plans.push(plan)
935
+ foldedSeqs.add(seq)
936
+ reclaim += plan.charsBefore - plan.charsAfter
937
+ charsBefore += plan.charsBefore
938
+ charsAfter += plan.charsAfter
939
+ }
940
+ if (plans.length === 0) return undefined
941
+ this.state.intentFoldedSeqs.get(session)?.forEach(seq => foldedSeqs.add(seq))
942
+ return { plans, reclaim, foldedSeqs, charsBefore, charsAfter, turn: pending.turn, summaryCallChars: pending.summaryCallChars }
943
+ }
944
+
739
945
  // ─────────── Advisory benefit model (statistics & suggestions only) ───────────
740
946
 
741
947
  /**
@@ -1358,7 +1564,7 @@ export class ToolResultPruner extends Service {
1358
1564
  ): PlannedReplacement | null {
1359
1565
  if (this.isRecoveryExempt(session, candidate)) return null
1360
1566
  if (candidate.characterPressure <= charsForTokens(policy.nativeTriggerTokens)) return null
1361
- const result = candidate.event.data.message as ToolResultMessage
1567
+ const result = candidate.event.data.message
1362
1568
  if (onlyTextBlocks(result.content) === null) return null
1363
1569
  const sourceSeq = rootToolResultSeq(session, candidate.seq)
1364
1570
  // R9b site: the marker's retrieve hint starts at the event line right
@@ -1410,7 +1616,7 @@ export class ToolResultPruner extends Service {
1410
1616
  view: CompactionTokenView,
1411
1617
  ): PlannedReplacement | null {
1412
1618
  if (typeof candidate.event.surfaceOp === 'object') return null
1413
- const result = candidate.event.data.message as ToolResultMessage
1619
+ const result = candidate.event.data.message
1414
1620
  const text = flattenPlainText(result.content)
1415
1621
  if (text === undefined) return null
1416
1622
  if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null
@@ -1458,7 +1664,7 @@ export class ToolResultPruner extends Service {
1458
1664
  // pre-step coordinate filter prevents previously-kept originals from ever
1459
1665
  // being reconsidered after their first request.
1460
1666
  if (typeof candidate.event.surfaceOp === 'object') return null
1461
- const result = candidate.event.data.message as ToolResultMessage
1667
+ const result = candidate.event.data.message
1462
1668
  if (candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)) return null
1463
1669
  const sourceSeq = candidate.seq
1464
1670
  const sourceRef = sourceRefFn(session, sourceSeq)
@@ -1536,7 +1742,7 @@ export class ToolResultPruner extends Service {
1536
1742
  // example one carrying an image) must never reach it. The character basis
1537
1743
  // no longer inherits the exact-tokenizer precondition that used to reject
1538
1744
  // this path implicitly, so the guard has to be explicit.
1539
- const redacted = candidate.event.data.message as ToolResultMessage
1745
+ const redacted = candidate.event.data.message
1540
1746
  if (onlyTextBlocks(redacted.content) === null) return null
1541
1747
  const text = [
1542
1748
  '[Tool result reduced to satisfy the completed-step aggregate budget]',
@@ -1570,7 +1776,7 @@ export class ToolResultPruner extends Service {
1570
1776
  historyMode?: HistoryMode,
1571
1777
  ): PlannedReplacement | null {
1572
1778
  if (!isError(candidate)) return null
1573
- const result = candidate.event.data.message as ToolResultMessage
1779
+ const result = candidate.event.data.message
1574
1780
  const blocks = onlyTextBlocks(result.content)
1575
1781
  if (blocks === null) return null
1576
1782
  const text = blocks.map(block => block.text).join('\n')
@@ -1628,15 +1834,17 @@ export class ToolResultPruner extends Service {
1628
1834
  const protectedSeqs = this.protectedHistoryCandidateSeqs(candidates, policy)
1629
1835
  const isUnsafe = (candidate: SnapshotCandidate): boolean => {
1630
1836
  if (this.isRecoveryExempt(session, candidate)) return true
1631
- const result = candidate.event.data.message as ToolResultMessage
1837
+ const result = candidate.event.data.message
1632
1838
  const block = onlyTextBlock(result.content)
1839
+ // Fold-once: an already-folded intent block is never re-candidated.
1840
+ if (block?.text.includes(INTENT_FOLD_MARKER) === true) return true
1633
1841
  return block?.text.includes('[Old tool result content cleared from active context]') === true
1634
1842
  }
1635
1843
  // Distinguish "nothing safe to touch" (recovery tool output or already
1636
1844
  // cleared) from "everything left is inside the protected working set":
1637
1845
  // both skip, but they are different operational facts.
1638
1846
  const safe = candidates.filter(candidate => !isUnsafe(candidate))
1639
- const eligible = safe.filter(candidate => !protectedSeqs.has(candidate.seq))
1847
+ const eligible: SnapshotCandidate[] = safe.filter(candidate => !protectedSeqs.has(candidate.seq))
1640
1848
  if (eligible.length === 0) {
1641
1849
  return safe.length === 0
1642
1850
  ? { kind: 'no-safe-candidates' }
@@ -1644,6 +1852,38 @@ export class ToolResultPruner extends Service {
1644
1852
  }
1645
1853
  const planned: PlannedReplacement[] = []
1646
1854
  let reclaim = 0
1855
+ // Turn-tail intent summary (task_2.5): a fold staged by a previous turn's
1856
+ // postflight lands FIRST, through the same plan pipeline as every other
1857
+ // reducer; its reclaim counts toward the batch target and its seqs are
1858
+ // removed from the ordinary loop (fold-once).
1859
+ const intentApplied = this.applyPendingIntentFold(session, policy, view, eligible)
1860
+ if (intentApplied !== undefined) {
1861
+ planned.push(...intentApplied.plans)
1862
+ reclaim += intentApplied.reclaim
1863
+ this.state.intentFoldedSeqs.set(session, intentApplied.foldedSeqs)
1864
+ this.state.pendingIntentFolds.delete(session)
1865
+ this.state.intentBaselines.set(session, view.totalTokens)
1866
+ recordIntentFold(String(session.id), {
1867
+ turn: intentApplied.turn,
1868
+ startSeq: intentApplied.foldedSeqs.size > 0 ? Math.min(...intentApplied.foldedSeqs) : 0,
1869
+ endSeq: intentApplied.foldedSeqs.size > 0 ? Math.max(...intentApplied.foldedSeqs) : 0,
1870
+ liveTokensBefore: view.totalTokens,
1871
+ at: Date.now(),
1872
+ })
1873
+ emitCompressionAudit(this.ctx.logger, {
1874
+ schemaVersion: 1,
1875
+ kind: 'intent-summary-outcome',
1876
+ sessionId: String(session.id),
1877
+ ok: true,
1878
+ reason: 'landed',
1879
+ foldedCount: intentApplied.plans.length,
1880
+ ...(intentApplied.charsBefore > 0 ? { retentionRatio: intentApplied.charsAfter / intentApplied.charsBefore } : {}),
1881
+ summaryCallChars: intentApplied.summaryCallChars,
1882
+ })
1883
+ for (let index = eligible.length - 1; index >= 0; index -= 1) {
1884
+ if (intentApplied.foldedSeqs.has(eligible[index]!.seq)) eligible.splice(index, 1)
1885
+ }
1886
+ }
1647
1887
  // Linked batches must reach the deadline target; unlinked batches keep
1648
1888
  // the traditional minimum-reclaim commit threshold. All arithmetic runs on
1649
1889
  // the character basis: token-named thresholds enter via charsForTokens.
@@ -1658,7 +1898,7 @@ export class ToolResultPruner extends Service {
1658
1898
  ? minReclaimChars
1659
1899
  : required
1660
1900
  for (const candidate of eligible) {
1661
- const result = candidate.event.data.message as ToolResultMessage
1901
+ const result = candidate.event.data.message
1662
1902
  const block = onlyTextBlock(result.content)
1663
1903
  // TokenPilot-inspired R2: a read output whose file was later mutated is
1664
1904
  // superseded — its text can no longer match the file — so it takes the
@@ -1867,7 +2107,7 @@ export class ToolResultPruner extends Service {
1867
2107
  if (event?.type !== 'tool/result'
1868
2108
  || event.data.turn !== assistant.data.turn || event.data.step !== assistant.data.step
1869
2109
  || event.data.error !== undefined) return true
1870
- const block = event.data.message as ToolResultMessage
2110
+ const block = event.data.message
1871
2111
  if (block.isError === true) return true
1872
2112
  // Images and other rich inner blocks stay fail-open: a TailTrim stub
1873
2113
  // would silently delete them from the active context.
@@ -2087,7 +2327,6 @@ export class ToolResultPruner extends Service {
2087
2327
 
2088
2328
  private land(session: Session, plan: PlannedReplacement): PrunedEntry | null {
2089
2329
  const { candidate } = plan
2090
- const result = candidate.event.data.message as ToolResultMessage
2091
2330
  // 0.1.7-rc.2: the tool message's own `content` is the result block set —
2092
2331
  // no wrapping result block anymore.
2093
2332
  const message = freezeMessage<ToolResultMessage>({
@@ -2322,7 +2561,11 @@ export class ToolResultPruner extends Service {
2322
2561
  manifestEventType: 'compaction/summary',
2323
2562
  manifestSeq,
2324
2563
  reducer: 'llm-summary',
2564
+ // Legacy manifest fields were written as free-form scalars; String() is
2565
+ // the intentional best-effort coercion of whatever the host stored.
2566
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
2325
2567
  provider: data.provider === undefined ? 'unknown' : String(data.provider),
2568
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
2326
2569
  model: data.model === undefined ? 'unknown' : String(data.model),
2327
2570
  tokensBefore: typeof data.shadowedTokenCount === 'number' ? data.shadowedTokenCount : null,
2328
2571
  tokensAfter: null,
@@ -205,6 +205,22 @@ export interface AdvisorOutcomeAuditRecord extends CompressionAuditBase {
205
205
  readonly latencyMs: number
206
206
  }
207
207
 
208
+ /** One turn-tail intent-summary pass: gate decision, ask outcome, or landing. Numeric metadata only. */
209
+ export interface IntentSummaryOutcomeAuditRecord extends CompressionAuditBase {
210
+ readonly kind: 'intent-summary-outcome'
211
+ readonly ok: boolean
212
+ /** Aligned decision/reason code (gate reason, 'parse-failed', 'landed', 'expired'...). */
213
+ readonly reason: string
214
+ readonly turnIndex?: number
215
+ /** Folded candidate count when a range was selected or landed. */
216
+ readonly foldedCount?: number
217
+ /** Aggregate retention ratio of the landed batch (charsAfter / charsBefore). */
218
+ readonly retentionRatio?: number
219
+ /** Characters spent on the summary-writer call itself (credit accounting). */
220
+ readonly summaryCallChars?: number
221
+ readonly latencyMs?: number
222
+ }
223
+
208
224
  /**
209
225
  * One advisory benefit-model label for a batch that LANDED. The retired review
210
226
  * gate used these bands to withhold a batch; a reduction must never block
@@ -247,6 +263,7 @@ export type CompressionAuditRecord =
247
263
  | SummaryLocatorAuditRecord
248
264
  | EstimatorOutcomeAuditRecord
249
265
  | AdvisorOutcomeAuditRecord
266
+ | IntentSummaryOutcomeAuditRecord
250
267
  | ReductionAdviceAuditRecord
251
268
 
252
269
  /** Minimal logger method consumed by the audit publisher. */
@@ -5,6 +5,7 @@ import type {
5
5
  AutoCompactSettings,
6
6
  CodeSkeletonSettings,
7
7
  CompressionPolicy,
8
+ IntentSummarySettings,
8
9
  CompressionProfile,
9
10
  CustomCompressionPolicy,
10
11
  PresetOptions,
@@ -86,7 +87,7 @@ function parseAutoCompactSettings(value: unknown): AutoCompactSettings {
86
87
  if (keys.length !== 1 || keys[0] !== 'thresholdPercent') {
87
88
  throw new TypeError(`Context-compression autoCompact: expected exactly "thresholdPercent", got "${keys.join('", "')}"`)
88
89
  }
89
- const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
90
+ const thresholdPercent = (value).thresholdPercent
90
91
  if (!isValidAutoCompactThresholdPercent(thresholdPercent)) {
91
92
  throw new TypeError(`Context-compression autoCompact.thresholdPercent (${String(thresholdPercent)}) must be an integer between ${String(AUTO_COMPACT_THRESHOLD_LIMITS.min)} and ${String(AUTO_COMPACT_THRESHOLD_LIMITS.max)}`)
92
93
  }
@@ -107,13 +108,34 @@ function parseCodeSkeletonSettings(value: unknown): CodeSkeletonSettings {
107
108
  if (keys.length !== 1 || keys[0] !== 'enabled') {
108
109
  throw new TypeError(`Context-compression codeSkeleton: expected exactly "enabled", got "${keys.join('", "')}"`)
109
110
  }
110
- const enabled = (value as Record<string, unknown>).enabled
111
+ const enabled = (value).enabled
111
112
  if (typeof enabled !== 'boolean') {
112
113
  throw new TypeError('Context-compression codeSkeleton.enabled must be a boolean')
113
114
  }
114
115
  return { enabled }
115
116
  }
116
117
 
118
+ /**
119
+ * Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
120
+ * section semantics: absent inherits the lossless `false` default, while a
121
+ * present-but-invalid section is an explicitly invalid document.
122
+ */
123
+ function parseIntentSummarySettings(value: unknown): IntentSummarySettings {
124
+ if (value === undefined) return { enabled: false }
125
+ if (!isPlainRecord(value)) {
126
+ throw new TypeError('Context-compression intentSummary must be a plain object')
127
+ }
128
+ const keys = Object.keys(value)
129
+ if (keys.length !== 1 || keys[0] !== 'enabled') {
130
+ throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join('", "')}"`)
131
+ }
132
+ const enabled = (value).enabled
133
+ if (typeof enabled !== 'boolean') {
134
+ throw new TypeError('Context-compression intentSummary.enabled must be a boolean')
135
+ }
136
+ return { enabled }
137
+ }
138
+
117
139
  /**
118
140
  * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
119
141
  * inherits the preset defaults; present-but-invalid is rejected, mirroring the
@@ -203,18 +225,18 @@ export function parsePresetOptionsSettings(value: unknown): PresetOptionsSetting
203
225
  if (value.summaryLocator !== undefined) result.summaryLocator = value.summaryLocator as boolean
204
226
  if (value.prefixStabilizer !== undefined) result.prefixStabilizer = value.prefixStabilizer as boolean
205
227
  if (value.readState !== undefined) result.readState = value.readState as boolean
206
- if (estimatorMode !== undefined) result.estimatorMode = estimatorMode as '' | 'host' | 'direct'
228
+ if (estimatorMode !== undefined) result.estimatorMode = estimatorMode
207
229
  if (value.estimatorProvider !== undefined) result.estimatorProvider = value.estimatorProvider as string
208
230
  if (value.estimatorModel !== undefined) result.estimatorModel = value.estimatorModel as string
209
231
  if (value.estimatorBaseUrl !== undefined) result.estimatorBaseUrl = value.estimatorBaseUrl as string
210
232
  if (value.estimatorApiKey !== undefined) result.estimatorApiKey = value.estimatorApiKey as string
211
- if (estimatorTimeoutMs !== undefined) result.estimatorTimeoutMs = estimatorTimeoutMs as number
212
- if (advisorMode !== undefined) result.advisorMode = advisorMode as '' | 'host' | 'direct'
213
- if (advisorTimeoutMs !== undefined) result.advisorTimeoutMs = advisorTimeoutMs as number
214
- if (advisorRefreshTurns !== undefined) result.advisorRefreshTurns = advisorRefreshTurns as number
215
- if (advisorScoreThreshold !== undefined) result.advisorScoreThreshold = advisorScoreThreshold as number
216
- if (advisorSampleLimit !== undefined) result.advisorSampleLimit = advisorSampleLimit as number
217
- if (advisorMinTokens !== undefined) result.advisorMinTokens = advisorMinTokens as number
233
+ if (estimatorTimeoutMs !== undefined) result.estimatorTimeoutMs = estimatorTimeoutMs
234
+ if (advisorMode !== undefined) result.advisorMode = advisorMode
235
+ if (advisorTimeoutMs !== undefined) result.advisorTimeoutMs = advisorTimeoutMs
236
+ if (advisorRefreshTurns !== undefined) result.advisorRefreshTurns = advisorRefreshTurns
237
+ if (advisorScoreThreshold !== undefined) result.advisorScoreThreshold = advisorScoreThreshold
238
+ if (advisorSampleLimit !== undefined) result.advisorSampleLimit = advisorSampleLimit
239
+ if (advisorMinTokens !== undefined) result.advisorMinTokens = advisorMinTokens
218
240
  return result
219
241
  }
220
242
 
@@ -253,6 +275,7 @@ export const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings =
253
275
  custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
254
276
  autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
255
277
  codeSkeleton: { enabled: false },
278
+ intentSummary: { enabled: false },
256
279
  }
257
280
 
258
281
  /**
@@ -290,7 +313,7 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
290
313
  // remain valid and inherit their defaults; the sections themselves stay
291
314
  // strictly shaped.
292
315
  const unknown = Object.keys(candidate).find(key =>
293
- key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'presetOptions')
316
+ key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'presetOptions')
294
317
  if (unknown !== undefined) {
295
318
  throw new TypeError(`Context-compression settings: unknown key "${unknown}"`)
296
319
  }
@@ -302,11 +325,13 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
302
325
  assertPresentSection(candidate, 'custom', isUsableCustomDocument)
303
326
  const autoCompact = parseAutoCompactSettings(candidate.autoCompact)
304
327
  const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton)
328
+ const intentSummary = parseIntentSummarySettings(candidate.intentSummary)
305
329
  const presetOptions = parsePresetOptionsSettings(candidate.presetOptions)
306
330
  return {
307
331
  ...contextCompressionSettingsInputSchema(candidate),
308
332
  autoCompact,
309
333
  codeSkeleton,
334
+ intentSummary,
310
335
  ...presetOptions === undefined ? {} : { presetOptions },
311
336
  }
312
337
  },
@@ -80,7 +80,7 @@ export function documentSectionSummaries(text: string): readonly { readonly id:
80
80
  const headings: { id: string, level: number, line: number }[] = []
81
81
  for (let index = 0; index < lines.length; index++) {
82
82
  const match = /^#{1,6}\s+(.*)$/.exec(lines[index] ?? '')
83
- if (match !== null) headings.push({ id: match[1]!.trim(), level: (lines[index]!.match(/^#+/) ?? ['#'])[0]!.length, line: index })
83
+ if (match !== null) headings.push({ id: match[1]!.trim(), level: (lines[index]!.match(/^#+/) ?? ['#'])[0].length, line: index })
84
84
  }
85
85
  return headings.map((heading, position) => {
86
86
  const from = heading.line + 1