dsh-brain/verify-client-build.mjs

228 lines
13 KiB
JavaScript

// Client-build verification.
// U0: the bundled client keeps the __ModuleLoader__ contract, loads like the
// legacy hand-written file, and registers the same settings seats.
// U1: the Brain panel registers on both native seats (main + sidebar.panellist)
// and degrades silently when a seat is missing.
import { once } from 'node:events'
import { existsSync, readFileSync } from 'node:fs'
import { mkdir, mkdtemp, rm } from 'node:fs/promises'
import { createServer } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createRequire } from 'node:module'
import vm from 'node:vm'
const require = createRequire(import.meta.url)
const React = require('react')
const results = []
function check(name, ok, detail = '') {
results.push({ name, ok })
console.log((ok ? 'PASS ' : 'FAIL ') + name + (detail === '' ? '' : ' :: ' + detail))
}
const bundle = readFileSync(new URL('./client/index.js', import.meta.url), 'utf8')
check('client bundle uses the __ModuleLoader__ contract', bundle.includes('__ModuleLoader__.load'))
check('client bundle id stays dsh-brain', /id:\s*['"]dsh-brain['"]/.test(bundle))
const cssModuleIds = [...bundle.matchAll(/^\s*\/\/ \S*?dsh-brain-css:(\S+)$/gm)].map((match) => match[1])
check('client CSS module comments use portable repository paths',
cssModuleIds.length === 2 && cssModuleIds.every((id) => /^src-client\/.*\.module\.css\.mjs$/.test(id)))
for (const seat of ['settings.section', 'plugins.bundle.config', 'sidebar.panellist']) {
check('client bundle registers ' + seat, bundle.includes(seat))
}
for (const label of ['连接与上报', '技能管理', 'MCP 管理', '概览', '部门']) {
check('client bundle keeps tab label ' + label, bundle.includes(label))
}
check('client bundle keeps the panel semantic anchor', bundle.includes('data-dsh-panel-entry') && bundle.includes('data-dsh-plugin'))
check('client bundle registers the better-sidebar tab surface', bundle.includes('dsh-brain:memory') && bundle.includes('registerTab') && bundle.includes('internal/service'))
check('better-sidebar view keeps a visible pause branch', bundle.includes('visible') && bundle.includes('项目记忆'))
for (const apiPath of ['/dsh-brain/local-memory/status', '/dsh-brain/local-memory/memories', '/dsh-brain/local-memory/documents', '/dsh-brain/local-memory/forget', '/dsh-brain/departments/list', '/dsh-brain/departments/create', '/dsh-brain/departments/update', '/dsh-brain/departments/disable', '/dsh-brain/departments/checkpoint', '/dsh-brain/departments/recall']) {
check('client bundle consumes ' + apiPath, bundle.includes(apiPath))
}
for (const label of ['记忆条目', '部门列表', '部门召回', '数据已变化,请刷新']) {
check('client bundle keeps U2 surface ' + label, bundle.includes(label))
}
check('client bundle is a single file with only react externals', (() => {
const requires = [...bundle.matchAll(/require\(\s*['"]([^'"]+)['"]\s*\)/g)].map((match) => match[1])
return requires.every((name) => name === 'react' || name === 'react/jsx-runtime')
})())
function loadBundle(file) {
const code = readFileSync(file, 'utf8')
let definition = null
const sandbox = {
window: {
__ModuleLoader__: { load(value) { definition = value } },
localStorage: { getItem: () => null, setItem: () => {} },
open: () => undefined,
},
console,
setTimeout,
clearTimeout,
fetch: async () => { throw new Error('fetch not available in verification') },
AbortController,
}
sandbox.window.window = sandbox.window
sandbox.globalThis = sandbox
vm.runInNewContext(code, sandbox, { filename: String(file) })
if (definition === null) throw new Error('bundle did not register with __ModuleLoader__: ' + file)
return definition.factory((name) => {
if (name === 'react') return React
if (name === 'react/jsx-runtime') return require('react/jsx-runtime')
throw new Error('unexpected require: ' + name)
})
}
function exercise(file) {
const mod = loadBundle(file)
const registrations = []
const ctx = {
slots: {
inject(seat, callback) { callback() },
register(options, component) {
registrations.push({ seat: options.name, options, component })
return () => {}
},
},
effect(setup) {
const dispose = typeof setup === 'function' ? setup() : undefined
return typeof dispose === 'function' ? dispose : () => {}
},
}
mod.apply(ctx)
return { name: mod.name, inject: mod.inject, registrations }
}
function shapeOf(entry) {
return {
seat: entry.seat,
name: entry.options.name,
id: entry.options.id,
key: entry.options.key,
order: entry.options.order,
label: typeof entry.options.label === 'function' ? entry.options.label() : undefined,
inject: typeof entry.options.inject === 'function' ? 'function' : undefined,
}
}
const current = exercise('client/index.js')
const seats = current.registrations.map((entry) => entry.seat)
check('apply registers settings + panel seats', ['settings.section', 'plugins.bundle.config', 'main', 'sidebar.panellist'].every((seat) => seats.includes(seat)), JSON.stringify(seats))
const bySeat = Object.fromEntries(current.registrations.map((entry) => [entry.seat, entry]))
check('settings.section keeps its id/order/label', JSON.stringify(shapeOf(bySeat['settings.section'])) === JSON.stringify({ seat: 'settings.section', name: 'settings.section', id: 'dsh-brain', key: undefined, order: 100, label: '云端记忆', inject: undefined }))
check('plugins.bundle.config keeps its key', JSON.stringify(shapeOf(bySeat['plugins.bundle.config'])) === JSON.stringify({ seat: 'plugins.bundle.config', name: 'plugins.bundle.config', id: undefined, key: 'dsh-brain', order: undefined, label: undefined, inject: undefined }))
check('main panel uses the dsh-brain panel key', bySeat['main'] !== undefined && bySeat['main'].options.key === 'dsh-brain' && typeof bySeat['main'].options.inject === 'function')
check('sidebar panellist row uses id dsh-brain at order 30 with Brain label', bySeat['sidebar.panellist'] !== undefined && bySeat['sidebar.panellist'].options.id === 'dsh-brain' && bySeat['sidebar.panellist'].options.order === 30 && bySeat['sidebar.panellist'].options.label() === 'Brain')
check('module exports name dsh-brain', current.name === 'dsh-brain' && Array.isArray(current.inject) && current.inject.includes('slots'))
let rendered = 0
for (const entry of current.registrations) {
const element = typeof entry.component === 'function' ? React.createElement(entry.component) : null
if (element !== null && typeof element === 'object' && element.type !== undefined) rendered += 1
}
check('registered components render without throwing', rendered === current.registrations.length)
let silentThrew = false
try {
const mod = loadBundle('client/index.js')
mod.apply({ slots: { inject() {}, register() { throw new Error('must not register') } }, effect(setup) { if (typeof setup === 'function') setup() } })
} catch { silentThrew = true }
check('missing panel seats degrade silently', !silentThrew)
let rejectThrew = false
try {
const mod = loadBundle('client/index.js')
mod.apply({ slots: { inject() { throw new Error('seat unavailable') }, register() { return () => {} } }, effect(setup) { if (typeof setup === 'function') setup() } })
} catch { rejectThrew = true }
check('rejecting panel seats degrade without throwing', !rejectThrew)
let sidebarDescriptor = null
let sidebarListener = null
let currentService = undefined
let sidebarThrew = false
try {
const mod = loadBundle('client/index.js')
const service = { registerTab(descriptor) { sidebarDescriptor = descriptor; return () => {} } }
mod.apply({
slots: { inject(seat, callback) { callback() }, register() { return () => {} } },
get(name) { return name === 'betterSidebar' ? currentService : undefined },
on(name, listener) { if (name === 'internal/service') sidebarListener = listener; return () => {} },
effect(setup) { if (typeof setup === 'function') setup() },
})
if (sidebarDescriptor !== null) throw new Error('tab must not register without a service')
currentService = service
sidebarListener('betterSidebar')
} catch { sidebarThrew = true }
check('better-sidebar tab is absent without the service', !sidebarThrew && sidebarDescriptor !== null)
check('better-sidebar tab registers with the expected descriptor', sidebarDescriptor !== null && sidebarDescriptor.id === 'dsh-brain:memory' && sidebarDescriptor.order === 60 && sidebarDescriptor.single === true && typeof sidebarDescriptor.title === 'function' && sidebarDescriptor.title() === '项目记忆' && typeof sidebarDescriptor.description === 'string' && sidebarDescriptor.description.includes('项目'))
check('better-sidebar tab hot-plugs through internal/service', sidebarListener !== null && typeof sidebarListener === 'function')
const legacyFile = new URL('./artifacts/analysis/client-legacy.js', import.meta.url)
if (existsSync(legacyFile)) {
const legacy = exercise(legacyFile)
const pickSettingsSeats = (value) => value.registrations.filter((entry) => entry.seat === 'settings.section' || entry.seat === 'plugins.bundle.config').map(shapeOf).sort((left, right) => left.seat.localeCompare(right.seat))
check('migration preserves settings registration shape', JSON.stringify(pickSettingsSeats(current)) === JSON.stringify(pickSettingsSeats(legacy)), JSON.stringify({ current: pickSettingsSeats(current), legacy: pickSettingsSeats(legacy) }))
} else {
console.log('SKIP legacy comparison (artifacts/analysis/client-legacy.js missing)')
}
// Keep the static request checks local to each consumer, so the presence of a
// workspace parameter elsewhere in the bundle cannot satisfy them.
const memoryTab = readFileSync(new URL('./src-client/panel/MemoryTab.tsx', import.meta.url), 'utf8')
const sidebar = readFileSync(new URL('./src-client/sidebar/ProjectMemoryView.tsx', import.meta.url), 'utf8')
check('memory tab scopes status, memories and documents to the active workspace',
memoryTab.includes("request('/dsh-brain/local-memory/status' + workspaceQuery(workspace))") &&
memoryTab.includes("'&offset=' + String(offset) + workspaceSuffix(workspace)") &&
memoryTab.includes("request('/dsh-brain/local-memory/documents' + workspaceQuery(workspace))"))
check('sidebar scopes status and memories to its workspace',
sidebar.includes('props.scope?.cwd') &&
sidebar.includes("request('/dsh-brain/local-memory/status' + workspaceQuery(workspace))") &&
sidebar.includes("'&workspace=' + encodeURIComponent(workspace)") &&
sidebar.includes("request('/dsh-brain/local-memory/memories?limit=50&offset=0' + suffix)"))
const root = await mkdtemp(join(tmpdir(), 'brain-ui-workspace-'))
try {
const [projectA, projectB] = [join(root, 'project a'), join(root, 'project b')]
await Promise.all([mkdir(projectA), mkdir(projectB)])
const { LocalMemoryManager, projectBrainRoot } = await import('./lib/local-memory/index.js')
const { createCoreRoutes, ROUTES } = await import('./lib/routes.js')
const localMemory = new LocalMemoryManager({ cwd: () => projectA, globalRoot: join(root, 'global') })
const a = await localMemory.withWorkspace(projectA, () => localMemory.remember({ scope: 'project', content: 'workspace A sample' }))
const b = await localMemory.withWorkspace(projectB, () => localMemory.remember({ scope: 'project', content: 'workspace B sample' }))
const documentB = await localMemory.addDocument({ title: 'Workspace B document', content: 'workspace B sample document' }, projectB)
const route = createCoreRoutes({ localMemory }).find((entry) => entry.path === ROUTES.localMemory)
const server = createServer((req, res) => {
void route.handler(req, res).catch(() => { res.statusCode = 500; res.end() })
})
server.listen(0, '127.0.0.1')
try {
await once(server, 'listening')
const origin = 'http://127.0.0.1:' + server.address().port
const base = origin + ROUTES.localMemory
const workspace = '?workspace=' + encodeURIComponent(projectB)
const getJson = async (suffix) => {
const response = await fetch(base + suffix)
if (!response.ok) throw new Error(suffix + ': HTTP ' + response.status)
return response.json()
}
const [defaultPage, scopedPage, status, documents] = await Promise.all([
getJson('/memories'), getJson('/memories' + workspace), getJson('/status' + workspace), getJson('/documents' + workspace),
])
check('omitting workspace still lists the default project', defaultPage.total === 1 && defaultPage.items[0]?.id === a.record.id)
check('workspace query lists only the selected project fixture', scopedPage.total === 1 && scopedPage.items[0]?.id === b.record.id)
check('status and documents read the selected project', status.projectRoot === projectBrainRoot(projectB) && documents.documents[0]?.id === documentB.id)
const forget = await fetch(base + '/forget', {
method: 'POST', headers: { origin, 'content-type': 'application/json' },
body: JSON.stringify({ id: b.record.id, expectedRevision: b.record.revision, workspace: projectB }),
})
check('forget uses the target workspace and preserves the default project', forget.ok && (await getJson('/memories' + workspace)).total === 0 && (await getJson('/memories')).items[0]?.id === a.record.id)
} finally {
await new Promise((resolve) => server.close(resolve))
}
} finally {
await rm(root, { recursive: true, force: true })
}
console.log('\n' + (results.every((result) => result.ok) ? 'ALL ' + results.length + ' CHECKS PASSED' : results.filter((result) => !result.ok).length + ' FAILED'))
process.exit(results.every((result) => result.ok) ? 0 : 1)