import assert from 'node:assert/strict'
import { createHash, randomUUID } from 'node:crypto'
import { spawn } from 'node:child_process'
import fs from 'node:fs'
import { createRequire, isBuiltin, registerHooks } from 'node:module'
import path from 'node:path'
import { pathToFileURL, fileURLToPath } from 'node:url'
const repo = path.resolve(process.argv[2])
const fixture = path.resolve(process.argv[3])
assert.deepEqual(fs.readdirSync(fixture), [], 'Use an empty temporary directory')
const base = pathToFileURL(repo + path.sep).href
const store = path.join(repo, 'node_modules', '.pnpm')
const require = createRequire(import.meta.url)
const ts = require(path.join(store, 'typescript@6.0.3/node_modules/typescript/lib/typescript.js'))
const cachedPackages = fs.readdirSync(store)
const pinned = new Map([['ajv', 'ajv@8.20.0']])
const packageRoots = new Map()
const sourceHashes = {}
const digest = (text) => createHash('sha256').update(text).digest('hex')
const fileUrl = (name) => pathToFileURL(name).href
const directories = (folder) => fs.readdirSync(folder, { withFileTypes: true })
.filter((entry) => entry.isDirectory()).map((entry) => path.join(folder, entry.name))
const read = (name) => JSON.parse(fs.readFileSync(name, 'utf8'))
for (const folder of [
...directories(path.join(repo, 'vendor')),
...directories(path.join(repo, 'packages')).flatMap(directories),
...directories(path.join(repo, 'apps')),
]) {
const manifest = path.join(folder, 'package.json')
if (fs.existsSync(manifest)) packageRoots.set(read(manifest).name, folder)
}
registerHooks({
resolve(specifier, context, nextResolve) {
if (isBuiltin(specifier) || /^(?:[./]|[a-z]+:)/i.test(specifier)) {
return nextResolve(specifier, context)
}
const segments = specifier.split('/')
const name = segments.splice(0, specifier.startsWith('@') ? 2 : 1).join('/')
const subpath = segments.join('/')
const root = packageRoots.get(name)
if (root) {
return nextResolve(fileUrl(path.join(root, subpath || 'src/index.ts')), context)
}
try {
return nextResolve(specifier, context)
} catch (error) {
if (error.code !== 'ERR_MODULE_NOT_FOUND' && error.code !== 'MODULE_NOT_FOUND') throw error
if (!context.parentURL?.startsWith(base)) throw error
const matches = cachedPackages.filter((entry) => entry.startsWith(name.replace('/', '+') + '@'))
const cached = pinned.get(name) ?? (matches.length === 1 ? matches[0] : undefined)
if (!cached) throw error
return nextResolve(specifier, { ...context, parentURL: fileUrl(path.join(store, cached, 'loader.mjs')) })
}
},
load(url, context, nextLoad) {
if (!url.startsWith(base) || !url.endsWith('.ts')) return nextLoad(url, context)
const filename = fileURLToPath(url)
const input = fs.readFileSync(filename, 'utf8')
sourceHashes[path.relative(repo, filename).split(path.sep).join('/')] = digest(input)
const output = ts.transpileModule(input, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } })
return { format: 'module', source: output.outputText, shortCircuit: true }
},
})
const cases = []
function expect(name, input, expected, actual) {
assert.deepEqual(actual, expected, name)
cases.push({ name, input, expected, actual, passed: true })
}
const workerSource = [
'process.send({ type: "ready", exposed: Object.keys(process.env).filter(name => /^LESSON_/.test(name)).sort() })',
'process.on("message", (msg) => {',
' if (msg === "stop" && process.argv[1] !== "ignore-stop") {',
' process.send({ type: "optional" })',
' process.stdout.write("final card result", () => process.disconnect())',
' }',
'})',
].join('\n')
const approvedNames = new Set(['LESSON_LOCALE', 'SYSTEMROOT'])
function selectEnvironment(entries) {
return Object.fromEntries(Object.entries(entries).filter(([name, value]) =>
typeof value === 'string' && approvedNames.has(name.toUpperCase())))
}
const synthetic = {
LESSON_LOCALE: 'zh-CN', LESSON_API_KEY: 'not-a-credential', LESSON_SECRET: 'not-a-credential',
LESSON_TOKEN: 'not-a-credential', LESSON_PASSWORD: 'not-a-credential', LESSON_PRIVATE_CONTEXT: 'omit too',
}
const env = selectEnvironment({ ...synthetic, SystemRoot: process.env.SystemRoot ?? process.env.SYSTEMROOT })
function startWorker(mode = 'normal') {
const child = spawn(process.execPath, ['-e', workerSource, mode], {
shell: false, windowsHide: true, cwd: fixture, env, stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
})
const ready = Promise.withResolvers()
const stdout = []
const stderr = []
const listeners = new Set()
let deadlinePassed = false
let closed = false
let disposing
let error
let graceTimer
const watchdog = setTimeout(() => child.kill('SIGKILL'), 5000)
child.stdout.on('data', (data) => stdout.push(data))
child.stderr.on('data', (data) => stderr.push(data))
child.on('message', (message) => {
if (message.type === 'ready') ready.resolve(message.exposed)
if (message.type === 'optional') for (const listener of listeners) listener()
})
child.once('error', (e) => { error = e; ready.reject(e) })
const done = new Promise((resolve, reject) => {
child.once('close', (exitCode, signal) => {
closed = true
clearTimeout(watchdog)
clearTimeout(graceTimer)
ready.reject(error ?? new Error('Worker closed before its handshake'))
if (error) reject(error)
else resolve({ timedOut: deadlinePassed, exitCode, signal,
stdout: Buffer.concat(stdout).toString('utf8'), stderr: Buffer.concat(stderr).toString('utf8') })
})
})
void ready.promise.catch(() => {})
void done.catch(() => {})
function dispose() {
if (disposing !== undefined) return disposing
listeners.clear()
if (!closed) {
if (child.connected) child.send('stop', () => {})
graceTimer = setTimeout(() => child.kill('SIGKILL'), 300)
}
disposing = done
return disposing
}
return { ready: ready.promise, done, listen: (listener) => listeners.add(listener), dispose,
deadline: () => { deadlinePassed = true; return dispose() },
signal: () => child.kill('SIGTERM'),
hasClosed: () => closed }
}
let run = startWorker()
const exposed = await run.ready
expect('only_allowlisted_synthetic_variables_reach_real_child', 'launch only the owned local worker',
{ exposed: ['LESSON_LOCALE'], sourceKeysRemain: 6 }, { exposed, sourceKeysRemain: Object.keys(synthetic).length })
let notifications = 0
run.listen(() => { notifications += 1 })
const returned = run.dispose()
const sameClose = run.dispose()
const disposed = await returned
expect('dispose_waits_for_close_and_final_output', 'dispose after handshake without exposing late optional notifications',
{ closed: true, output: 'final card result', notifications: 0, samePromise: true },
{ closed: run.hasClosed(), output: disposed.stdout, notifications, samePromise: returned === sameClose })
expect('normal_worker_reports_all_fields', 'graceful stop with no expired timer',
[false, 0, null], [disposed.timedOut, disposed.exitCode, disposed.signal])
run = startWorker()
await run.ready
const deadline = await new Promise((resolve, reject) => {
setTimeout(() => run.deadline().then(resolve, reject), 20)
})
expect('deadline_can_coexist_with_zero_exit', '20ms real deadline followed by cooperative IPC shutdown',
[true, 0, null, 'final card result'], [deadline.timedOut, deadline.exitCode, deadline.signal, deadline.stdout])
run = startWorker()
await run.ready
assert.equal(run.signal(), true)
const signalled = await run.done
expect('signalled_child_reports_signal_without_exit_code', 'signal only the owned worker after its handshake',
[false, null, 'SIGTERM'], [signalled.timedOut, signalled.exitCode, signalled.signal])
run = startWorker('ignore-stop')
await run.ready
const forced = await run.dispose()
expect('forced_stop_still_awaits_actual_child_close', 'ignore cooperative stop and terminate the owned child after the grace window',
[true, null, 'SIGKILL'], [run.hasClosed(), forced.exitCode, forced.signal])
const privateDir = path.join(fixture, 'spill-' + randomUUID())
fs.mkdirSync(privateDir, { mode: 0o700 })
const spillPath = path.join(privateDir, randomUUID() + '.txt')
const fd = fs.openSync(spillPath, 'wx', 0o600)
try { fs.writeFileSync(fd, 'public demo line\n', 'utf8') } finally { fs.closeSync(fd) }
let collision
try {
const duplicate = fs.openSync(spillPath, 'wx', 0o600)
fs.closeSync(duplicate)
} catch (error) {
collision = error.code
}
expect('exclusive_spill_creation_preserves_existing_bytes', 'try exclusive creation twice at the owned test path',
{ second: 'EEXIST', bytes: 'public demo line\n' }, { second: collision, bytes: fs.readFileSync(spillPath, 'utf8') })
if (process.platform !== 'win32') {
expect('posix_rights_restrict_access_to_owner', 'stat own spill directory and file',
[0o700, 0o600], [fs.statSync(privateDir).mode & 0o777, fs.statSync(spillPath).mode & 0o777])
}
const target = path.join(fixture, 'actual-directory')
fs.mkdirSync(target)
const marker = path.join(target, 'keep.txt')
fs.writeFileSync(marker, 'preserve target', 'utf8')
const link = path.join(fixture, 'owned-directory-link')
fs.symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir')
const isLink = fs.lstatSync(link).isSymbolicLink()
assert.equal(isLink, true)
fs.unlinkSync(link)
expect('unlink_preserves_actual_directory_and_contents', 'unlink a verified lab-owned link',
{ linkRemoved: true, originalDirectory: true, marker: 'preserve target' },
{ linkRemoved: !fs.existsSync(link), originalDirectory: fs.statSync(target).isDirectory(), marker: fs.readFileSync(marker, 'utf8') })
if (process.platform === 'win32') {
const secondLink = path.join(fixture, 'test-nonrecursive-rm')
fs.symlinkSync(target, secondLink, 'junction')
let result
try {
fs.rmSync(secondLink)
result = 'removed'
} catch (error) {
result = error.code
} finally {
if (fs.existsSync(secondLink)) {
assert.equal(fs.lstatSync(secondLink).isSymbolicLink(), true)
fs.unlinkSync(secondLink)
}
}
expect('nonrecursive_rm_on_windows_junction', 'call nonrecursive rmSync on a lab-owned junction',
{ result: 'removed', untouched: true }, { result, untouched: fs.existsSync(marker) })
}
let realDirectoryRefused = false
try { fs.unlinkSync(target) } catch { realDirectoryRefused = true }
expect('unlink_rejects_a_real_directory', 'try unlink on actual lab-owned directory',
{ refused: true, marker: true }, { refused: realDirectoryRefused, marker: fs.existsSync(marker) })
const { Context } = await import('@deepseek-ai/cordis')
const { default: Sessions } = await import('@deepseek-ai/dsh-session')
const ctx = new Context()
try {
await ctx.plugin(Sessions)
const session = ctx.sessions.create('defensive-lesson-session')
const path = []
ctx.on('session/event', (owner) => {
if (owner !== session) return
path.push('sync')
throw new Error('synthetic synchronous failure')
})
ctx.on('session/event', async (owner) => {
if (owner !== session) return
path.push('async')
throw new Error('synthetic rejected observer')
})
ctx.on('session/event', (owner, event) => { if (owner === session) path.push(event.type) })
const event = session.append('turn/start', { turn: 1 })
await Promise.resolve()
expect('committed_append_survives_observer_failures', 'two failing real session observers followed by a healthy one',
{ order: ['sync', 'async', 'turn/start'], committed: true },
{ order: path, committed: session.snapshotEvents().some(({ seq }) => seq === event.seq && event.type === 'turn/start') })
} finally {
await ctx.fiber.dispose()
}
const { normalizeLlmFailure } = await import(base + 'packages/llm/llm/src/adapter-failure.ts')
const { LlmError } = await import('@deepseek-ai/dsh-llm')
const raw = { message: 'Synthetic provider busy', code: 'LESSON_BUSY', status: 503 }
expect('structured_provider_failure_normalises_without_losing_facts', 'use actual adapter-side normalizer',
{ structured: raw, fallback: { message: 'synthetic unknown', code: 'UNKNOWN' } },
{ structured: normalizeLlmFailure(LlmError.fromFailure(raw)), fallback: normalizeLlmFailure(new Error('synthetic unknown')) })
console.log(JSON.stringify({
cases, node: process.version, typescript: ts.version, platform: process.platform,
code_sha256: digest(fs.readFileSync(fileURLToPath(import.meta.url))),
source_hashes: Object.fromEntries(Object.entries(sourceHashes).sort(([a], [b]) => a.localeCompare(b))),
posix_modes_checked: process.platform !== 'win32', windows_acl_checked: false, live_agent_interval_tested: false,
subprocess_scope: 'owned Node worker only', environment_fixture_only: true,
}, null, 2))
本例需在 Windows、Node.js 24.22.3、TypeScript 6.0.3、固定版本源码、临时目录。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Node.js 24.22.3、TypeScript 6.0.3、固定版本源码、临时目录。
入口文件:projects/deepseek-harness-defensive-patterns/defensive-boundaries.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
defensive-boundaries.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows、Node.js 24.22.3、TypeScript 6.0.3、固定版本源码、临时目录。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a132.zip
课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a128.zip