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

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 (55) hide show
  1. package/.github/workflows/ci.yml +39 -39
  2. package/CHANGELOG.ja.md +217 -220
  3. package/CHANGELOG.ko.md +211 -214
  4. package/CHANGELOG.md +392 -376
  5. package/CHANGELOG.zh.md +196 -199
  6. package/README.md +97 -97
  7. package/README.zh.md +86 -86
  8. package/package.json +18 -17
  9. package/packages/selector/dsh.plugin.json +1 -1
  10. package/packages/selector/lib/client.js +733 -0
  11. package/packages/selector/lib/style.css +46 -46
  12. package/packages/selector/src/client/decode.ts +53 -53
  13. package/packages/selector/src/client/index.ts +30 -0
  14. package/packages/selector/src/client/locales/de.ts +98 -0
  15. package/packages/selector/src/client/locales/es.ts +98 -0
  16. package/packages/selector/src/client/locales/fr.ts +98 -0
  17. package/packages/selector/src/client/locales/it.ts +98 -0
  18. package/packages/selector/src/client/locales/ja.ts +98 -0
  19. package/packages/selector/src/client/locales/ko.ts +98 -0
  20. package/packages/selector/src/client/locales/ru.ts +98 -0
  21. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  22. package/packages/selector/src/preset-overlay.ts +629 -629
  23. package/packages/selector/src/profiles.ts +414 -414
  24. package/packages/selector/src/pruner/content.ts +198 -198
  25. package/packages/selector/src/pruner/state.ts +57 -57
  26. package/packages/selector/src/pruner.ts +2665 -2665
  27. package/packages/selector/src/runtime/audit.ts +303 -303
  28. package/packages/selector/src/runtime/config.ts +731 -731
  29. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  30. package/packages/selector/src/runtime/summary-command.ts +133 -133
  31. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -233
  32. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -204
  33. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -53
  34. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -65
  35. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -125
  36. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -37
  37. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  38. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +306 -306
  39. package/packages/selector/src/runtime/types.ts +358 -358
  40. package/packages/selector/tests/built/client-artifact.spec.ts +61 -61
  41. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
  42. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
  43. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
  44. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
  45. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
  46. package/packages/selector/tests/host-preset-overlay.host.spec.ts +203 -203
  47. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  48. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  49. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -62
  50. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -156
  51. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -154
  52. package/scripts/packed-components-smoke.mjs +734 -734
  53. package/tests/TEST_INVENTORY.md +41 -41
  54. package/tsconfig.tests.json +17 -17
  55. package/vitest.config.ts +57 -57
@@ -1,125 +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
- }
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
+ }
@@ -1,37 +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
- }
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
+ }
@@ -1,128 +1,128 @@
1
- /**
2
- * TokenPilot-inspired A2: Exact Sources locator block appended to the Auto
3
- * Compact summary checkpoint AFTER compaction/end.
4
- *
5
- * The block carries three kinds of locators over the shadowed range — the seq
6
- * range itself, spill files named by the Harness spill notices, and files
7
- * touched by read/grep-style tool calls — so details removed by the LLM
8
- * summary remain recoverable through ordinary file reads, the recovery tool,
9
- * or session event references. The block is only a few hundred bytes and is
10
- * skipped entirely when it would locate nothing concrete.
11
- */
12
- import type { SessionEvent } from '@deepseek-ai/dsh-session'
13
-
14
- /** One resolved compaction transaction to annotate. */
15
- export interface CompactionTrace {
16
- readonly compactionId: string
17
- readonly summarySeq: number
18
- readonly summaryShadowedRange: { readonly start: number, readonly end: number }
19
- }
20
-
21
- /** Files touched by read/grep-style tool calls inside the range. */
22
- const TOUCHED_FILE_TOOL = /(?:^|[-_])?(?:read|write|edit|glob|grep|view|str_replace_editor)(?:$|[-_])/i
23
- /** Spill notice paths emitted by the Harness output-retention policy. */
24
- const SPILL_PATH = /stored at:\s*([^\s)\]]+)/g
25
- /** Tool call arguments keys that commonly carry a file path. */
26
- const PATH_KEYS = ['path', 'file_path'] as const
27
-
28
- /**
29
- * Find the latest compaction/summary event matching the compaction id of a
30
- * compaction/end event. Returns undefined when the transaction cannot be
31
- * identified — the caller must skip rather than guess.
32
- */
33
- export function findCompactionTrace(
34
- events: readonly SessionEvent[],
35
- compactionId: string,
36
- ): CompactionTrace | undefined {
37
- let trace: CompactionTrace | undefined
38
- for (const event of events) {
39
- if (event.type === 'compaction/summary' && event.data.compactionId === compactionId) {
40
- trace = {
41
- compactionId,
42
- summarySeq: event.seq,
43
- summaryShadowedRange: event.data.shadowedRange,
44
- }
45
- }
46
- }
47
- return trace
48
- }
49
-
50
- /** Extract spill file paths from one text chunk. */
51
- export function extractSpillPaths(text: string): string[] {
52
- const paths: string[] = []
53
- for (const match of text.matchAll(SPILL_PATH)) {
54
- const path = match[1]?.replace(/[.,;]+$/, '')
55
- if (path !== undefined && path.length > 0) paths.push(path)
56
- }
57
- return paths
58
- }
59
-
60
- /** Extract touched file paths from one tool/call event's arguments. */
61
- export function extractTouchedPath(name: string, argumentsText: string): string | undefined {
62
- if (!TOUCHED_FILE_TOOL.test(name)) return undefined
63
- let parsed: unknown
64
- try {
65
- parsed = JSON.parse(argumentsText)
66
- } catch {
67
- return undefined
68
- }
69
- if (typeof parsed !== 'object' || parsed === null) return undefined
70
- const record = parsed as Record<string, unknown>
71
- for (const key of PATH_KEYS) {
72
- const value = record[key]
73
- if (typeof value === 'string' && value.length > 0) return value
74
- }
75
- return undefined
76
- }
77
-
78
- /** Result of one locator block build: text plus locator census for auditing. */
79
- export interface LocatorBlock {
80
- readonly text: string
81
- readonly spillFiles: number
82
- readonly touchedFiles: number
83
- }
84
-
85
- /**
86
- * Build the Exact Sources block for one shadowed range, or null when the
87
- * range locates nothing concrete (no spill files and no touched files).
88
- */
89
- export function buildLocatorBlock(
90
- events: readonly SessionEvent[],
91
- shadowedRange: { readonly start: number, readonly end: number },
92
- ): LocatorBlock | null {
93
- const spillFiles = new Set<string>()
94
- const touchedFiles = new Set<string>()
95
- for (let seq = shadowedRange.start; seq <= shadowedRange.end && seq < events.length; seq += 1) {
96
- const event = events[seq]
97
- if (event === undefined) continue
98
- if (event.type === 'tool/call') {
99
- const path = extractTouchedPath(event.data.name, event.data.arguments)
100
- if (path !== undefined) touchedFiles.add(path)
101
- continue
102
- }
103
- if (event.type === 'tool/result' || event.type === 'user/message') {
104
- // tool/result nests content under data.message; user/message carries it directly.
105
- const data = event.data as { content?: unknown, message?: { content?: unknown } }
106
- const content = Array.isArray(data.content) ? data.content : data.message?.content
107
- if (!Array.isArray(content)) continue
108
- for (const block of content as Array<{ type?: unknown, text?: unknown }>) {
109
- if (block.type === 'text' && typeof block.text === 'string') {
110
- for (const path of extractSpillPaths(block.text)) spillFiles.add(path)
111
- }
112
- }
113
- }
114
- }
115
- if (spillFiles.size === 0 && touchedFiles.size === 0) return null
116
- const lines = [
117
- '## Exact Sources (locators)',
118
- `- seq range: ${String(shadowedRange.start)}-${String(shadowedRange.end)}`,
119
- ...[...spillFiles].map(path => `- spill file: ${path}`),
120
- ...[...touchedFiles].map(path => `- file touched: ${path}`),
121
- '(Use `read <spill file>` or `context_compression_retrieve` with a `session://` source — pass start_line/max_lines to window the text — to restore exact text.)',
122
- ]
123
- return {
124
- text: lines.join('\n'),
125
- spillFiles: spillFiles.size,
126
- touchedFiles: touchedFiles.size,
127
- }
128
- }
1
+ /**
2
+ * TokenPilot-inspired A2: Exact Sources locator block appended to the Auto
3
+ * Compact summary checkpoint AFTER compaction/end.
4
+ *
5
+ * The block carries three kinds of locators over the shadowed range — the seq
6
+ * range itself, spill files named by the Harness spill notices, and files
7
+ * touched by read/grep-style tool calls — so details removed by the LLM
8
+ * summary remain recoverable through ordinary file reads, the recovery tool,
9
+ * or session event references. The block is only a few hundred bytes and is
10
+ * skipped entirely when it would locate nothing concrete.
11
+ */
12
+ import type { SessionEvent } from '@deepseek-ai/dsh-session'
13
+
14
+ /** One resolved compaction transaction to annotate. */
15
+ export interface CompactionTrace {
16
+ readonly compactionId: string
17
+ readonly summarySeq: number
18
+ readonly summaryShadowedRange: { readonly start: number, readonly end: number }
19
+ }
20
+
21
+ /** Files touched by read/grep-style tool calls inside the range. */
22
+ const TOUCHED_FILE_TOOL = /(?:^|[-_])?(?:read|write|edit|glob|grep|view|str_replace_editor)(?:$|[-_])/i
23
+ /** Spill notice paths emitted by the Harness output-retention policy. */
24
+ const SPILL_PATH = /stored at:\s*([^\s)\]]+)/g
25
+ /** Tool call arguments keys that commonly carry a file path. */
26
+ const PATH_KEYS = ['path', 'file_path'] as const
27
+
28
+ /**
29
+ * Find the latest compaction/summary event matching the compaction id of a
30
+ * compaction/end event. Returns undefined when the transaction cannot be
31
+ * identified — the caller must skip rather than guess.
32
+ */
33
+ export function findCompactionTrace(
34
+ events: readonly SessionEvent[],
35
+ compactionId: string,
36
+ ): CompactionTrace | undefined {
37
+ let trace: CompactionTrace | undefined
38
+ for (const event of events) {
39
+ if (event.type === 'compaction/summary' && event.data.compactionId === compactionId) {
40
+ trace = {
41
+ compactionId,
42
+ summarySeq: event.seq,
43
+ summaryShadowedRange: event.data.shadowedRange,
44
+ }
45
+ }
46
+ }
47
+ return trace
48
+ }
49
+
50
+ /** Extract spill file paths from one text chunk. */
51
+ export function extractSpillPaths(text: string): string[] {
52
+ const paths: string[] = []
53
+ for (const match of text.matchAll(SPILL_PATH)) {
54
+ const path = match[1]?.replace(/[.,;]+$/, '')
55
+ if (path !== undefined && path.length > 0) paths.push(path)
56
+ }
57
+ return paths
58
+ }
59
+
60
+ /** Extract touched file paths from one tool/call event's arguments. */
61
+ export function extractTouchedPath(name: string, argumentsText: string): string | undefined {
62
+ if (!TOUCHED_FILE_TOOL.test(name)) return undefined
63
+ let parsed: unknown
64
+ try {
65
+ parsed = JSON.parse(argumentsText)
66
+ } catch {
67
+ return undefined
68
+ }
69
+ if (typeof parsed !== 'object' || parsed === null) return undefined
70
+ const record = parsed as Record<string, unknown>
71
+ for (const key of PATH_KEYS) {
72
+ const value = record[key]
73
+ if (typeof value === 'string' && value.length > 0) return value
74
+ }
75
+ return undefined
76
+ }
77
+
78
+ /** Result of one locator block build: text plus locator census for auditing. */
79
+ export interface LocatorBlock {
80
+ readonly text: string
81
+ readonly spillFiles: number
82
+ readonly touchedFiles: number
83
+ }
84
+
85
+ /**
86
+ * Build the Exact Sources block for one shadowed range, or null when the
87
+ * range locates nothing concrete (no spill files and no touched files).
88
+ */
89
+ export function buildLocatorBlock(
90
+ events: readonly SessionEvent[],
91
+ shadowedRange: { readonly start: number, readonly end: number },
92
+ ): LocatorBlock | null {
93
+ const spillFiles = new Set<string>()
94
+ const touchedFiles = new Set<string>()
95
+ for (let seq = shadowedRange.start; seq <= shadowedRange.end && seq < events.length; seq += 1) {
96
+ const event = events[seq]
97
+ if (event === undefined) continue
98
+ if (event.type === 'tool/call') {
99
+ const path = extractTouchedPath(event.data.name, event.data.arguments)
100
+ if (path !== undefined) touchedFiles.add(path)
101
+ continue
102
+ }
103
+ if (event.type === 'tool/result' || event.type === 'user/message') {
104
+ // tool/result nests content under data.message; user/message carries it directly.
105
+ const data = event.data as { content?: unknown, message?: { content?: unknown } }
106
+ const content = Array.isArray(data.content) ? data.content : data.message?.content
107
+ if (!Array.isArray(content)) continue
108
+ for (const block of content as Array<{ type?: unknown, text?: unknown }>) {
109
+ if (block.type === 'text' && typeof block.text === 'string') {
110
+ for (const path of extractSpillPaths(block.text)) spillFiles.add(path)
111
+ }
112
+ }
113
+ }
114
+ }
115
+ if (spillFiles.size === 0 && touchedFiles.size === 0) return null
116
+ const lines = [
117
+ '## Exact Sources (locators)',
118
+ `- seq range: ${String(shadowedRange.start)}-${String(shadowedRange.end)}`,
119
+ ...[...spillFiles].map(path => `- spill file: ${path}`),
120
+ ...[...touchedFiles].map(path => `- file touched: ${path}`),
121
+ '(Use `read <spill file>` or `context_compression_retrieve` with a `session://` source — pass start_line/max_lines to window the text — to restore exact text.)',
122
+ ]
123
+ return {
124
+ text: lines.join('\n'),
125
+ spillFiles: spillFiles.size,
126
+ touchedFiles: touchedFiles.size,
127
+ }
128
+ }