dsh-context-compression-improved 0.5.2 → 0.5.4

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 (32) hide show
  1. package/.gitattributes +1 -0
  2. package/.github/workflows/ci.yml +7 -1
  3. package/CHANGELOG.ja.md +169 -119
  4. package/CHANGELOG.ko.md +167 -118
  5. package/CHANGELOG.md +304 -250
  6. package/CHANGELOG.zh.md +152 -109
  7. package/docs/installation.md +103 -103
  8. package/docs/installation.zh.md +100 -100
  9. package/package.json +2 -1
  10. package/packages/selector/cordis.patch.yml +5 -6
  11. package/packages/selector/package.json +1 -1
  12. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  13. package/packages/selector/src/client/locales.ts +196 -196
  14. package/packages/selector/src/index.ts +463 -463
  15. package/packages/selector/src/pruner/state.ts +50 -50
  16. package/packages/selector/src/pruner.ts +2402 -2402
  17. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +188 -188
  18. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +149 -149
  19. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  20. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  21. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  22. package/packages/selector/tests/public/package-contract.client.spec.ts +20 -0
  23. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -232
  24. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  25. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  26. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  27. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  28. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  29. package/packages/selector/tests/settings-seat.client.spec.ts +29 -4
  30. package/scripts/packed-install-e2e.mjs +163 -44
  31. package/scripts/toolclass-corpus-replay.mjs +281 -281
  32. package/scripts/verify-release.mjs +43 -2
@@ -28,8 +28,15 @@ interface CapturedRegistration {
28
28
  readonly component: unknown
29
29
  }
30
30
 
31
- /** Drive apply against a stub host and capture every slot registration. */
32
- function collectRegistrations(): { declared: string[]; registrations: CapturedRegistration[] } {
31
+ /**
32
+ * Drive apply against a stub host and capture every slot registration.
33
+ * @param options - `registerThrows` models an older host that does not declare
34
+ * the seat: the slot boundary rejects the registration, exactly the shape the
35
+ * 0.1.2-era hosts had.
36
+ */
37
+ function collectRegistrations(
38
+ options: { readonly registerThrows?: boolean } = {},
39
+ ): { declared: string[]; registrations: CapturedRegistration[] } {
33
40
  const declared: string[] = []
34
41
  const registrations: CapturedRegistration[] = []
35
42
  const ctx = {
@@ -45,8 +52,9 @@ function collectRegistrations(): { declared: string[]; registrations: CapturedRe
45
52
  for (const step of steps) { void step }
46
53
  return () => {}
47
54
  },
48
- register: (options: Record<string, unknown>, component: unknown) => {
49
- registrations.push({ slot: String(options['name']), options, component })
55
+ register: (record: Record<string, unknown>, component: unknown) => {
56
+ if (options.registerThrows === true) throw new Error(`unknown slot ${String(record['name'])}`)
57
+ registrations.push({ slot: String(record['name']), options: record, component })
50
58
  return () => {}
51
59
  },
52
60
  },
@@ -90,4 +98,21 @@ describe('settings-seat contract (standalone settings.section only)', () => {
90
98
  expect(declared).not.toContain('settings.plugins.tab')
91
99
  expect(declared).not.toContain('settings.plugin.item')
92
100
  })
101
+
102
+ it('survives an older host that does not declare the seat, warning instead of crashing', () => {
103
+ // Cross-version tolerance: a host without this seat rejects the
104
+ // registration at the slot boundary. apply() must swallow that and warn —
105
+ // the historical failure mode was apply() bailing out, which silently took
106
+ // EVERY settings entry down with it.
107
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
108
+ try {
109
+ const { declared } = collectRegistrations({ registerThrows: true })
110
+ // It tried the seat (so the degradation is "loud", not a silent no-op)…
111
+ expect(declared).toEqual(['settings.section'])
112
+ // …and the rejection never escaped apply().
113
+ expect(warn).toHaveBeenCalled()
114
+ } finally {
115
+ warn.mockRestore()
116
+ }
117
+ })
93
118
  })
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto'
2
2
  import { spawn } from 'node:child_process'
3
3
  import { createReadStream } from 'node:fs'
4
4
  import { copyFile, mkdir, mkdtemp, readFile, readdir, realpath, rm, stat, writeFile } from 'node:fs/promises'
5
- import { readFileSync, readdirSync } from 'node:fs'
5
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
6
6
  import { createServer } from 'node:http'
7
7
  import { createRequire } from 'node:module'
8
8
  import { tmpdir } from 'node:os'
@@ -316,10 +316,35 @@ async function runOfficialCloneCliSmoke(referenceRoot, registry, upgradeFrom, ca
316
316
  let added = false
317
317
  const environment = { ...process.env, DSH_HOME: dshHome }
318
318
  let lastLifecycle = { command: '(none)', code: 0, stdout: '', stderr: '' }
319
+ // Positive controls for the CLI invocation path (issue #2). Declared at
320
+ // function scope so the failure evidence can always report them, and assigned
321
+ // once the clone checkout exists (spawn needs `cwd: worktree` to resolve).
322
+ let scriptLayerControl = { code: null, stdout: '', stderr: '' }
323
+ let directEntryControl = { code: null, stdout: '', stderr: '' }
324
+ /** Path of the tiny runner that invokes the CLI's exported entry (see below). */
325
+ let cliRunnerPath = null
326
+ /**
327
+ * Run the clone's CLI.
328
+ *
329
+ * Measured root cause of issue #2: the pinned clone's `apps/cli/src/bin.ts`
330
+ * dispatches through `if (import.meta.main) { await runCli() }`, and under
331
+ * tsx that flag evaluates falsy — so the module loads and does NOTHING. Both
332
+ * `pnpm dsh …` (the clone's own `dsh` script) and a direct
333
+ * `node --import tsx/esm apps/cli/src/bin.ts …` therefore exit 0 with empty
334
+ * output, which is exactly what the two positive controls report. The leg
335
+ * calls the CLI's EXPORTED entry instead, with argv shaped the way the entry
336
+ * would see it, so the lifecycle exercises the CLI rather than the loader's
337
+ * handling of a self-execution guard.
338
+ */
319
339
  const dsh = async (...args) => {
320
- const outcome = await captureOutcome('pnpm', ['dsh', ...args], { cwd: worktree, env: environment })
340
+ if (cliRunnerPath === null) throw new Error('e2e: the CLI runner probe was not prepared')
341
+ const outcome = await captureOutcome(
342
+ process.execPath,
343
+ ['--import', 'tsx/esm', cliRunnerPath, ...args],
344
+ { cwd: worktree, env: environment },
345
+ )
321
346
  lastLifecycle = {
322
- command: `pnpm dsh ${args.join(' ')}`,
347
+ command: `dsh ${args.join(' ')}`,
323
348
  code: outcome.code ?? -1,
324
349
  stdout: outcome.stdout,
325
350
  stderr: outcome.stderr,
@@ -332,10 +357,14 @@ async function runOfficialCloneCliSmoke(referenceRoot, registry, upgradeFrom, ca
332
357
  ].filter(Boolean).join('\n'))
333
358
  }
334
359
  }
335
- const dumpConfig = () => capture('pnpm', ['dsh', '--profile', 'web', '--dump-config'], {
336
- cwd: worktree,
337
- env: environment,
338
- }).then(captured => captured.stdout)
360
+ const dumpConfig = () => capture(
361
+ process.execPath,
362
+ ['--import', 'tsx/esm', cliRunnerPath, '--profile', 'web', '--dump-config'],
363
+ {
364
+ cwd: worktree,
365
+ env: environment,
366
+ },
367
+ ).then(captured => captured.stdout)
339
368
 
340
369
  /** Installed manifest of the profile-resolved plugin package. */
341
370
  const profilePackages = () => {
@@ -367,6 +396,9 @@ async function runOfficialCloneCliSmoke(referenceRoot, registry, upgradeFrom, ca
367
396
  `last lifecycle: ${lastLifecycle.command} (exit ${String(lastLifecycle.code)})`,
368
397
  `lifecycle stdout: ${lastLifecycle.stdout.trim()}`,
369
398
  `lifecycle stderr: ${lastLifecycle.stderr.trim()}`,
399
+ // Positive controls: see the comment where they are captured (issue #2).
400
+ `control script-layer (pnpm dsh --version): exit ${String(scriptLayerControl.code)} out=${scriptLayerControl.stdout.trim()} err=${scriptLayerControl.stderr.trim()}`,
401
+ `control direct-entry (tsx bin.ts --version): exit ${String(directEntryControl.code)} out=${directEntryControl.stdout.trim()} err=${directEntryControl.stderr.trim()}`,
370
402
  `profile dependencies: ${declared}`,
371
403
  `profiles/web/node_modules: ${installed}`,
372
404
  ].join('\n'), { cause: error })
@@ -379,16 +411,47 @@ async function runOfficialCloneCliSmoke(referenceRoot, registry, upgradeFrom, ca
379
411
  }
380
412
 
381
413
  /**
382
- * Peers a headless official profile can never provide: pure web-host UI
383
- * packages supplied by the web app, not the CLI installation. The list is
384
- * REVIEWED and exact — any OTHER unresolved selector peer fails the gate,
385
- * and every web/client peer is still import-verified from the built
386
- * client libraries below.
414
+ * Host-plane runtime entries of the installed package. `client.js` is
415
+ * excluded: it is a lazy-CJS web artifact whose requires (`react`, the
416
+ * ui-slot packages) the web bundler supplies, and that stack is verified
417
+ * from the built client libraries below.
387
418
  */
388
- const WEB_ONLY_HEADLESS_UNRESOLVED_PEERS = [
389
- '@deepseek-ai/dsh-client-ui-primitives',
390
- '@deepseek-ai/dsh-client-ui-slots',
391
- ]
419
+ const HOST_PLANE_ENTRIES = ['index.js', 'pruner.js', 'advisor-state.js', 'tail-trim.js', 'invariant.js']
420
+
421
+ /**
422
+ * Bare package names the installed package's host-plane runtime files import.
423
+ *
424
+ * The runtime directory is read off the INSTALLED manifest's own `main` rather
425
+ * than assumed: the tarball this gate packs is `packages/selector` (`main`
426
+ * `lib/index.js`), while the published root manifest points at
427
+ * `packages/selector/lib/index.js`. Guessing either one read the wrong tree
428
+ * and failed closed on an ENOENT that said nothing about the plugin.
429
+ *
430
+ * @param selectorDir - Installed directory of the plugin package.
431
+ * @param selectorManifest - The installed manifest, for its `main` field.
432
+ * @returns The package roots the host must be able to resolve.
433
+ */
434
+ const hostPlaneRuntimeImports = async (selectorDir, selectorManifest) => {
435
+ const main = selectorManifest?.main
436
+ if (typeof main !== 'string' || main.length === 0) {
437
+ throw new Error(`installed package declares no main entry: ${JSON.stringify(selectorManifest?.main)}`)
438
+ }
439
+ const runtimeDir = dirname(join(selectorDir, main))
440
+ if (!existsSync(runtimeDir)) {
441
+ throw new Error(`installed package main ${main} points at a directory that is not in the tarball: ${runtimeDir}`)
442
+ }
443
+ const names = new Set()
444
+ for (const entry of HOST_PLANE_ENTRIES) {
445
+ const source = await readFile(join(runtimeDir, entry), 'utf8')
446
+ for (const match of source.matchAll(/(?:^|[^.\w])(?:import|export)\s[^;]*?from\s*['"]([^'"]+)['"]|(?:^|[^.\w])(?:import|require)\s*\(\s*['"]([^'"]+)['"]\s*\)/gmu)) {
447
+ const specifier = match[1] ?? match[2]
448
+ if (specifier.startsWith('.') || specifier.startsWith('node:')) continue
449
+ names.add(specifier.split('/').slice(0, specifier.startsWith('@') ? 2 : 1).join('/'))
450
+ }
451
+ }
452
+ if (names.size === 0) throw new Error('installed package exposes no host-plane runtime import to verify')
453
+ return names
454
+ }
392
455
 
393
456
  /**
394
457
  * Verify every web/client peer exists as a BUILT artifact resolvable from
@@ -436,37 +499,41 @@ async function runOfficialCloneCliSmoke(referenceRoot, registry, upgradeFrom, ca
436
499
  }
437
500
 
438
501
  /**
439
- * Prove the plugin actually loads in the official profile: pnpm's peers
440
- * check cannot see the healed profiles/node_modules fallback by design, so
441
- * the release gate resolves and imports instead. Fail-closed parts: every
442
- * RUNTIME peer (the engine surface the headless host must provide) and the
443
- * selector's node entry with a callable apply(). The selector's remaining
444
- * unresolved peers must equal the REVIEWED web-only whitelist above —
445
- * anything else (a newly missing host dependency) fails immediately.
502
+ * Prove the plugin actually loads in the official profile: pnpm's peers check
503
+ * cannot see the healed profiles/node_modules fallback by design, so the
504
+ * release gate resolves and imports instead. Fail-closed parts:
505
+ *
506
+ * - every bare specifier the HOST-plane runtime files import must resolve from
507
+ * the profile. That set is DERIVED from the installed artifact rather than
508
+ * listed by hand: 0.5.3 imported `@deepseek-ai/schemastery` while declaring
509
+ * it in no manifest a consumer reads, and a hand-maintained whitelist plus a
510
+ * hand-maintained dependency list could not see it;
511
+ * - every declared runtime dependency must resolve (the install surface);
512
+ * - the node entry must import and export a callable `apply()`;
513
+ * - a declared peer may stay unresolved only when no host-plane file imports
514
+ * it — the web-host client packages are supplied by the web app, and their
515
+ * built libraries are verified separately below.
446
516
  */
447
517
  const provePluginLoads = async () => {
448
- const { profileRoot, selector } = profilePackages()
518
+ const { profileRoot, selectorPath, selector } = profilePackages()
449
519
  const selectorPeers = Object.keys(selector.peerDependencies ?? {})
450
- const enginePeers = selectorPeers.filter(peer => !WEB_ONLY_HEADLESS_UNRESOLVED_PEERS.includes(peer))
451
- for (const allowed of WEB_ONLY_HEADLESS_UNRESOLVED_PEERS) {
452
- if (!selectorPeers.includes(allowed)) {
453
- throw new Error(`web-only whitelist names a peer the selector no longer declares: ${allowed}`)
454
- }
455
- }
520
+ const selectorDependencies = Object.keys(selector.dependencies ?? {})
521
+ const runtimeImports = [...await hostPlaneRuntimeImports(dirname(selectorPath), selector)].sort()
522
+ const required = [...new Set([...runtimeImports, ...selectorDependencies])].sort()
456
523
  const script = [
457
524
  "const { createRequire } = require('node:module')",
458
525
  `const requireFromProfile = createRequire(String.raw\`${join(profileRoot, 'package.json')}\`)`,
459
- `for (const peer of ${JSON.stringify(enginePeers)}) {`,
460
- ' requireFromProfile.resolve(peer)',
526
+ `for (const name of ${JSON.stringify(required)}) {`,
527
+ ' requireFromProfile.resolve(name)',
461
528
  '}',
462
529
  "const selectorEntry = requireFromProfile.resolve('dsh-context-compression-improved')",
463
530
  'const plugin = require(selectorEntry)',
464
531
  "if (typeof plugin.apply !== 'function') throw new Error('selector entry exports no apply()')",
465
- `const unresolved = []`,
532
+ 'const unresolvedPeers = []',
466
533
  `for (const peer of ${JSON.stringify(selectorPeers)}) {`,
467
- ' try { requireFromProfile.resolve(peer) } catch { unresolved.push(peer) }',
534
+ ' try { requireFromProfile.resolve(peer) } catch { unresolvedPeers.push(peer) }',
468
535
  '}',
469
- "console.log('LOAD_OK ' + JSON.stringify(unresolved))",
536
+ "console.log('LOAD_OK ' + JSON.stringify(unresolvedPeers))",
470
537
  ].join('\n')
471
538
  const outcome = await captureOutcome(process.execPath, ['--input-type=commonjs', '-e', script], {
472
539
  cwd: worktree,
@@ -474,17 +541,17 @@ async function runOfficialCloneCliSmoke(referenceRoot, registry, upgradeFrom, ca
474
541
  })
475
542
  const marker = outcome.stdout.split('\n').find(line => line.startsWith('LOAD_OK'))
476
543
  if (outcome.code !== 0 || marker === undefined) {
477
- throw new Error(`official profile failed to load the plugin and its engine peers:\n${outcome.stdout}\n${outcome.stderr}`)
544
+ throw new Error(`official profile failed to load the plugin, its host-plane imports and its engine peers:\n${outcome.stdout}\n${outcome.stderr}`)
478
545
  }
479
- const unresolved = JSON.parse(marker.slice('LOAD_OK '.length))
480
- const unexpected = unresolved.filter(peer => !WEB_ONLY_HEADLESS_UNRESOLVED_PEERS.includes(peer))
481
- if (unexpected.length > 0) {
482
- throw new Error(`selector peers failed to resolve headless outside the reviewed web-only whitelist: ${unexpected.join(', ')}`)
546
+ const unresolvedPeers = JSON.parse(marker.slice('LOAD_OK '.length))
547
+ const importedWithoutProvider = unresolvedPeers.filter(peer => runtimeImports.includes(peer))
548
+ if (importedWithoutProvider.length > 0) {
549
+ throw new Error(`selector peers the host-plane runtime imports did not resolve from the profile: ${importedWithoutProvider.join(', ')}`)
483
550
  }
484
551
  return {
485
- enginePeers: enginePeers.length,
486
- headlessUnresolvedSelectorPeers: unresolved,
487
- whitelist: WEB_ONLY_HEADLESS_UNRESOLVED_PEERS,
552
+ hostPlaneRuntimeImports: runtimeImports,
553
+ installedRuntimeDependencies: selectorDependencies,
554
+ unresolvedSelectorPeers: unresolvedPeers,
488
555
  builtClientPeersVerified: await proveBuiltClientPeersLoad(),
489
556
  }
490
557
  }
@@ -660,8 +727,60 @@ async function runOfficialCloneCliSmoke(referenceRoot, registry, upgradeFrom, ca
660
727
  // dsh-base + dsh-web-app, the only bundle that mounts agent-presets and
661
728
  // therefore the selector's preset overlay — so build both library faces
662
729
  // AND the web frontend; the healed profiles/node_modules fallback also
663
- // symlinks the CLI's own workspace packages.
730
+ // symlinks the CLI's own workspace packages, which is why the checkout's
731
+ // `vendor/schemastery/lib` has to exist too.
664
732
  await run('pnpm', ['run', 'build'], { cwd: worktree })
733
+ // Fail closed on the artifacts every later probe needs. Measured on the Node
734
+ // this workflow used to pin (24.0.0): `tsx` leaves `import.meta.main`
735
+ // undefined there, the clone's guarded `scripts/build.ts` exited 0 in about
736
+ // eight seconds having emitted nothing, and the boot probe then failed twice
737
+ // over — `client bundles not found; run \`pnpm run build\` before launch`
738
+ // from client composition, and `Cannot find module
739
+ // .../profiles/node_modules/@deepseek-ai/schemastery/lib/index.mjs` from the
740
+ // plugin, because the installation fallback resolves that name to the source
741
+ // checkout's `vendor/schemastery`, whose `lib` only this build produces.
742
+ for (const artifact of [
743
+ 'packages/client/ui-settings/lib/client.js',
744
+ 'vendor/schemastery/lib/index.mjs',
745
+ ]) {
746
+ if (!existsSync(join(worktree, artifact))) {
747
+ throw new Error([
748
+ `official clone build produced no ${artifact}`,
749
+ 'the clone\'s build script is `tsx scripts/build.ts`, guarded by `if (import.meta.main)`;',
750
+ 'tsx leaves that flag undefined on Node < 24.2, so the build exits 0 without building',
751
+ ].join(' '))
752
+ }
753
+ }
754
+
755
+ // Positive controls (recorded, never asserted), captured HERE because the
756
+ // clone checkout must exist: `cwd: worktree` is what makes spawn work at
757
+ // all. The clone's `dsh` script is `node --import tsx/esm
758
+ // apps/cli/src/bin.ts`, and bin.ts' `plugin` mode ALWAYS calls runPlugin —
759
+ // which either initializes the profile (printing `dsh: initialized profile
760
+ // …`), forwards pnpm's inherited stdio, or reports a missing pnpm with exit
761
+ // 127. It therefore cannot exit 0 with empty output, so a silent lifecycle
762
+ // means the CLI never reached that mode. These two probes tell the two
763
+ // candidate causes apart: the package manager's script layer swallowing the
764
+ // invocation, versus the CLI entry itself. See issue #2.
765
+ scriptLayerControl = await captureOutcome('pnpm', ['dsh', '--version'], { cwd: worktree, env: environment })
766
+ directEntryControl = await captureOutcome(
767
+ process.execPath,
768
+ ['--import', 'tsx/esm', 'apps/cli/src/bin.ts', '--version'],
769
+ { cwd: worktree, env: environment },
770
+ )
771
+ // The runner the lifecycle uses. It imports the entry and calls the
772
+ // exported `runCli()` after shaping argv exactly as the entry would see it
773
+ // (`argv[1]` = the entry path), so every mode the entry supports — profile
774
+ // boot, plugin forwarding, config dumps, help, version — behaves as it does
775
+ // when the file really is the process entry point.
776
+ cliRunnerPath = join(temporaryRoot, 'run-cli.mjs')
777
+ await writeFile(cliRunnerPath, [
778
+ "import { pathToFileURL } from 'node:url'",
779
+ `const entry = ${JSON.stringify(join(worktree, 'apps/cli/src/bin.ts'))}`,
780
+ 'process.argv = [process.argv[0], entry, ...process.argv.slice(2)]',
781
+ 'const { runCli } = await import(pathToFileURL(entry).href)',
782
+ 'await runCli()',
783
+ ].join('\n'), 'utf8')
665
784
 
666
785
  // Real lifecycle: start on the published previous release.
667
786
  if (upgradeFrom === undefined) throw new Error('release gate requires the previous published release for the official lifecycle')