/** Failure policy through the built Web process and native configuration watcher. */ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { createServer } from 'node:http' import { join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { execa } from 'execa' import { describe, expect, it } from 'vitest' import { FiberState } from '@deepseek-ai/cordis' const repoRoot = fileURLToPath(new URL('../../../../../../', import.meta.url)) const bin = join(repoRoot, 'apps/cli/lib/bin.js') const built = existsSync(bin) && existsSync(join(repoRoot, 'apps/web/dist/index.html')) const failures = [ ['import', 'missing.mjs'], ['module evaluation', 'matrix module evaluation'], ['schema', 'matrix schema failure'], ['config expression', 'matrix config expression'], ['disabled expression', 'matrix disabled expression'], ['sync apply', 'matrix sync apply'], ['async apply', 'matrix async apply'], ['dependency', 'matrixMissingService'], ] as const type Failure = typeof failures[number][0] function fixture() { const root = mkdtempSync(join(tmpdir(), 'dsh-web-failure-matrix-')) const home = join(root, 'home') mkdirSync(home) const events = join(root, 'events') const diagnostics = join(root, 'diagnostics') const serverUrl = join(root, 'server-url') const states = join(root, 'states') const stop = join(root, 'stop') const patch = join(home, 'cordis.patch.yml') const watcher = join(root, 'watcher.patch.yml') // Native delivery remains real; completed writes bypass Chokidar's 50 ms change suppression. writeFileSync(watcher, JSON.stringify([{ id: 'hmr', disabled: false, config: { root: [], awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 20 }, } }]) + '\n') writeFileSync(events, '') writeFileSync(diagnostics, '') writeFileSync(states, '{}') const observerPath = join(root, 'observer.mjs') // HMR reports through Cordis logger exporters; WARN is above their default INFO threshold. writeFileSync(observerPath, [ "import { appendFileSync, writeFileSync, renameSync, rmSync } from 'node:fs'", "import { inspect } from 'node:util'", 'export function apply(ctx, config) {', ' const report = message => appendFileSync(config.path, message.args.map(arg => inspect(arg)).join(" ") + "\\n")', ' ctx.logger.buffer.forEach(report)', ' ctx.logger.exporter({ levels: { default: 3 }, export: report })', ' const timer = setInterval(() => {', ' const loader = ctx.get("loader")', ' if (!loader) return', ' writeFileSync(config.states + ".tmp", JSON.stringify(Object.fromEntries([...loader.entries()].map(entry => [entry.options.id, entry.fiber?.state]))))', ' renameSync(config.states + ".tmp", config.states)', ' }, 20)', ' ctx.effect(() => () => { clearInterval(timer) })', ' ctx.inject(["webServer", "connection"], scope => {', ' writeFileSync(config.url, scope.connection.authenticatedUrl(`http://127.0.0.1:${scope.webServer.port}`))', ' scope.effect(() => () => { rmSync(config.url, { force: true }) })', ' })', '}', '', ].join('\n')) const observer = { id: 'matrix-log-observer', name: pathToFileURL(observerPath).href, config: { path: diagnostics, url: serverUrl, states } } const plugin = join(root, 'probe.mjs') writeFileSync(plugin, [ "import { appendFileSync, existsSync } from 'node:fs'", 'export const Config = { "~standard": { version: 1, vendor: "matrix", validate(value) {', ' return value.mode === "schema" ? { issues: [{ message: "matrix schema failure" }] } : { value }', '} } }', 'export const apply = (ctx, config) => {', ' if (config.mode === "sync apply") throw new Error("matrix sync apply")', ' return activate(ctx, config)', '}', 'async function activate(ctx, config) {', ' if (config.mode === "async apply") { await Promise.resolve(); throw new Error("matrix async apply") }', ' if (config.provider) ctx.provide(config.provider, true)', ' if (config.mode === "detached") setImmediate(() => { void Promise.reject(new Error("matrix detached failure")) })', ' appendFileSync(config.events, `${config.label} apply ${config.generation}\\n`)', ' const timer = setInterval(() => { if (existsSync(config.stop)) process.emit("SIGTERM") }, 20)', ' ctx.effect(() => () => { clearInterval(timer); appendFileSync(config.events, `${config.label} dispose ${config.generation}\\n`) })', '}', '', ].join('\n')) writeFileSync(join(root, 'evaluation.mjs'), 'throw new Error("matrix module evaluation")\n') const url = pathToFileURL(plugin).href const config = (label: string, generation: number, mode = '') => ({ label, generation, mode, events, stop }) const witness = (generation: number) => ({ id: 'matrix-witness', name: url, config: config('witness', generation) }) const target = (id: string, failure?: Failure, generation = 1) => ({ id, name: failure === 'import' ? pathToFileURL(join(root, 'missing.mjs')).href : failure === 'module evaluation' ? pathToFileURL(join(root, 'evaluation.mjs')).href : url, ...(failure === 'dependency' ? { inject: ['matrixMissingService'] } : {}), config: config('target', generation, failure), }) const render = (id: string, failure?: Failure, generation = 1) => { let text = `- insert: ${JSON.stringify([observer, witness(generation), target(id, failure, generation)])}` if (failure === 'config expression') text += `\n- id: ${id}\n config: !!js "(() => { throw new Error('matrix config expression') })()"\n` if (failure === 'disabled expression') text += `\n- id: ${id}\n disabled: !!js "(() => { throw new Error('matrix disabled expression') })()"\n` return text + '\n' } writeFileSync(patch, JSON.stringify([{ insert: [observer, witness(0)] }]) + '\n') return { root, home, events, diagnostics, serverUrl, states, observer, stop, patch, watcher, render, url, config, witness, target } } function start(f: ReturnType, extra: string[] = []) { const child = execa(process.execPath, [bin, '--profile', 'web', '--patch', f.watcher, ...extra, '--no-open', '--port', '0'], { cwd: f.root, env: { ...process.env, DSH_HOME: f.home, DSH_AGENTS_HOME: join(f.root, '.agents'), DSH_TELEMETRY_DISABLED: '1', DEEPSEEK_API_KEY: 'keyless-matrix-no-call', NODE_NO_WARNINGS: '1' }, input: '', reject: false, timeout: 110_000, killSignal: 'SIGKILL', }) let stdout = '' let stderr = '' child.stdout?.setEncoding('utf8').on('data', (text: string) => { stdout += text }) child.stderr?.setEncoding('utf8').on('data', (text: string) => { stderr += text }) let exited = false void child.then(() => { exited = true }) async function wait(predicate: () => boolean) { try { await expect.poll(() => { if (exited) throw new Error('Web process exited') return predicate() }, { timeout: 45_000 }).toBe(true) } catch (cause) { throw new Error(`Web condition failed\n${stdout}\n${stderr}\n${readFileSync(f.diagnostics, 'utf8')}\n${readFileSync(f.events, 'utf8')}`, { cause }) } } async function serves(currentServer = false) { await wait(() => /dsh web: http:\/\//u.test(stdout)) const url = currentServer ? readFileSync(f.serverUrl, 'utf8') : /dsh web: (http:\/\/[^\s]+)/u.exec(stdout)?.[1] if (!url) throw new Error('Missing Web URL') const auth = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(10_000) }) const cookie = auth.headers.get('set-cookie')?.split(';', 1)[0] if (!cookie) throw new Error('Missing Web authentication cookie') const response = await fetch(new URL('/', url), { headers: { cookie }, signal: AbortSignal.timeout(10_000) }) expect(response.status).toBe(200) const html = await response.text() expect(html).toContain('__DSH_BOOT__') const bundlePath = /