dsh-prompt-customizer 0.5.0 → 0.9.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 (51) hide show
  1. package/README.en.md +26 -2
  2. package/README.md +129 -15
  3. package/build.mjs +219 -0
  4. package/client/client.js +8160 -3465
  5. package/client/client.js.map +7 -1
  6. package/cordis.patch.yml +6 -3
  7. package/lib/index.js +16360 -905
  8. package/lib/index.js.map +7 -0
  9. package/package.json +50 -38
  10. package/scripts/fixtures/rc2-mode.mjs +12 -0
  11. package/scripts/fixtures/rc2-preview.snapshot.json +35 -0
  12. package/scripts/fixtures/rc2-runtime.mjs +85 -0
  13. package/scripts/fixtures/rc2.cordis.yml +31 -0
  14. package/scripts/fixtures/rc2.overlay.yml +9 -0
  15. package/scripts/smoke-client.mjs +382 -0
  16. package/scripts/smoke-host.mjs +130 -0
  17. package/scripts/test-mcp-layering.mjs +441 -0
  18. package/scripts/test-mcp-tool-disable.mjs +420 -0
  19. package/scripts/test-rc2-runtime.mjs +42 -0
  20. package/scripts/test-skill-manager.mjs +170 -0
  21. package/scripts/test-skill-toggles.mjs +100 -0
  22. package/lib/catalog.js +0 -131
  23. package/lib/effective.js +0 -161
  24. package/lib/promotion.js +0 -80
  25. package/lib/schema.js +0 -125
  26. package/lib/sectionOps.d.mts +0 -67
  27. package/lib/sectionOps.mjs +0 -269
  28. package/lib/store.js +0 -124
  29. package/lib/vars.js +0 -147
  30. package/lib/zh/cordis.mjs +0 -110
  31. package/lib/zh/core.mjs +0 -47
  32. package/lib/zh/index.d.mts +0 -8
  33. package/lib/zh/index.mjs +0 -23
  34. package/lib/zh/sdk.mjs +0 -22
  35. package/lib/zh/teams.mjs +0 -19
  36. package/lib/zh/undo.mjs +0 -18
  37. package/src/client/Panel.tsx +0 -532
  38. package/src/client/PresetsPane.tsx +0 -298
  39. package/src/client/PreviewPane.tsx +0 -73
  40. package/src/client/PreviewTools.tsx +0 -33
  41. package/src/client/SectionsPane.tsx +0 -331
  42. package/src/client/ToolsPane.tsx +0 -230
  43. package/src/client/error-boundary.tsx +0 -48
  44. package/src/client/index.ts +0 -97
  45. package/src/client/locales.ts +0 -301
  46. package/src/client/nav.tsx +0 -284
  47. package/src/client/preset-io.ts +0 -226
  48. package/src/client/presets.ts +0 -413
  49. package/src/client/shell.tsx +0 -179
  50. package/src/client/styles.ts +0 -59
  51. package/src/client/types.ts +0 -125
@@ -0,0 +1,382 @@
1
+ /**
2
+ * dsh-prompt-customizer — browser half smoke test.
3
+ *
4
+ * Executes `lib/client.js` under a stubbed DSH client environment and asserts:
5
+ * 1. it registers exactly one `__ModuleLoader__` entry with the right id
6
+ * 2. the factory exports `apply` (function) and `inject` (array)
7
+ * 3. every member the bundle reads off `@deepseek-ai/dsh-client-ui-primitives`
8
+ * exists in the DSH build installed here — the stub Proxy below cannot see
9
+ * an upstream rename, and a missing named export is a runtime crash inside
10
+ * the panel rather than a build error (how the 0.1.7 icon rename slipped
11
+ * through: 13 renamed icons, zero build/test failures, dead panel)
12
+ * 4. `apply(ctx)` mounts the capability modules (skills panel + prompt locale)
13
+ * without throwing
14
+ *
15
+ * Usage: node scripts/smoke-client.mjs
16
+ */
17
+
18
+ import { existsSync, readFileSync } from 'node:fs'
19
+ import { resolve, dirname, join } from 'node:path'
20
+ import { fileURLToPath } from 'node:url'
21
+ import vm from 'node:vm'
22
+
23
+ const HERE = dirname(fileURLToPath(import.meta.url))
24
+ const ROOT = resolve(HERE, '..')
25
+ const CLIENT = resolve(ROOT, 'client/client.js')
26
+
27
+ /** The one DSH client module the bundle requires at runtime. */
28
+ const PRIMITIVES = '@deepseek-ai/dsh-client-ui-primitives'
29
+ /** Bare name + scope, for filesystem joins (`PRIMITIVES` keeps the specifier). */
30
+ const PRIMITIVES_NAME = 'dsh-client-ui-primitives'
31
+ const SCOPE = '@deepseek-ai'
32
+
33
+ /**
34
+ * Translate one PATH entry into a Windows-usable absolute prefix.
35
+ *
36
+ * A git-bash/MSYS `PATH` reaches Node in POSIX form (`/c/nvm4w/nodejs`), which
37
+ * `node:path` on win32 would turn into `\c\nvm4w\nodejs` and never find; the
38
+ * `dsh` CLI's own install root is what carries the client packages.
39
+ */
40
+ function nativePrefix(entry) {
41
+ const trimmed = entry.trim().replace(/^"|"$/g, '')
42
+ if (process.platform !== 'win32') return trimmed
43
+ const msys = /^\/([A-Za-z])\/(.*)$/.exec(trimmed)
44
+ if (msys !== null) return `${msys[1].toUpperCase()}:/${msys[2]}`
45
+ return trimmed
46
+ }
47
+
48
+ /** Candidate directories that may hold the installed primitives package. */
49
+ function primitivesCandidates() {
50
+ const home = process.env.DSH_HOME ?? join(process.env.USERPROFILE ?? process.env.HOME ?? '', '.dsh')
51
+ const candidates = []
52
+ /**
53
+ * One install root: the globally installed `dsh` CLI keeps its DSH packages
54
+ * (client ones included) in its own nested `node_modules`, so probe there
55
+ * first, then the plain hoisted form.
56
+ */
57
+ const pushRoot = (root) => {
58
+ if (root === undefined || root.trim() === '') return
59
+ candidates.push(join(root, 'node_modules', SCOPE, 'dsh', 'node_modules', SCOPE, PRIMITIVES_NAME))
60
+ candidates.push(join(root, 'node_modules', SCOPE, PRIMITIVES_NAME))
61
+ }
62
+ // The running Node's own root carries the globally installed dsh.
63
+ pushRoot(dirname(process.execPath))
64
+ const pathValue = process.env.PATH ?? process.env.Path ?? ''
65
+ for (const entry of pathValue.split(process.platform === 'win32' ? ';' : ':')) pushRoot(nativePrefix(entry))
66
+ // A profile-launched host hoists DSH packages one level above the profile.
67
+ pushRoot(join(home, 'profiles'))
68
+ return candidates
69
+ }
70
+
71
+ /** Locate the installed primitives package, or undefined when absent. */
72
+ function findPrimitives() {
73
+ for (const dir of primitivesCandidates()) {
74
+ if (existsSync(join(dir, 'package.json')) && existsSync(join(dir, 'lib', 'index.js'))) return dir
75
+ }
76
+ return undefined
77
+ }
78
+
79
+ /** Exported names of the installed primitives build (`export { ... }` block). */
80
+ function exportedNamesOf(dir) {
81
+ const code = readFileSync(join(dir, 'lib', 'index.js'), 'utf8')
82
+ const names = new Set()
83
+ for (const block of code.matchAll(/export\s*\{([^}]*)\}/g)) {
84
+ for (const part of block[1].split(',')) {
85
+ const clean = part.trim().split(/\s+as\s+/).pop()?.trim()
86
+ if (clean !== undefined && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(clean)) names.add(clean)
87
+ }
88
+ }
89
+ return names
90
+ }
91
+
92
+ /**
93
+ * Members the built bundle reads off the primitives module, scanned statically.
94
+ *
95
+ * Static rather than runtime on purpose: esbuild emits `(0, import_x.IconFoo)`
96
+ * at each JSX *use site*, so a component that never renders in this stub
97
+ * environment would never touch the property — the icon rename that motivated
98
+ * this check lived exactly there. The bundle is CJS with one `require` binding
99
+ * per source file, so binding name + member accesses cover every read.
100
+ */
101
+ function bundlePrimitivesMembers(file) {
102
+ const code = readFileSync(file, 'utf8')
103
+ const members = new Set()
104
+ const spec = PRIMITIVES.replace(/[/\\^$*+?.()|[\]{}]/g, '\\$&')
105
+ for (const binding of code.matchAll(new RegExp(`(?:var|const|let)\\s+([A-Za-z0-9_$]+)\\s*=\\s*require\\("${spec}"\\)`, 'g'))) {
106
+ const name = binding[1]
107
+ for (const hit of code.matchAll(new RegExp(`${name}\\.([A-Za-z_$][A-Za-z0-9_$]*)`, 'g'))) members.add(hit[1])
108
+ }
109
+ return members
110
+ }
111
+
112
+ const primitivesDir = findPrimitives()
113
+ const primitivesExports = primitivesDir === undefined ? undefined : exportedNamesOf(primitivesDir)
114
+ const primitivesMembersRead = bundlePrimitivesMembers(CLIENT)
115
+ const primitivesMembersMissing = new Set(
116
+ [...primitivesMembersRead].filter(name => primitivesExports !== undefined && !primitivesExports.has(name)),
117
+ )
118
+
119
+ /** Stand-in for any React component export. */
120
+ function stubComponent(name) {
121
+ const Comp = () => ({ __stub: name })
122
+ Object.defineProperty(Comp, 'name', { value: name })
123
+ return Comp
124
+ }
125
+
126
+ /**
127
+ * Minimal DOM node. The nav-row mounting code walks the real sidebar with
128
+ * `compareDocumentPosition`, so the stub has to answer it or the skills module
129
+ * bails out before reaching the interesting code paths.
130
+ */
131
+ function stubNode(tag = 'div') {
132
+ const node = {
133
+ tagName: String(tag).toUpperCase(),
134
+ children: [],
135
+ style: {},
136
+ dataset: {},
137
+ classList: { add: () => {}, remove: () => {}, toggle: () => {}, contains: () => false },
138
+ attrs: {},
139
+ appendChild(child) { node.children.push(child); return child },
140
+ insertBefore(child) { node.children.unshift(child); return child },
141
+ removeChild(child) {
142
+ const i = node.children.indexOf(child)
143
+ if (i >= 0) node.children.splice(i, 1)
144
+ return child
145
+ },
146
+ remove() {},
147
+ setAttribute(k, v) { node.attrs[k] = v },
148
+ getAttribute(k) { return node.attrs[k] ?? null },
149
+ removeAttribute(k) { delete node.attrs[k] },
150
+ addEventListener() {},
151
+ removeEventListener() {},
152
+ querySelector: () => null,
153
+ querySelectorAll: () => [],
154
+ getBoundingClientRect: () => ({ x: 0, y: 0, top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0 }),
155
+ contains: () => false,
156
+ compareDocumentPosition: () => 0,
157
+ getRootNode: () => sandbox.document,
158
+ focus: () => {},
159
+ click: () => {},
160
+ }
161
+ return node
162
+ }
163
+
164
+ /** Explicit React overrides. Kept separate so the Proxy below can consult it
165
+ * first — a bare `get` trap would otherwise shadow every one of these. */
166
+ const REACT_OVERRIDES = {
167
+ createElement: (type, props, ...children) => ({ type, props, children }),
168
+ cloneElement: (el) => el,
169
+ isValidElement: () => false,
170
+ Children: { map: () => [], forEach: () => {}, count: () => 0, toArray: () => [] },
171
+ Fragment: Symbol('Fragment'),
172
+ // Real class, not a stub function: `class X extends Component` is a
173
+ // module-top-level evaluation (error boundaries), and extending the
174
+ // generic stub function throws "is not a constructor".
175
+ Component: class Component {
176
+ constructor(props) {
177
+ this.props = props
178
+ this.state = null
179
+ }
180
+
181
+ setState() {}
182
+
183
+ forceUpdate() {}
184
+
185
+ render() {
186
+ return null
187
+ }
188
+ },
189
+ StrictMode: stubComponent('StrictMode'),
190
+ Suspense: stubComponent('Suspense'),
191
+ memo: (comp) => comp,
192
+ forwardRef: (render) => render,
193
+ lazy: () => stubComponent('Lazy'),
194
+ startTransition: (fn) => fn?.(),
195
+ createRef: () => ({ current: null }),
196
+ createContext: () => ({ Provider: stubComponent('Provider'), Consumer: stubComponent('Consumer') }),
197
+ useState: (init) => [typeof init === 'function' ? init() : init, () => {}],
198
+ useReducer: (reducer, init) => [init, () => {}],
199
+ useEffect: () => {},
200
+ useLayoutEffect: () => {},
201
+ useInsertionEffect: () => {},
202
+ useMemo: (fn) => fn(),
203
+ useCallback: (fn) => fn,
204
+ useRef: (init) => ({ current: init }),
205
+ useImperativeHandle: () => {},
206
+ useContext: () => ({}),
207
+ useId: () => 'stub-id',
208
+ useDebugValue: () => {},
209
+ useSyncExternalStore: (_sub, get) => get(),
210
+ useTransition: () => [false, (fn) => fn?.()],
211
+ useDeferredValue: (v) => v,
212
+ }
213
+
214
+ /** Everything the bundle may ask the platform for. */
215
+ const MODULES = {
216
+ 'react': new Proxy(REACT_OVERRIDES, {
217
+ // Known export → the real override; anything else (icon sets, future
218
+ // hooks) falls back to a stub component.
219
+ get: (target, prop) => {
220
+ if (typeof prop !== 'string') return undefined
221
+ if (Object.hasOwn(target, prop)) return target[prop]
222
+ return stubComponent(prop)
223
+ },
224
+ has: () => true,
225
+ }),
226
+ 'react/jsx-runtime': {
227
+ jsx: (type, props) => ({ type, props }),
228
+ jsxs: (type, props) => ({ type, props }),
229
+ Fragment: Symbol('Fragment'),
230
+ },
231
+ 'react-dom': { createPortal: (node) => node },
232
+ 'react-dom/client': { createRoot: () => ({ render: () => {}, unmount: () => {} }) },
233
+ // A stub component for any member: the export check above compares the
234
+ // bundle's static reads with the installed build, so a rename is reported
235
+ // there rather than turning into a confusing throw inside apply().
236
+ '@deepseek-ai/dsh-client-ui-primitives': new Proxy({}, {
237
+ get: (_t, prop) => (typeof prop === 'string' ? stubComponent(prop) : undefined),
238
+ has: () => true,
239
+ }),
240
+ }
241
+
242
+ // ── capture the loader registration ──────────────────────────────────────
243
+ const registrations = []
244
+ const sandbox = {
245
+ __ModuleLoader__: { load: (entry) => { registrations.push(entry) } },
246
+ document: {
247
+ head: stubNode('head'),
248
+ body: stubNode('body'),
249
+ documentElement: stubNode('html'),
250
+ createElement: (tag) => stubNode(tag),
251
+ createTextNode: (text) => ({ nodeType: 3, textContent: text }),
252
+ querySelector: () => null,
253
+ querySelectorAll: () => [],
254
+ getElementById: () => null,
255
+ getElementsByTagName: () => [],
256
+ addEventListener: () => {},
257
+ removeEventListener: () => {},
258
+ },
259
+ console,
260
+ // Timers are recorded but never scheduled: the nav-mount poller would
261
+ // otherwise keep the event loop alive and hang the smoke run.
262
+ setTimeout: (() => { let id = 0; return (fn, ms) => { void fn; void ms; return ++id } })(),
263
+ clearTimeout: () => {},
264
+ setInterval: (() => { let id = 0; return (fn, ms) => { void fn; void ms; return ++id } })(),
265
+ clearInterval: () => {},
266
+ queueMicrotask: (fn) => fn(),
267
+ fetch: async () => ({ ok: false, status: 599, json: async () => ({}) }),
268
+ AbortController,
269
+ localStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} },
270
+ matchMedia: () => ({ matches: false, addEventListener: () => {}, removeEventListener: () => {} }),
271
+ requestAnimationFrame: (fn) => setTimeout(() => fn(Date.now()), 0),
272
+ cancelAnimationFrame: (id) => clearTimeout(id),
273
+ getComputedStyle: () => ({ getPropertyValue: () => '' }),
274
+ MutationObserver: class { observe() {} disconnect() {} },
275
+ ResizeObserver: class { observe() {} unobserve() {} disconnect() {} },
276
+ CSS: { supports: () => false },
277
+ }
278
+ // Browsers alias `window` to the global object; the bundle uses `window.setInterval`.
279
+ sandbox.window = sandbox
280
+ sandbox.globalThis = sandbox
281
+ sandbox.self = sandbox
282
+ sandbox.top = sandbox
283
+ sandbox.parent = sandbox
284
+ sandbox.location = { href: 'http://127.0.0.1:0/', origin: 'http://127.0.0.1:0', protocol: 'http:', host: '127.0.0.1:0' }
285
+ sandbox.navigator = { userAgent: 'dsh-prompt-customizer-smoke', language: 'zh-CN', maxTouchPoints: 0 }
286
+ sandbox.innerWidth = 1440
287
+ sandbox.innerHeight = 900
288
+ sandbox.devicePixelRatio = 1
289
+ sandbox.addEventListener = () => {}
290
+ sandbox.removeEventListener = () => {}
291
+ sandbox.dispatchEvent = () => true
292
+ sandbox.getComputedStyle = () => ({ getPropertyValue: () => '' })
293
+ sandbox.scrollTo = () => {}
294
+
295
+ const context = vm.createContext(sandbox)
296
+ const code = readFileSync(CLIENT, 'utf8')
297
+ new vm.Script(code, { filename: CLIENT }).runInContext(context)
298
+
299
+ // ── assertions ───────────────────────────────────────────────────────────
300
+ const fail = (msg) => { console.error(`FAIL ${msg}`); process.exitCode = 1 }
301
+ const pass = (msg) => console.log(`ok ${msg}`)
302
+
303
+ if (registrations.length !== 1) fail(`expected 1 loader registration, got ${registrations.length}`)
304
+ else pass('registered exactly one __ModuleLoader__ entry')
305
+
306
+ const entry = registrations[0]
307
+ if (entry?.id !== 'dsh-prompt-customizer') fail(`expected id "dsh-prompt-customizer", got ${JSON.stringify(entry?.id)}`)
308
+ else pass('loader id is "dsh-prompt-customizer"')
309
+
310
+ const require = (id) => {
311
+ if (id in MODULES) return MODULES[id]
312
+ throw new Error(`[smoke] unexpected require(${id}) — add it to the stub table`)
313
+ }
314
+
315
+ const mod = entry.factory(require)
316
+ if (typeof mod.apply !== 'function') fail('factory did not export apply()')
317
+ else pass('factory exports apply()')
318
+ if (!Array.isArray(mod.inject)) fail('factory did not export inject[]')
319
+ else pass(`factory exports inject[] = [${mod.inject.join(', ')}]`)
320
+
321
+ // 三个已移除的模块不得再出现在客户端入口上。
322
+ for (const gone of ['buildActivityGrid', 'activityColor', 'ACTIVITY_COLUMNS']) {
323
+ if (gone in mod) fail(`removed module still exports ${gone}`)
324
+ }
325
+
326
+ // ── run apply() against a stub client context ────────────────────────────
327
+ const registered = []
328
+ const slots = []
329
+ const namespaces = []
330
+ const ctx = {
331
+ effect: (fn) => { registered.push(typeof fn === 'function' ? fn() : undefined); return () => {} },
332
+ locale: {
333
+ register: (ns) => { namespaces.push(ns); return () => {} },
334
+ bind: () => (key) => String(key),
335
+ },
336
+ slots: {
337
+ register: (spec, comp) => {
338
+ if (comp === undefined) throw new Error('slots.register called without component')
339
+ slots.push(spec.key === undefined ? spec.name : `${spec.name}#${spec.key}`)
340
+ return () => {}
341
+ },
342
+ inject: (name, factory) => { factory?.(); return () => {} },
343
+ },
344
+ get: (name) => (name === 'sessions' ? { list: { getSnapshot: () => ({ byId: {} }) } } : undefined),
345
+ }
346
+
347
+ try {
348
+ mod.apply(ctx)
349
+ pass('apply(ctx) mounted the capability modules without throwing')
350
+ } catch (error) {
351
+ fail(`apply(ctx) threw: ${error?.stack ?? error}`)
352
+ }
353
+
354
+ // 内核(@deepseek-ai/dsh-client-ui-skill)owns the `skill` locale namespace, the
355
+ // `tool.call.toolview` row keyed `skill`, and the `/` slash source. All three
356
+ // registries throw on a duplicate name/key, and the second registrant is the one
357
+ // that throws — so a duplicate here kills the KERNEL's apply and takes the whole
358
+ // client plugin chain down (hit for real in 0.6.0). Assert we register none of them.
359
+ if (slots.includes('tool.call.toolview#skill')) fail('registered the kernel-owned skill tool row (tool.call.toolview#skill)')
360
+ else pass('no duplicate skill tool row (kernel owns tool.call.toolview#skill)')
361
+ if (namespaces.includes('skill')) fail('registered the kernel-owned locale namespace "skill"')
362
+ else pass('no duplicate "skill" locale namespace (kernel owns it)')
363
+ if (namespaces.includes('prompt-customizer')) pass('prompt locale namespace registered ("prompt-customizer")')
364
+ else fail('prompt locale namespace "prompt-customizer" was not registered')
365
+
366
+ // ── the platform surface the bundle actually reads must exist in this DSH ──
367
+ if (primitivesExports === undefined) {
368
+ console.log('skip installed DSH client packages not found — export check skipped')
369
+ } else {
370
+ pass(`primitives export check ran against ${primitivesDir} (${primitivesExports.size} exports)`)
371
+ if (primitivesMembersRead.size === 0) fail('bundle read no primitives exports — the platform stub was bypassed')
372
+ else pass(`bundle reads ${primitivesMembersRead.size} primitives members`)
373
+ if (primitivesMembersMissing.size > 0) {
374
+ fail(`primitives members missing from this DSH build: ${[...primitivesMembersMissing].sort().join(', ')}`)
375
+ } else {
376
+ pass('every primitives member the bundle reads exists in this DSH build')
377
+ }
378
+ }
379
+
380
+ console.log(`\n${process.exitCode ? 'SMOKE FAILED' : 'SMOKE PASSED'} — ${CLIENT}`)
381
+ // Explicit exit: stubbed modules may hold listeners/timers that keep node alive.
382
+ process.exit(process.exitCode ?? 0)
@@ -0,0 +1,130 @@
1
+ /**
2
+ * dsh-prompt-customizer — host half smoke test.
3
+ *
4
+ * Imports the real `lib/index.js` and asserts the Cordis plugin contract, then
5
+ * runs `apply()` against a stub host context to prove the skills + MCP modules
6
+ * mount and register their routes without touching the real DSH runtime.
7
+ *
8
+ * Usage: node scripts/smoke-host.mjs
9
+ */
10
+
11
+ import { resolve, dirname } from 'node:path'
12
+ import { fileURLToPath, pathToFileURL } from 'node:url'
13
+
14
+ const HERE = dirname(fileURLToPath(import.meta.url))
15
+ const ROOT = resolve(HERE, '..')
16
+
17
+ const fail = (msg) => { console.error(`FAIL ${msg}`); process.exitCode = 1 }
18
+ const pass = (msg) => console.log(`ok ${msg}`)
19
+
20
+ // ── 1. import the plugin ─────────────────────────────────────────────────
21
+ let mod
22
+ try {
23
+ mod = await import(pathToFileURL(resolve(ROOT, 'lib/index.js')).href)
24
+ pass('lib/index.js imported (@deepseek-ai/* resolved from the live profile)')
25
+ } catch (error) {
26
+ fail(`cannot import lib/index.js: ${error?.stack ?? error}`)
27
+ process.exit(process.exitCode ?? 1)
28
+ }
29
+
30
+ // ── 2. Cordis plugin contract ────────────────────────────────────────────
31
+ if (mod.name !== 'dsh-prompt-customizer') fail(`expected name "dsh-prompt-customizer", got ${JSON.stringify(mod.name)}`)
32
+ else pass(`name = ${JSON.stringify(mod.name)}`)
33
+
34
+ if (!Array.isArray(mod.inject)) fail('inject is not an array')
35
+ else pass(`inject = [${mod.inject.join(', ')}]`)
36
+
37
+ for (const svc of ['webServer', 'tools']) {
38
+ if (!mod.inject.includes(svc)) fail(`inject is missing required service "${svc}"`)
39
+ }
40
+ pass('inject covers every service the skills + MCP modules reach for')
41
+
42
+ if (typeof mod.apply !== 'function') fail('apply is not a function')
43
+ else pass('apply is a function')
44
+
45
+ // ── 3. run apply() against a stub host context ───────────────────────────
46
+ const routes = new Map()
47
+ const listeners = new Map()
48
+ const tools = []
49
+ const logs = []
50
+
51
+ const ctx = {
52
+ logger: { info: (m) => logs.push(['info', m]), warn: (m) => logs.push(['warn', m]), debug: () => {} },
53
+ webServer: {
54
+ register(route) {
55
+ if (routes.has(route.path)) throw new Error(`duplicate route ${route.path}`)
56
+ routes.set(route.path, route)
57
+ return () => routes.delete(route.path)
58
+ },
59
+ },
60
+ tools: {
61
+ register(definition) {
62
+ if (typeof definition.name !== 'string') throw new Error('tool without name')
63
+ tools.push(definition.name)
64
+ return () => { const i = tools.indexOf(definition.name); if (i >= 0) tools.splice(i, 1) }
65
+ },
66
+ },
67
+ on: (event, handler) => {
68
+ if (!listeners.has(event)) listeners.set(event, [])
69
+ listeners.get(event).push(handler)
70
+ return () => {}
71
+ },
72
+ get: (name) => ctx[name],
73
+ effect: (fn) => { fn?.(); return () => {} },
74
+ // 提示词模块在自己的子作用域里挂 systemPrompt;stub 同步回调即可挂上。
75
+ inject: (names, callback) => { callback(ctx); return () => {} },
76
+ settings: { get: () => ({ providers: {} }), register: () => () => {} },
77
+ systemPrompt: {
78
+ assemble: async () => ({ sections: [], tools: [], contexts: [] }),
79
+ layers: { merge: () => new Map() },
80
+ variable: () => () => {},
81
+ },
82
+ sessionProjections: { register: () => () => {}, stateOf: () => undefined },
83
+ }
84
+
85
+ try {
86
+ await mod.apply(ctx, {})
87
+ pass('apply(ctx) completed without throwing')
88
+ } catch (error) {
89
+ fail(`apply(ctx) threw: ${error?.stack ?? error}`)
90
+ }
91
+
92
+ // ── 4. what actually got mounted ─────────────────────────────────────────
93
+ const paths = [...routes.keys()].sort()
94
+ console.log(`\n routes (${paths.length}):`)
95
+ for (const p of paths) console.log(` ${p}`)
96
+
97
+ console.log(`\n tools (${tools.length}):`)
98
+ for (const t of tools) console.log(` ${t}`)
99
+
100
+ console.log(`\n listeners (${listeners.size}): ${[...listeners.keys()].join(', ')}`)
101
+
102
+ const need = (cond, msg) => (cond ? pass(msg) : fail(msg))
103
+ need(paths.some(p => p.startsWith('/api/skill-manager')), 'skill routes registered (/api/skill-manager/*)')
104
+ // 技能面板的开关与「Agent 预设」筛选条都打这条;漏了就全 404、面板顶部没有预设条。
105
+ need(paths.some(p => p.startsWith('/api/skill-toggles')), 'skill toggle routes registered (/api/skill-toggles/*)')
106
+ need(paths.some(p => p.startsWith('/api/skill-health')), 'skill health route registered (/api/skill-health)')
107
+ need(paths.some(p => p.startsWith('/api/mcp-recommended')), 'mcp recommended route registered (/api/mcp-recommended)')
108
+ need(paths.some(p => p.startsWith('/api/triad/mcp-status')), 'mcp status route registered (/api/triad/mcp-status)')
109
+ need(paths.some(p => p.startsWith('/api/triad/mcp-config')), 'mcp config route registered (/api/triad/mcp-config)')
110
+ need(paths.some(p => p.startsWith('/api/triad/mcp-preview')), 'mcp preview route registered (/api/triad/mcp-preview)')
111
+ need(paths.some(p => p.startsWith('/api/prompt-customizer')), 'prompt customizer routes registered (/api/prompt-customizer/*)')
112
+ need(listeners.has('agent/created'), 'agent/created hooked (预设层开关与遮蔽)')
113
+ need(listeners.has('tools/change'), 'tools/change hooked (装配过滤失效重算)')
114
+ need(listeners.has('system-prompt/assemble'), 'system-prompt/assemble hooked (提示词段覆盖)')
115
+
116
+ // 三个已移除的模块不得留下任何路由、工具或事件钩子。
117
+ const leftovers = paths.filter(p => /^\/api\/(dsh-memory|usage-stats|triad-automation)/.test(p))
118
+ need(leftovers.length === 0, `removed modules left no routes${leftovers.length > 0 ? `: ${leftovers.join(', ')}` : ''}`)
119
+ need(tools.length === 0, `no model tools registered${tools.length > 0 ? `: ${tools.join(', ')}` : ''}`)
120
+ need(!listeners.has('agent/pre-step'), 'agent/pre-step injection gone')
121
+ need(!listeners.has('session/event'), 'session/event capture gone')
122
+
123
+ const warns = logs.filter(([lvl]) => lvl === 'warn')
124
+ if (warns.length > 0) {
125
+ console.log('\n warnings during apply:')
126
+ for (const [, m] of warns) console.log(` ${m}`)
127
+ }
128
+
129
+ console.log(`\n${process.exitCode ? 'SMOKE FAILED' : 'SMOKE PASSED'} — ${resolve(ROOT, 'lib/index.js')}`)
130
+ process.exit(process.exitCode ?? 0)