dsh-context-compression-improved 0.10.5 → 0.11.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 (85) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/CHANGELOG.zh.md +9 -0
  3. package/README.de.md +1 -1
  4. package/assets/dshfind-card.svg +33 -0
  5. package/docs/shallow-teaching-preset-template.md +46 -0
  6. package/package.json +6 -6
  7. package/packages/selector/dsh.plugin.json +2 -2
  8. package/packages/selector/lib/client.d.ts +8 -0
  9. package/packages/selector/lib/client.js +212 -3
  10. package/packages/selector/lib/index.js +1 -1
  11. package/packages/selector/lib/profiles.d.ts +34 -0
  12. package/packages/selector/lib/pruner.d.ts +55 -0
  13. package/packages/selector/lib/pruner.js +1925 -303
  14. package/packages/selector/lib/savings-integral.js +126 -3
  15. package/packages/selector/lib/tool-result.js +9 -1
  16. package/packages/selector/package.json +21 -21
  17. package/packages/selector/src/client/CompressionProfileControls.tsx +33 -0
  18. package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
  19. package/packages/selector/src/client/decode.ts +5 -1
  20. package/packages/selector/src/client/index.ts +4 -0
  21. package/packages/selector/src/client/locales/de.ts +7 -0
  22. package/packages/selector/src/client/locales/es.ts +7 -0
  23. package/packages/selector/src/client/locales/fr.ts +7 -0
  24. package/packages/selector/src/client/locales/it.ts +7 -0
  25. package/packages/selector/src/client/locales/ja.ts +7 -0
  26. package/packages/selector/src/client/locales/ko.ts +7 -0
  27. package/packages/selector/src/client/locales/ru.ts +7 -0
  28. package/packages/selector/src/client/locales.ts +14 -0
  29. package/packages/selector/src/client/monitor-fab.ts +14 -0
  30. package/packages/selector/src/client/settings-section.tsx +9 -2
  31. package/packages/selector/src/profiles.ts +103 -0
  32. package/packages/selector/src/pruner.ts +310 -4
  33. package/packages/selector/src/runtime/audit.ts +1 -0
  34. package/packages/selector/src/runtime/config.ts +88 -1
  35. package/packages/selector/src/runtime/fold-router.ts +143 -0
  36. package/packages/selector/src/runtime/monitor.ts +31 -0
  37. package/packages/selector/src/runtime/reducers.ts +1 -1
  38. package/packages/selector/src/runtime/sediment-card.ts +126 -0
  39. package/packages/selector/src/runtime/sediment-clock.ts +87 -0
  40. package/packages/selector/src/runtime/sediment-guard.ts +136 -0
  41. package/packages/selector/src/runtime/sediment-publish.ts +144 -0
  42. package/packages/selector/src/runtime/sediment-span.ts +170 -0
  43. package/packages/selector/src/runtime/sediment.ts +209 -0
  44. package/packages/selector/src/runtime/shallow-tools.ts +342 -0
  45. package/packages/selector/src/runtime/tool-names.ts +6 -0
  46. package/packages/selector/src/runtime/triage/masks.ts +128 -0
  47. package/packages/selector/src/runtime/triage/shallow.ts +132 -0
  48. package/packages/selector/src/runtime/triage/signals.ts +167 -0
  49. package/packages/selector/src/runtime/triage/types.ts +125 -0
  50. package/packages/selector/src/runtime/types.ts +28 -0
  51. package/packages/selector/tests/fixtures/sediment-pool/52adc205-cloud-5.orig.txt +231 -0
  52. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-25.orig.txt +236 -0
  53. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-38.orig.txt +220 -0
  54. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-42.orig.txt +140 -0
  55. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-53.orig.txt +117 -0
  56. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-local-10.orig.txt +67 -0
  57. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-45.orig.txt +119 -0
  58. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-49.orig.txt +119 -0
  59. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-63.orig.txt +131 -0
  60. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-75.orig.txt +196 -0
  61. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-76.orig.txt +71 -0
  62. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-85.orig.txt +126 -0
  63. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-86.orig.txt +86 -0
  64. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-87.orig.txt +50 -0
  65. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-96.orig.txt +102 -0
  66. package/packages/selector/tests/public/package-contract.client.spec.ts +7 -4
  67. package/packages/selector/tests/runtime/fold-router.spec.ts +140 -0
  68. package/packages/selector/tests/runtime/sediment-card.spec.ts +111 -0
  69. package/packages/selector/tests/runtime/sediment-config.spec.ts +56 -0
  70. package/packages/selector/tests/runtime/sediment-guard.spec.ts +71 -0
  71. package/packages/selector/tests/runtime/sediment-masks.spec.ts +95 -0
  72. package/packages/selector/tests/runtime/sediment-orchestrator.spec.ts +166 -0
  73. package/packages/selector/tests/runtime/sediment-pool-share.spec.ts +65 -0
  74. package/packages/selector/tests/runtime/sediment-publish.spec.ts +142 -0
  75. package/packages/selector/tests/runtime/sediment-real-shapes.spec.ts +158 -0
  76. package/packages/selector/tests/runtime/sediment-settings.spec.ts +73 -0
  77. package/packages/selector/tests/runtime/sediment-signals.spec.ts +124 -0
  78. package/packages/selector/tests/runtime/sediment-span.spec.ts +92 -0
  79. package/packages/selector/tests/runtime/shallow-primitives.spec.ts +135 -0
  80. package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
  81. package/scripts/hosts.d.mts +3 -0
  82. package/scripts/hosts.mjs +3 -1
  83. package/scripts/sediment-latency-report.mjs +63 -0
  84. package/scripts/verify-release.mjs +7 -2
  85. package/$null +0 -1
@@ -0,0 +1,342 @@
1
+ /**
2
+ * Shallow-read tool surface (plan cci-sedimentation-triage, Phase 4.5).
3
+ *
4
+ * Registers the upgrade-discard primitives next to the existing retrieve tool:
5
+ * - `context_compression_probe` — O(1) header sample → recommended shallow view
6
+ * - `context_compression_shallow` — the map: classified shallow view + checkpoint
7
+ * - `context_compression_discard` — drops one side of a shallow/full pair,
8
+ * guarded so the MAP only dies under full coverage; the checkpoint line
9
+ * always survives (R11).
10
+ *
11
+ * The decision core is exported pure (`buildShallowView`, `parseReadCoverage`,
12
+ * registry helpers) so the guard arithmetic is unit-testable without a host;
13
+ * `installShallowTools` only adapts those to `defineTool`.
14
+ */
15
+ import fs from 'node:fs/promises'
16
+ import path from 'node:path'
17
+ import type { Context } from '@deepseek-ai/cordis'
18
+ import type { SessionSeq as SessionSeqBrand } from '@deepseek-ai/dsh-session'
19
+ import { defineTool } from '@deepseek-ai/dsh-tools'
20
+ import { PTC_BINDING_NOTE, RUNTIME_TOOL_NAMES } from './tool-names.ts'
21
+ import {
22
+ buildShallowFooter,
23
+ classifyShallowSample,
24
+ evaluateDiscardGuard,
25
+ normalizeToolPath,
26
+ renderCheckpointLine,
27
+ shallowFingerprint,
28
+ type ReadPairSide,
29
+ } from './triage/shallow.ts'
30
+ import { skeletonFromRead } from './triage/masks.ts'
31
+ import { sessionEvents } from './session-events.ts'
32
+ import { getSavingsLedger } from './savings.ts'
33
+ import { tailTrimMessage } from './tail-trim.ts'
34
+ import type { ShallowCheckpoint } from './triage/types.ts'
35
+
36
+ const PROBE_SAMPLE_BYTES = 2_048
37
+ const SHALLOW_MAX_BYTES = 2_000_000
38
+ const REF_PATTERN = /^session:\/\/([^/]+)\/event\/(\d+)$/
39
+
40
+ /** Live shallow maps per session, keyed by normalized path. */
41
+ export interface ShallowEntry {
42
+ readonly seq: number
43
+ readonly checkpoint: ShallowCheckpoint
44
+ readonly bodyTokens: number
45
+ discarded: boolean
46
+ }
47
+
48
+ const registry = new WeakMap<object, Map<string, ShallowEntry>>()
49
+
50
+ export function shallowRegistryFor(session: object): Map<string, ShallowEntry> {
51
+ let map = registry.get(session)
52
+ if (map === undefined) {
53
+ map = new Map()
54
+ registry.set(session, map)
55
+ }
56
+ return map
57
+ }
58
+
59
+ /** The live (undiscarded) map for a path, if any — footer pairing source. */
60
+ export function liveShallowFor(session: object, rawPath: string): ShallowEntry | undefined {
61
+ const entry = shallowRegistryFor(session).get(normalizeToolPath(rawPath))
62
+ return entry !== undefined && !entry.discarded ? entry : undefined
63
+ }
64
+
65
+ /** Pure view builder shared by the shallow tool and tests. */
66
+ export function buildShallowView(
67
+ text: string,
68
+ method: ReturnType<typeof classifyShallowSample>['method'],
69
+ rawPath: string,
70
+ seq: number,
71
+ ): { readonly body: string; readonly checkpoint: ShallowCheckpoint | null } {
72
+ const lines = text.replace(/\n+$/, '').split('\n')
73
+ const checkpointBase = {
74
+ path: normalizeToolPath(rawPath),
75
+ coverage: `${lines.length} lines`,
76
+ ref: `event/${seq}`,
77
+ fingerprint: shallowFingerprint(text),
78
+ }
79
+ if (method === 'code-skeleton') {
80
+ const verdict = skeletonFromRead(text, seq, rawPath)
81
+ if (verdict !== null && verdict.kind === 'skeleton') {
82
+ const body = `${verdict.lines.join('\n')}\n[… body elided: ${verdict.totalLines - verdict.lines.length} lines / ${verdict.elidedChars} chars]`
83
+ return { body, checkpoint: verdict.checkpoint ?? { ...checkpointBase } }
84
+ }
85
+ // zero-hit code: honest head/tail instead of an empty skeleton
86
+ return headTailView(lines, checkpointBase)
87
+ }
88
+ if (method === 'json-skeleton') {
89
+ try {
90
+ const parsed: unknown = JSON.parse(text)
91
+ const keys: string[] = []
92
+ collectJsonKeys(parsed, '', keys, 40)
93
+ if (keys.length === 0) return headTailView(lines, checkpointBase)
94
+ return { body: `${keys.join('\n')}\n[… ${lines.length} lines of JSON values elided]`, checkpoint: { ...checkpointBase } }
95
+ } catch {
96
+ return headTailView(lines, checkpointBase)
97
+ }
98
+ }
99
+ if (method === 'csv-header') {
100
+ const header = lines.slice(0, 3).join('\n')
101
+ return { body: `${header}\n[… ${Math.max(0, lines.length - 3)} data rows elided]`, checkpoint: { ...checkpointBase } }
102
+ }
103
+ if (method === 'toc-lines') {
104
+ const headings = lines.filter(line => /^#{1,6} |^\s*\*\*\w/.test(line)).slice(0, 60)
105
+ if (headings.length === 0) return headTailView(lines, checkpointBase)
106
+ return { body: `${headings.join('\n')}\n[… ${lines.length} lines under the outline elided]`, checkpoint: { ...checkpointBase } }
107
+ }
108
+ return headTailView(lines, checkpointBase)
109
+ }
110
+
111
+ function headTailView(
112
+ lines: string[],
113
+ base: ShallowCheckpoint,
114
+ ): { body: string; checkpoint: ShallowCheckpoint } {
115
+ const head = lines.slice(0, 20)
116
+ const tail = lines.slice(-10)
117
+ const middle = Math.max(0, lines.length - head.length - tail.length)
118
+ return {
119
+ body: [...head, ...(middle > 0 ? [`[… ${middle} lines elided]`] : []), ...tail].join('\n'),
120
+ checkpoint: base,
121
+ }
122
+ }
123
+
124
+ function collectJsonKeys(node: unknown, prefix: string, out: string[], cap: number): void {
125
+ if (out.length >= cap) return
126
+ if (Array.isArray(node)) {
127
+ out.push(`${prefix}[] (${node.length})`)
128
+ if (node.length > 0) collectJsonKeys(node[0], `${prefix}[]`, out, cap)
129
+ return
130
+ }
131
+ if (node !== null && typeof node === 'object') {
132
+ for (const [key, value] of Object.entries(node)) {
133
+ if (out.length >= cap) return
134
+ const at = `${prefix}.${key}`.replace(/^\./, '')
135
+ if (value !== null && typeof value === 'object') collectJsonKeys(value, at, out, cap)
136
+ else out.push(at)
137
+ }
138
+ }
139
+ }
140
+
141
+ /** Coverage of a host `read` call from its arguments JSON (pairing input). */
142
+ export function parseReadCoverage(argsJson: string): ReadPairSide['coverage'] {
143
+ let args: Record<string, unknown>
144
+ try {
145
+ args = JSON.parse(argsJson) as Record<string, unknown>
146
+ } catch {
147
+ return { kind: 'slice', from: 1, to: 0 } // matches nothing
148
+ }
149
+ const offset = typeof args.offset === 'number' && Number.isSafeInteger(args.offset) ? Math.max(0, args.offset) : 0
150
+ const limit = typeof args.limit === 'number' && Number.isSafeInteger(args.limit) ? args.limit : undefined
151
+ if (limit === undefined && offset === 0) return { kind: 'full' }
152
+ const from = offset + 1
153
+ const to = limit === undefined ? Number.MAX_SAFE_INTEGER : offset + limit
154
+ return { kind: 'slice', from, to }
155
+ }
156
+
157
+ /**
158
+ * Register probe/shallow/discard. Reachability and the pairing registry are
159
+ * in-process truth; every tool call stays inside the caller's own session.
160
+ */
161
+ export function installShallowTools(ctx: Context): void {
162
+ const OUTPUT = {
163
+ schema: { type: 'string' as const },
164
+ render: (_args: unknown, value: string) => [{ type: 'text' as const, text: value }],
165
+ }
166
+
167
+ ctx.systemPrompt.section({
168
+ name: 'tool:context-compression-shallow',
169
+ order: 115,
170
+ text: `Before reading a large unknown file, call ${RUNTIME_TOOL_NAMES.PROBE} with its path to pick the right shallow view, then ${RUNTIME_TOOL_NAMES.SHALLOW} to get the map (declaration/outline/keys + checkpoint line) instead of the full body. `
171
+ + `After a full read supersedes a live map, or a map's body is no longer needed, ${RUNTIME_TOOL_NAMES.DISCARD} frees it — the checkpoint line always remains and ${RUNTIME_TOOL_NAMES.RETRIEVE} can still recover the body. `
172
+ + 'Never reconstitute discarded output from memory or guesswork; use the ref. '
173
+ + PTC_BINDING_NOTE,
174
+ })
175
+
176
+ ctx.tools.register(defineTool({
177
+ name: RUNTIME_TOOL_NAMES.PROBE,
178
+ description: `Read at most the first ${PROBE_SAMPLE_BYTES} bytes of a file and return the recommended shallow view method with reasons. ${PTC_BINDING_NOTE}`,
179
+ parameters: {
180
+ path: { type: 'string', required: true, description: 'File path to probe.' },
181
+ },
182
+ output: OUTPUT,
183
+ isConcurrencySafe: () => true,
184
+ async execute(args) {
185
+ const handle = await fs.open(args.path, 'r')
186
+ try {
187
+ const buffer = Buffer.alloc(PROBE_SAMPLE_BYTES)
188
+ const { bytesRead } = await handle.read(buffer, 0, PROBE_SAMPLE_BYTES, 0)
189
+ const stat = await handle.stat()
190
+ const verdict = classifyShallowSample(
191
+ buffer.subarray(0, bytesRead).toString('utf8'),
192
+ path.extname(args.path),
193
+ stat.size,
194
+ )
195
+ return `${verdict.method} | ${verdict.reason} | size ${stat.size} B`
196
+ } finally {
197
+ await handle.close()
198
+ }
199
+ },
200
+ }))
201
+
202
+ ctx.tools.register(defineTool({
203
+ name: RUNTIME_TOOL_NAMES.SHALLOW,
204
+ description: 'Return a shallow view (declaration skeleton / JSON keys / outline / csv header + head/tail) of a file plus its permanent checkpoint line. Cheaper than a full read; pairs with discard and retrieve. ' + PTC_BINDING_NOTE,
205
+ parameters: {
206
+ path: { type: 'string', required: true, description: 'File path to view shallowly.' },
207
+ method: { type: 'string', description: `Override the classified view: json-skeleton | code-skeleton | csv-header | toc-lines | head-tail.` },
208
+ },
209
+ output: OUTPUT,
210
+ isConcurrencySafe: () => true,
211
+ async execute(args, exec) {
212
+ if (exec.agent === undefined) throw new Error(`${RUNTIME_TOOL_NAMES.SHALLOW} requires an agent session`)
213
+ const stat = await fs.stat(args.path)
214
+ if (stat.size > SHALLOW_MAX_BYTES) {
215
+ throw new Error(`${RUNTIME_TOOL_NAMES.SHALLOW}: file is ${stat.size} B, above the ${SHALLOW_MAX_BYTES} B shallow cap; read slices instead`)
216
+ }
217
+ const text = await fs.readFile(args.path, 'utf8')
218
+ const method = (args.method ?? classifyShallowSample(
219
+ text.slice(0, PROBE_SAMPLE_BYTES), path.extname(args.path), stat.size,
220
+ ).method) as ReturnType<typeof classifyShallowSample>['method']
221
+ const events = sessionEvents(exec.agent.session as never)
222
+ const seq = events.length
223
+ const { body, checkpoint } = buildShallowView(text, method, args.path, seq)
224
+ if (checkpoint !== null) {
225
+ shallowRegistryFor(exec.agent.session).set(checkpoint.path, {
226
+ seq,
227
+ checkpoint,
228
+ bodyTokens: Math.ceil((body.length + checkpoint.path.length) / 4),
229
+ discarded: false,
230
+ })
231
+ return `${body}\n\n${renderCheckpointLine(checkpoint)}`
232
+ }
233
+ return body
234
+ },
235
+ }))
236
+
237
+ ctx.tools.register(defineTool({
238
+ name: RUNTIME_TOOL_NAMES.DISCARD,
239
+ description: 'Free one side of a shallow/full read pair from the context: the live shallow map (only when a covering full read spans it) or a full read whose map suffices. The checkpoint line always remains; retrieve can recover bodies by ref. ' + PTC_BINDING_NOTE,
240
+ parameters: {
241
+ ref: { type: 'string', required: true, description: 'session://<current-session-id>/event/<seq> of the shallow map to discard.' },
242
+ covering_ref: { type: 'string', description: 'event ref of the full read that supersedes the map (required to discard the map).' },
243
+ },
244
+ output: OUTPUT,
245
+ isConcurrencySafe: () => false,
246
+ async execute(args, exec) {
247
+ if (exec.agent === undefined) throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD} requires an agent session`)
248
+ const session = exec.agent.session
249
+ const match = REF_PATTERN.exec(args.ref)
250
+ if (match === null || match[1] !== String(session.id)) {
251
+ throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD}: ref must be session://<current-session-id>/event/<seq>`)
252
+ }
253
+ const targetSeq = Number(match[2])
254
+ const registryMap = shallowRegistryFor(session)
255
+ const entry = [...registryMap.values()].find(candidate => candidate.seq === targetSeq)
256
+ if (entry === undefined) {
257
+ throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD}: ${args.ref} is not a live shallow map of this session (only ${RUNTIME_TOOL_NAMES.SHALLOW} results are discardable here)`)
258
+ }
259
+ if (entry.discarded) return `${renderCheckpointLine(entry.checkpoint)} (already discarded)`
260
+ const coveringRef = args.covering_ref
261
+ if (coveringRef === undefined) {
262
+ throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD}: discarding the map requires covering_ref of the full read that supersedes it`)
263
+ }
264
+ const coveringMatch = REF_PATTERN.exec(coveringRef)
265
+ if (coveringMatch === null || coveringMatch[1] !== String(session.id)) {
266
+ throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD}: covering_ref must be in the current session`)
267
+ }
268
+ const events = sessionEvents(session as never) as unknown as ReadonlyArray<Record<string, unknown>>
269
+ const coveringEvent = events[Number(coveringMatch[2])]
270
+ if (coveringEvent?.type !== 'tool/result') {
271
+ throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD}: covering_ref does not cite a tool/result`)
272
+ }
273
+ const coveringMessage = (coveringEvent.data as Record<string, unknown> | undefined)?.message as Record<string, unknown> | undefined
274
+ const coveringArgs = typeof coveringMessage?.toolCallId === 'string'
275
+ ? findCallArgs(events, coveringMessage.toolCallId)
276
+ : undefined
277
+ const covering: ReadPairSide = {
278
+ seq: Number(coveringMatch[2]),
279
+ path: coveringArgs?.path ?? '',
280
+ coverage: coveringArgs === undefined
281
+ ? { kind: 'slice', from: 1, to: 0 }
282
+ : parseReadCoverage(coveringArgs.argsJson),
283
+ }
284
+ const mapSide: ReadPairSide = {
285
+ seq: entry.seq,
286
+ path: entry.checkpoint.path,
287
+ coverage: { kind: 'full' }, // a map stands for the whole file outline
288
+ }
289
+ const guard = evaluateDiscardGuard({ map: mapSide, covering })
290
+ if (!guard.allowed) {
291
+ throw new Error(`${RUNTIME_TOOL_NAMES.DISCARD}: refused (${guard.reason}) — the map covers the whole file and the cited read does not supersede it`)
292
+ }
293
+ const message = tailTrimMessage(renderCheckpointLine(entry.checkpoint))
294
+ session.append('user/message', message as never, {
295
+ surfaceOp: { op: 'replace', startSeq: entry.seq as SessionSeqBrand, endSeq: entry.seq as SessionSeqBrand },
296
+ sourceEventSeqs: [entry.seq as SessionSeqBrand],
297
+ })
298
+ entry.discarded = true
299
+ // 记账隔离(T4.9):模型发起的弃对节省单列 component,不与插件发起压缩混算。
300
+ getSavingsLedger().recordSaving({
301
+ sessionId: String(session.id),
302
+ component: 'shallow-discard',
303
+ tokensBefore: entry.bodyTokens,
304
+ tokensAfter: Math.ceil(renderCheckpointLine(entry.checkpoint).length / 4),
305
+ basis: 'characters',
306
+ sourceSeq: entry.seq,
307
+ replacementSeq: entry.seq,
308
+ originalText: `${entry.checkpoint.path} shallow body`,
309
+ })
310
+ return buildShallowFooter(entry.checkpoint, 0) + `\n[discarded] ${renderCheckpointLine(entry.checkpoint)}`
311
+ },
312
+ }))
313
+ }
314
+
315
+ /** Find the arguments JSON + file path of the call owning a tool/result. */
316
+ function findCallArgs(
317
+ events: ReadonlyArray<Record<string, unknown>>,
318
+ callId: string,
319
+ ): { path: string; argsJson: string } | undefined {
320
+ for (const event of events) {
321
+ if (event.type !== 'assistant/message') continue
322
+ const message = (event.data as Record<string, unknown> | undefined)?.message as Record<string, unknown> | undefined
323
+ const blocks = Array.isArray(message?.content) ? message.content : []
324
+ for (const raw of blocks) {
325
+ const block = raw as Record<string, unknown> | null
326
+ if (block !== null && block.type === 'tool-call' && block.id === callId) {
327
+ const argsJson = typeof block.arguments === 'string'
328
+ ? block.arguments
329
+ : JSON.stringify(block.arguments ?? {})
330
+ let filePath: string
331
+ try {
332
+ const parsed = JSON.parse(argsJson) as Record<string, unknown>
333
+ filePath = typeof parsed.file_path === 'string' ? parsed.file_path : typeof parsed.path === 'string' ? parsed.path : ''
334
+ } catch {
335
+ filePath = ''
336
+ }
337
+ return { path: filePath, argsJson }
338
+ }
339
+ }
340
+ }
341
+ return undefined
342
+ }
@@ -9,6 +9,12 @@
9
9
  */
10
10
  export const RUNTIME_TOOL_NAMES = Object.freeze({
11
11
  RETRIEVE: 'context_compression_retrieve',
12
+ /** Shallow read preview: declaration skeleton over a type-classified view. */
13
+ SHALLOW: 'context_compression_shallow',
14
+ /** Upgrade-discard pair primitive: drop one side of a shallow/full read pair. */
15
+ DISCARD: 'context_compression_discard',
16
+ /** O(1) header probe recommending which shallow view fits a file. */
17
+ PROBE: 'context_compression_probe',
12
18
  } as const)
13
19
 
14
20
  /** Every runtime tool this plugin registers and later judges against. */
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Line-C deterministic masks (plan cci-sedimentation-triage, Phase 2).
3
+ *
4
+ * Two extractions replace enumeration (findings F5 "extraction over
5
+ * enumeration"):
6
+ * 1. `manifestFromCall` — write-family results collapse to the touched-file
7
+ * list. Paths come from CALL ARGS first: result text usually says "written"
8
+ * without full paths (replay round-1 failure mode).
9
+ * 2. `skeletonFromRead` — large read results collapse to declaration lines.
10
+ * Matching runs on the gutter-stripped view (the host's `N: ` prefix defeats
11
+ * naive declaration regexes — the CCI JSON-skeleton trap), while CAPTURED
12
+ * lines keep their gutter because it is the model's inline locator into the
13
+ * original file, same convention as `hasReadGutter` in reducers.
14
+ *
15
+ * Both fail open: returning `null` means "not maskable", the caller keeps the
16
+ * normal reduction path. Zero-hit is a normal outcome, not an error.
17
+ *
18
+ * @module runtime/triage/masks
19
+ */
20
+ import { hasReadGutter } from '../reducers.ts'
21
+ import { normalizeToolPath, shallowFingerprint } from './shallow.ts'
22
+ import type { MaskVerdict } from './types.ts'
23
+
24
+ /** Write-family tool names whose results are pure "what changed" manifests. */
25
+ const WRITE_TOOLS = /^(write|edit|apply_patch|multi_edit|create|search_replace)$/i
26
+
27
+ /** Read-family tool names eligible for skeleton masking. */
28
+ const READ_TOOLS = /^(read|read_file|view)$/i
29
+
30
+ /** Read results below this char length stay verbatim (masking would lose more than it saves). */
31
+ const MASK_READ_MIN_CHARS = 3_000
32
+
33
+ /** Declaration-ish line starts across the languages this corpus exercises. */
34
+ const SKELETON_PATTERN = /^\s*(?:import |from \S+ import |export |package |use |fn |func |def |class |interface |type |impl |enum |pub |const |let |var |async function|public |private |protected |static |#define|template)/
35
+
36
+ /** Hard caps keep one card section bounded regardless of input size. */
37
+ const MANIFEST_MAX_PATHS = 12
38
+ const SKELETON_MAX_LINES = 40
39
+
40
+ /** Gutter prefix added by the host's `formatReadOutput`; strip for MATCHING only. */
41
+ const GUTTER_STRIP = /^(\d+): /
42
+
43
+ /** Text-fallback path pattern: absolute-ish paths and extension-bearing names. */
44
+ const PATH_FALLBACK = /((?:[A-Za-z]:)?[\\/][^\s"'`,:]{3,}|\.?[\w./\\-]+\.(?:ts|tsx|js|mjs|py|go|rs|md|json|ya?ml|css|html))(?::\d+)?/g
45
+
46
+ function collectArgPaths(argsJson: string): string[] {
47
+ let parsed: unknown
48
+ try {
49
+ parsed = JSON.parse(argsJson)
50
+ } catch {
51
+ return []
52
+ }
53
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return []
54
+ const record = parsed as Record<string, unknown>
55
+ const singles = [record.file_path, record.path, record.filePath]
56
+ const list = Array.isArray(record.paths) ? record.paths : []
57
+ const edits = Array.isArray(record.edits) ? record.edits : []
58
+ const out: string[] = []
59
+ for (const entry of [...singles, ...list, ...edits.map(item => (item as Record<string, unknown> | null)?.path)]) {
60
+ if (typeof entry === 'string' && entry.trim() !== '') out.push(entry.trim())
61
+ }
62
+ return out
63
+ }
64
+
65
+ /**
66
+ * Collapse a write-family result to its touched-file manifest.
67
+ * Args first, result text only as fallback; never throws on broken args.
68
+ */
69
+ export function manifestFromCall(name: string, argsJson: string, text: string, seq = 0): MaskVerdict | null {
70
+ if (!WRITE_TOOLS.test(name)) return null
71
+ const fromArgs = collectArgPaths(argsJson)
72
+ const candidates = fromArgs.length > 0
73
+ ? fromArgs
74
+ : (text.match(PATH_FALLBACK) ?? []).map(entry => entry.replace(/:\d+$/, ''))
75
+ const paths = [...new Set(candidates)].slice(0, MANIFEST_MAX_PATHS)
76
+ if (paths.length === 0) return null
77
+ return { kind: 'manifest', paths, seq }
78
+ }
79
+
80
+ /**
81
+ * Collapse a large read result to its declaration skeleton. Returns `null`
82
+ * for small reads, non-read content, and zero-hit bodies (prose dumps) —
83
+ * fail-open to the normal reducer path. Captured lines keep the gutter.
84
+ * With a target `path`, the verdict carries the permanent checkpoint layer
85
+ * (plan R11): path/coverage/fingerprint survive any later `discard`.
86
+ */
87
+ export function skeletonFromRead(text: string, seq = 0, path?: string): MaskVerdict | null {
88
+ if (text.length < MASK_READ_MIN_CHARS) return null
89
+ const lines = text.replace(/\n+$/, '').split('\n')
90
+ const guttered = hasReadGutter(lines)
91
+ const kept: string[] = []
92
+ for (const line of lines) {
93
+ const matchView = guttered ? line.replace(GUTTER_STRIP, '') : line
94
+ if (SKELETON_PATTERN.test(matchView)) {
95
+ kept.push(line)
96
+ if (kept.length >= SKELETON_MAX_LINES) break
97
+ }
98
+ }
99
+ if (kept.length === 0) return null
100
+ const keptChars = kept.reduce((sum, line) => sum + line.length + 1, 0)
101
+ return {
102
+ kind: 'skeleton',
103
+ lines: kept,
104
+ totalLines: lines.length,
105
+ elidedChars: Math.max(0, text.length - keptChars),
106
+ seq,
107
+ ...(path === undefined || path.trim() === ''
108
+ ? {}
109
+ : {
110
+ checkpoint: {
111
+ path: normalizeToolPath(path),
112
+ coverage: `${lines.length} lines`,
113
+ ref: `event/${seq}`,
114
+ fingerprint: shallowFingerprint(text),
115
+ },
116
+ }),
117
+ }
118
+ }
119
+
120
+ /** Read-family predicate for the wiring site (keeps tool-name regex single-sourced here). */
121
+ export function isReadToolName(name: string): boolean {
122
+ return READ_TOOLS.test(name)
123
+ }
124
+
125
+ /** Write-family predicate for the wiring site. */
126
+ export function isWriteToolName(name: string): boolean {
127
+ return WRITE_TOOLS.test(name)
128
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Shallow-read primitives (plan cci-sedimentation-triage, Phase 4.5).
3
+ *
4
+ * Pure decision layer for the upgrade-discard pair:
5
+ * - `normalizeToolPath` — the pairing key (drive letter lowered, separators
6
+ * unified, `./` resolved); false pairing must fail CLOSED (no footer, guard
7
+ * refuses), never silently drop content;
8
+ * - `classifyShallowSample` — the `probe` decision: O(1) header sample picks
9
+ * which shallow view fits (T4.12);
10
+ * - `evaluateDiscardGuard` — the asymmetric protection (M20): discarding the
11
+ * MAP when the covering full read is only a slice is refused; discarding
12
+ * the full read while the checkpoint survives is always allowed;
13
+ * - `buildShallowFooter` / `renderCheckpointLine` — the data-shaped teaching
14
+ * that rides the pruner seam (findings F5: reminders as data, not rules).
15
+ */
16
+ import type { ShallowCheckpoint } from './types.ts'
17
+
18
+ /** Windows-first corpus; forward slashes accepted everywhere. */
19
+ export function normalizeToolPath(raw: string): string {
20
+ const unified = raw.replace(/\\/g, '/').replace(/^\.\//, '')
21
+ const lowered = /^[A-Za-z]:\//.test(unified)
22
+ ? `${unified[0]!.toLowerCase()}${unified.slice(1)}`
23
+ : unified
24
+ // collapse duplicate separators and trailing slash, keep leading root
25
+ const collapsed = lowered.replace(/\/{2,}/g, '/').replace(/\/$/, '')
26
+ // resolve `..` segments lexically (no fs access here)
27
+ const segments = collapsed.split('/')
28
+ const out: string[] = []
29
+ for (const segment of segments) {
30
+ if (segment === '..') out.pop()
31
+ else if (segment !== '.' && segment !== '') out.push(segment)
32
+ }
33
+ const joined = out.join('/')
34
+ return collapsed.startsWith('/') ? `/${joined}` : joined
35
+ }
36
+
37
+ /** Shallow view methods the probe can recommend. */
38
+ export type ShallowMethod = 'json-skeleton' | 'code-skeleton' | 'csv-header' | 'toc-lines' | 'head-tail'
39
+
40
+ export interface ProbeVerdict {
41
+ readonly method: ShallowMethod
42
+ readonly reason: string
43
+ }
44
+
45
+ const JSON_START = /^[{[]/
46
+ const CSV_HINT = /^[^\n,]*,.*\n(?:[^\n,]*,.*){2,}/
47
+ const FRONTMATTER_HINT = /^---\n/
48
+
49
+ /** Classify from a bounded header sample only — the body is never opened here. */
50
+ export function classifyShallowSample(head: string, ext: string, totalBytes: number): ProbeVerdict {
51
+ const extension = ext.toLowerCase().replace(/^\./, '')
52
+ const trimmed = head.replace(/^\uFEFF/, '').trimStart()
53
+ if (extension === 'json' || extension === 'jsonc' || (JSON_START.test(trimmed) && (extension === '' || extension === 'jsonl'))) {
54
+ return { method: 'json-skeleton', reason: 'structured JSON: key skeleton beats raw text' }
55
+ }
56
+ if (extension === 'jsonl' || extension === 'ndjson') {
57
+ return { method: 'code-skeleton', reason: 'record stream: head/tail records with counts' }
58
+ }
59
+ if (extension === 'csv' || extension === 'tsv' || (totalBytes > 2000 && CSV_HINT.test(trimmed))) {
60
+ return { method: 'csv-header', reason: 'tabular: header row + row count, rows elided' }
61
+ }
62
+ if (['md', 'markdown', 'rst', 'txt', 'adoc'].includes(extension)) {
63
+ return { method: 'toc-lines', reason: 'prose: heading outline, bodies elided' }
64
+ }
65
+ if (['ts', 'tsx', 'js', 'jsx', 'mjs', 'py', 'go', 'rs', 'java', 'c', 'h', 'cc', 'cpp', 'cs', 'kt', 'swift', 'php', 'rb'].includes(extension)
66
+ || FRONTMATTER_HINT.test(trimmed) === false && /^\s*(?:import|from|package|use|def|fn|class|const|function)/.test(trimmed)) {
67
+ return { method: 'code-skeleton', reason: 'source code: declarations kept, bodies elided' }
68
+ }
69
+ if (totalBytes < 4000) {
70
+ return { method: 'head-tail', reason: 'small enough that a plain slice is the honest view' }
71
+ }
72
+ return { method: 'toc-lines', reason: 'unknown shape: line-structure outline as safe default' }
73
+ }
74
+
75
+ /** One side of a discard pair. */
76
+ export interface ReadPairSide {
77
+ readonly seq: number
78
+ readonly path: string
79
+ /** 'full' covers whole file; 'slice' carries the covered line window. */
80
+ readonly coverage: { readonly kind: 'full' } | { readonly kind: 'slice'; readonly from: number; readonly to: number }
81
+ }
82
+
83
+ export interface DiscardGuardInput {
84
+ /** The MAP side being considered for discard (the skeleton result). */
85
+ readonly map: ReadPairSide
86
+ /** The covering side claimed to supersede the map. */
87
+ readonly covering: ReadPairSide
88
+ }
89
+
90
+ /**
91
+ * The asymmetric guard (findings F6): losing the map costs far more than the
92
+ * saved bytes. Discarding the map requires the covering read to span it
93
+ * fully; equal paths after normalization are a precondition, never assumed.
94
+ */
95
+ export function evaluateDiscardGuard(input: DiscardGuardInput): { readonly allowed: boolean; readonly reason: string } {
96
+ const mapPath = normalizeToolPath(input.map.path)
97
+ const coveringPath = normalizeToolPath(input.covering.path)
98
+ if (mapPath === '' || coveringPath === '' || mapPath !== coveringPath) {
99
+ return { allowed: false, reason: `path-mismatch:${input.map.path}|${input.covering.path}` }
100
+ }
101
+ if (input.map.coverage.kind === 'full') {
102
+ // map covers everything; only a full covering read supersedes it
103
+ if (input.covering.coverage.kind === 'full') return { allowed: true, reason: 'covered-full' }
104
+ return { allowed: false, reason: 'map-is-full-need-full-coverage' }
105
+ }
106
+ if (input.covering.coverage.kind === 'full') return { allowed: true, reason: 'covered-by-full' }
107
+ const fromOk = input.covering.coverage.from <= input.map.coverage.from
108
+ const toOk = input.covering.coverage.to >= input.map.coverage.to
109
+ return fromOk && toOk
110
+ ? { allowed: true, reason: 'covered-by-window' }
111
+ : { allowed: false, reason: `window-gap:${input.map.coverage.from}-${input.map.coverage.to} vs ${input.covering.coverage.from}-${input.covering.coverage.to}` }
112
+ }
113
+
114
+ /** Footer riding a full read that pairs with a live shallow map (T4.8). */
115
+ export function buildShallowFooter(checkpoint: ShallowCheckpoint, savedTokens: number): string {
116
+ return `[cci-shallow-pair] 同文件的浅读视图 ${checkpoint.ref}(≈${savedTokens} tok)仍在上下文;确认不再需要时可调 context_compression_discard 释放(检查点行会保留)。被省略的输出不要凭本行推测补写。`
117
+ }
118
+
119
+ /** The one permanent line a discarded map leaves behind (R11). */
120
+ export function renderCheckpointLine(checkpoint: ShallowCheckpoint): string {
121
+ return `[cci-checkpoint] ${checkpoint.path} | ${checkpoint.coverage} | ref ${checkpoint.ref} | fp ${checkpoint.fingerprint}`
122
+ }
123
+
124
+ /** Cheap order-sensitive header hash + size; staleness hint only, never authority. */
125
+ export function shallowFingerprint(text: string): string {
126
+ const head = text.slice(0, 512)
127
+ let hash = 5381
128
+ for (let index = 0; index < head.length; index += 1) {
129
+ hash = ((hash << 5) + hash + head.charCodeAt(index)) >>> 0
130
+ }
131
+ return `${text.length.toString(16)}-${hash.toString(16)}`
132
+ }