// 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 === 1 && 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('Brain does not bundle a replacement for the Mnemon right tab', !bundle.includes('dsh-brain:memory')) // Memory reads moved to the Mnemon bridge (single source of truth); the local // forget path stays for the future write round. Departments are unchanged. for (const apiPath of ['/dsh-brain/mnemon/runtime', '/dsh-brain/mnemon/list', '/dsh-brain/mnemon/status', '/dsh-brain/mnemon/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') 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) 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)') } // The global panel must pass an explicit scope to both management tabs. const layout = readFileSync(new URL('./src-client/panel/BrainPanel.tsx', import.meta.url), 'utf8') const patch = readFileSync(new URL('./cordis.patch.yml', import.meta.url), 'utf8') check('global panel binds both tabs to global data', layout.includes("h(MemoryTab, { scope: 'global' })") && layout.includes("h(DepartmentTab, { scope: 'global' })")) check('the UI loader row mounts at the package root for browser discovery', /id: dsh-brain-ui\r?\n(?: *#[^\r\n]*\r?\n)* *name: dsh-brain\r?\n *config:\r?\n *entry: ui(?:\r?\n|$)/.test(patch)) check('settings section mounts the full plugin config form', bySeat['settings.section']?.component === bySeat['plugins.bundle.config']?.component && typeof bySeat['settings.section']?.component === 'function') 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 + '&scope=project'), ]) 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 invalidDocuments = await Promise.all([ fetch(base + '/documents?scope=project'), fetch(base + '/documents' + workspace + '&scope=global'), ]) check('explicit document scope requires a project workspace', invalidDocuments.every(({ status }) => status === 400)) 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)