dsh-context-compression-improved 0.5.7 → 0.5.8

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 (61) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/package.json +16 -17
  3. package/packages/selector/dsh.plugin.json +1 -1
  4. package/packages/selector/lib/client.d.ts +59 -0
  5. package/packages/selector/lib/client.js +1012 -17
  6. package/packages/selector/lib/{advisor-state.js → config.js} +816 -65
  7. package/packages/selector/lib/index.d.ts +13 -1
  8. package/packages/selector/lib/index.js +295 -3
  9. package/packages/selector/lib/pruner.d.ts +65 -0
  10. package/packages/selector/lib/pruner.js +497 -262
  11. package/packages/selector/lib/style.css +42 -0
  12. package/packages/selector/src/client/CompressionProfileControls.tsx +67 -0
  13. package/packages/selector/src/client/CompressionProfileSelector.module.css +29 -0
  14. package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
  15. package/packages/selector/src/client/decode.ts +10 -2
  16. package/packages/selector/src/client/index.ts +62 -0
  17. package/packages/selector/src/client/locales/de.ts +43 -0
  18. package/packages/selector/src/client/locales/es.ts +43 -0
  19. package/packages/selector/src/client/locales/fr.ts +43 -0
  20. package/packages/selector/src/client/locales/it.ts +43 -0
  21. package/packages/selector/src/client/locales/ja.ts +43 -0
  22. package/packages/selector/src/client/locales/ko.ts +43 -0
  23. package/packages/selector/src/client/locales/ru.ts +43 -0
  24. package/packages/selector/src/client/locales.ts +86 -0
  25. package/packages/selector/src/client/monitor-fab.ts +336 -0
  26. package/packages/selector/src/client/savings-card.tsx +150 -0
  27. package/packages/selector/src/client/settings-section.tsx +18 -2
  28. package/packages/selector/src/index.ts +215 -5
  29. package/packages/selector/src/profiles.ts +37 -0
  30. package/packages/selector/src/pruner/state.ts +7 -0
  31. package/packages/selector/src/pruner.ts +337 -3
  32. package/packages/selector/src/runtime/audit.ts +17 -0
  33. package/packages/selector/src/runtime/config.ts +52 -2
  34. package/packages/selector/src/runtime/monitor.ts +235 -0
  35. package/packages/selector/src/runtime/retrieve.ts +24 -2
  36. package/packages/selector/src/runtime/savings.ts +337 -0
  37. package/packages/selector/src/runtime/summary-command.ts +127 -0
  38. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +46 -1
  39. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +55 -0
  40. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  41. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  42. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  43. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  44. package/packages/selector/src/runtime/types.ts +19 -0
  45. package/packages/selector/tests/auto-compact.client.spec.tsx +2 -1
  46. package/packages/selector/tests/code-skeleton.client.spec.ts +3 -2
  47. package/packages/selector/tests/custom-contract.client.spec.ts +3 -2
  48. package/packages/selector/tests/estimator-channel.client.spec.tsx +1 -0
  49. package/packages/selector/tests/estimator-route-registration.host.spec.ts +10 -4
  50. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  51. package/packages/selector/tests/preset-options-write.client.spec.ts +1 -0
  52. package/packages/selector/tests/profiles.client.spec.tsx +4 -2
  53. package/packages/selector/tests/runtime/audit.spec.ts +1 -0
  54. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  55. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  56. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  57. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  58. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  59. package/packages/selector/tests/settings-seat.client.spec.ts +19 -7
  60. package/scripts/packed-install-e2e.mjs +1 -1
  61. package/scripts/verify-release.mjs +2 -1
@@ -0,0 +1,127 @@
1
+ /**
2
+ * `/ctx-summary off|on|status` — in-session temporary override for the
3
+ * turn-tail intent-summary gate.
4
+ *
5
+ * The override is session-scoped by design: settings are session-frozen
6
+ * (changes only affect newly observed sessions), so "temporarily disable and
7
+ * resume" can only be expressed as runtime state. Overrides die with the
8
+ * process and never leak across sessions. `off` wins over the settings gate;
9
+ * `on` never bypasses the numeric growth gates — it only lifts the
10
+ * settings/override veto.
11
+ *
12
+ * Registration mirrors the host's own `/compact` command: optional
13
+ * `commands`-service injection (a host without the registry simply never
14
+ * mounts the command), dynamic `CommandDefinitionId` brand import with a
15
+ * plain fallback so a stripped host cannot break plugin load.
16
+ */
17
+ import type { Context } from '@deepseek-ai/cordis'
18
+ import {
19
+ getLastIntentFold,
20
+ getObservedIntentEnabled,
21
+ getSummaryOverride,
22
+ setSummaryOverride,
23
+ } from './tokenpilot/advisor-state.ts'
24
+ import { INTENT_GATE_FLOOR_FRACTION, INTENT_GATE_GROWTH_TOKENS } from './tokenpilot/intent-gate.ts'
25
+
26
+ export const SUMMARY_COMMAND_NAME = 'ctx-summary'
27
+
28
+ const USAGE = 'Usage: /ctx-summary off|on|status'
29
+
30
+ export type SummaryCommandArgs = 'off' | 'on' | 'status'
31
+
32
+ /** Parse the raw argument string; `undefined` = unrecognized (usage error). */
33
+ export function parseSummaryCommandArgs(rawInput: string): SummaryCommandArgs | undefined {
34
+ const token = rawInput.trim().toLowerCase()
35
+ if (token === 'off' || token === 'on' || token === 'status') return token
36
+ return undefined
37
+ }
38
+
39
+ function describeFold(sessionId: string): string {
40
+ const fold = getLastIntentFold(sessionId)
41
+ if (fold === undefined) return 'none'
42
+ return `turn ${fold.turn}, seq ${fold.startSeq}..${fold.endSeq}`
43
+ }
44
+
45
+ /** Human-facing status line; observability only, never a decision input. */
46
+ export function formatSummaryStatus(sessionId: string): string {
47
+ const override = getSummaryOverride(sessionId)
48
+ const enabled = getObservedIntentEnabled(sessionId)
49
+ const enabledText = enabled === undefined ? 'unknown (gate not evaluated yet)' : enabled ? 'yes' : 'no'
50
+ return [
51
+ `ctx-summary status:`,
52
+ ` override: ${override ?? 'default (settings-driven)'}`,
53
+ ` intentSummary enabled (settings): ${enabledText}`,
54
+ ` gate: floor >${Math.round(INTENT_GATE_FLOOR_FRACTION * 100)}% of window AND growth >${INTENT_GATE_GROWTH_TOKENS} tokens since last fold`,
55
+ ` last fold: ${describeFold(sessionId)}`,
56
+ ].join('\n')
57
+ }
58
+
59
+ /** Resolve the invoking agent's session id (`''` when the host exposes none). */
60
+ function sessionIdOf(agent: unknown): string {
61
+ const session = (agent as { session?: { id?: unknown } } | undefined)?.session
62
+ if (session === undefined || session.id === undefined || session.id === null) return ''
63
+ return String(session.id)
64
+ }
65
+
66
+ type CommandsServiceLike = {
67
+ register: (definition: {
68
+ definitionId?: unknown
69
+ name: string
70
+ description: string
71
+ handler: (invocation: { agent?: unknown, rawInput?: unknown }) => Promise<{ kind: 'success' | 'error', text: string }>
72
+ }) => unknown
73
+ }
74
+
75
+ /** Best-effort `CommandDefinitionId` brand; `undefined` on stripped hosts (registered without it). */
76
+ async function loadCommandDefinitionId(): Promise<((id: string) => unknown) | undefined> {
77
+ try {
78
+ const mod = (await import('@deepseek-ai/dsh-commands')) as { CommandDefinitionId?: (id: string) => unknown }
79
+ return mod.CommandDefinitionId
80
+ } catch {
81
+ return undefined
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Mount `/ctx-summary` for every composed human-command adapter. Never
87
+ * throws: the command is a convenience surface, and a host without the
88
+ * commands service (or with an incompatible registry shape) simply runs
89
+ * without it.
90
+ */
91
+ export function registerSummaryCommand(ctx: Context): void {
92
+ ctx.inject(['commands'], (injected) => {
93
+ const commands = (injected as { commands?: unknown }).commands as CommandsServiceLike | undefined
94
+ if (commands === undefined || typeof commands.register !== 'function') return
95
+ void (async () => {
96
+ try {
97
+ const definitionId = await loadCommandDefinitionId()
98
+ await commands.register({
99
+ name: SUMMARY_COMMAND_NAME,
100
+ description: 'Turn-tail intent summary: temporarily disable/resume or inspect status',
101
+ ...(definitionId === undefined ? {} : { definitionId: definitionId('dsh-context-compression-improved/ctx-summary') }),
102
+ handler: async (invocation) => {
103
+ const rawInput = typeof invocation.rawInput === 'string' ? invocation.rawInput : ''
104
+ const args = parseSummaryCommandArgs(rawInput)
105
+ if (args === undefined) return { kind: 'error' as const, text: USAGE }
106
+ const sessionId = sessionIdOf(invocation.agent)
107
+ if (args === 'status') {
108
+ if (sessionId === '') return { kind: 'error' as const, text: 'ctx-summary: no session is attached to this invocation' }
109
+ return { kind: 'success' as const, text: formatSummaryStatus(sessionId) }
110
+ }
111
+ if (sessionId === '') return { kind: 'error' as const, text: 'ctx-summary: no session is attached to this invocation' }
112
+ setSummaryOverride(sessionId, args)
113
+ return {
114
+ kind: 'success' as const,
115
+ text: args === 'off'
116
+ ? 'ctx-summary: turn-tail intent summary paused for this session (until process restart or `/ctx-summary on`)'
117
+ : 'ctx-summary: turn-tail intent summary resumed for this session (numeric gates still apply)',
118
+ }
119
+ },
120
+ })
121
+ } catch {
122
+ // Registry rejected the definition (shape drift, closed union): the
123
+ // plugin keeps working, only the convenience command is absent.
124
+ }
125
+ })()
126
+ })
127
+ }
@@ -69,7 +69,7 @@ export function buildAdvisorScoringUserPrompt(
69
69
  }
70
70
 
71
71
  /** Pull the first balanced JSON object out of a possibly chatty answer. */
72
- function firstJsonObject(text: string): Record<string, unknown> | undefined {
72
+ export function firstJsonObject(text: string): Record<string, unknown> | undefined {
73
73
  const start = text.indexOf('{')
74
74
  if (start < 0) return undefined
75
75
  let depth = 0
@@ -186,3 +186,48 @@ export function parseAdvisorScores(
186
186
  }
187
187
  return scores.size > 0 ? scores : undefined
188
188
  }
189
+
190
+ /** Hard character cap for one intent-summary answer (summary segment only). */
191
+ export const INTENT_SUMMARY_CHAR_CAP = 1_600
192
+
193
+ /**
194
+ * Intent-summary writer prompts (task_2.3). Input records are already
195
+ * semantic-role-masked by intent-input-mask.ts: read-class candidates are
196
+ * one-line "read X" records, keep-class candidates carry skeleton heads and
197
+ * VERBATIM error lines. The model writes ONLY the summary segment — it never
198
+ * revoices error lines, and its answer must stay inside the char cap.
199
+ */
200
+ export function buildIntentSummarySystemPrompt(): string {
201
+ return [
202
+ 'You write one concise intent summary of folded tool results for a coding agent session.',
203
+ 'Input: the session task (todolist) and per-tool slimmed records (read lines, or skeleton heads with verbatim error lines).',
204
+ `Write ONLY what the agent DID and LEARNED in this span, as flowing prose under ${INTENT_SUMMARY_CHAR_CAP} characters.`,
205
+ 'Mention which files/areas were consulted and what changed, so a later turn can continue without the originals.',
206
+ 'Never invent files, commands, or outcomes absent from the records. Never revoice error lines; they are preserved verbatim elsewhere.',
207
+ 'Answer with ONLY one JSON object: {"summary":"<prose>"}. Never add commentary.',
208
+ ].join(' ')
209
+ }
210
+
211
+ export function buildIntentSummaryUserPrompt(
212
+ taskText: string,
213
+ records: readonly string[],
214
+ tailText: string,
215
+ ): string {
216
+ const nl = String.fromCharCode(10)
217
+ const lines = [
218
+ `task: ${taskText.replace(/\s+/gu, ' ').slice(0, 600)}`,
219
+ records.length > 0 ? `records:${nl}${records.join(nl)}` : 'records: (none)',
220
+ tailText.trim().length > 0 ? `recent tail:${nl}${tailText.trim().slice(0, 1_200)}` : 'recent tail: (none)',
221
+ ]
222
+ return lines.join(nl + nl)
223
+ }
224
+
225
+ /** Fail-open parse of one intent-summary answer; `undefined` on any malformed shape. */
226
+ export function parseIntentSummaryAnswer(text: string): { readonly summary: string } | undefined {
227
+ const parsed = firstJsonObject(text)
228
+ if (parsed === undefined) return undefined
229
+ const summary = parsed.summary
230
+ if (typeof summary !== 'string' || summary.trim().length === 0) return undefined
231
+ if (summary.length > INTENT_SUMMARY_CHAR_CAP * 2) return undefined
232
+ return { summary: summary.trim().slice(0, INTENT_SUMMARY_CHAR_CAP) }
233
+ }
@@ -147,3 +147,58 @@ export function invalidateOnTaskChange(state: AdvisorState, todoVersion: string)
147
147
  state.lastSummaryTurn = -1
148
148
  return true
149
149
  }
150
+
151
+ // ─────────── Turn-tail intent summary: session-scoped overrides and records ───────────
152
+
153
+ /**
154
+ * `/ctx-summary off|on` overrides, keyed by session id (string). The command
155
+ * handler only sees `invocation.agent.session.id`, not the pruner's Session
156
+ * object, so these are id-keyed rather than WeakMap'd. Entries are two-char
157
+ * strings per session and cleared whenever the override is lifted.
158
+ */
159
+ const summaryOverrides = new Map<string, 'on' | 'off'>()
160
+
161
+ /** Read the session's `/ctx-summary` override; `undefined` = default (settings-driven). */
162
+ export function getSummaryOverride(sessionId: string): 'on' | 'off' | undefined {
163
+ return summaryOverrides.get(sessionId)
164
+ }
165
+
166
+ /** Set or clear (`undefined`) the session's `/ctx-summary` override. */
167
+ export function setSummaryOverride(sessionId: string, value: 'on' | 'off' | undefined): void {
168
+ if (value === undefined) summaryOverrides.delete(sessionId)
169
+ else summaryOverrides.set(sessionId, value)
170
+ }
171
+
172
+ /** Last observed `intentSummary.enabled` for a session, for `/ctx-summary status`. */
173
+ const lastObservedIntentEnabled = new Map<string, boolean>()
174
+
175
+ /** Record the gate input the pass last evaluated for this session. */
176
+ export function observeIntentEnabled(sessionId: string, enabled: boolean): void {
177
+ lastObservedIntentEnabled.set(sessionId, enabled)
178
+ }
179
+
180
+ /** The settings-side enabled flag last observed for the session, if any. */
181
+ export function getObservedIntentEnabled(sessionId: string): boolean | undefined {
182
+ return lastObservedIntentEnabled.get(sessionId)
183
+ }
184
+
185
+ /** One landed intent fold, kept for `/ctx-summary status` (one per session). */
186
+ export interface IntentFoldRecord {
187
+ readonly turn: number
188
+ readonly startSeq: number
189
+ readonly endSeq: number
190
+ readonly liveTokensBefore: number
191
+ readonly at: number
192
+ }
193
+
194
+ const lastIntentFolds = new Map<string, IntentFoldRecord>()
195
+
196
+ /** Record a landed intent fold for the session (newest wins). */
197
+ export function recordIntentFold(sessionId: string, record: IntentFoldRecord): void {
198
+ lastIntentFolds.set(sessionId, record)
199
+ }
200
+
201
+ /** The most recent landed intent fold for the session, if any. */
202
+ export function getLastIntentFold(sessionId: string): IntentFoldRecord | undefined {
203
+ return lastIntentFolds.get(sessionId)
204
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Turn-tail intent summary: pending-fold types and pure block builders
3
+ * (task_2.4/2.5). The pass orchestration lives in the pruner (it owns the
4
+ * channel, gate inputs, and landing machinery); this module owns the data
5
+ * contract and the deterministic intent-block rendering. The model writes
6
+ * ONLY the summary segment — block rendering here is fully deterministic.
7
+ */
8
+ import type { IntentRole } from './intent-input-mask.ts'
9
+
10
+ /** One staged fold awaiting the next pressure round. */
11
+ export interface PendingIntentFold {
12
+ readonly createdAt: number
13
+ readonly turn: number
14
+ /** Inclusive seq span of the folded candidates. */
15
+ readonly startSeq: number
16
+ readonly endSeq: number
17
+ /** LLM-written summary segment (fail-open parsed, char-capped). */
18
+ readonly summary: string
19
+ /** Verbatim error lines collected across the batch (never LLM-revoiced). */
20
+ readonly errorLines: readonly string[]
21
+ /** Per-candidate faces: read-mask single lines ride the block, keep-class lines prompt-only. */
22
+ readonly records: ReadonlyArray<{ readonly seq: number, readonly role: IntentRole, readonly toolName: string, readonly line: string }>
23
+ /** Characters consumed by the summary-writer call (credit accounting). */
24
+ readonly summaryCallChars: number
25
+ }
26
+
27
+ /** Marker written into every folded block; its presence makes a seq unfoldable again (fold-once). */
28
+ export const INTENT_FOLD_MARKER = '[Intent summary'
29
+
30
+ /** Render the replacement text for one folded candidate. Pure. */
31
+ export function renderIntentFoldBlock(pending: PendingIntentFold, seq: number): string {
32
+ const start = pending.startSeq
33
+ const end = pending.endSeq
34
+ if (seq === start) {
35
+ const readLines = pending.records
36
+ .filter(record => record.role === 'read-mask')
37
+ .map(record => record.line)
38
+ const consulted = readLines.length > 0 ? `Consulted: ${readLines.join('; ')}` : ''
39
+ const errorBlock = pending.errorLines.length > 0
40
+ ? `\nError lines (verbatim):\n${pending.errorLines.join('\n')}`
41
+ : ''
42
+ return [
43
+ `${INTENT_FOLD_MARKER} of folded tool results seq ${start}..${end}]`,
44
+ pending.summary,
45
+ consulted,
46
+ errorBlock,
47
+ '[Original content remains in the session log at the listed seq values.]',
48
+ ].filter(part => part.length > 0).join('\n')
49
+ }
50
+ const record = pending.records.find(entry => entry.seq === seq)
51
+ const face = record === undefined ? `${seq}` : record.role === 'read-mask' ? record.line : `${record.toolName} result folded into the batch intent summary`
52
+ return `${INTENT_FOLD_MARKER} folded into the batch summary above (seq ${start}..${end})] ${face}`
53
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Turn-tail intent-summary growth gate (TokenPilot-inspired E2).
3
+ *
4
+ * Pure decision helper evaluated at the turn-boundary postflight: it decides
5
+ * whether this turn may spend a summary-writer LLM call and stage a fold for
6
+ * the next pressure round. The gate is deliberately conservative — every
7
+ * unresolved input (unknown context window, non-finite counters) fails closed
8
+ * toward "do not run", because a skipped fold is free while a wasted summary
9
+ * call is not. Content safety is unaffected either way: fail-open semantics
10
+ * live in the fold landing path, not here.
11
+ */
12
+
13
+ /** Floor: the live surface must exceed this fraction of the context window. */
14
+ export const INTENT_GATE_FLOOR_FRACTION = 0.45
15
+
16
+ /** Growth: the live surface must have grown by more than this since the last landed fold. */
17
+ export const INTENT_GATE_GROWTH_TOKENS = 50_000
18
+
19
+ /** Session-scoped user override set through `/ctx-summary off|on`. */
20
+ export type SummaryOverride = 'on' | 'off' | undefined
21
+
22
+ export interface IntentGateInput {
23
+ /** Frozen `intentSummary.enabled` setting for the session. */
24
+ enabled: boolean
25
+ /** `/ctx-summary` override; `'off'` wins over everything, `'on'` never bypasses the numeric gates. */
26
+ override: SummaryOverride
27
+ /** Exact live-surface token estimate from the compaction view. */
28
+ liveTokens: number
29
+ /** Host context window in tokens; `undefined` fails the floor check. */
30
+ contextWindow: number | undefined
31
+ /** Live-surface tokens at the time the last fold landed (0 = never folded). */
32
+ baselineTokens: number
33
+ }
34
+
35
+ export interface IntentGateSnapshot extends IntentGateInput {
36
+ readonly decision: boolean
37
+ readonly reason: 'disabled' | 'override-off' | 'no-window' | 'below-floor' | 'below-growth' | 'passed'
38
+ }
39
+
40
+ function isUsableNumber(value: number): boolean {
41
+ return Number.isFinite(value) && value >= 0
42
+ }
43
+
44
+ /** Evaluate the growth gate. Boundary-exact: equality never triggers. */
45
+ export function shouldRunIntentFold(input: IntentGateInput): boolean {
46
+ return evaluateIntentGate(input).decision === true
47
+ }
48
+
49
+ /** Same evaluation with the reason attached, for audits and `/ctx-summary status`. */
50
+ export function evaluateIntentGate(input: IntentGateInput): IntentGateSnapshot {
51
+ const snapshot = (decision: boolean, reason: IntentGateSnapshot['reason']): IntentGateSnapshot => ({
52
+ ...input,
53
+ decision,
54
+ reason,
55
+ })
56
+ if (!input.enabled) return snapshot(false, 'disabled')
57
+ if (input.override === 'off') return snapshot(false, 'override-off')
58
+ if (!isUsableNumber(input.liveTokens)) return snapshot(false, 'below-floor')
59
+ if (input.contextWindow === undefined || !isUsableNumber(input.contextWindow)) return snapshot(false, 'no-window')
60
+ if (!(input.liveTokens > input.contextWindow * INTENT_GATE_FLOOR_FRACTION)) return snapshot(false, 'below-floor')
61
+ if (!isUsableNumber(input.baselineTokens)) return snapshot(false, 'below-growth')
62
+ const growth = input.liveTokens - input.baselineTokens
63
+ if (!(growth > INTENT_GATE_GROWTH_TOKENS)) return snapshot(false, 'below-growth')
64
+ return snapshot(true, 'passed')
65
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Semantic-role input masking for the intent-summary writer (task_2.2).
3
+ *
4
+ * The intent summary records historical TASK semantics — for read-class tools
5
+ * the semantics are "read X", never the file body, so the body is masked to a
6
+ * one-line record before it can reach the summary prompt. Write-class results
7
+ * (edits) ARE task semantics and keep their skeleton + verbatim error lines.
8
+ *
9
+ * Classification REUSES `classifyToolSource()` (reducers.ts routes on the
10
+ * same classes): hand-rolling a name→role map here would regress its fixed
11
+ * misclassification edges (mcp→generic, web_search/memory_search not being
12
+ * content search, glob being path-listing, execute_sql not being shell).
13
+ * Only the write class is layered on top — `ToolClass` has no write member.
14
+ */
15
+ import { classifyToolSource, type ToolClass } from '../toolclass.ts'
16
+
17
+ export type IntentRole = 'read-mask' | 'write-keep' | 'conservative'
18
+
19
+ /** Exact-token write layer, same tokenization discipline as toolclass. */
20
+ const WRITE_NAMES = new Set(['apply_patch', 'multi_edit', 'create_file', 'write_to_file', 'str_replace_editor'])
21
+ const WRITE_TOKENS = new Set(['write', 'edit', 'patch'])
22
+
23
+ function hasWriteToken(name: string): boolean {
24
+ const lowered = name.toLowerCase()
25
+ if (WRITE_NAMES.has(lowered)) return true
26
+ return lowered.split(/[-_/]+/).some(token => WRITE_TOKENS.has(token))
27
+ }
28
+
29
+ /**
30
+ * Role for one candidate. The write layer is consulted first; everything
31
+ * else defers to the shared classifier. `shell`/`generic` stay conservative
32
+ * (skeleton + error lines, never a blind mask) — a bash result can be a
33
+ * mutation even when its name says nothing.
34
+ */
35
+ export function classifyIntentRole(toolName: string, command: string, text?: string): IntentRole {
36
+ if (hasWriteToken(toolName)) return 'write-keep'
37
+ const toolClass: ToolClass = classifyToolSource(toolName, command, text)
38
+ if (toolClass === 'read' || toolClass === 'search' || toolClass === 'path-listing') return 'read-mask'
39
+ return 'conservative'
40
+ }
41
+
42
+ /** One candidate's slimmed face for the summary prompt. */
43
+ export interface MaskedCandidate {
44
+ readonly seq: number
45
+ readonly role: IntentRole
46
+ /** Read-mask single line; skeleton/error lines for keep roles. */
47
+ readonly record: string
48
+ }
49
+
50
+ const ERROR_LINE_PATTERN = /\b(error|failed|failure|exception|panic|fatal|traceback|unreachable|denied)\b/i
51
+ const KEEP_HEAD_LINES = 40
52
+ const KEEP_HEAD_CHARS = 2_000
53
+
54
+ /** Verbatim error/warn lines kept out of the LLM's hands and into the intent block. */
55
+ export function extractErrorLines(text: string): string[] {
56
+ return text.split('\n').filter(line => ERROR_LINE_PATTERN.test(line)).slice(0, 10)
57
+ }
58
+
59
+ /** Count lines and code points for the read-mask record tail. */
60
+ function scaleOf(text: string): { lines: number, chars: number } {
61
+ const lines = text.length === 0 ? 0 : text.split('\n').length
62
+ return { lines, chars: text.length }
63
+ }
64
+
65
+ /**
66
+ * Build the prompt face for one candidate. Read-mask output contains NONE of
67
+ * the original body — only the tool name, the call's target argument, and
68
+ * the dropped scale — so a hostile body can never leak into the summary.
69
+ */
70
+ export function maskCandidateForSummary(
71
+ seq: number,
72
+ toolName: string,
73
+ argumentsText: string,
74
+ text: string,
75
+ ): MaskedCandidate {
76
+ const role = classifyIntentRole(toolName, extractCommand(argumentsText), text)
77
+ if (role === 'read-mask') {
78
+ const { lines, chars } = scaleOf(text)
79
+ return {
80
+ seq,
81
+ role,
82
+ record: `${toolName} ${extractTarget(argumentsText)} -> masked (${lines} lines / ${chars} chars)`,
83
+ }
84
+ }
85
+ const head = text.split('\n', KEEP_HEAD_LINES).join('\n').slice(0, KEEP_HEAD_CHARS)
86
+ const errorLines = extractErrorLines(text)
87
+ const errorBlock = errorLines.length > 0 ? `\nerror lines (verbatim):\n${errorLines.join('\n')}` : ''
88
+ return {
89
+ seq,
90
+ role,
91
+ record: `${toolName} (seq ${seq})\n${head}${errorBlock}`,
92
+ }
93
+ }
94
+
95
+ /** Extract a short command head from a tool-call arguments JSON string. */
96
+ function extractCommand(argumentsText: string): string {
97
+ try {
98
+ const parsed: unknown = JSON.parse(argumentsText)
99
+ if (parsed !== null && typeof parsed === 'object') {
100
+ const command = (parsed as { command?: unknown }).command
101
+ if (typeof command === 'string') return command.slice(0, 200)
102
+ }
103
+ } catch {
104
+ // arguments are free-form for some tools; classification still works.
105
+ }
106
+ return ''
107
+ }
108
+
109
+ /** Extract the most target-like string argument (path/query/url) for read-mask records. */
110
+ export function extractTarget(argumentsText: string): string {
111
+ try {
112
+ const parsed: unknown = JSON.parse(argumentsText)
113
+ if (parsed !== null && typeof parsed === 'object') {
114
+ const record = parsed as Record<string, unknown>
115
+ const target = [record.path, record.file_path, record.query, record.url, record.pattern, record.glob]
116
+ .find(candidate => typeof candidate === 'string' && candidate.trim().length > 0)
117
+ if (typeof target === 'string') return target.slice(0, 160)
118
+ const first = Object.values(record).find(value => typeof value === 'string')
119
+ if (typeof first === 'string') return first.slice(0, 160)
120
+ }
121
+ } catch {
122
+ // free-form arguments degrade to an unlabeled mask record
123
+ }
124
+ return '(unparsed target)'
125
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Deterministic fold-range selection for the turn-tail intent summary
3
+ * (task_2.1). The host — never the model — decides WHAT gets folded: the
4
+ * consumed increment outside the protected working set, oldest-first
5
+ * (tail-biased folding keeps the cached request prefix byte-stable).
6
+ */
7
+ import type { SnapshotCandidate } from '../../pruner/types.ts'
8
+
9
+ /** Per-batch cap: one pass never folds more than this many candidates. */
10
+ export const INTENT_RANGE_MAX_CANDIDATES = 20
11
+
12
+ export interface IntentRangeInput {
13
+ /** Pressure candidates already filtered to safe/eligible faces by the caller. */
14
+ readonly candidates: readonly SnapshotCandidate[]
15
+ /** Protected working-set seqs (never foldable). */
16
+ readonly protectedSeqs: ReadonlySet<number>
17
+ /** Already-folded seqs (fold-once: never reconsidered). */
18
+ readonly foldedSeqs: ReadonlySet<number>
19
+ /** Per-batch cap so one pass cannot fold unboundedly. */
20
+ readonly maxCandidates: number
21
+ }
22
+
23
+ /**
24
+ * Oldest-first selection of foldable candidates. Excludes the protected
25
+ * working set and already-folded seqs; caps the batch size.
26
+ */
27
+ export function computeIntentRange(
28
+ input: IntentRangeInput,
29
+ ): { readonly seqs: number[], readonly skippedProtected: number, readonly skippedFolded: number } {
30
+ const unprotected = input.candidates.filter(candidate => !input.protectedSeqs.has(candidate.seq))
31
+ const skippedProtected = input.candidates.length - unprotected.length
32
+ const eligible = unprotected.filter(candidate => !input.foldedSeqs.has(candidate.seq))
33
+ const skippedFolded = unprotected.length - eligible.length
34
+ // Oldest-first: seq ascending == oldest first in the append-only log.
35
+ const ordered = [...eligible].sort((a, b) => a.seq - b.seq)
36
+ return { seqs: ordered.slice(0, Math.max(0, input.maxCandidates)).map(candidate => candidate.seq), skippedProtected, skippedFolded }
37
+ }
@@ -131,6 +131,21 @@ export interface CodeSkeletonSettings {
131
131
  enabled: boolean
132
132
  }
133
133
 
134
+ /**
135
+ * Orthogonal turn-tail intent-summary gate. Independent of every profile:
136
+ * when enabled, the turn-boundary growth gate may fold consumed-increment
137
+ * tool results into an LLM-written intent block (skeleton + verbatim error
138
+ * lines are kept; the model only ever writes the summary segment).
139
+ */
140
+ export interface IntentSummarySettings {
141
+ enabled: boolean
142
+ }
143
+
144
+ /** Floating compression-monitor panel (FAB); visibility switch. */
145
+ export interface MonitorPanelSettings {
146
+ enabled: boolean
147
+ }
148
+
134
149
  /**
135
150
  * Persisted sub-capability overrides for the `tokenpilot-inspired` preset.
136
151
  * Absent fields inherit the preset defaults; the section is only meaningful
@@ -171,6 +186,10 @@ export interface ContextCompressionSettings {
171
186
  autoCompact: AutoCompactSettings
172
187
  /** Code-skeleton reducer gate snapped independently of `profile`. */
173
188
  codeSkeleton: CodeSkeletonSettings
189
+ /** Turn-tail intent-summary gate snapped independently of `profile`. */
190
+ intentSummary: IntentSummarySettings
191
+ /** Floating compression-monitor panel (FAB); absent inherits hidden. */
192
+ monitorPanel?: MonitorPanelSettings
174
193
  /** Optional tokenpilot-inspired sub-capability overrides; absent inherits preset defaults. */
175
194
  presetOptions?: PresetOptionsSettings
176
195
  }
@@ -90,6 +90,7 @@ function mountAutoCompact(options: MountOptions = {}) {
90
90
  custom: structuredClone(DEFAULT_CUSTOM),
91
91
  autoCompact: { thresholdPercent: 80 },
92
92
  codeSkeleton: { enabled: false },
93
+ intentSummary: { enabled: false },
93
94
  },
94
95
  base: undefined,
95
96
  user: undefined,
@@ -153,7 +154,7 @@ describe('Auto Compact threshold controls', () => {
153
154
  cleanup()
154
155
  mountAutoCompact({
155
156
  settingsSection: true,
156
- value: { profile: 'balanced', custom: structuredClone(DEFAULT_CUSTOM), autoCompact: { thresholdPercent: 73 }, codeSkeleton: { enabled: false } },
157
+ value: { profile: 'balanced', custom: structuredClone(DEFAULT_CUSTOM), autoCompact: { thresholdPercent: 73 }, codeSkeleton: { enabled: false }, intentSummary: { enabled: false } },
157
158
  })
158
159
  expect(screen.getByLabelText<HTMLInputElement>(INPUT_LABEL).value).toBe('73')
159
160
  })
@@ -23,6 +23,7 @@ describe('codeSkeleton confirm-on-write client contract', () => {
23
23
  custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
24
24
  autoCompact: { thresholdPercent: 80 },
25
25
  codeSkeleton: { enabled: false },
26
+ intentSummary: { enabled: false },
26
27
  }
27
28
  const snapshot = (): SettingsScopeSnapshot<ContextCompressionSettings> => ({
28
29
  status: 'ready',
@@ -56,9 +57,9 @@ describe('codeSkeleton confirm-on-write client contract', () => {
56
57
  settingsScope: { bind: vi.fn(() => scope) },
57
58
  slots: {
58
59
  inject: (_slot: string, install: () => unknown) => { install() },
59
- register: (registration: { inject?: () => CompressionSelectorInjected }) => {
60
+ register: (registration: { name?: string, inject?: () => CompressionSelectorInjected }) => {
60
61
  // The R4 overlay registration carries no inject face; keep the card's.
61
- if (typeof registration.inject === 'function') injected = registration.inject
62
+ if (registration.name === 'settings.section' && typeof registration.inject === 'function') injected = registration.inject
62
63
  return () => {}
63
64
  },
64
65
  },
@@ -88,6 +88,7 @@ describe('context compression browser contract', () => {
88
88
  custom: structuredClone(CUSTOM),
89
89
  autoCompact: { thresholdPercent: 80 },
90
90
  codeSkeleton: { enabled: false },
91
+ intentSummary: { enabled: false },
91
92
  }
92
93
  const snapshot = (): SettingsScopeSnapshot<ContextCompressionSettings> => ({
93
94
  status: 'ready',
@@ -148,9 +149,9 @@ describe('context compression browser contract', () => {
148
149
  settingsScope: { bind: vi.fn(() => scope) },
149
150
  slots: {
150
151
  inject: (_slot: string, install: () => unknown) => { install() },
151
- register: (registration: { inject?: () => CompressionSelectorInjected }) => {
152
+ register: (registration: { name?: string, inject?: () => CompressionSelectorInjected }) => {
152
153
  // The R4 overlay registration carries no inject face; keep the card's.
153
- if (typeof registration.inject === 'function') injected = registration.inject
154
+ if (registration.name === 'settings.section' && typeof registration.inject === 'function') injected = registration.inject
154
155
  return () => {}
155
156
  },
156
157
  },
@@ -99,6 +99,7 @@ function mountEstimator(
99
99
  custom: structuredClone(DEFAULT_CUSTOM),
100
100
  autoCompact: { thresholdPercent: 80 },
101
101
  codeSkeleton: { enabled: false },
102
+ intentSummary: { enabled: false },
102
103
  presetOptions: presetOptions ?? {},
103
104
  },
104
105
  base: undefined,