蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

用实际结果验证复盘结论

JAVASCRIPTNode.js 24.22.3、TypeScript 6.0.3、固定版本源码、仅本机回环临时服务。postmortem-evidence.mjs
postmortem-evidence.mjs172 行
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))
本例需在 Node.js 24.22.3、TypeScript 6.0.3、固定版本源码、仅本机回环临时服务。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Node.js 24.22.3、TypeScript 6.0.3、固定版本源码、仅本机回环临时服务。

入口文件:projects/deepseek-harness-postmortem/postmortem-evidence.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 postmortem-evidence.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Node.js 24.22.3、TypeScript 6.0.3、固定版本源码、仅本机回环临时服务。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:DeepSeek Harness

课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a128.zip

下载课程关联工程包:DeepSeek Harness

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a152.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习