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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.ja.md +9 -0
  2. package/CHANGELOG.ko.md +9 -0
  3. package/CHANGELOG.md +26 -0
  4. package/CHANGELOG.zh.md +9 -0
  5. package/README.md +1 -0
  6. package/README.zh.md +1 -0
  7. package/eslint.config.js +76 -30
  8. package/package.json +18 -17
  9. package/packages/selector/dsh.plugin.json +1 -1
  10. package/packages/selector/lib/client.js +14 -3
  11. package/packages/selector/lib/index.js +92 -1
  12. package/packages/selector/lib/{advisor-state.js → intent-gate.js} +91 -3
  13. package/packages/selector/lib/profiles.d.ts +9 -0
  14. package/packages/selector/lib/pruner.d.ts +59 -0
  15. package/packages/selector/lib/pruner.js +410 -8
  16. package/packages/selector/lib/style.css +46 -46
  17. package/packages/selector/src/client/decode.ts +6 -2
  18. package/packages/selector/src/deepseek-v4-tokenizer.ts +1 -1
  19. package/packages/selector/src/index.ts +418 -411
  20. package/packages/selector/src/preset-overlay.ts +3 -0
  21. package/packages/selector/src/profiles.ts +30 -10
  22. package/packages/selector/src/pruner/content.ts +1 -1
  23. package/packages/selector/src/pruner/state.ts +7 -0
  24. package/packages/selector/src/pruner.ts +253 -9
  25. package/packages/selector/src/runtime/audit.ts +17 -0
  26. package/packages/selector/src/runtime/config.ts +36 -11
  27. package/packages/selector/src/runtime/reducers.ts +1 -1
  28. package/packages/selector/src/runtime/summary-command.ts +133 -0
  29. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +46 -1
  30. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +55 -0
  31. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  32. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  33. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  34. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  35. package/packages/selector/src/runtime/tokenpilot/locator.ts +2 -2
  36. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +4 -1
  37. package/packages/selector/src/runtime/types.ts +12 -0
  38. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
  39. package/packages/selector/tests/built/client-artifact.spec.ts +2 -0
  40. package/packages/selector/tests/code-skeleton.client.spec.ts +94 -93
  41. package/packages/selector/tests/custom-contract.client.spec.ts +223 -222
  42. package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
  43. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
  44. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
  45. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
  46. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
  47. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
  48. package/packages/selector/tests/host-preset-overlay.host.spec.ts +203 -203
  49. package/packages/selector/tests/preset-options-write.client.spec.ts +188 -187
  50. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  51. package/packages/selector/tests/runtime/audit.spec.ts +275 -274
  52. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +3 -3
  53. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +4 -4
  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/public/public-runtime.spec.ts +5 -0
  57. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  58. package/packages/selector/tests/standing-generation.host.spec.ts +15 -35
  59. package/scripts/packed-components-smoke.mjs +2 -0
  60. package/scripts/packed-install-e2e.mjs +1275 -1273
  61. package/scripts/verify-release.mjs +318 -317
  62. package/tsconfig.tests.json +3 -1
  63. package/vitest.config.ts +14 -0
  64. package/.agents-stash-064.patch +0 -39
  65. package/_dsh_devdeps.json +0 -50
  66. package/_verify064/package/package.json +0 -162
  67. package/_verify064/package/packages/selector/src/client/index.ts +0 -232
package/CHANGELOG.ja.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  > 完全な履歴(アップストリーム 0.1.0 以前を含む)は [CHANGELOG.md](CHANGELOG.md) を参照。このファイルはフォークの追加エントリーのみを翻訳したものです。 · [English](CHANGELOG.md) · [中文](CHANGELOG.zh.md) · [한국어](CHANGELOG.ko.md)
4
4
 
5
+ <<<<<<< HEAD
6
+ ## 0.7.0-beta.1 - 2026-09-27
7
+
8
+ ### 追加
9
+
10
+ - ターン末尾インテント要約(`intentSummary.enabled`、デフォルト無効):成長ゲート(ライブ表面がウィンドウの 45% 超、かつ前回フォールドより 50K トークン超の増加)を通過した場合、ターン境界のポストフライトが「消費済み増分」をセマンティックロールでマスク——read 系ツール結果は共有の `classifyToolSource()`(write レイヤー追加)経由で 1 行の対象/規模レコードに、write 系はスケルトン先頭と逐語エラー行を保持——し、要約ライター LLM 呼び出しは 1 回のみ(todolist アンカー、JSON のみ、fail-open)。フォールドは次の圧力ラウンドで既存の plan/apply 機構を通じて候補ごとの `intent-summary` ブロックとして着地し、先頭ブロックが要約・読み取りレコード・逐語エラー行を、残りはマスク行と seq 範囲の出身情報を担う。fold-once:折りたたまれた seq(`INTENT_FOLD_MARKER` 含むブロック)は再候補になりません。監査に `intent-summary-outcome`(保持率と要約呼び出しコストのクレジット計上)を追加。
11
+ - `/ctx-summary off|on|status`:セッション単位の一時的な無効化/再開/状態表示(設定はセッション凍結のため「一時」はランタイム状態でのみ可能)。プロセスとともに消滅し、セッションを跨ぎません。
12
+ =======
5
13
  ## 0.6.5 - 2026-09-29
6
14
 
7
15
  ### Fixed
@@ -43,6 +51,7 @@
43
51
  - このバージョンは stash から公開され、どのブランチにもコミットされなかった;
44
52
  compat/0.1.7 は 0.6.5 でレジストリ tarball とバイト一致する内容を復元した。
45
53
 
54
+ >>>>>>> compat/0.1.7
46
55
  ## 0.5.4 - 2026-09-20
47
56
 
48
57
 
package/CHANGELOG.ko.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  > 전체 히스토리(업스트림 0.1.0 이전 포함)는 [CHANGELOG.md](CHANGELOG.md)를 참고하세요. 이 파일은 포크의 추가 항목만 번역한 것입니다. · [English](CHANGELOG.md) · [中文](CHANGELOG.zh.md) · [日本語](CHANGELOG.ja.md)
4
4
 
5
+ <<<<<<< HEAD
6
+ ## 0.7.0-beta.1 - 2026-09-27
7
+
8
+ ### 추가
9
+
10
+ - 턴 말머리 인텐트 요약(`intentSummary.enabled`, 기본 꺼짐): 성장 게이트(라이브 표면이 창의 45% 초과, 마지막 폴드 대비 50K 토큰 초과 증가)를 통과하면 턴 경계 포스트플라이트가 "소비된 증분"을 의미론적 역할로 마스킹합니다——read 계열 도구 결과는 공유 `classifyToolSource()`(write 레이어 추가)를 통해 1줄 대상/규모 레코드로, write 계열은 스켈레톤 헤드와 축자적 오류 행을 유지——한 번의 요약 작성기 LLM 호출만 소비합니다(todolist 앵커, JSON 전용, fail-open). 폴드는 다음 압력 라운드에서 기존 plan/apply 메커니즘을 통해 후보별 `intent-summary` 블록으로 착지하며, 첫 블록이 요약·읽기 레코드·축자적 오류 행을, 나머지는 마스크 행과 seq 범위 출처 각주를 담습니다. fold-once: 접힌 seq(`INTENT_FOLD_MARKER` 포함 블록)는 다시 후보가 되지 않습니다. 감사에 `intent-summary-outcome`(보존율 및 요약 호출 비용 크레딧) 추가.
11
+ - `/ctx-summary off|on|status`: 세션 범위의 임시 비활성화/재개/상태 조회(설정은 세션 고정이므로 "임시"는 런타임 상태로만 가능). 프로세스와 함께 소멸하며 세션을 cross하지 않습니다.
12
+ =======
5
13
  ## 0.6.5 - 2026-09-29
6
14
 
7
15
  ### Fixed
@@ -39,6 +47,7 @@
39
47
  - 이 버전은 stash에서 공개되어 어떤 브랜치에도 커밋되지 않았음; compat/0.1.7은 0.6.5에서
40
48
  레지스트리 tarball과 바이트 단위로 일치하는 콘텐츠를 복원.
41
49
 
50
+ >>>>>>> compat/0.1.7
42
51
  ## 0.5.4 - 2026-09-20
43
52
 
44
53
 
package/CHANGELOG.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  All notable changes use this file. The project follows semantic versioning after `0.1.0`.
4
4
 
5
+ <<<<<<< HEAD
6
+ ## 0.7.0-beta.1 - 2026-09-27
7
+
8
+ ### Added
9
+
10
+ - Turn-tail intent summary (`intentSummary.enabled`, default off): when the
11
+ growth gate passes (live surface > 45% of the context window AND more than
12
+ 50K tokens grown since the last fold), the turn-boundary postflight masks
13
+ the consumed increment to semantic-role records — read-class tool results
14
+ become one-line target/scale records via the shared `classifyToolSource()`
15
+ classifier plus a write-class layer, write-class results keep skeleton
16
+ heads plus verbatim error lines — and spends ONE summary-writer LLM call
17
+ (todolist-anchored, JSON-only, fail-open). The staged fold lands on the
18
+ next pressure round through the ordinary plan/apply machinery as per-
19
+ candidate `intent-summary` blocks: the first carries the LLM summary
20
+ segment, consulted-record lines, and verbatim error lines; the rest carry
21
+ their mask line and a seq-range provenance footer. Fold-once: folded seqs
22
+ (and anything carrying the `INTENT_FOLD_MARKER`) are never re-candidated.
23
+ Rewrite audits carry `intent-summary-outcome` records with retention ratio
24
+ and summary-call credit accounting.
25
+ - `/ctx-summary off|on|status`: session-scoped temporary override for the
26
+ gate (settings are session-frozen, so "temporary" can only live in runtime
27
+ state); dies with the process, never crosses sessions, and reports the
28
+ override, observed settings flag, gate constants, and the last landed fold.
29
+ =======
5
30
  ## 0.6.5 - 2026-09-29
6
31
 
7
32
  ### Fixed
@@ -47,6 +72,7 @@ All notable changes use this file. The project follows semantic versioning after
47
72
  - Released from a stash and never committed to any branch (the working tree that published it
48
73
  was lost); compat/0.1.7 restored the exact content in 0.6.5 and byte-verified it against
49
74
  the registry tarball before continuing.
75
+ >>>>>>> compat/0.1.7
50
76
 
51
77
  ## 0.5.4 - 2026-09-20
52
78
 
package/CHANGELOG.zh.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  > 完整历史(含上游 0.1.0 及更早版本)见 [CHANGELOG.md](CHANGELOG.md)。本文件只翻译本 fork 的新增条目。 · [English](CHANGELOG.md) · [日本語](CHANGELOG.ja.md) · [한국어](CHANGELOG.ko.md)
4
4
 
5
+ <<<<<<< HEAD
6
+ ## 0.7.0-beta.1 - 2026-09-27
7
+
8
+ ### 新增
9
+
10
+ - 回合末意图摘要(`intentSummary.enabled`,默认关):增长门控通过(活跃表面 > 窗口 45% 且距上次折叠增长超 50K token)后,回合收尾阶段把"已消费增量"按语义角色 mask——读类工具结果经共享的 `classifyToolSource()`(另加 write 先行层)压缩为单行目标/规模记录,写类保留骨架头与逐字错误行——然后只花一次摘要写手 LLM 调用(todolist 锚定、JSON-only、fail-open)。折叠在下一压力回合经既有 plan/apply 机器落地为逐候选 `intent-summary` 块:首块携带 LLM 摘要段、读取记录行与逐字错误行,其余块携带各自 mask 行与 seq 区间溯源脚注。fold-once:已折叠 seq(及含 `INTENT_FOLD_MARKER` 的块)永不再进入候选。审计新增 `intent-summary-outcome` 记录,含保持率与摘要调用成本(credit 净额)。
11
+ - `/ctx-summary off|on|status`:会话作用域临时禁用/恢复/查看状态(settings 是 session-frozen,"临时"只能活在运行时状态);随进程消亡、不跨会话,status 报告覆盖、观测到的设置开关、门控常量与最近一次折叠。
12
+ =======
5
13
  ## 0.6.5 - 2026-09-29
6
14
 
7
15
  ### Fixed
@@ -39,6 +47,7 @@
39
47
  - 该版本从 stash 发布、未提交到任何分支(发布它的那棵工作树丢失);compat/0.1.7 在 0.6.5
40
48
  中恢复了与其注册表 tarball 逐字节核验一致的完整内容。
41
49
 
50
+ >>>>>>> compat/0.1.7
42
51
  ## 0.5.4 - 2026-09-20
43
52
 
44
53
 
package/README.md CHANGED
@@ -7,6 +7,7 @@
7
7
  > [!NOTE]
8
8
  > **What this fork adds on top of upstream 0.1.0:**
9
9
  >
10
+ > - A **turn-tail intent summary** (`intentSummary.enabled`, default off): when the growth gate passes (>45% of the window, >50K tokens grown since the last fold), consumed-increment tool results are masked to semantic-role records (read-class → one-line target/scale records; write-class keep skeleton + verbatim error lines), one LLM writer call produces the summary segment, and the fold lands on the next pressure round as per-candidate blocks with seq provenance. Fold-once, fail-open, with retention-ratio and call-cost audits. Session-scoped `/ctx-summary off|on|status` pauses/resumes it without touching settings.
10
11
  > - An orthogonal **code-skeleton compression gate** (`codeSkeleton.enabled`, default off): the first exposure of an oversized fresh source-code tool result can keep a skeleton of imports and declarations — bodies elided, error lines kept — before the regular reducers run.
11
12
  > - A settings toggle for that gate in the same selector settings section, independent of every compression profile.
12
13
  > - An ESLint baseline wired into CI, a `test:watch` TDD loop, and documentation in English, Simplified Chinese, Japanese, and Korean.
package/README.zh.md CHANGED
@@ -7,6 +7,7 @@
7
7
  > [!NOTE]
8
8
  > **本fork 在上游 0.1.0 之上新增:*
9
9
  >
10
+ > - **回合末意图摘要**(`intentSummary.enabled`,默认关闭):增长门控通过(>窗口 45% 且距上次折叠增长 >50K token)后,把"已消费增量"按语义角色 mask——读类工具结果压成单行目标/规模记录,写类保留骨架与逐字错误行——一次 LLM 写手调用产出摘要段,下一压力回合落地为带 seq 溯源的逐候选块。fold-once、fail-open,审计含保持率与调用成本。会话内 `/ctx-summary off|on|status` 可临时暂停/恢复,不动设置。
10
11
  > - 正交的**代码骨架压缩门**(`codeSkeleton.enabled`,默认关闭):超大源码类工具结果首次曝光时,可先保留导入与声明的骨架——省略函数体并保留错误行——再进入常规 reducer。
11
12
  > - 同一选择器设置区内新增该门的开关,独立于所有压缩 Profile。
12
13
  > - 接入 CI 的 ESLint 基线、`test:watch` TDD 环路,以及英/中日韩四语文档。
package/eslint.config.js CHANGED
@@ -1,30 +1,76 @@
1
- import js from '@eslint/js'
2
- import globals from 'globals'
3
- import tseslint from 'typescript-eslint'
4
-
5
- export default tseslint.config(
6
- {
7
- ignores: ['**/node_modules/**', '**/lib/**', '**/dist/**', '**/coverage/**', 'docs/**'],
8
- },
9
- js.configs.recommended,
10
- ...tseslint.configs.recommended,
11
- {
12
- files: ['packages/**/*.{ts,tsx}', 'scripts/**/*.{js,mjs}', 'eslint.config.js'],
13
- languageOptions: {
14
- globals: { ...globals.browser, ...globals.node },
15
- },
16
- rules: {
17
- '@typescript-eslint/no-unused-vars': ['error', {
18
- argsIgnorePattern: '^_',
19
- varsIgnorePattern: '^_',
20
- caughtErrorsIgnorePattern: '^_',
21
- destructuredArrayIgnorePattern: '^_',
22
- }],
23
- },
24
- },
25
- {
26
- // Terminal normalization intentionally matches ANSI/BEL control characters.
27
- files: ['packages/selector/src/runtime/reducers.ts'],
28
- rules: { 'no-control-regex': 'off' },
29
- },
30
- )
1
+ import js from '@eslint/js'
2
+ import globals from 'globals'
3
+ import tseslint from 'typescript-eslint'
4
+
5
+ const noUnusedVars = ['error', {
6
+ argsIgnorePattern: '^_',
7
+ varsIgnorePattern: '^_',
8
+ caughtErrorsIgnorePattern: '^_',
9
+ destructuredArrayIgnorePattern: '^_',
10
+ }]
11
+
12
+ // Gate scripts and test hosts legitimately traffic in `any` (JSON payloads,
13
+ // untyped Harness service bridges); the unsafe-family noise there would drown
14
+ // the signal, so they are scoped out while every other type-checked rule stays.
15
+ const noUnsafeFamily = Object.fromEntries(
16
+ [
17
+ 'no-unsafe-argument',
18
+ 'no-unsafe-assignment',
19
+ 'no-unsafe-call',
20
+ 'no-unsafe-member-access',
21
+ 'no-unsafe-return',
22
+ ].map(rule => [`@typescript-eslint/${rule}`, 'off']),
23
+ )
24
+
25
+ export default tseslint.config(
26
+ {
27
+ ignores: [
28
+ '**/node_modules/**', '**/lib/**', '**/dist/**', '**/coverage/**',
29
+ 'docs/**', 'scripts-dist/**',
30
+ // Vendored 0.1.5-era helper shipped as plain JS; it has no tsconfig
31
+ // project, so type-checked rules cannot run on it.
32
+ 'packages/selector/tests/helpers/legacy-settings/**',
33
+ ],
34
+ },
35
+ js.configs.recommended,
36
+ ...tseslint.configs.recommendedTypeChecked,
37
+ {
38
+ // First-party TypeScript: full type-checked strength. Everything linted
39
+ // here is included in tsconfig.tests.json (the only root-level project).
40
+ files: ['packages/**/*.ts', 'packages/**/*.tsx', 'vitest.config.ts', 'vitest.built.config.ts'],
41
+ languageOptions: {
42
+ globals: { ...globals.browser, ...globals.node },
43
+ parserOptions: {
44
+ project: ['tsconfig.tests.json'],
45
+ tsconfigRootDir: import.meta.dirname,
46
+ },
47
+ },
48
+ rules: { '@typescript-eslint/no-unused-vars': noUnusedVars },
49
+ },
50
+ {
51
+ // Spec files implement mock async methods purely to satisfy typed host
52
+ // interfaces; requiring an await inside every one of them is noise.
53
+ files: ['packages/selector/tests/**'],
54
+ rules: { '@typescript-eslint/require-await': 'off', ...noUnsafeFamily },
55
+ },
56
+ {
57
+ // Standalone .mjs gate scripts live outside every tsconfig; the default
58
+ // project gives type-checked rules a loose type surface to work with.
59
+ files: ['scripts/**/*.{js,mjs}', 'eslint.config.js'],
60
+ languageOptions: {
61
+ globals: { ...globals.browser, ...globals.node },
62
+ parserOptions: {
63
+ projectService: {
64
+ allowDefaultProject: ['eslint.config.js', 'scripts/*.mjs'],
65
+ },
66
+ tsconfigRootDir: import.meta.dirname,
67
+ },
68
+ },
69
+ rules: { '@typescript-eslint/no-unused-vars': noUnusedVars, ...noUnsafeFamily },
70
+ },
71
+ {
72
+ // Terminal normalization intentionally matches ANSI/BEL control characters.
73
+ files: ['packages/selector/src/runtime/reducers.ts'],
74
+ rules: { 'no-control-regex': 'off' },
75
+ },
76
+ )
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-context-compression-improved",
3
- "version": "0.6.5",
3
+ "version": "0.7.0-beta.1",
4
4
  "publishConfig": {
5
5
  "tag": "dsh-0.1.7"
6
6
  },
@@ -50,25 +50,10 @@
50
50
  "type": "git",
51
51
  "url": "git+https://github.com/drscrewdriver/dsh-context-compression-improved.git"
52
52
  },
53
- "packageManager": "pnpm@11.7.0",
54
53
  "engines": {
55
54
  "node": "^22.19.0 || >=24.0.0",
56
55
  "dsh": ">=0.1.7-rc.1 <0.1.8-0"
57
56
  },
58
- "scripts": {
59
- "build": "pnpm -r --if-present run bundle",
60
- "typecheck": "pnpm --filter dsh-context-compression-improved run bundle && pnpm --filter dsh-context-compression-improved run typecheck && pnpm run typecheck:tests",
61
- "typecheck:tests": "tsc --noEmit -p tsconfig.tests.json",
62
- "lint": "eslint packages scripts eslint.config.js",
63
- "lint:fix": "eslint packages scripts eslint.config.js --fix",
64
- "test": "vitest run",
65
- "test:watch": "vitest",
66
- "test:built": "vitest run --config vitest.built.config.ts",
67
- "test:e2e:packed": "node scripts/packed-install-e2e.mjs",
68
- "test:unit": "vitest run",
69
- "verify:release": "node scripts/verify-release.mjs",
70
- "pack:dry-run": "pnpm -r --if-present run pack:dry-run"
71
- },
72
57
  "peerDependencies": {
73
58
  "@deepseek-ai/dsh-client-locale": ">=0.1.7-rc.1 <0.1.8-0",
74
59
  "@deepseek-ai/dsh-client-ui-primitives": ">=0.1.7-rc.1 <0.1.8-0",
@@ -149,6 +134,7 @@
149
134
  "@types/js-yaml": "^4.0.9",
150
135
  "@types/node": "^22.20.0",
151
136
  "@types/react": "~18.3.1",
137
+ "@vitest/coverage-v8": "^4.1.11",
152
138
  "eslint": "^10.10.0",
153
139
  "globals": "^17.12.0",
154
140
  "jsdom": "29.1.1",
@@ -159,5 +145,20 @@
159
145
  "typescript": "^6.0.3",
160
146
  "typescript-eslint": "^8.69.0",
161
147
  "vitest": "^4.1.8"
148
+ },
149
+ "scripts": {
150
+ "build": "pnpm -r --if-present run bundle",
151
+ "typecheck": "pnpm --filter dsh-context-compression-improved run bundle && pnpm --filter dsh-context-compression-improved run typecheck && pnpm run typecheck:tests",
152
+ "typecheck:tests": "tsc --noEmit -p tsconfig.tests.json",
153
+ "lint": "eslint packages scripts eslint.config.js",
154
+ "lint:fix": "eslint packages scripts eslint.config.js --fix",
155
+ "test": "vitest run",
156
+ "test:coverage": "vitest run --coverage",
157
+ "test:watch": "vitest",
158
+ "test:built": "vitest run --config vitest.built.config.ts",
159
+ "test:e2e:packed": "node scripts/packed-install-e2e.mjs",
160
+ "test:unit": "vitest run",
161
+ "verify:release": "node scripts/verify-release.mjs",
162
+ "pack:dry-run": "pnpm -r --if-present run pack:dry-run"
162
163
  }
163
- }
164
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "dsh-external/dsh-context-compression-improved",
3
- "version": "0.6.5",
3
+ "version": "0.7.0-beta.1",
4
4
  "main": "./lib/index.js",
5
5
  "description": "Auditable tool-result context-compression selector with code-skeleton gate for DeepSeek Harness",
6
6
  "engines": {
@@ -60,6 +60,15 @@ window.__ModuleLoader__.load({
60
60
  const enabled = value.enabled;
61
61
  return typeof enabled === "boolean" ? { enabled } : void 0;
62
62
  }
63
+ /** Browser-safe mirror of the runtime intentSummary section (absent inherits off). */
64
+ function decodeIntentSummarySettings(value) {
65
+ if (value === void 0) return { enabled: false };
66
+ if (!isPlainRecord(value)) return void 0;
67
+ const keys = Object.keys(value);
68
+ if (keys.length !== 1 || keys[0] !== "enabled") return void 0;
69
+ const enabled = value.enabled;
70
+ return typeof enabled === "boolean" ? { enabled } : void 0;
71
+ }
63
72
  /**
64
73
  * Browser mirror of the runtime presetOptions section: absent inherits the
65
74
  * preset defaults (decodes to `undefined`); present values must be a plain
@@ -1160,7 +1169,7 @@ window.__ModuleLoader__.load({
1160
1169
  /**
1161
1170
  * Decode one stored context-compression settings document with exactly the
1162
1171
  * runtime schema's strictness: a plain object with only `profile`, `custom`,
1163
- * `autoCompact`, and `codeSkeleton` keys, a supported profile, a valid Custom
1172
+ * `autoCompact`, `codeSkeleton`, and `intentSummary` keys, a supported profile, a valid Custom
1164
1173
  * document canonicalized to v3 exactly as the runtime resolver would, a
1165
1174
  * strictly-shaped autoCompact section (absent inherits the 80% default), and
1166
1175
  * a strictly-shaped codeSkeleton gate (absent inherits off). Anything else
@@ -1169,17 +1178,19 @@ window.__ModuleLoader__.load({
1169
1178
  */
1170
1179
  function decodeSettings(value) {
1171
1180
  if (!isPlainRecord(value)) return void 0;
1172
- if (Object.keys(value).some((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "presetOptions")) return;
1181
+ if (Object.keys(value).some((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "intentSummary" && key !== "presetOptions")) return;
1173
1182
  const profile = value.profile;
1174
1183
  const custom = value.custom;
1175
1184
  const autoCompact = decodeAutoCompactSettings(value.autoCompact);
1176
1185
  const codeSkeleton = decodeCodeSkeletonSettings(value.codeSkeleton);
1186
+ const intentSummary = decodeIntentSummarySettings(value.intentSummary);
1177
1187
  const presetOptions = decodePresetOptionsSettings(value.presetOptions);
1178
- return typeof profile === "string" && COMPRESSION_PROFILES.includes(profile) && isCustomCompressionPolicy(custom) && autoCompact !== void 0 && codeSkeleton !== void 0 ? {
1188
+ return typeof profile === "string" && COMPRESSION_PROFILES.includes(profile) && isCustomCompressionPolicy(custom) && autoCompact !== void 0 && codeSkeleton !== void 0 && intentSummary !== void 0 ? {
1179
1189
  profile,
1180
1190
  custom: canonicalizeCustomPolicy(custom),
1181
1191
  autoCompact,
1182
1192
  codeSkeleton,
1193
+ intentSummary,
1183
1194
  ...presetOptions === void 0 ? {} : { presetOptions }
1184
1195
  } : void 0;
1185
1196
  }
@@ -1,4 +1,4 @@
1
- import { l as DEFAULT_CONTEXT_COMPRESSION_SETTINGS, t as getAdvisorState } from "./advisor-state.js";
1
+ import { a as getLastIntentFold, i as getAdvisorState, n as INTENT_GATE_GROWTH_TOKENS, o as getObservedIntentEnabled, p as setSummaryOverride, s as getSummaryOverride, t as INTENT_GATE_FLOOR_FRACTION, v as DEFAULT_CONTEXT_COMPRESSION_SETTINGS } from "./intent-gate.js";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
  import { createHash } from "node:crypto";
@@ -75,6 +75,96 @@ async function buildEstimatorCatalog(deps) {
75
75
  };
76
76
  }
77
77
  //#endregion
78
+ //#region src/runtime/summary-command.ts
79
+ const SUMMARY_COMMAND_NAME = "ctx-summary";
80
+ const USAGE = "Usage: /ctx-summary off|on|status";
81
+ /** Parse the raw argument string; `undefined` = unrecognized (usage error). */
82
+ function parseSummaryCommandArgs(rawInput) {
83
+ const token = rawInput.trim().toLowerCase();
84
+ if (token === "off" || token === "on" || token === "status") return token;
85
+ }
86
+ function describeFold(sessionId) {
87
+ const fold = getLastIntentFold(sessionId);
88
+ if (fold === void 0) return "none";
89
+ return `turn ${fold.turn}, seq ${fold.startSeq}..${fold.endSeq}`;
90
+ }
91
+ /** Human-facing status line; observability only, never a decision input. */
92
+ function formatSummaryStatus(sessionId) {
93
+ const override = getSummaryOverride(sessionId);
94
+ const enabled = getObservedIntentEnabled(sessionId);
95
+ const enabledText = enabled === void 0 ? "unknown (gate not evaluated yet)" : enabled ? "yes" : "no";
96
+ return [
97
+ `ctx-summary status:`,
98
+ ` override: ${override ?? "default (settings-driven)"}`,
99
+ ` intentSummary enabled (settings): ${enabledText}`,
100
+ ` gate: floor >${Math.round(INTENT_GATE_FLOOR_FRACTION * 100)}% of window AND growth >${INTENT_GATE_GROWTH_TOKENS} tokens since last fold`,
101
+ ` last fold: ${describeFold(sessionId)}`
102
+ ].join("\n");
103
+ }
104
+ /** Resolve the invoking agent's session id (`''` when the host exposes none). */
105
+ function sessionIdOf(agent) {
106
+ const session = agent?.session;
107
+ if (session === void 0 || session.id === void 0 || session.id === null) return "";
108
+ return String(session.id);
109
+ }
110
+ /** Best-effort `CommandDefinitionId` brand; `undefined` on stripped hosts (registered without it). */
111
+ async function loadCommandDefinitionId() {
112
+ try {
113
+ return (await import("@deepseek-ai/dsh-commands")).CommandDefinitionId;
114
+ } catch {
115
+ return;
116
+ }
117
+ }
118
+ /**
119
+ * Mount `/ctx-summary` for every composed human-command adapter. Never
120
+ * throws: the command is a convenience surface, and a host without the
121
+ * commands service (or with an incompatible registry shape) simply runs
122
+ * without it.
123
+ */
124
+ function registerSummaryCommand(ctx) {
125
+ ctx.inject(["commands"], (injected) => {
126
+ const commands = injected.commands;
127
+ if (commands === void 0 || typeof commands.register !== "function") return;
128
+ (async () => {
129
+ try {
130
+ const definitionId = await loadCommandDefinitionId();
131
+ await commands.register({
132
+ name: SUMMARY_COMMAND_NAME,
133
+ description: "Turn-tail intent summary: temporarily disable/resume or inspect status",
134
+ ...definitionId === void 0 ? {} : { definitionId: definitionId("dsh-context-compression-improved/ctx-summary") },
135
+ handler: async (invocation) => {
136
+ const args = parseSummaryCommandArgs(typeof invocation.rawInput === "string" ? invocation.rawInput : "");
137
+ if (args === void 0) return {
138
+ kind: "error",
139
+ text: USAGE
140
+ };
141
+ const sessionId = sessionIdOf(invocation.agent);
142
+ if (args === "status") {
143
+ if (sessionId === "") return {
144
+ kind: "error",
145
+ text: "ctx-summary: no session is attached to this invocation"
146
+ };
147
+ return {
148
+ kind: "success",
149
+ text: formatSummaryStatus(sessionId)
150
+ };
151
+ }
152
+ if (sessionId === "") return {
153
+ kind: "error",
154
+ text: "ctx-summary: no session is attached to this invocation"
155
+ };
156
+ setSummaryOverride(sessionId, args);
157
+ return {
158
+ kind: "success",
159
+ text: args === "off" ? "ctx-summary: turn-tail intent summary paused for this session (until process restart or `/ctx-summary on`)" : "ctx-summary: turn-tail intent summary resumed for this session (numeric gates still apply)"
160
+ };
161
+ }
162
+ });
163
+ } catch {}
164
+ })();
165
+ });
166
+ }
167
+ //#endregion
78
168
  //#region src/preset-overlay.ts
79
169
  /** Plugin-owned, reversible compression overlays for native agent presets. */
80
170
  /**
@@ -742,6 +832,7 @@ function apply(ctx, config = {}) {
742
832
  try {
743
833
  if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx);
744
834
  if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx);
835
+ registerSummaryCommand(ctx);
745
836
  if (config.presetOverlay !== true) return;
746
837
  ctx.inject(["agentPresets"], (presetsCtx) => {
747
838
  const installation = decorateAgentPresets(presetsCtx.agentPresets, {
@@ -373,6 +373,20 @@ function parseCodeSkeletonSettings(value) {
373
373
  return { enabled };
374
374
  }
375
375
  /**
376
+ * Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
377
+ * section semantics: absent inherits the lossless `false` default, while a
378
+ * present-but-invalid section is an explicitly invalid document.
379
+ */
380
+ function parseIntentSummarySettings(value) {
381
+ if (value === void 0) return { enabled: false };
382
+ if (!isPlainRecord(value)) throw new TypeError("Context-compression intentSummary must be a plain object");
383
+ const keys = Object.keys(value);
384
+ if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join("\", \"")}"`);
385
+ const enabled = value.enabled;
386
+ if (typeof enabled !== "boolean") throw new TypeError("Context-compression intentSummary.enabled must be a boolean");
387
+ return { enabled };
388
+ }
389
+ /**
376
390
  * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
377
391
  * inherits the preset defaults; present-but-invalid is rejected, mirroring the
378
392
  * codeSkeleton section semantics.
@@ -479,7 +493,8 @@ const DEFAULT_CONTEXT_COMPRESSION_SETTINGS = {
479
493
  profile: "balanced",
480
494
  custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
481
495
  autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
482
- codeSkeleton: { enabled: false }
496
+ codeSkeleton: { enabled: false },
497
+ intentSummary: { enabled: false }
483
498
  };
484
499
  /**
485
500
  * Parse one settings document with the persisted-section semantics: `undefined`
@@ -497,17 +512,19 @@ const ContextCompressionSettingsSchema = z.transform(z.any().required(), (value)
497
512
  if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
498
513
  assertPlainDataTree(value);
499
514
  const candidate = structuredClone(value);
500
- const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "presetOptions");
515
+ const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "intentSummary" && key !== "presetOptions");
501
516
  if (unknown !== void 0) throw new TypeError(`Context-compression settings: unknown key "${unknown}"`);
502
517
  assertPresentSection(candidate, "profile", isSupportedProfile);
503
518
  assertPresentSection(candidate, "custom", isUsableCustomDocument);
504
519
  const autoCompact = parseAutoCompactSettings(candidate.autoCompact);
505
520
  const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton);
521
+ const intentSummary = parseIntentSummarySettings(candidate.intentSummary);
506
522
  const presetOptions = parsePresetOptionsSettings(candidate.presetOptions);
507
523
  return {
508
524
  ...contextCompressionSettingsInputSchema(candidate),
509
525
  autoCompact,
510
526
  codeSkeleton,
527
+ intentSummary,
511
528
  ...presetOptions === void 0 ? {} : { presetOptions }
512
529
  };
513
530
  }).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS);
@@ -958,5 +975,76 @@ function invalidateOnTaskChange(state, todoVersion) {
958
975
  state.lastSummaryTurn = -1;
959
976
  return true;
960
977
  }
978
+ /**
979
+ * `/ctx-summary off|on` overrides, keyed by session id (string). The command
980
+ * handler only sees `invocation.agent.session.id`, not the pruner's Session
981
+ * object, so these are id-keyed rather than WeakMap'd. Entries are two-char
982
+ * strings per session and cleared whenever the override is lifted.
983
+ */
984
+ const summaryOverrides = /* @__PURE__ */ new Map();
985
+ /** Read the session's `/ctx-summary` override; `undefined` = default (settings-driven). */
986
+ function getSummaryOverride(sessionId) {
987
+ return summaryOverrides.get(sessionId);
988
+ }
989
+ /** Set or clear (`undefined`) the session's `/ctx-summary` override. */
990
+ function setSummaryOverride(sessionId, value) {
991
+ if (value === void 0) summaryOverrides.delete(sessionId);
992
+ else summaryOverrides.set(sessionId, value);
993
+ }
994
+ /** Last observed `intentSummary.enabled` for a session, for `/ctx-summary status`. */
995
+ const lastObservedIntentEnabled = /* @__PURE__ */ new Map();
996
+ /** Record the gate input the pass last evaluated for this session. */
997
+ function observeIntentEnabled(sessionId, enabled) {
998
+ lastObservedIntentEnabled.set(sessionId, enabled);
999
+ }
1000
+ /** The settings-side enabled flag last observed for the session, if any. */
1001
+ function getObservedIntentEnabled(sessionId) {
1002
+ return lastObservedIntentEnabled.get(sessionId);
1003
+ }
1004
+ const lastIntentFolds = /* @__PURE__ */ new Map();
1005
+ /** Record a landed intent fold for the session (newest wins). */
1006
+ function recordIntentFold(sessionId, record) {
1007
+ lastIntentFolds.set(sessionId, record);
1008
+ }
1009
+ /** The most recent landed intent fold for the session, if any. */
1010
+ function getLastIntentFold(sessionId) {
1011
+ return lastIntentFolds.get(sessionId);
1012
+ }
1013
+ //#endregion
1014
+ //#region src/runtime/tokenpilot/intent-gate.ts
1015
+ /**
1016
+ * Turn-tail intent-summary growth gate (TokenPilot-inspired E2).
1017
+ *
1018
+ * Pure decision helper evaluated at the turn-boundary postflight: it decides
1019
+ * whether this turn may spend a summary-writer LLM call and stage a fold for
1020
+ * the next pressure round. The gate is deliberately conservative — every
1021
+ * unresolved input (unknown context window, non-finite counters) fails closed
1022
+ * toward "do not run", because a skipped fold is free while a wasted summary
1023
+ * call is not. Content safety is unaffected either way: fail-open semantics
1024
+ * live in the fold landing path, not here.
1025
+ */
1026
+ /** Floor: the live surface must exceed this fraction of the context window. */
1027
+ const INTENT_GATE_FLOOR_FRACTION = .45;
1028
+ /** Growth: the live surface must have grown by more than this since the last landed fold. */
1029
+ const INTENT_GATE_GROWTH_TOKENS = 5e4;
1030
+ function isUsableNumber(value) {
1031
+ return Number.isFinite(value) && value >= 0;
1032
+ }
1033
+ /** Same evaluation with the reason attached, for audits and `/ctx-summary status`. */
1034
+ function evaluateIntentGate(input) {
1035
+ const snapshot = (decision, reason) => ({
1036
+ ...input,
1037
+ decision,
1038
+ reason
1039
+ });
1040
+ if (!input.enabled) return snapshot(false, "disabled");
1041
+ if (input.override === "off") return snapshot(false, "override-off");
1042
+ if (!isUsableNumber(input.liveTokens)) return snapshot(false, "below-floor");
1043
+ if (input.contextWindow === void 0 || !isUsableNumber(input.contextWindow)) return snapshot(false, "no-window");
1044
+ if (!(input.liveTokens > input.contextWindow * .45)) return snapshot(false, "below-floor");
1045
+ if (!isUsableNumber(input.baselineTokens)) return snapshot(false, "below-growth");
1046
+ if (!(input.liveTokens - input.baselineTokens > 5e4)) return snapshot(false, "below-growth");
1047
+ return snapshot(true, "passed");
1048
+ }
961
1049
  //#endregion
962
- export { deepFreeze as C, assertNever as S, resolveConfig as _, AUTO_COMPACT_THRESHOLD_LIMITS as a, DEFAULT_CUSTOM_COMPRESSION_POLICY as b, DEFAULTS as c, charsForTokens as d, charsToTokens as f, parseContextCompressionSettings as g, isValidAutoCompactThresholdPercent as h, recordScore as i, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as l, isCompressionProfile as m, invalidateOnTaskChange as n, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as o, codePointLength as p, recordRecertified as r, ContextCompressionSettingsSchema as s, getAdvisorState as t, PRUNE_MARKER as u, resolvePolicy as v, COMPRESSION_PROFILES as w, resolveCustomPolicy as x, CustomCompressionPolicySchema as y };
1050
+ export { resolveCustomPolicy as A, isCompressionProfile as C, resolvePolicy as D, resolveConfig as E, deepFreeze as M, COMPRESSION_PROFILES as N, CustomCompressionPolicySchema as O, codePointLength as S, parseContextCompressionSettings as T, DEFAULTS as _, getLastIntentFold as a, charsForTokens as b, invalidateOnTaskChange as c, recordRecertified as d, recordScore as f, ContextCompressionSettingsSchema as g, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as h, getAdvisorState as i, assertNever as j, DEFAULT_CUSTOM_COMPRESSION_POLICY as k, observeIntentEnabled as l, AUTO_COMPACT_THRESHOLD_LIMITS as m, INTENT_GATE_GROWTH_TOKENS as n, getObservedIntentEnabled as o, setSummaryOverride as p, evaluateIntentGate as r, getSummaryOverride as s, INTENT_GATE_FLOOR_FRACTION as t, recordIntentFold as u, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as v, isValidAutoCompactThresholdPercent as w, charsToTokens as x, PRUNE_MARKER as y };
@@ -68,6 +68,13 @@ interface AutoCompactSettings {
68
68
  interface CodeSkeletonSettings {
69
69
  enabled: boolean;
70
70
  }
71
+ /**
72
+ * Orthogonal turn-tail intent-summary gate, mirrored browser-safe from the
73
+ * runtime: independent of every profile, default off.
74
+ */
75
+ interface IntentSummarySettings {
76
+ enabled: boolean;
77
+ }
71
78
  /** Browser-safe mirror of the runtime presetOptions section. */
72
79
  interface PresetOptionsSettings {
73
80
  readonly dedupeToolResults?: boolean;
@@ -98,6 +105,8 @@ interface ContextCompressionSettings {
98
105
  autoCompact: AutoCompactSettings;
99
106
  /** Code-skeleton reducer gate captured independently of `profile`. */
100
107
  codeSkeleton: CodeSkeletonSettings;
108
+ /** Turn-tail intent-summary gate captured independently of `profile`. */
109
+ intentSummary: IntentSummarySettings;
101
110
  /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
102
111
  presetOptions?: PresetOptionsSettings;
103
112
  }