DeepSeek Harness 事故复盘与工程验证
回顾四类历史事故,用独立本地用例验证入口、归因和外部结果。
学完这一章,你能够
- 回顾四类历史事故,用独立本地用例验证入口、归因和外部结果。
复盘为什么防线没有发现问题
复盘适合机制隐蔽、逃逸原因可重复、重新排查代价又高的故障。先用短摘要写清用户看到的现象,再记下机制、漏检环节和可验证的新增防护。复盘中的历史结论要绑定版本,程序对新版本的判断由当前运行证据支持。
四份历史记录怎样改变验证方式
事故 0001 的编辑器连接失败源于加载器选择的模块形状缺少注入声明。手工挂载测试已经传入正确形状,因此即使覆盖率很高也没有见到交付入口上的调用失败。修复整理了导出形状,并加入实际 Loader 冒烟。本站模块用具名声明提供内存依赖,经当前 Loader 挂载后读取预期值。编辑器和真实 ACP 握手另待核验。
事故 0002 中,早期版本的配置标签解析后留在历史开关位置,导致文件工具从实际注册表缺席。快照更新把缺工具错误保存为预期。后续补了显式配置、静态校验和语义结果断言。固定版本的 Loader 已有独立的 disabled 表达式求值分支,并拒绝普通对象作为该选项。本站只用常量 true 与 false 切换无副作用的课程笔记,核对当前行为。这里的版本变化不能外推为文件系统权限承诺。
事故 0003 中,HTTP 成功和备用服务可用都没有验证用户所在会话的界面。新增防护让启动器公开规范环回身份和运行模式,并检查实际浏览器路径。实验让同一回环服务的两个入口返回相同状态和标题,用运行身份判断哪一个才是目标。真实产品的桌面、GUI 路径、热更新和快速拒绝仍需独立验收。
事故 0004 将普通无匹配退出和旧隔离器的提示混成基础设施故障。新增的诊断契约检查非零状态、对应后端的致命行和明确排除的通知。文件搜索也改用结构化的进程能力,减少 shell 层归因。本站向当前分类器提供合成 stderr,普通退出加通知仍属于命令结果,指定状态和致命行同时匹配才认定启动器失败。未运行旧内核。
建立互补的测试层与独立断言
用单元测试压边界、覆盖率寻找未执行代码、快照查外部行为漂移,再用生产入口冒烟验证接线。需要验证真实模型时才使用获授权的提供方环境,缺少凭据的跳过结果要单独登记。本章只运行独立本地验证。
通过调用目标入口或重新读取实际文件核对外部结果。验收文本本身不能证明文件被修改。样本既重新读取已写入的判定文件,也核对旁边未修改文件的字节哈希。
让文档引用唯一事实
类型和 JSDoc 可各自变更,verify-type-equiv 类门禁分别解析和对照它们。本站用 TypeScript 解析自己编写的片段,核对同一声明在不同排版下等价,再分别检出字段类型和注释变化。完整仓库门禁另待运行。把接口契约放在一个维护位置,其他页面引用。双语文档和生成图谱按仓库流程核对更新。
写一段结论可追溯的摘要
示例摘要写给课程维护者。预览检查接受了备用阅读页,因为测试把 HTTP 状态当作页面身份。测试漏掉了同状态、同标题的反例。新增回环双入口用例,按页身份断言,并重新读取真实判定文件和未触碰文件的字节。用一句说明把这项改进绑定到能重复工作的测试。
全课程依本站稳定目录有 33 章。回看从安装和各入口,到插件、配置、作用域和工具,再到分发、审批、会话与防御性工程。维护者可从实际入口、可观测结果和审计证据逐项确认行为,把局部运行、环境例外和用户验收分别登记。
复盘四问
| 关注点 | 应该记录的证据 |
|---|---|
| 现象 | 说明用户可见错误、范围和时间,供快速定位。 |
| 机制 | 描述可检验的因果链与条件,不归咎某个人。 |
| 漏检原因 | 指出测试入口、工具、流程或契约的具体缺口。 |
| 防止复发 | 给出会明确失败的测试或工程规则,并关联决策记录。 |
测试层的职责
| 层 | 固定版本命令 | 目标与边界 |
|---|---|---|
| 单元 | pnpm run test | 检查模块行为、异常、顺序和并发边界,需补正常入口测试。 |
| 覆盖率 | pnpm run test:coverage | 找未执行的行和分支,与行为断言一并使用。 |
| 真实 API 端到端 | pnpm run test:e2e | 验证已授权提供方环境和真实请求。缺配置时如实记录跳过。 |
| 快照与浏览器 | pnpm run test:snapshot / pnpm run test:web | 比较规定工件和浏览器行为,并判断结果是否真正符合目标。 |
用实际结果验证复盘结论
import assert from 'node:assert/strict'
import { createHash } from 'node:crypto'
import { createServer } from 'node:http'
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 { Context, Service } = await import('@deepseek-ai/cordis')
const { Loader, validateOptions } = await import(base + 'vendor/loader/src/index.ts')
const { classifyRunnerFailure } = await import(base + 'packages/sandbox/sandbox/src/diagnostics.ts')
const ctx = new Context()
const output = []
class LessonNotes extends Service {
constructor(parent) { super(parent, 'lessonNotes') }
record(value) { output.push(value) }
}
const write = (filename, content) => fs.writeFileSync(path.join(fixture, filename), content, 'utf8')
write('note-plugin.mjs', [
'export const name = "owned-note-plugin"',
'export const inject = ["lessonNotes"]',
'export function apply(ctx, config) { ctx.lessonNotes.record(config.note) }',
].join('\n'))
try {
await ctx.plugin(LessonNotes)
await ctx.plugin(Loader, { baseUrl: fileUrl(fixture + path.sep) })
const install = async (id, disabled, note) => {
await ctx.loader.create({ id, name: './note-plugin.mjs', disabled, config: { note } })
const entry = ctx.loader.resolve(id)
await entry.fiber?.await()
return { disabled: entry.disabled, running: Boolean(entry.fiber) }
}
expect('normal_loader_path_keeps_declared_dependency', 'load a local named-export note plugin through the real Loader',
{ disabled: false, running: true, notes: ['named module runs'] },
{ ...await install('plain-note', false, 'named module runs'), notes: [...output] })
const on = await install('enabled-constant', { __jsExpr: 'false' }, 'constant false')
const off = await install('disabled-constant', { __jsExpr: 'true' }, 'constant true')
expect('current_loader_resolves_owned_disabled_constants', 'harmless constant conditions on local note entries',
{ on: { disabled: false, running: true }, off: { disabled: true, running: false }, notes: ['named module runs', 'constant false'] },
{ on, off, notes: output })
expect('loader_checks_invalid_non_expression_metadata', 'ask current validator about a regular object in disabled',
[['disabled']], validateOptions({ name: './note-plugin.mjs', disabled: { example: false } }, ':').map((issue) => issue.path))
} finally {
await ctx.fiber.dispose()
}
const rules = [{ allowedExitCodes: [125], fatalSignatures: ['runner: fatal'], informationalLines: ['runner: notice only'] }]
expect('runner_notice_and_no_match_remain_child_outcome', 'ordinary exit 1 and synthetic informational output',
null, classifyRunnerFailure(1, 'runner: notice only\nno match', rules) ?? null)
expect('runner_fatal_needs_status_and_diagnostic', 'run the genuine classifier on two synthetic 125 records',
['runner: fatal before start', null],
[classifyRunnerFailure(125, 'runner: notice only\nrunner: fatal before start', rules)?.detail ?? null,
classifyRunnerFailure(125, 'runner: notice only', rules) ?? null])
const fixtureContents = { '/primary': { identity: 'primary-reading', title: 'Lesson ready' },
'/spare': { identity: 'other-reading', title: 'Lesson ready' } }
const server = createServer((req, res) => {
if (!Object.hasOwn(fixtureContents, req.url)) { res.writeHead(404).end(); return }
res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(fixtureContents[req.url]))
})
await new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(0, '127.0.0.1', resolve)
})
try {
const origin = 'http://127.0.0.1:' + server.address().port
const verify = async (route) => {
const response = await fetch(origin + route)
const page = await response.json()
return { status: response.status, title: page.title, accepted: page.identity === 'primary-reading' }
}
expect('same_http_status_does_not_prove_surface_identity', 'two loopback pages have the same status and headline',
[{ status: 200, title: 'Lesson ready', accepted: true }, { status: 200, title: 'Lesson ready', accepted: false }],
[await verify('/primary'), await verify('/spare')])
} finally {
await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()))
}
const unrelated = path.join(fixture, 'unrelated.txt')
fs.writeFileSync(unrelated, Buffer.from([0xab, 0x0d, 0x0a, 0xff]))
const before = digest(fs.readFileSync(unrelated))
write('decision.txt', 'accepted only when the identity matches\n')
expect('verify_changed_artifact_and_unrelated_bytes_externally', 're-read both files from disk after writing the fixture decision',
{ changed: 'accepted only when the identity matches\n', untouched: true },
{ changed: fs.readFileSync(path.join(fixture, 'decision.txt'), 'utf8'), untouched: digest(fs.readFileSync(unrelated)) === before })
function definition(source) {
const file = ts.createSourceFile('lesson.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
const node = file.statements.find(ts.isInterfaceDeclaration)
assert.ok(node)
return { name: node.name.text, fields: node.members.map((field) => field.getText(file)),
docs: node.jsDoc?.map((doc) => doc.comment) ?? [] }
}
const declaration = '/** Preserve the selected card identity. */\ninterface Check { id: string }'
const exampleDocs = '/** Preserve the selected card identity. */\ninterface Check {\n id: string\n}'
expect('type_and_jsdoc_can_drift_independently', 'run TypeScript parsing over owned documentation specimens',
{ exact: true, typeChange: true, docChange: true },
{ exact: JSON.stringify(definition(declaration)) === JSON.stringify(definition(exampleDocs)),
typeChange: JSON.stringify(definition(declaration).fields) !== JSON.stringify(definition(declaration.replace('id: string', 'id: number')).fields),
docChange: JSON.stringify(definition(declaration).docs) !== JSON.stringify(definition(declaration.replace('selected', 'displayed')).docs) })
console.log(JSON.stringify({
cases, node: process.version, typescript: ts.version,
code_sha256: digest(fs.readFileSync(fileURLToPath(import.meta.url))),
source_hashes: Object.fromEntries(Object.entries(sourceHashes).sort(([a], [b]) => a.localeCompare(b))),
historical_incidents_reproduced: false, model_requests: 0, web_hmr_tested: false,
observations_scope: 'current loader, runner diagnostics, local surface identity, artifact bytes, TypeScript syntax',
}, null, 2))
- 真实 Loader 能挂载具名声明的笔记插件。两个回环页面都返回 200,只有目标身份通过。重新读取文件可确认实际修改和旁边原字节保留。
所需环境:Node.js 24.22.3、TypeScript 6.0.3、固定版本源码、仅本机回环临时服务。
当前源码 SHA256:b01639b92011055cc3f47a75c1cad42f2c848a2e727a6e5f026b6cf6b55c3822
本地复跑
按 ZIP 内的 README 准备空目录并运行。
所需环境:Node.js 24.22.3、TypeScript 6.0.3、固定版本源码、仅本机回环临时服务。
ZIP SHA256:798409e9172bd04bbf35d3e76ca5ef9cff425751845860858326fe13ab69168a
常见错误与边界
- 断言实际入口和外部结果。
- 保留旧版事故的适用条件,重新观察当前版本。
练习与解答
两个页面同为 HTTP 200 时,怎么区分谁应验收?
展开参考解答
用目标会话或应用给出的规范入口和可观察身份核对,不凭状态码和标题推断。