dsh-dev-plan-presets 0.0.0-stage → 0.3.0

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.
@@ -0,0 +1,290 @@
1
+ /**
2
+ * 测试夹具:不启动 DSH、不读 profile,只用最小 Cordis 形状驱动真实插件代码。
3
+ *
4
+ * 覆盖的是“代码真的会做什么”:
5
+ * - apply() 是否真的注册了 preset、是否交还 disposer;
6
+ * - agent/created 是否只碰子代理;
7
+ * - agent/pre-step 越界是否 reject + cancel + 通知父会话;
8
+ * - HTTP 设置路由是否真的读写配置;
9
+ * - 回退是否真的写进 description/persona。
10
+ */
11
+
12
+ import { join } from 'node:path'
13
+ import { pathToFileURL } from 'node:url'
14
+
15
+ /** 加载真实模块(每次带 cache-bust,避免多测试互相污染)。 */
16
+ export async function loadModules(root) {
17
+ const stamp = `?test=${Date.now()}-${Math.random().toString(36).slice(2)}`
18
+ const url = (file) => pathToFileURL(join(root, file)).href + stamp
19
+ return {
20
+ settings: await import(url('settings.js')),
21
+ preset: await import(url('preset.js')),
22
+ guard: await import(url('guard.js')),
23
+ index: await import(url('index.js')),
24
+ }
25
+ }
26
+
27
+ const noopLogger = () => ({ warn() {}, info() {}, error() {} })
28
+
29
+ /**
30
+ * 创建最小 Context。
31
+ * @param {object} options
32
+ * @param {any} [options.config]
33
+ * @param {any[]} [options.entries] loader entries
34
+ * @param {any} [options.registry] agentPresets
35
+ * @param {any} [options.agents] ctx.get('agents')
36
+ * @param {any} [options.configEditor]
37
+ * @param {any} [options.webServer]
38
+ */
39
+ export function createFakeContext(options = {}) {
40
+ const disposers = []
41
+ const pending = []
42
+ const listeners = new Map()
43
+ const injectQueue = []
44
+ const loggerCalls = { info: [], warn: [], error: [] }
45
+ const logger = options.logger ?? {
46
+ info: (...args) => loggerCalls.info.push(args.map(String).join(' ')),
47
+ warn: (...args) => loggerCalls.warn.push(args.map(String).join(' ')),
48
+ error: (...args) => loggerCalls.error.push(args.map(String).join(' ')),
49
+ }
50
+ const services = new Map()
51
+ if (options.registry) services.set('agentPresets', options.registry)
52
+ if (options.agents) services.set('agents', options.agents)
53
+ if (options.configEditor) services.set('configEditor', options.configEditor)
54
+ if (options.webServer) services.set('webServer', options.webServer)
55
+ if (options.llm) services.set('llm', options.llm)
56
+
57
+ const context = {
58
+ logger,
59
+ fiber: { entry: options.entry ?? { id: 'dev-plan-presets', options: { config: options.config } } },
60
+ loader: { entries: () => options.entries ?? [] },
61
+ get(name) {
62
+ return services.get(name)
63
+ },
64
+ on(event, handler) {
65
+ const list = listeners.get(event) ?? []
66
+ list.push(handler)
67
+ listeners.set(event, list)
68
+ const off = () => {
69
+ const current = listeners.get(event) ?? []
70
+ const index = current.indexOf(handler)
71
+ if (index >= 0) current.splice(index, 1)
72
+ }
73
+ disposers.push(off)
74
+ return off
75
+ },
76
+ effect(body) {
77
+ let result
78
+ try {
79
+ result = body()
80
+ } catch {
81
+ return () => {}
82
+ }
83
+ if (result && typeof result.then === 'function') {
84
+ pending.push(result)
85
+ result.then((dispose) => {
86
+ if (typeof dispose === 'function') disposers.push(dispose)
87
+ })
88
+ return () => {}
89
+ }
90
+ if (result && typeof result[Symbol.iterator] === 'function' && typeof result !== 'function') {
91
+ const yielded = []
92
+ try {
93
+ for (const dispose of result) if (typeof dispose === 'function') yielded.push(dispose)
94
+ } catch {
95
+ /* ignore */
96
+ }
97
+ disposers.push(() => {
98
+ for (const dispose of yielded.reverse()) dispose()
99
+ })
100
+ return () => {}
101
+ }
102
+ if (typeof result === 'function') {
103
+ disposers.push(result)
104
+ return result
105
+ }
106
+ return () => {}
107
+ },
108
+ inject(deps = [], callback) {
109
+ const run = (child) => {
110
+ try {
111
+ callback(child)
112
+ } catch (error) {
113
+ loggerCalls.error.push(String(error?.message ?? error))
114
+ }
115
+ }
116
+ const ready = deps.every((dep) => services.has(dep))
117
+ if (ready) {
118
+ const child = makeChild(context, services, deps)
119
+ run(child)
120
+ return () => {}
121
+ }
122
+ injectQueue.push({ deps, run, services })
123
+ return () => {}
124
+ },
125
+ provide(name, service) {
126
+ services.set(name, service)
127
+ for (const item of [...injectQueue]) {
128
+ if (item.deps.every((dep) => item.services.has(dep))) {
129
+ injectQueue.splice(injectQueue.indexOf(item), 1)
130
+ item.run(makeChild(context, item.services, item.deps))
131
+ }
132
+ }
133
+ },
134
+ }
135
+
136
+ return {
137
+ ctx: context,
138
+ services,
139
+ loggerCalls,
140
+ listeners,
141
+ effects: disposers,
142
+ async flush() {
143
+ for (let round = 0; round < 6; round += 1) {
144
+ await new Promise((resolve) => setTimeout(resolve, 0))
145
+ const settled = [...pending]
146
+ pending.length = 0
147
+ await Promise.allSettled(settled)
148
+ }
149
+ },
150
+ async dispose() {
151
+ for (const dispose of disposers.reverse()) {
152
+ try {
153
+ await dispose()
154
+ } catch {
155
+ /* cleanup best effort */
156
+ }
157
+ }
158
+ },
159
+ }
160
+ }
161
+
162
+ function makeChild(parent, services, deps) {
163
+ const child = Object.create(parent)
164
+ for (const dep of deps) {
165
+ if (dep === 'agentPresets') child.agentPresets = services.get(dep)
166
+ if (dep === 'webServer') child.webServer = services.get(dep)
167
+ }
168
+ return child
169
+ }
170
+
171
+ export function createFakeRegistry({ rows = [], registerError, presetForSession } = {}) {
172
+ return {
173
+ definitions: [],
174
+ released: [],
175
+ rows,
176
+ async list() {
177
+ return this.rows
178
+ },
179
+ async register(definition) {
180
+ if (registerError) throw registerError
181
+ this.definitions.push(definition)
182
+ return async () => {
183
+ this.released.push(definition.id)
184
+ }
185
+ },
186
+ presetForSession(session) {
187
+ if (typeof presetForSession === 'function') return presetForSession(session)
188
+ return session?.header?.agentPreset ?? null
189
+ },
190
+ }
191
+ }
192
+
193
+ export function createFakeConfigEditor() {
194
+ return {
195
+ edits: [],
196
+ async edit(entry, change) {
197
+ const next = change({}, {})
198
+ this.edits.push({ entry, next })
199
+ },
200
+ }
201
+ }
202
+
203
+ export function createFakeWebServer(options = {}) {
204
+ const handlers = new Map()
205
+ const origin = options.origin ?? 'http://127.0.0.1:1162'
206
+ return {
207
+ handlers,
208
+ getOrigin() {
209
+ return origin
210
+ },
211
+ register(route) {
212
+ handlers.set(route.path, route.handler)
213
+ return () => handlers.delete(route.path)
214
+ },
215
+ }
216
+ }
217
+
218
+ export function createFakeAgent(options = {}) {
219
+ const selects = []
220
+ const cancelled = []
221
+ const injected = []
222
+ const stepHandlers = []
223
+ const agentEffects = []
224
+ const header = {}
225
+ if (options.parentSession) header.parentSession = options.parentSession
226
+ if (options.origin) header.origin = options.origin
227
+ if (options.agentPreset) header.agentPreset = options.agentPreset
228
+ if (options.delegationDepth !== undefined) header.delegationDepth = options.delegationDepth
229
+ if (options.isSeeded !== undefined) header.isSeeded = options.isSeeded
230
+ const model = { current: () => options.current }
231
+ if (options.select !== null) {
232
+ model.select = options.select ?? ((route) => selects.push({ ...route }))
233
+ }
234
+ const agent = {
235
+ id: options.id ?? 'child-1',
236
+ session: { id: `session-${options.id ?? 'child-1'}`, header },
237
+ model,
238
+ cancel: (cause) => cancelled.push(cause),
239
+ inject: (message) => injected.push(message),
240
+ ctx: {
241
+ on(event, handler) {
242
+ if (event === 'agent/pre-step') stepHandlers.push(handler)
243
+ return () => {
244
+ const index = stepHandlers.indexOf(handler)
245
+ if (index >= 0) stepHandlers.splice(index, 1)
246
+ }
247
+ },
248
+ effect(body) {
249
+ const result = body()
250
+ if (typeof result === 'function') agentEffects.push(result)
251
+ return result
252
+ },
253
+ },
254
+ }
255
+ return { agent, selects, cancelled, injected, stepHandlers, agentEffects }
256
+ }
257
+
258
+ /** 构造一个只实现 state/config 路由所需的 req/res。 */
259
+ export async function callRoute(handler, method, body, headers = {}) {
260
+ return await new Promise((resolve, reject) => {
261
+ const res = {
262
+ code: 200,
263
+ headers: {},
264
+ writeHead(code, headers) {
265
+ this.code = code
266
+ this.headers = headers ?? {}
267
+ },
268
+ end(payload) {
269
+ try {
270
+ resolve({ code: this.code, headers: this.headers, body: payload ? JSON.parse(payload) : null })
271
+ } catch (error) {
272
+ reject(error)
273
+ }
274
+ },
275
+ }
276
+ const requestHeaders = { ...headers }
277
+ // 大多数测试提交 JSON;显式传 headers 可覆盖为 text/plain 等。
278
+ if (body !== undefined && requestHeaders['content-type'] === undefined) {
279
+ requestHeaders['content-type'] = 'application/json'
280
+ }
281
+ const req = {
282
+ method,
283
+ headers: requestHeaders,
284
+ async *[Symbol.asyncIterator]() {
285
+ if (body !== undefined) yield typeof body === 'string' ? body : JSON.stringify(body)
286
+ },
287
+ }
288
+ Promise.resolve(handler(req, res)).catch(reject)
289
+ })
290
+ }