dsh-context-compression-improved 0.10.5 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/CHANGELOG.zh.md +9 -0
  3. package/docs/shallow-teaching-preset-template.md +46 -0
  4. package/package.json +5 -5
  5. package/packages/selector/dsh.plugin.json +1 -1
  6. package/packages/selector/lib/client.d.ts +8 -0
  7. package/packages/selector/lib/client.js +212 -3
  8. package/packages/selector/lib/index.js +1 -1
  9. package/packages/selector/lib/profiles.d.ts +34 -0
  10. package/packages/selector/lib/pruner.d.ts +55 -0
  11. package/packages/selector/lib/pruner.js +1925 -303
  12. package/packages/selector/lib/savings-integral.js +126 -3
  13. package/packages/selector/lib/tool-result.js +9 -1
  14. package/packages/selector/package.json +1 -1
  15. package/packages/selector/src/client/CompressionProfileControls.tsx +33 -0
  16. package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
  17. package/packages/selector/src/client/decode.ts +5 -1
  18. package/packages/selector/src/client/index.ts +4 -0
  19. package/packages/selector/src/client/locales/de.ts +7 -0
  20. package/packages/selector/src/client/locales/es.ts +7 -0
  21. package/packages/selector/src/client/locales/fr.ts +7 -0
  22. package/packages/selector/src/client/locales/it.ts +7 -0
  23. package/packages/selector/src/client/locales/ja.ts +7 -0
  24. package/packages/selector/src/client/locales/ko.ts +7 -0
  25. package/packages/selector/src/client/locales/ru.ts +7 -0
  26. package/packages/selector/src/client/locales.ts +14 -0
  27. package/packages/selector/src/client/monitor-fab.ts +14 -0
  28. package/packages/selector/src/client/settings-section.tsx +9 -2
  29. package/packages/selector/src/profiles.ts +103 -0
  30. package/packages/selector/src/pruner.ts +310 -4
  31. package/packages/selector/src/runtime/audit.ts +1 -0
  32. package/packages/selector/src/runtime/config.ts +88 -1
  33. package/packages/selector/src/runtime/fold-router.ts +143 -0
  34. package/packages/selector/src/runtime/monitor.ts +31 -0
  35. package/packages/selector/src/runtime/reducers.ts +1 -1
  36. package/packages/selector/src/runtime/sediment-card.ts +126 -0
  37. package/packages/selector/src/runtime/sediment-clock.ts +87 -0
  38. package/packages/selector/src/runtime/sediment-guard.ts +136 -0
  39. package/packages/selector/src/runtime/sediment-publish.ts +144 -0
  40. package/packages/selector/src/runtime/sediment-span.ts +170 -0
  41. package/packages/selector/src/runtime/sediment.ts +209 -0
  42. package/packages/selector/src/runtime/shallow-tools.ts +342 -0
  43. package/packages/selector/src/runtime/tool-names.ts +6 -0
  44. package/packages/selector/src/runtime/triage/masks.ts +128 -0
  45. package/packages/selector/src/runtime/triage/shallow.ts +132 -0
  46. package/packages/selector/src/runtime/triage/signals.ts +167 -0
  47. package/packages/selector/src/runtime/triage/types.ts +125 -0
  48. package/packages/selector/src/runtime/types.ts +28 -0
  49. package/packages/selector/tests/fixtures/sediment-pool/52adc205-cloud-5.orig.txt +231 -0
  50. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-25.orig.txt +236 -0
  51. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-38.orig.txt +220 -0
  52. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-42.orig.txt +140 -0
  53. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-53.orig.txt +117 -0
  54. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-local-10.orig.txt +67 -0
  55. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-45.orig.txt +119 -0
  56. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-49.orig.txt +119 -0
  57. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-63.orig.txt +131 -0
  58. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-75.orig.txt +196 -0
  59. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-76.orig.txt +71 -0
  60. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-85.orig.txt +126 -0
  61. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-86.orig.txt +86 -0
  62. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-87.orig.txt +50 -0
  63. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-96.orig.txt +102 -0
  64. package/packages/selector/tests/public/package-contract.client.spec.ts +7 -4
  65. package/packages/selector/tests/runtime/fold-router.spec.ts +140 -0
  66. package/packages/selector/tests/runtime/sediment-card.spec.ts +111 -0
  67. package/packages/selector/tests/runtime/sediment-config.spec.ts +56 -0
  68. package/packages/selector/tests/runtime/sediment-guard.spec.ts +71 -0
  69. package/packages/selector/tests/runtime/sediment-masks.spec.ts +95 -0
  70. package/packages/selector/tests/runtime/sediment-orchestrator.spec.ts +166 -0
  71. package/packages/selector/tests/runtime/sediment-pool-share.spec.ts +65 -0
  72. package/packages/selector/tests/runtime/sediment-publish.spec.ts +142 -0
  73. package/packages/selector/tests/runtime/sediment-real-shapes.spec.ts +158 -0
  74. package/packages/selector/tests/runtime/sediment-settings.spec.ts +73 -0
  75. package/packages/selector/tests/runtime/sediment-signals.spec.ts +124 -0
  76. package/packages/selector/tests/runtime/sediment-span.spec.ts +92 -0
  77. package/packages/selector/tests/runtime/shallow-primitives.spec.ts +135 -0
  78. package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
  79. package/scripts/hosts.d.mts +3 -0
  80. package/scripts/sediment-latency-report.mjs +63 -0
  81. package/scripts/verify-release.mjs +7 -2
  82. package/$null +0 -1
@@ -139,6 +139,107 @@ export interface MonitorPanelSettings {
139
139
  enabled: boolean
140
140
  }
141
141
 
142
+ /**
143
+ * Orthogonal turn-tail sedimentation gate (plan cci-sedimentation-triage,
144
+ * R1/R13): whole-turn atomic replacement primary, span as the oversized-turn
145
+ * split and cache-strict fallback granularity. Default OFF; absent inherits
146
+ * the off defaults exactly like `monitorPanel`. Session-frozen like every
147
+ * selector setting: edits affect newly observed sessions only.
148
+ */
149
+ export interface SedimentSettings {
150
+ enabled: boolean
151
+ /** Replacement granularity; `span` also serves as the cache-strict fallback. */
152
+ granularity: 'turn' | 'span'
153
+ /** Closing-summary qualification floor (tokens); below it the three-tier narrative fallback engages (R13). */
154
+ minClosingTokens: number
155
+ /** Rewrite guard: a cut must save at least tail-rewrite × ratio (community 1:15 evidence, findings F2). */
156
+ rewriteGuardRatio: number
157
+ /** Upper bound for one whole-turn replacement span before it splits (oversized turns). */
158
+ maxTurnSpanTokens: number
159
+ /**
160
+ * Append-only extra failure-signal patterns (R2 extension slot). Merging
161
+ * NEVER replaces the built-in base set; invalid regex entries reject the
162
+ * whole section (never silently dropped).
163
+ */
164
+ extraSignalPatterns?: string[]
165
+ /** Fold narrative channel (Phase 4); '' keeps narrative tier 2 inert. */
166
+ foldMode?: '' | 'host' | 'direct'
167
+ foldBaseUrl?: string
168
+ foldBaseUrlKey?: string
169
+ foldStrataProvider?: string
170
+ foldStrataModel?: string
171
+ foldLocal35Provider?: string
172
+ foldLocal35Model?: string
173
+ }
174
+
175
+ /** Off-defaults mirrored browser-safe from the runtime sediment section. */
176
+ export const DEFAULT_SEDIMENT_SETTINGS: SedimentSettings = {
177
+ enabled: false,
178
+ granularity: 'turn',
179
+ minClosingTokens: 120,
180
+ rewriteGuardRatio: 3,
181
+ maxTurnSpanTokens: 32_000,
182
+ }
183
+
184
+ /**
185
+ * Browser-safe mirror of the runtime sediment section (absent inherits the off
186
+ * defaults). Strict like the other gates: unknown keys, wrong types, or an
187
+ * unparseable extra pattern invalidate the whole section — never coerced.
188
+ */
189
+ export function decodeSedimentSettings(value: unknown): SedimentSettings | undefined {
190
+ if (value === undefined) return { ...DEFAULT_SEDIMENT_SETTINGS }
191
+ if (!isPlainRecord(value)) return undefined
192
+ const allowed = new Set(['enabled', 'granularity', 'minClosingTokens', 'rewriteGuardRatio', 'maxTurnSpanTokens', 'extraSignalPatterns', 'foldMode', 'foldBaseUrl', 'foldBaseUrlKey', 'foldStrataProvider', 'foldStrataModel', 'foldLocal35Provider', 'foldLocal35Model'])
193
+ if (Object.keys(value).some(key => !allowed.has(key))) return undefined
194
+ if (value.enabled !== undefined && typeof value.enabled !== 'boolean') return undefined
195
+ if (value.granularity !== undefined && value.granularity !== 'turn' && value.granularity !== 'span') return undefined
196
+ if (value.foldMode !== undefined && value.foldMode !== '' && value.foldMode !== 'host' && value.foldMode !== 'direct') return undefined
197
+ for (const key of ['foldBaseUrl', 'foldBaseUrlKey', 'foldStrataProvider', 'foldStrataModel', 'foldLocal35Provider', 'foldLocal35Model'] as const) {
198
+ if (value[key] !== undefined && typeof value[key] !== 'string') return undefined
199
+ }
200
+ const bounded: Array<[unknown, number, number]> = [
201
+ [value.minClosingTokens, 40, 2_000],
202
+ [value.rewriteGuardRatio, 1, 10],
203
+ [value.maxTurnSpanTokens, 4_000, 64_000],
204
+ ]
205
+ for (const [entry, min, max] of bounded) {
206
+ if (entry !== undefined
207
+ && (typeof entry !== 'number' || !Number.isSafeInteger(entry) || entry < min || entry > max)) return undefined
208
+ }
209
+ if (value.extraSignalPatterns !== undefined) {
210
+ if (!Array.isArray(value.extraSignalPatterns)
211
+ || value.extraSignalPatterns.some(entry => typeof entry !== 'string' || !isSafeSignalPattern(entry))) return undefined
212
+ }
213
+ return {
214
+ enabled: (value.enabled as boolean | undefined) ?? DEFAULT_SEDIMENT_SETTINGS.enabled,
215
+ granularity: (value.granularity as 'turn' | 'span' | undefined) ?? DEFAULT_SEDIMENT_SETTINGS.granularity,
216
+ minClosingTokens: (value.minClosingTokens as number | undefined) ?? DEFAULT_SEDIMENT_SETTINGS.minClosingTokens,
217
+ rewriteGuardRatio: (value.rewriteGuardRatio as number | undefined) ?? DEFAULT_SEDIMENT_SETTINGS.rewriteGuardRatio,
218
+ maxTurnSpanTokens: (value.maxTurnSpanTokens as number | undefined) ?? DEFAULT_SEDIMENT_SETTINGS.maxTurnSpanTokens,
219
+ ...value.extraSignalPatterns === undefined
220
+ ? {}
221
+ : { extraSignalPatterns: [...value.extraSignalPatterns as string[]] },
222
+ ...(value.foldMode === undefined ? {} : { foldMode: value.foldMode as '' | 'host' | 'direct' }),
223
+ ...(value.foldBaseUrl === undefined ? {} : { foldBaseUrl: value.foldBaseUrl as string }),
224
+ ...(value.foldBaseUrlKey === undefined ? {} : { foldBaseUrlKey: value.foldBaseUrlKey as string }),
225
+ ...(value.foldStrataProvider === undefined ? {} : { foldStrataProvider: value.foldStrataProvider as string }),
226
+ ...(value.foldStrataModel === undefined ? {} : { foldStrataModel: value.foldStrataModel as string }),
227
+ ...(value.foldLocal35Provider === undefined ? {} : { foldLocal35Provider: value.foldLocal35Provider as string }),
228
+ ...(value.foldLocal35Model === undefined ? {} : { foldLocal35Model: value.foldLocal35Model as string }),
229
+ }
230
+ }
231
+
232
+ /** Accept only parseable, length-bounded patterns; caps keep one scan linear. */
233
+ function isSafeSignalPattern(entry: string): boolean {
234
+ if (entry.length === 0 || entry.length > 200) return false
235
+ try {
236
+ new RegExp(entry)
237
+ return true
238
+ } catch {
239
+ return false
240
+ }
241
+ }
242
+
142
243
  /**
143
244
  * Decode the persisted codeSkeleton section with exactly the runtime schema's
144
245
  * strictness: absent means the lossless off default; present values must be a
@@ -346,6 +447,8 @@ export interface ContextCompressionSettings {
346
447
  intentSummary: IntentSummarySettings
347
448
  /** Floating compression-monitor panel (FAB); absent inherits hidden. */
348
449
  monitorPanel?: MonitorPanelSettings
450
+ /** Turn-tail sedimentation gate (plan cci-sedimentation-triage); absent inherits the off defaults. */
451
+ sediment?: SedimentSettings
349
452
  /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
350
453
  presetOptions?: PresetOptionsSettings
351
454
  }
@@ -60,6 +60,14 @@ import {
60
60
  tailTrimStub,
61
61
  } from './runtime/tail-trim.ts'
62
62
  import { installContextCompressionRetrieve } from './runtime/retrieve.ts'
63
+ import { installShallowTools, liveShallowFor } from './runtime/shallow-tools.ts'
64
+ import { buildShallowFooter } from './runtime/triage/shallow.ts'
65
+ import { SedimentOrchestrator } from './runtime/sediment.ts'
66
+ import { FoldRouter, foldTier } from './runtime/fold-router.ts'
67
+ import { SedimentFeedbackWatcher } from './runtime/sediment-guard.ts'
68
+ import { detectPtcMode, readStateBlind } from './runtime/sediment-guard.ts'
69
+ import { isWriteToolName } from './runtime/triage/masks.ts'
70
+ import { estimateTokens } from './runtime/sediment-card.ts'
63
71
  import { RUNTIME_TOOL_NAMES } from './runtime/tool-names.ts'
64
72
  import type { PrunerState } from './pruner/state.ts'
65
73
  import { countOmittedLines, CAPACITY_PRESSURE_RATIO } from './pruner/tuning.ts'
@@ -117,7 +125,7 @@ import { computeIntentRange, INTENT_RANGE_MAX_CANDIDATES } from './runtime/token
117
125
  import { INTENT_FOLD_MARKER, renderIntentFoldBlock } from './runtime/tokenpilot/intent-fold.ts'
118
126
  import { buildIntentSummarySystemPrompt, buildIntentSummaryUserPrompt, parseIntentSummaryAnswer } from './runtime/tokenpilot/advisor-prompt.ts'
119
127
  import { getSummaryOverride, observeIntentEnabled, recordIntentFold } from './runtime/tokenpilot/advisor-state.ts'
120
- import { observeContextUsage } from './runtime/monitor.ts'
128
+ import { observeContextUsage, setSedimentObservation } from './runtime/monitor.ts'
121
129
  import { compressionMessageSource, viewToolResult } from './compat/tool-result.ts'
122
130
 
123
131
  import {
@@ -132,6 +140,36 @@ import { kickStatsBackfillOnDispose } from './runtime/stats-backfill.ts'
132
140
  import { sampleIntegralBoundary } from './runtime/savings-integral.ts'
133
141
  import { projectSessionSavings } from './runtime/savings-projection.ts'
134
142
 
143
+ /** Loose read-only event face for sediment accounting (sessionEvents is opaque across generations). */
144
+ type LooseRecord = Record<string, unknown>
145
+ type LooseEvent = Readonly<Record<string, unknown>>
146
+
147
+ function looseEvents(session: Session): readonly LooseEvent[] {
148
+ return sessionEvents(session) as unknown as readonly LooseEvent[]
149
+ }
150
+
151
+ function looseData(event: LooseEvent | undefined): LooseRecord | undefined {
152
+ return event?.data as LooseRecord | undefined
153
+ }
154
+
155
+ function looseContent(event: LooseEvent | undefined): readonly unknown[] {
156
+ const data = looseData(event)
157
+ const message = (data?.message ?? data) as LooseRecord | undefined
158
+ const content = message?.content
159
+ return Array.isArray(content) ? content : []
160
+ }
161
+
162
+ /** Flatten the visible text of any surface event for sediment accounting. */
163
+ function sedimentEventText(event: LooseEvent | undefined): string {
164
+ return looseContent(event)
165
+ .filter(block => {
166
+ const record = block as LooseRecord | null
167
+ return record !== null && record.type === 'text' && typeof record.text === 'string'
168
+ })
169
+ .map(block => (block as { text: string }).text)
170
+ .join('\n')
171
+ }
172
+
135
173
  /** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
136
174
  function originalTextForSavings(candidate: SnapshotCandidate): string | undefined {
137
175
  return flattenPlainText(viewToolResult(candidate.event.data.message).blocks as ContentBlock[])
@@ -301,6 +339,8 @@ export class ToolResultPruner extends Service {
301
339
  super(ctx, 'toolResultPruner')
302
340
  ctx.inject(['tools', 'systemPrompt'], recoveryCtx => {
303
341
  installContextCompressionRetrieve(recoveryCtx)
342
+ // Upgrade-discard pair primitives (plan cci-sedimentation-triage Phase 4.5).
343
+ installShallowTools(recoveryCtx)
304
344
  })
305
345
  this.state = {
306
346
  config: resolveConfig(config),
@@ -368,6 +408,17 @@ export class ToolResultPruner extends Service {
368
408
  ctx.logger.warn('context-compression summary locator failed open: %o', error)
369
409
  }
370
410
  }
411
+ if (event.type === 'turn/end') {
412
+ // Sedimentation (plan cci-sedimentation-triage): the enabled gate is
413
+ // the first check inside — with default-off settings this returns
414
+ // without touching the orchestrator, the event reader, or the ledger.
415
+ try {
416
+ this.sedimentTurnEnd(session)
417
+ } catch (error: unknown) {
418
+ this.auditFailure(session, 'pressure', 'sediment', error)
419
+ ctx.logger.warn('context-compression sediment pass failed open: %o', error)
420
+ }
421
+ }
371
422
  })
372
423
 
373
424
  // This is the true first-exposure boundary available in the Harness:
@@ -428,7 +479,26 @@ export class ToolResultPruner extends Service {
428
479
  String(agent.session.id),
429
480
  new Set([...agent.session.surface.nodes].map(Number)),
430
481
  )
431
- } catch { /* 观测失败静默:维持上次口径 */ }
482
+ } catch { /* 观测失败静默:维持上次口径 */ }
483
+ // T3.11/T5.1:负反馈消费点——把账本增量交给会话级 watcher,
484
+ // conservative 状态与沉降刀数写进监控观测位(面板 sediment 块)。
485
+ try {
486
+ const feedbackSessionId = String(agent.session.id)
487
+ let watcher = this.sedimentWatchers.get(agent.session)
488
+ if (watcher === undefined) {
489
+ watcher = new SedimentFeedbackWatcher()
490
+ this.sedimentWatchers.set(agent.session, watcher)
491
+ }
492
+ const mode = watcher.observe(getSavingsLedger().snapshot(feedbackSessionId))
493
+ setSedimentObservation(feedbackSessionId, {
494
+ conservative: mode.conservative,
495
+ reason: mode.reason,
496
+ cuts: this.sedimentCuts.get(feedbackSessionId) ?? 0,
497
+ })
498
+ if (mode.conservative) {
499
+ this.warnOnce(agent.session, 'sediment:conservative', 'context-compression sediment feedback armed conservative mode: %s', mode.reason)
500
+ }
501
+ } catch { /* 观测失败静默:反馈环维持上次状态 */ }
432
502
  // TokenPilot-inspired E1: advisory estimator pass, strictly off the
433
503
  // synchronous chain. Verdicts only feed the next pressure pass.
434
504
  void this.postflightEstimatorPass(agent.session, signal).catch(() => undefined)
@@ -652,6 +722,232 @@ export class ToolResultPruner extends Service {
652
722
  return snapshot
653
723
  }
654
724
 
725
+ private readonly sedimentOrchestrators = new WeakMap<Session, SedimentOrchestrator>()
726
+ private readonly sedimentWatchers = new WeakMap<Session, SedimentFeedbackWatcher>()
727
+ private readonly sedimentCuts = new Map<string, number>()
728
+ private readonly ptcAgingMemo = new WeakMap<Session, { events: number, blocked: boolean }>()
729
+
730
+ /**
731
+ * PTC aging short-circuit (T3.10): when an omnibus runner is registered and
732
+ * no direct write-family tool call is observed in the session, the regex
733
+ * superseded predicate is blind (writes fold into run_code bodies) — the
734
+ * rule-based aging branch is disabled for that session. Active only while
735
+ * the sediment gate is on: with default-off settings the existing readState
736
+ * behavior is byte-identical.
737
+ */
738
+ private ptcAgingBlocked(session: Session): boolean {
739
+ if (this.activeSettings(session).sediment?.enabled !== true) return false
740
+ const events = looseEvents(session)
741
+ const memo = this.ptcAgingMemo.get(session)
742
+ if (memo !== undefined && memo.events === events.length) return memo.blocked
743
+ let blocked = false
744
+ const hasTool = (name: string): boolean => {
745
+ try {
746
+ return (this.ctx.get('tools') as { get?: (n: string) => unknown } | undefined)?.get?.(name) !== undefined
747
+ } catch {
748
+ return false
749
+ }
750
+ }
751
+ if (detectPtcMode(hasTool)) {
752
+ let observedCalls = 0
753
+ let writeHits = 0
754
+ for (const event of events) {
755
+ if (event.type !== 'assistant/message') continue
756
+ for (const raw of looseContent(event)) {
757
+ const block = raw as LooseRecord | null
758
+ if (block !== null && block.type === 'tool-call') {
759
+ observedCalls += 1
760
+ if (isWriteToolName(String(block.name ?? ''))) writeHits += 1
761
+ }
762
+ }
763
+ }
764
+ blocked = readStateBlind(true, writeHits, observedCalls)
765
+ }
766
+ this.ptcAgingMemo.set(session, { events: events.length, blocked })
767
+ return blocked
768
+ }
769
+
770
+ /**
771
+ * Sedimentation entry (plan cci-sedimentation-triage T3.6): whole-turn
772
+ * replacement decided at `turn/end`, inside the quiet seam before the next
773
+ * request derives. Disabled sessions exit at the settings gate with zero
774
+ * downstream work; committed cards flush like any other surface write.
775
+ */
776
+ private sedimentTurnEnd(session: Session): void {
777
+ const settings = this.activeSettings(session).sediment
778
+ if (settings === undefined || settings.enabled !== true) return
779
+ const events = sessionEvents(session)
780
+ let turn: number | undefined
781
+ for (let index = events.length - 1; index >= 0; index -= 1) {
782
+ const candidate = events[index]
783
+ if (candidate?.type === 'turn/end') {
784
+ const value = (candidate.data as { turn?: unknown }).turn
785
+ if (typeof value === 'number') { turn = value; break }
786
+ }
787
+ }
788
+ if (turn === undefined) return
789
+ const orchestrator = this.sedimentOrchestratorFor(session, settings)
790
+ let officialCheckpointSeq: number | undefined
791
+ for (const seq of [...session.surface.nodes].reverse()) {
792
+ const event = events[seq]
793
+ if (event?.type !== 'user/message') continue
794
+ const kind = (event.data as { source?: { kind?: unknown } }).source?.kind
795
+ if (kind === 'compact-checkpoint') { officialCheckpointSeq = seq; break }
796
+ }
797
+ let compactionOpen = false
798
+ for (let index = events.length - 1; index >= 0; index -= 1) {
799
+ const type = events[index]?.type
800
+ if (type === 'compaction/end') break
801
+ if (type === 'compaction/start') { compactionOpen = true; break }
802
+ }
803
+ const outcomePromise = orchestrator.handleTurnEnd(session as never, turn, {
804
+ lastEventType: 'turn/end',
805
+ inFlightRequest: this.state.activeRequestBoundaries.get(session) !== undefined,
806
+ compactionOpen,
807
+ officialCheckpointSeq,
808
+ resumeFirstBatch: false,
809
+ })
810
+ void outcomePromise.then(outcome => {
811
+ if (outcome.committed) {
812
+ try {
813
+ void (this.ctx as { sessions?: { flush?: (s: Session) => unknown } }).sessions?.flush?.(session)
814
+ } catch {
815
+ /* flush failure leaves the card durable in the event log; next flush picks it up */
816
+ }
817
+ }
818
+ }).catch(error => {
819
+ this.auditFailure(session, 'pressure', 'sediment', error)
820
+ this.ctx.logger.warn('context-compression sediment commit failed open: %o', error)
821
+ })
822
+ }
823
+
824
+ private sedimentOrchestratorFor(session: Session, settings: NonNullable<ContextCompressionSettings['sediment']>): SedimentOrchestrator {
825
+ let orchestrator = this.sedimentOrchestrators.get(session)
826
+ if (orchestrator !== undefined) return orchestrator
827
+ orchestrator = new SedimentOrchestrator({
828
+ settingsFor: () => this.activeSettings(session).sediment,
829
+ eventsFor: (_s, turn) => looseEvents(session)
830
+ .filter(event => looseData(event)?.turn === turn)
831
+ .map(event => {
832
+ const data = looseData(event)
833
+ return {
834
+ seq: event.seq as number,
835
+ type: event.type as string,
836
+ ...(data === undefined ? {} : { data }),
837
+ }
838
+ }),
839
+ callInfoFor: () => {
840
+ const map = new Map<string, { name: string; argsJson: string }>()
841
+ for (const event of looseEvents(session)) {
842
+ if (event.type !== 'assistant/message') continue
843
+ for (const raw of looseContent(event)) {
844
+ const block = raw as LooseRecord | null
845
+ if (block !== null && block.type === 'tool-call' && typeof block.id === 'string') {
846
+ map.set(block.id, {
847
+ name: String(block.name ?? 'tool'),
848
+ argsJson: typeof block.arguments === 'string' ? block.arguments : JSON.stringify(block.arguments ?? {}),
849
+ })
850
+ }
851
+ }
852
+ }
853
+ return (callId: string | undefined) => (callId === undefined ? undefined : map.get(callId))
854
+ },
855
+ tailTokensFor: (_s, endSeq) => {
856
+ let tail = 0
857
+ for (const event of looseEvents(session)) {
858
+ if (typeof event.seq !== 'number' || event.seq <= endSeq) continue
859
+ tail += estimateTokens(sedimentEventText(event))
860
+ }
861
+ return tail
862
+ },
863
+ // Narrative tier 2 (T4.5): fold channel exists only when configured.
864
+ ...(settings.foldMode === undefined || settings.foldMode === ''
865
+ ? {}
866
+ : {
867
+ fold: {
868
+ run: async (sessionId, prompt, signal) => {
869
+ // T5.3 observability: fold P99 sampling rides this one log line;
870
+ // the latency budget measured here is the LAN call itself.
871
+ const started = Date.now()
872
+ const outcome = await new FoldRouter(this.ctx, settings).fold(sessionId, prompt, signal)
873
+ this.ctx.logger.info(
874
+ 'context-compression sediment fold (%s): tier=%s ok=%s latencyMs=%d%s',
875
+ sessionId, foldTier(prompt.inputTokens), outcome.text !== undefined,
876
+ Date.now() - started,
877
+ outcome.audit.ok ? '' : ` reason=${outcome.audit.reason ?? 'unknown'}`,
878
+ )
879
+ return outcome.text
880
+ },
881
+ },
882
+ }),
883
+ // T3.11 consumption: conservative state tightens the rewrite guard.
884
+ feedback: () => {
885
+ const watcher = this.sedimentWatchers.get(session)
886
+ return watcher === undefined
887
+ ? { conservative: false, reason: 'ok' }
888
+ : { conservative: watcher.conservative, reason: watcher.conservative ? 'net-negative-streak' : 'ok' }
889
+ },
890
+ onLanded: (sessionId, savedTokens, tier, result) => {
891
+ this.sedimentCuts.set(sessionId, (this.sedimentCuts.get(sessionId) ?? 0) + 1)
892
+ this.ctx.logger.info(
893
+ 'context-compression sediment landed (%s): turn saved %d tok via %s narrative',
894
+ sessionId, savedTokens, tier,
895
+ )
896
+ // 节省统计与 tail-trim 同口径:从 manifest 事件回取 shadowed 原文配对键。
897
+ const allEvents = looseEvents(session)
898
+ const manifestEvent = allEvents.find(event => event.seq === result.manifestSeq)
899
+ const shadowedSeqs: number[] = (looseData(manifestEvent)?.shadowedSeqs as number[] | undefined) ?? []
900
+ const originalText = shadowedSeqs
901
+ .map(seq => sedimentEventText(allEvents[seq]))
902
+ .join('\n')
903
+ const tokensBefore = (looseData(manifestEvent)?.shadowedTokenCount as number | undefined) ?? savedTokens
904
+ if (originalText.length > 0) {
905
+ getSavingsLedger().recordSaving({
906
+ sessionId,
907
+ component: 'sediment',
908
+ tokensBefore,
909
+ tokensAfter: Math.max(0, tokensBefore - savedTokens),
910
+ basis: 'characters',
911
+ sourceSeq: result.manifestSeq ?? 0,
912
+ replacementSeq: result.replacementSeq ?? 0,
913
+ originalText,
914
+ })
915
+ }
916
+ },
917
+ onSkip: (sessionId, reason) => {
918
+ this.ctx.logger.debug?.(
919
+ 'context-compression sediment skipped (%s): %s', sessionId, reason,
920
+ )
921
+ },
922
+ })
923
+ this.sedimentOrchestrators.set(session, orchestrator)
924
+ return orchestrator
925
+ }
926
+
927
+ /**
928
+ * T4.8 pairing footer: when a read-class result supersedes a live shallow
929
+ * map of the same file, the reduced text carries the data-shaped reminder
930
+ * (sibling ref + discard hint). Non-read calls, unparseable arguments, and
931
+ * sessions without a live map all return undefined — zero side effects.
932
+ */
933
+ private shallowPairFooter(
934
+ session: Session,
935
+ candidate: { call: { name: string; arguments: string } },
936
+ ): string | undefined {
937
+ if (/^(read|read_file|view)$/i.test(candidate.call.name) === false) return undefined
938
+ let filePath: string
939
+ try {
940
+ const parsed = JSON.parse(candidate.call.arguments) as Record<string, unknown>
941
+ filePath = typeof parsed.file_path === 'string' ? parsed.file_path
942
+ : typeof parsed.path === 'string' ? parsed.path : ''
943
+ } catch {
944
+ return undefined
945
+ }
946
+ if (filePath === '') return undefined
947
+ const entry = liveShallowFor(session, filePath)
948
+ return entry === undefined ? undefined : buildShallowFooter(entry.checkpoint, entry.bodyTokens)
949
+ }
950
+
655
951
  /**
656
952
  * TokenPilot-inspired A2: replace the compaction summary checkpoint node
657
953
  * with the same summary plus an Exact Sources locator block. Fails open:
@@ -726,6 +1022,9 @@ export class ToolResultPruner extends Service {
726
1022
  const policy = this.activePolicy(session)
727
1023
  const presetOptions = policy?.presetOptions
728
1024
  if (policy === undefined || presetOptions?.readState !== true) return
1025
+ // T3.10: PTC-blind sessions must not feed the estimator either — its
1026
+ // verdicts unlock the same aging branch the short-circuit just closed.
1027
+ if (this.ptcAgingBlocked(session)) return
729
1028
  const estimatorMode = presetOptions.estimator?.mode ?? ''
730
1029
  if (estimatorMode === '') return
731
1030
  const failures = this.state.estimatorFailures.get(session)
@@ -1883,9 +2182,15 @@ export class ToolResultPruner extends Service {
1883
2182
  codeSkeleton,
1884
2183
  })
1885
2184
  if (output !== null) {
2185
+ // T4.8 pairing footer: a read result that supersedes a live shallow
2186
+ // map carries the data-shaped reminder (sibling ref + discard hint).
2187
+ const footer = this.shallowPairFooter(session, candidate)
2188
+ const reducedText = footer === undefined
2189
+ ? output.text
2190
+ : `${output.text}\n\n${footer}`
1886
2191
  const plan = this.plan(
1887
2192
  candidate,
1888
- [{ ...textBlock, text: output.text }],
2193
+ [{ ...textBlock, text: reducedText }],
1889
2194
  sourceSeq,
1890
2195
  output.reducer,
1891
2196
  'fresh',
@@ -2101,7 +2406,7 @@ export class ToolResultPruner extends Service {
2101
2406
  // TokenPilot-inspired R2: a read output whose file was later mutated is
2102
2407
  // superseded — its text can no longer match the file — so it takes the
2103
2408
  // small whole-result placeholder before the ordinary reducer runs.
2104
- if (policy.presetOptions?.readState === true && block !== null) {
2409
+ if (policy.presetOptions?.readState === true && block !== null && !this.ptcAgingBlocked(session)) {
2105
2410
  const readPath = toolCallPath(candidate.call.arguments)
2106
2411
  const estimatorExpired = this.state.estimatorVerdicts.get(session)?.get(candidate.seq) === true
2107
2412
  if (readPath !== undefined
@@ -2843,6 +3148,7 @@ export class ToolResultPruner extends Service {
2843
3148
  | 'terminal-pass'
2844
3149
  | 'policy-resolution'
2845
3150
  | 'summary-locator'
3151
+ | 'sediment'
2846
3152
  | 'publication',
2847
3153
  error: unknown,
2848
3154
  ): void {
@@ -143,6 +143,7 @@ export interface CompressionFailureAuditRecord extends CompressionAuditBase {
143
143
  | 'terminal-pass'
144
144
  | 'policy-resolution'
145
145
  | 'summary-locator'
146
+ | 'sediment'
146
147
  | 'publication'
147
148
  readonly component?: CompressionAuditComponent
148
149
  readonly manifestSeq?: number
@@ -7,6 +7,7 @@ import type {
7
7
  CompressionPolicy,
8
8
  IntentSummarySettings,
9
9
  MonitorPanelSettings,
10
+ SedimentSettings,
10
11
  CompressionProfile,
11
12
  CustomCompressionPolicy,
12
13
  PresetOptions,
@@ -159,6 +160,89 @@ function parseMonitorPanelSettings(value: unknown): MonitorPanelSettings {
159
160
  return { enabled }
160
161
  }
161
162
 
163
+ /** Off defaults for the sediment gate; mirrored browser-side in profiles.ts DEFAULT_SEDIMENT_SETTINGS. */
164
+ export const DEFAULT_SEDIMENT_SETTINGS: SedimentSettings = {
165
+ enabled: false,
166
+ granularity: 'turn',
167
+ minClosingTokens: 120,
168
+ rewriteGuardRatio: 3,
169
+ maxTurnSpanTokens: 32_000,
170
+ }
171
+
172
+ const SEDIMENT_KEYS: ReadonlySet<string> = new Set([
173
+ 'enabled', 'granularity', 'minClosingTokens', 'rewriteGuardRatio', 'maxTurnSpanTokens', 'extraSignalPatterns',
174
+ 'foldMode', 'foldBaseUrl', 'foldBaseUrlKey', 'foldStrataProvider', 'foldStrataModel', 'foldLocal35Provider', 'foldLocal35Model',
175
+ ])
176
+
177
+ function isSafeSignalPatternSource(entry: unknown): boolean {
178
+ return typeof entry === 'string' && entry.length > 0 && entry.length <= 200
179
+ && (() => { try { new RegExp(entry); return true } catch { return false } })()
180
+ }
181
+
182
+ /**
183
+ * Strictly parse the persisted sediment section (plan cci-sedimentation-triage
184
+ * T0.2/T0.3): absent inherits the off defaults; present-but-invalid values
185
+ * throw — never coerced, never silently dropped.
186
+ */
187
+ function parseSedimentSettings(value: unknown): SedimentSettings {
188
+ if (value === undefined) return { ...DEFAULT_SEDIMENT_SETTINGS }
189
+ if (!isPlainRecord(value)) {
190
+ throw new TypeError('Context-compression sediment must be a plain object')
191
+ }
192
+ const unknownKey = Object.keys(value).find(key => !SEDIMENT_KEYS.has(key))
193
+ if (unknownKey !== undefined) {
194
+ throw new TypeError(`Context-compression sediment: unknown key "${unknownKey}"`)
195
+ }
196
+ if (value.enabled !== undefined && typeof value.enabled !== 'boolean') {
197
+ throw new TypeError('Context-compression sediment.enabled must be a boolean')
198
+ }
199
+ if (value.granularity !== undefined && value.granularity !== 'turn' && value.granularity !== 'span') {
200
+ throw new TypeError('Context-compression sediment.granularity must be "turn" or "span"')
201
+ }
202
+ const bounded: Array<[string, unknown, number, number]> = [
203
+ ['minClosingTokens', value.minClosingTokens, 40, 2_000],
204
+ ['rewriteGuardRatio', value.rewriteGuardRatio, 1, 10],
205
+ ['maxTurnSpanTokens', value.maxTurnSpanTokens, 4_000, 64_000],
206
+ ]
207
+ for (const [name, entry, min, max] of bounded) {
208
+ if (entry !== undefined
209
+ && (typeof entry !== 'number' || !Number.isSafeInteger(entry) || entry < min || entry > max)) {
210
+ throw new TypeError(`Context-compression sediment.${name} must be an integer in [${min}, ${max}]`)
211
+ }
212
+ }
213
+ if (value.extraSignalPatterns !== undefined) {
214
+ if (!Array.isArray(value.extraSignalPatterns)
215
+ || value.extraSignalPatterns.some(entry => !isSafeSignalPatternSource(entry))) {
216
+ throw new TypeError('Context-compression sediment.extraSignalPatterns must be parseable non-empty patterns')
217
+ }
218
+ }
219
+ if (value.foldMode !== undefined && value.foldMode !== '' && value.foldMode !== 'host' && value.foldMode !== 'direct') {
220
+ throw new TypeError('Context-compression sediment.foldMode must be "", "host", or "direct"')
221
+ }
222
+ for (const key of ['foldBaseUrl', 'foldBaseUrlKey', 'foldStrataProvider', 'foldStrataModel', 'foldLocal35Provider', 'foldLocal35Model'] as const) {
223
+ if (value[key] !== undefined && typeof value[key] !== 'string') {
224
+ throw new TypeError(`Context-compression sediment.${key} must be a string`)
225
+ }
226
+ }
227
+ return {
228
+ enabled: value.enabled as boolean | undefined ?? DEFAULT_SEDIMENT_SETTINGS.enabled,
229
+ granularity: value.granularity as 'turn' | 'span' | undefined ?? DEFAULT_SEDIMENT_SETTINGS.granularity,
230
+ minClosingTokens: value.minClosingTokens as number | undefined ?? DEFAULT_SEDIMENT_SETTINGS.minClosingTokens,
231
+ rewriteGuardRatio: value.rewriteGuardRatio as number | undefined ?? DEFAULT_SEDIMENT_SETTINGS.rewriteGuardRatio,
232
+ maxTurnSpanTokens: value.maxTurnSpanTokens as number | undefined ?? DEFAULT_SEDIMENT_SETTINGS.maxTurnSpanTokens,
233
+ ...value.extraSignalPatterns === undefined
234
+ ? {}
235
+ : { extraSignalPatterns: [...value.extraSignalPatterns as string[]] },
236
+ ...(value.foldMode === undefined ? {} : { foldMode: value.foldMode as '' | 'host' | 'direct' }),
237
+ ...(value.foldBaseUrl === undefined ? {} : { foldBaseUrl: value.foldBaseUrl as string }),
238
+ ...(value.foldBaseUrlKey === undefined ? {} : { foldBaseUrlKey: value.foldBaseUrlKey as string }),
239
+ ...(value.foldStrataProvider === undefined ? {} : { foldStrataProvider: value.foldStrataProvider as string }),
240
+ ...(value.foldStrataModel === undefined ? {} : { foldStrataModel: value.foldStrataModel as string }),
241
+ ...(value.foldLocal35Provider === undefined ? {} : { foldLocal35Provider: value.foldLocal35Provider as string }),
242
+ ...(value.foldLocal35Model === undefined ? {} : { foldLocal35Model: value.foldLocal35Model as string }),
243
+ }
244
+ }
245
+
162
246
  /**
163
247
  * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
164
248
  * inherits the preset defaults; present-but-invalid is rejected, mirroring the
@@ -302,6 +386,7 @@ export const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings =
302
386
  codeSkeleton: { enabled: false },
303
387
  intentSummary: { enabled: false },
304
388
  monitorPanel: { enabled: false },
389
+ sediment: { ...DEFAULT_SEDIMENT_SETTINGS },
305
390
  }
306
391
 
307
392
  /**
@@ -339,7 +424,7 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
339
424
  // remain valid and inherit their defaults; the sections themselves stay
340
425
  // strictly shaped.
341
426
  const unknown = Object.keys(candidate).find(key =>
342
- key !== 'profile' && key !== 'custom' && key !== 'ptcCustom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'presetOptions')
427
+ key !== 'profile' && key !== 'custom' && key !== 'ptcCustom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'sediment' && key !== 'presetOptions')
343
428
  if (unknown !== undefined) {
344
429
  throw new TypeError(`Context-compression settings: unknown key "${unknown}"`)
345
430
  }
@@ -354,6 +439,7 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
354
439
  const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton)
355
440
  const intentSummary = parseIntentSummarySettings(candidate.intentSummary)
356
441
  const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel)
442
+ const sediment = parseSedimentSettings(candidate.sediment)
357
443
  const presetOptions = parsePresetOptionsSettings(candidate.presetOptions)
358
444
  return {
359
445
  ...contextCompressionSettingsInputSchema(candidate),
@@ -361,6 +447,7 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
361
447
  codeSkeleton,
362
448
  intentSummary,
363
449
  monitorPanel,
450
+ sediment,
364
451
  ...presetOptions === undefined ? {} : { presetOptions },
365
452
  }
366
453
  },