import assert from 'node:assert/strict' import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { test } from 'node:test' import { apply, inject, name } from '../index.js' function fakeCtx() { const tools = [] const guards = [] const handlers = {} return { tools: { register(def) { tools.push(def); return () => {} }, guard(fn) { guards.push(fn); return () => {} }, }, on(event, handler) { handlers[event] = handler; return () => {} }, get() { return undefined }, toolsList: tools, guards, handlers, } } test('插件导出与注入符合 DSH 约定', () => { assert.equal(name, 'sansheng') assert.deepEqual(inject, ['tools']) }) test('apply 注册全部工具、门禁与派发观测,并能读损坏的 DS Bot 状态文件', async () => { const dir = await mkdtemp(join(tmpdir(), 'sansheng-plugin-')) try { const dsbotState = join(dir, 'bot-state.json') await writeFile(dsbotState, '{ 不是 JSON', 'utf8') const ctx = fakeCtx() await apply(ctx, { statePath: join(dir, 'sansheng.json'), dsbotStatePath: dsbotState }) const names = ctx.toolsList.map(def => def.name).sort() assert.deepEqual(names, [ 'sansheng_bind', 'sansheng_provision', 'sansheng_reconcile', 'sansheng_review', 'sansheng_status', ]) assert.equal(ctx.guards.length, 1, '装了 group_goal 门禁') assert.equal(typeof ctx.handlers['tools/execute'], 'function', '装了派发观测') const status = ctx.toolsList.find(def => def.name === 'sansheng_status') const text = await status.execute({}, { agent: { id: 'some-session' } }) assert.match(text, /还没有绑定任何项目/) for (const def of ctx.toolsList) { assert.equal(def.parameters.type, 'object', `${def.name} 的参数是 JSON Schema`) assert.equal(typeof def.output?.render, 'function', `${def.name} 有文本渲染`) } } finally { await rm(dir, { recursive: true, force: true }) } }) test('宿主提供 webServer 时注册右栏数据接口', async () => { const dir = await mkdtemp(join(tmpdir(), 'sansheng-plugin-')) try { const routes = [] const ctx = fakeCtx() ctx.effect = fn => fn() ctx.get = (name, fallback) => (name === 'webServer' ? { register: options => { routes.push(options); return () => {} } } : fallback) await apply(ctx, { statePath: join(dir, 'sansheng.json'), dsbotStatePath: join(dir, 'missing-bot-state.json'), }) assert.equal(routes.length, 1, '注册了 /sansheng/state') assert.equal(routes[0].path, '/sansheng/state') } finally { await rm(dir, { recursive: true, force: true }) } })