From 6d6a805d46c6a16d6f20a3743fbb0b3dd142a446 Mon Sep 17 00:00:00 2001 From: d-robotics <27971988066@qq.com> Date: Fri, 14 Aug 2026 15:35:49 +0800 Subject: [PATCH] =?UTF-8?q?feat(v3):=20P1+P2=20=E5=85=A8=E8=90=BD=E5=9C=B0?= =?UTF-8?q?=20=E2=80=94=20T06=E2=80=93T17=20+=20=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?=E9=9B=86=E6=88=90=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 12 模块多 agent 并行开发(dev+test+fix 每,两层 + barrier): - T06 PbaSession 事件溯源 + deriveMessages + logged 不变量 - T07 PbaEventBus typed event bus + waterfall + ScopeKey 隔离 - T08 能力接缝三角色(board-link + flash Provider/Registry/consumer) - T09 compaction 完整工程(token-meter/pruner/summarizer/spill) - T10 CI 质量门 + snapshot + doc-sync - T11 类型镜像漂移检测(tsconfig.realpi + type-drift-check) - T12 子代理 + 工作流编排(parallel/pipeline/InlineSubagentProvider) - T13 上下文注入三段(inject/steer/followup) - T14 plan/goal/todo checkpoint logged state(look-ahead 状态机) - T15 profile/bundle 分层(维修诊断 vs 嵌入式开发,共享 base) - T16 多 LLM provider 适配(ProviderRegistry + glm-5.2/deepseek) - T17 审批接缝(fail-closed auto-deny)+ credentials/settings/lsp 集成(串行): - src/index.ts 公共 re-export(board-link/flash 具名避 shared/types 重名) - tests/system-integration.test.ts 跨模块 10 闭环(事件溯源→compaction→bus→ 接缝→checkpoint→inject→workflow→approval→provider→profile) - 全量 tsc=0;vitest 39 文件 2449 passed/5 skipped(1044 baseline +~1400 模块 + 10 系统) - 密钥铁律:\${DROBOTICS_LLM_KEY} 占位,grep sk- 明文 0 68 workflow agent / 0 error / ~3M token;mutation 测试每模块 3-9 seeded bug 全杀。 Co-Authored-By: Claude --- .github/workflows/ci.yml | 123 + .gitignore | 4 + scripts/doc-sync.ts | 251 ++ scripts/e2e-snapshot.ts | 197 ++ scripts/t06-t17.workflow.mjs | 448 +++ scripts/type-drift-check.ts | 199 ++ src/capabilities/approval.ts | 184 ++ src/capabilities/board-link/index.ts | 170 ++ .../board-link/providers/local.ts | 41 + .../board-link/providers/rdk-s100-serial.ts | 94 + .../board-link/providers/rdk-x5-ssh.ts | 131 + src/capabilities/board-link/types.ts | 124 + src/capabilities/credentials.ts | 139 + src/capabilities/flash/index.ts | 167 ++ src/capabilities/flash/providers/dd.ts | 435 +++ src/capabilities/flash/providers/dfu.ts | 122 + src/capabilities/flash/providers/fastboot.ts | 123 + src/capabilities/flash/providers/openocd.ts | 129 + src/capabilities/flash/types.ts | 572 ++++ src/capabilities/lsp.ts | 85 + src/capabilities/settings.ts | 184 ++ src/capabilities/subagent/index.ts | 278 ++ src/capabilities/workflow/index.ts | 172 ++ src/compaction/spill.ts | 178 ++ src/compaction/summarizer.ts | 159 ++ src/compaction/token-meter.ts | 88 + src/compaction/tool-result-pruner.ts | 227 ++ src/core/checkpoint-state.ts | 284 ++ src/core/context-injector.ts | 418 +++ src/core/pba-event-bus.ts | 393 +++ src/core/pba-session.ts | 437 +++ src/core/provider-registry.ts | 474 ++++ src/index.ts | 42 + src/profiles/base.ts | 273 ++ src/profiles/embedded-dev.ts | 60 + src/profiles/index.ts | 77 + src/profiles/repair-diagnosis.ts | 44 + tests/capabilities-misc.test.ts | 1320 +++++++++ tests/capability-seams.test.ts | 2523 +++++++++++++++++ tests/checkpoint-state.test.ts | 1157 ++++++++ tests/compaction.test.ts | 1328 +++++++++ tests/context-injector.test.ts | 1167 ++++++++ tests/doc-sync.test.ts | 1993 +++++++++++++ tests/pba-event-bus.test.ts | 729 +++++ tests/pba-session.test.ts | 1053 +++++++ tests/profiles.test.ts | 1481 ++++++++++ tests/provider-registry.test.ts | 1085 +++++++ tests/system-integration.test.ts | 243 ++ tests/type-drift-check.test.ts | 749 +++++ tests/workflow.test.ts | 1329 +++++++++ tsconfig.realpi.json | 11 + 51 files changed, 23694 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 scripts/doc-sync.ts create mode 100644 scripts/e2e-snapshot.ts create mode 100644 scripts/t06-t17.workflow.mjs create mode 100644 scripts/type-drift-check.ts create mode 100644 src/capabilities/approval.ts create mode 100644 src/capabilities/board-link/index.ts create mode 100644 src/capabilities/board-link/providers/local.ts create mode 100644 src/capabilities/board-link/providers/rdk-s100-serial.ts create mode 100644 src/capabilities/board-link/providers/rdk-x5-ssh.ts create mode 100644 src/capabilities/board-link/types.ts create mode 100644 src/capabilities/credentials.ts create mode 100644 src/capabilities/flash/index.ts create mode 100644 src/capabilities/flash/providers/dd.ts create mode 100644 src/capabilities/flash/providers/dfu.ts create mode 100644 src/capabilities/flash/providers/fastboot.ts create mode 100644 src/capabilities/flash/providers/openocd.ts create mode 100644 src/capabilities/flash/types.ts create mode 100644 src/capabilities/lsp.ts create mode 100644 src/capabilities/settings.ts create mode 100644 src/capabilities/subagent/index.ts create mode 100644 src/capabilities/workflow/index.ts create mode 100644 src/compaction/spill.ts create mode 100644 src/compaction/summarizer.ts create mode 100644 src/compaction/token-meter.ts create mode 100644 src/compaction/tool-result-pruner.ts create mode 100644 src/core/checkpoint-state.ts create mode 100644 src/core/context-injector.ts create mode 100644 src/core/pba-event-bus.ts create mode 100644 src/core/pba-session.ts create mode 100644 src/core/provider-registry.ts create mode 100644 src/profiles/base.ts create mode 100644 src/profiles/embedded-dev.ts create mode 100644 src/profiles/index.ts create mode 100644 src/profiles/repair-diagnosis.ts create mode 100644 tests/capabilities-misc.test.ts create mode 100644 tests/capability-seams.test.ts create mode 100644 tests/checkpoint-state.test.ts create mode 100644 tests/compaction.test.ts create mode 100644 tests/context-injector.test.ts create mode 100644 tests/doc-sync.test.ts create mode 100644 tests/pba-event-bus.test.ts create mode 100644 tests/pba-session.test.ts create mode 100644 tests/profiles.test.ts create mode 100644 tests/provider-registry.test.ts create mode 100644 tests/system-integration.test.ts create mode 100644 tests/type-drift-check.test.ts create mode 100644 tests/workflow.test.ts create mode 100644 tsconfig.realpi.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..a1b184e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,123 @@ +# CI 质量门(T10)—— per-file 覆盖门 + doc-sync + type-drift-check +# 见架构设计文档_v3.md §5.9 +# +# 两个 Job: +# quality-gate —— 每次 push/PR 跑:vitest per-file 100% 覆盖门 + tsc 类型检查 +# + doc-sync 锚点对齐(调本仓 scripts/doc-sync.ts) +# type-drift —— 周期(schedule)+ 手动触发跑:类型镜像漂移检测 +# (调 T11 的 scripts/type-drift-check.ts,需 ../pi/packages 源码) +# 非「每次提交」跑,因 type-drift 需真 pi 源码树且属升版级检查。 + +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + schedule: + # 每周二 03:17 UTC 跑 type-drift(错峰,避开 :00) + - cron: "17 3 * * 2" + workflow_dispatch: + +permissions: + contents: read + +jobs: + # ========================================================================== + # quality-gate:per-file 100% 覆盖 + 类型检查 + doc-sync + # ========================================================================== + quality-gate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: "20" + cache: "npm" + + - name: Install deps + run: npm ci + + - name: Typecheck (tsc --noEmit) + run: npm run typecheck + + # per-file 100% 覆盖门:v8 istanbul,thresholds.perFile 对 src/**/*.ts 逐文件 + - name: Test + per-file 100% coverage gate + run: | + npx vitest run \ + --coverage.enabled \ + --coverage.provider=v8 \ + --coverage.include='src/**/*.ts' \ + --coverage.thresholds.perFile=true \ + --coverage.thresholds.lines=100 \ + --coverage.thresholds.branches=100 \ + --coverage.thresholds.functions=100 \ + --coverage.thresholds.statements=100 + + # doc-sync:校验架构文档锚点 file:line 与代码对齐,不符即红。 + # 用 stdin ESM + 动态 import(process.cwd() 可移植),规避 tsx -e 的 + # eval-CJS 上下文无法解析 .js→.ts 相对路径的问题。 + - name: doc-sync + run: | + cat <<'EOF' | npx tsx --input-type=module + const cwd = process.cwd(); + const m = await import(cwd + "/scripts/doc-sync.js"); + const r = m.checkDocSync({ + readFile: m.defaultReadFile, + grepSymbol: m.defaultGrepSymbol, + anchors: m.DEFAULT_DOC_ANCHORS, + }); + if (!r.ok) { + console.error("doc-sync mismatches:\n" + r.mismatches + .map(x => ` - ${x.anchor.docFile}:${x.anchor.docLine} -> ${x.reason}`) + .join("\n")); + process.exit(1); + } + console.log("doc-sync: all anchors aligned"); + EOF + + # ========================================================================== + # type-drift:类型镜像漂移检测(周期 + 手动,需真 pi 源码树) + # ========================================================================== + type-drift: + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: "20" + cache: "npm" + + - name: Install deps + run: npm ci + + # type-drift-check 需 ../pi/packages 真源码(tsconfig.realpi.json paths 指向) + # 源码树不在本仓(gitignore 的 pi 符号链接/目录);缺源码则无法验证,跳过并告警 + - name: Verify pi source tree present + id: pi-src + run: | + if [ -d "../pi/packages" ]; then + echo "present=true" >> "$GITHUB_OUTPUT" + else + echo "::warning::../pi/packages not present; type-drift-check skipped (no source to verify against)" + echo "present=false" >> "$GITHUB_OUTPUT" + fi + + - name: type-drift-check + if: steps.pi-src.outputs.present == 'true' + run: | + cat <<'EOF' | npx tsx --input-type=module + const cwd = process.cwd(); + const m = await import(cwd + "/scripts/type-drift-check.js"); + const r = m.checkTypeDrift({}); + if (r.driftDetected) { + console.error("type drift detected (pba src mirror stale):\n" + r.pbaErrors.join("\n")); + process.exit(1); + } + console.log("type-drift: no drift"); + console.log("pi-internal errors (ignored): " + r.piInternalErrors.length); + EOF diff --git a/.gitignore b/.gitignore index 9760d45..a44aca0 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,7 @@ models.json.bak native/landlock-run/landlock-run-stub native/landlock-run/landlock-run-aarch64 native/landlock-run/landlock-run-aarch64-gnu + +# 变异测试运行时产物(m1-m4.mjs 等测试时生成的 bug 副本,不入库) +tests/.mutation-kill/ +*.mutation.mjs diff --git a/scripts/doc-sync.ts b/scripts/doc-sync.ts new file mode 100644 index 0000000..cdb7fb6 --- /dev/null +++ b/scripts/doc-sync.ts @@ -0,0 +1,251 @@ +/** + * @module doc-sync + * + * 文档锚点同步校验(T10)—— 校验架构文档的 file:line 锚点与代码对齐。 + * + * 为什么需要:架构设计文档_v3.md 通篇用 `src/foo.ts:NN` 锚点引用真实代码 + * (如「`src/core/tool-pipeline.ts`:实现 `ToolPipeline` 调度器」)。代码重构后 + * 文档锚点易漂移——文件路径搬走、符号改名、整段删除——而文档仍指旧位置, + * 误导后续维护者。本模块把「文档声称的锚点 ⟺ 代码真实存在」做成可注入的纯校验, + * CI 跑之,锚点与代码不符即红。 + * + * 双侧校验(一个 DocAnchor 同时钉住文档侧与代码侧): + * - 文档侧:docFile 的第 docLine 行必须确实引用 codeFile(锚点位置没飘)。 + * - 代码侧:codeSymbol 必须在 codeFile 中存在(grepSymbol 返回 >0 行号)。 + * 任一侧不符即记一条 mismatch,附可读 reason。两侧皆过才 ok。 + * + * fail-closed(安全不变式): + * - docFile 不可读 / docLine 越界 → mismatch(无法确认锚点对齐,安全默认红)。 + * - codeFile 不可读 → mismatch(同上)。 + * - grepSymbol 返回 ≤0(约定 -1 表未命中;0 表非法行号)→ mismatch。 + * + * 正交阶段(单一职责,确定性可测): + * checkDocSync(纯校验,readFile/grepSymbol 注入)为唯一主入口; + * defaultReadFile / defaultGrepSymbol 是真 IO 适配器(CI 装配,单测注入 mock); + * DEFAULT_DOC_ANCHORS 是已人工核对落地的锚点清单(CI 默认跑)。 + * + * 纯逻辑 + readFile/grepSymbol 可注入,零 pi 运行时依赖,可离线单测。 + * 见架构设计文档_v3.md §5.9(CI 质量门:doc-sync 文档门)。 + */ + +import { readFileSync } from "node:fs"; + +// ============================================================================ +// 命名常量 —— 消灭魔法值 +// ============================================================================ + +/** + * grepSymbol「未命中」哨兵。行号 1-indexed,故 ≤0 一律视为未命中(兼容 -1 与 0 + * 两种约定,fail-closed:歧义即红)。 + */ +const GREP_NOT_FOUND_MAX = 0; + +/** 默认架构文档文件(doc-sync 校验对象)。 */ +const DEFAULT_DOC_FILE = "架构设计文档_v3.md"; + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** + * 一条文档锚点:声明「docFile 的第 docLine 行引用了 codeFile 中的 codeSymbol」。 + * + * docFile / codeFile 均为仓库相对路径。docLine 1-indexed。 + */ +export interface DocAnchor { + /** 文档文件(仓库相对路径,如 "架构设计文档_v3.md")。 */ + readonly docFile: string; + /** 文档内锚点行号(1-indexed)。 */ + readonly docLine: number; + /** 锚点引用的代码文件(仓库相对路径,如 "src/core/tool-pipeline.ts")。 */ + readonly codeFile: string; + /** 锚点声称在 codeFile 中存在的符号(子串匹配,如 "ToolPipeline")。 */ + readonly codeSymbol: string; +} + +/** 单条锚点校验不符。 */ +export interface DocSyncMismatch { + /** 触发不符的锚点。 */ + readonly anchor: DocAnchor; + /** 人类可读的不符原因。 */ + readonly reason: string; +} + +/** checkDocSync 返回值。 */ +export interface DocSyncResult { + /** 全部锚点两侧皆过即 true。 */ + readonly ok: boolean; + /** 不符清单(保持锚点输入序,稳定可测)。 */ + readonly mismatches: readonly DocSyncMismatch[]; +} + +/** readFile 抽象(注入以便单测 mock,避免真 fs)。 */ +export type ReadFile = (path: string) => string; + +/** grepSymbol 抽象(注入以便单测 mock)。返回 1-indexed 行号,未命中返回 -1。 */ +export type GrepSymbol = (file: string, symbol: string) => number; + +// ============================================================================ +// 真 IO 适配器 —— CI 装配用(单测注入 mock 替代) +// ============================================================================ + +/** + * 默认 readFile:同步读 UTF-8 文本。 + * + * 抛错(文件不存在等)由调用方 {@link checkDocSync} 的 try/catch 兜成 mismatch。 + * + * @param path 仓库相对路径。 + * @returns 文件 UTF-8 文本。 + */ +export const defaultReadFile: ReadFile = (path) => readFileSync(path, "utf8"); + +/** + * 默认 grepSymbol:在 file 中按行子串查找 symbol,返回首个命中行号(1-indexed)。 + * + * 子串匹配即可(注释/实现皆算)——doc-sync 只关心「符号概念仍在该文件」, + * 不要求精确到定义行。未命中返回 -1。 + * + * @param file 代码文件路径。 + * @param symbol 要查的符号子串。 + * @returns 首个命中行号(1-indexed),未命中 -1。 + */ +export const defaultGrepSymbol: GrepSymbol = (file, symbol) => { + const text = readFileSync(file, "utf8"); + const lines = text.split("\n"); + for (let i = 0; i < lines.length; i++) { + if (lines[i].includes(symbol)) return i + 1; + } + return -1; +}; + +// ============================================================================ +// DEFAULT_DOC_ANCHORS —— 已人工核对落地的锚点(CI 默认跑) +// ============================================================================ + +/** + * 深冻结 DocAnchor 数组:外层数组 + 逐元素对象均 Object.freeze。 + * + * Object.freeze(arr) 仅浅冻结——元素 DocAnchor 对象的 docFile/docLine 等属性 + * 仍可写、可被运行时静默篡改(如 `DEFAULT_DOC_ANCHORS[0].docFile = 'x'` 不抛错)。 + * 逐元素 Object.freeze 方达「深冻结」语义,兑现下方注释的安全不变式承诺。 + * + * @param anchors 待冻结锚点(元素须为纯对象)。 + * @returns 深冻结后的同一引用(外层 + 元素皆 Object.isFrozen===true)。 + */ +function deepFreezeAnchors(anchors: readonly DocAnchor[]): readonly DocAnchor[] { + for (const anchor of anchors) { + Object.freeze(anchor); + } + return Object.freeze(anchors) as readonly DocAnchor[]; +} + +/** + * 默认锚点清单。每条均经人工核对:docLine 行确实引用 codeFile,codeSymbol 确在 + * codeFile 中存在。新增锚点须先核对再追加,勿盲填。 + * + * 深冻结(deepFreezeAnchors):外层数组 + 逐元素对象均 Object.freeze, + * 防运行时意外篡改 docFile/docLine 等字段(与 sandbox-policy 的 + * DEFAULT_BOARD_SANDBOX_POLICY 同范式)。 + */ +export const DEFAULT_DOC_ANCHORS: readonly DocAnchor[] = deepFreezeAnchors([ + { + docFile: DEFAULT_DOC_FILE, + docLine: 274, + codeFile: "src/extensions/hardware-state.ts", + codeSymbol: "replayFromEntries", + }, + { + docFile: DEFAULT_DOC_FILE, + docLine: 582, + codeFile: "src/core/tool-pipeline.ts", + codeSymbol: "ToolPipeline", + }, + { + docFile: DEFAULT_DOC_FILE, + docLine: 749, + codeFile: "src/core/sandbox-policy.ts", + codeSymbol: "probeSandbox", + }, +]); + +// ============================================================================ +// checkDocSync —— 主入口(纯逻辑,readFile/grepSymbol 注入) +// ============================================================================ + +/** + * 校验文档锚点 file:line 与代码对齐。 + * + * 对每个 anchor 做双侧校验: + * 1. 文档侧——读 docFile,取第 docLine 行,确认其确实引用 codeFile + * (字符串包含 codeFile 路径)。docFile 不可读 / 行越界 → mismatch(fail-closed)。 + * 2. 代码侧——grepSymbol(codeFile, codeSymbol) 返回 >0 行号表存在; + * ≤0 或抛错 → mismatch(fail-closed:无法确认存在即视为漂移)。 + * + * mismatches 保持锚点输入序(稳定、可测);ok 当且仅当 mismatches 为空。 + * + * 纯逻辑、readFile/grepSymbol 可注入、无 pi 运行时依赖、确定性可测。 + * + * @param opts.readFile 文件读取器(默认 fs.readFileSync;单测注入 mock)。 + * @param opts.anchors 待校验锚点清单。 + * @param opts.grepSymbol 符号查找器(默认按行子串;单测注入 mock)。 + * @returns 校验结果(ok + mismatches)。 + */ +export function checkDocSync(opts: { + readFile: ReadFile; + anchors: readonly DocAnchor[]; + grepSymbol: GrepSymbol; +}): DocSyncResult { + const { readFile, anchors, grepSymbol } = opts; + const mismatches: DocSyncMismatch[] = []; + + for (const anchor of anchors) { + // ---- 文档侧 ---- + let docText: string; + try { + docText = readFile(anchor.docFile); + } catch { + mismatches.push({ + anchor, + reason: `doc file not readable: ${anchor.docFile}`, + }); + continue; + } + + const docLines = docText.split("\n"); + const docLine = docLines[anchor.docLine - 1]; + if (docLine === undefined) { + mismatches.push({ + anchor, + reason: `doc line ${anchor.docLine} out of range (file has ${docLines.length} lines)`, + }); + continue; + } + if (!docLine.includes(anchor.codeFile)) { + mismatches.push({ + anchor, + reason: `doc line ${anchor.docLine} does not reference "${anchor.codeFile}"`, + }); + continue; + } + + // ---- 代码侧 ---- + let codeLine: number; + try { + codeLine = grepSymbol(anchor.codeFile, anchor.codeSymbol); + } catch { + mismatches.push({ + anchor, + reason: `code file not readable: ${anchor.codeFile}`, + }); + continue; + } + if (codeLine <= GREP_NOT_FOUND_MAX) { + mismatches.push({ + anchor, + reason: `symbol "${anchor.codeSymbol}" not found in ${anchor.codeFile}`, + }); + } + } + + return { ok: mismatches.length === 0, mismatches }; +} diff --git a/scripts/e2e-snapshot.ts b/scripts/e2e-snapshot.ts new file mode 100644 index 0000000..5fd76fd --- /dev/null +++ b/scripts/e2e-snapshot.ts @@ -0,0 +1,197 @@ +/** + * @module e2e-snapshot + * + * 闭环 snapshot 回归对比(T10)—— 结构化深比较 actual vs baseline。 + * + * 为什么需要:联网 key 跑最小闭环(工具调用序列 / 硬件状态快照 / 判据输出), + * 落一份 baseline snapshot 入库;后续回归跑同用例,对比 actual 与 baseline, + * 任何叶子漂移即 CI 红。用结构化路径而非全文本 diff,定位精确到字段。 + * + * 设计:把 actual / baseline 各自拍平成 path→序列化值 的扁平表,再对 path 集合 + * 做集合运算: + * - added : actual 有、baseline 无(回归新增字段) + * - removed: baseline 有、actual 无(回归丢失字段) + * - changed: 同 path 两边序列化值不同(值漂移) + * - match : 三者皆空 + * + * 拍平规则(确定性): + * - 原始值 / null / 非纯对象(Date/Map 等)→ 叶子,JSON 序列化。 + * - 纯对象 → 按 key 递归,path 以 "." 连接(根 key 不加前导点)。 + * - 数组 → 按下标递归,下标作 path 段("a.0.b")。 + * - 空对象 "{}" / 空数组 "[]" → 叶子(结构本身是值,结构变化即漂移)。 + * path 升序排序 → added/removed/changed 输出稳定(元蜕变不变式:确定性)。 + * + * 纯逻辑、零 IO、零 pi 运行时依赖、可离线单测。 + * 见架构设计文档_v3.md §5.9(CI 质量门:真实 API snapshot)。 + */ + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** 闭环 snapshot 对比差异。path 为点号连接的扁平字段路径。 */ +export interface SnapshotDiff { + /** actual 与 baseline 结构完全一致即 true。 */ + readonly match: boolean; + /** actual 独有 path(baseline 缺失)。升序。 */ + readonly added: readonly string[]; + /** baseline 独有 path(actual 缺失)。升序。 */ + readonly removed: readonly string[]; + /** 两边皆有 path 但序列化值不同。升序。 */ + readonly changed: readonly string[]; +} + +// ============================================================================ +// 内部工具:序列化 / 纯对象判定 / 拍平 +// ============================================================================ + +/** + * 序列化叶子值,保证「不同语义值 → 不同串」不碰撞。 + * + * JSON.stringify 的已知陷阱(本函数逐一规避): + * - undefined → 返回裸 undefined(非串)→ 此处特判为 "undefined"。 + * - NaN / Infinity / -Infinity → 均序列化为 "null",与真 null 碰撞 → + * 分别特判为 "NaN" / "Infinity" / "-Infinity"。 + * - function → 返回裸 undefined → 特判为 "function"(与「键不存在」的 + * undefined 哨兵区分,保证同函数自反 match=true)。 + * - symbol → JSON.stringify 返回裸 undefined(非串)→ 会落到 "undefined" + * 与真 undefined 碰撞 → 特判为 "symbol"(不透明身份类型,与 function 同 + * 处理范式:不序列化内部描述,保证自反 match=true 且与 undefined 区分)。 + * - bigint → JSON.stringify 抛 TypeError("Do not know how to serialize a + * BigInt")未被兜底 → 特判为 `bigint:${value}`(带类型前缀以与 JSON 序列化 + * 的数字 "1" / 字符串 "\"1\"" 区分,同时保留数值供漂移检测:BigInt(1) 与 + * BigInt(2) 串不同 → changed;BigInt(1) 自反 → match=true)。 + * - -0(负零)→ JSON.stringify(-0) 返回 "0",与正零 0 碰撞,而 + * Object.is(-0, 0) === false(语义不同)→ 特判为 "-0"(在 number 分支内 + * 优先于 NaN / Infinity 判定,保证 -0 与 0 串不同 → 0→-0 漂移即 changed; + * -0 自反 → match=true)。 + * 其余(null / 有限数字 / 字符串 / 布尔 / 非纯对象 toJSON)走 JSON 标准序列化, + * 稳定可比。 + */ +function serializeLeaf(value: unknown): string { + if (value === undefined) return "undefined"; + if (typeof value === "function") return "function"; + if (typeof value === "symbol") return "symbol"; + if (typeof value === "bigint") return `bigint:${value}`; + if (typeof value === "number") { + // -0 与 0 语义不同(Object.is(-0,0)===false)但 JSON.stringify 均得 "0" + // → 优先特判 "-0",避免 0↔-0 漂移被静默掩盖。 + if (Object.is(value, -0)) return "-0"; + if (Number.isNaN(value)) return "NaN"; + if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity"; + } + const serialized = JSON.stringify(value); + return serialized === undefined ? "undefined" : serialized; +} + +/** 是否纯对象(proto 为 null 或 Object.prototype)。Date/Map/类实例 → false → 当叶子。 */ +function isPlainObject(value: object): boolean { + const proto = Object.getPrototypeOf(value); + return proto === null || proto === Object.prototype; +} + +/** path 连接:根 prefix 为空串时直接取段,否则以 "." 连接。 */ +function joinPath(prefix: string, segment: string): string { + return prefix === "" ? segment : `${prefix}.${segment}`; +} + +/** + * 把 value 拍平进 out(path→序列化值)。递归纯对象/数组,其余当叶子。 + * + * @param value 待拍平值。 + * @param prefix 当前 path 前缀(根为 "")。 + * @param out 累积目标表。 + */ +function flatten(value: unknown, prefix: string, out: Map): void { + // 原始值或 null(typeof null === "object",故先判 null) + if (value === null || typeof value !== "object") { + out.set(prefix, serializeLeaf(value)); + return; + } + + // 数组:空数组当叶子,否则按下标递归 + if (Array.isArray(value)) { + if (value.length === 0) { + out.set(prefix, "[]"); + return; + } + for (let i = 0; i < value.length; i++) { + flatten(value[i], joinPath(prefix, String(i)), out); + } + return; + } + + // 非纯对象(Date/Map/Set/类实例)→ 叶子(走 toJSON),经 serializeLeaf 统一守卫 + if (!isPlainObject(value)) { + out.set(prefix, serializeLeaf(value)); + return; + } + + // 纯对象:空对象当叶子,否则按 key 递归 + const entries = Object.entries(value as Record); + if (entries.length === 0) { + out.set(prefix, "{}"); + return; + } + for (const [key, child] of entries) { + flatten(child, joinPath(prefix, key), out); + } +} + +// ============================================================================ +// compareSnapshot —— 主入口(纯逻辑) +// ============================================================================ + +/** + * 结构化深比较 actual 与 baseline,返回字段级差异。 + * + * 拍平两侧为 path→序列化值 表后做集合运算: + * - added = actual 有 baseline 无的 path + * - removed = baseline 有 actual 无的 path + * - changed = 两边皆有但值不同的 path + * 三者升序排列保证确定性;match 当且仅当三者皆空。 + * + * 不变式:compareSnapshot(a,b) 与 compareSnapshot(b,a) 的 added/removed 互换、 + * changed 不变、match 不变——对称性可单测。空输入(undefined/null)当叶子处理。 + * + * 纯逻辑、零 IO、无 pi 运行时依赖、确定性可测。 + * + * @param actual 回归实跑产出的 snapshot。 + * @param baseline 入库基线 snapshot。 + * @returns 字段级差异。 + */ +export function compareSnapshot(actual: unknown, baseline: unknown): SnapshotDiff { + const actualFlat = new Map(); + const baselineFlat = new Map(); + flatten(actual, "", actualFlat); + flatten(baseline, "", baselineFlat); + + const added: string[] = []; + const removed: string[] = []; + const changed: string[] = []; + + for (const [path, value] of actualFlat) { + const baselineValue = baselineFlat.get(path); + if (baselineValue === undefined) { + added.push(path); + } else if (baselineValue !== value) { + changed.push(path); + } + } + for (const [path] of baselineFlat) { + if (!actualFlat.has(path)) { + removed.push(path); + } + } + + added.sort(); + removed.sort(); + changed.sort(); + + return { + match: added.length === 0 && removed.length === 0 && changed.length === 0, + added, + removed, + changed, + }; +} diff --git a/scripts/t06-t17.workflow.mjs b/scripts/t06-t17.workflow.mjs new file mode 100644 index 0000000..5670c30 --- /dev/null +++ b/scripts/t06-t17.workflow.mjs @@ -0,0 +1,448 @@ +// physical_byte_agent — T06–T17 多 agent 并行开发工作流 +// 两层 + barrier:Layer0(无依赖)并行 → barrier → Layer1(依赖 Layer0)并行。 +// 每模块 pipeline:dev → test → fix(≤3)。barrel index.ts 任何 agent 都不碰(集成阶段我串行接)。 +// 纯 JS,无 Date.now/Math.random。 + +export const meta = { + name: 'pba-t06-t17-build', + description: 'physical_byte_agent P1+P2 (T06–T17) 多 agent 并行开发:dev+test+fix 每模块', + phases: [ + { title: 'Layer0', detail: 'T06/T07/T08/T11/T16/T17 并行 dev→test→fix' }, + { title: 'Layer1', detail: 'T09/T13/T14/T15/T12/T10 并行 dev→test→fix(依赖 Layer0)' }, + ], +}; + +const DIR = '/Users/d-robotics/Desktop/physical_byte_agent'; + +// ───────────────────────── schemas ───────────────────────── +const DEV_SCHEMA = { + type: 'object', + required: ['module', 'files', 'exports', 'smokeTestCount', 'vitestGreen', 'notes'], + properties: { + module: { type: 'string' }, + files: { type: 'array', items: { type: 'string' } }, + exports: { type: 'array', items: { type: 'string' } }, + smokeTestCount: { type: 'integer' }, + vitestGreen: { type: 'boolean' }, + notes: { type: 'string' }, + }, +}; +const TEST_SCHEMA = { + type: 'object', + required: ['module', 'testFile', 'testCount', 'methods', 'mutationBugsPlanted', 'mutationKilled', 'allGreen', 'findings'], + properties: { + module: { type: 'string' }, + testFile: { type: 'string' }, + testCount: { type: 'integer' }, + methods: { type: 'array', items: { type: 'string' } }, + mutationBugsPlanted: { type: 'integer' }, + mutationKilled: { type: 'integer' }, + allGreen: { type: 'boolean' }, + findings: { + type: 'array', + items: { + type: 'object', + required: ['severity', 'summary', 'file'], + properties: { + severity: { type: 'string', enum: ['high', 'medium', 'low'] }, + summary: { type: 'string' }, + file: { type: 'string' }, + line: { type: 'integer' }, + failureScenario: { type: 'string' }, + }, + }, + }, + }, +}; + +// ───────────────────────── module specs ───────────────────────── +// 每个模块:key, title, files(严格独占), testFile, contract(精确导出+签名), spec, refs, deps +const MODULES = [ + // ═══════════════════════ LAYER 0 ═══════════════════════ + { + key: 'T06', layer: 0, + title: 'PbaSession 事件溯源 + deriveMessages', + files: ['src/core/pba-session.ts'], + testFile: 'tests/pba-session.test.ts', + contract: `PbaSessionEventMap (interface): keys turn/step/user-message/assistant-message/tool-call/tool-result/hw:state/flash-log/verify-record/checkpoint-change,每键映射到该事件的 data 形状(你定义合理字段)。 +class PbaSession { + constructor(opts: { appendEntry: (type: string, data: unknown) => void; deepFreeze?: boolean }); + append(event: { type: string; data: unknown }): void; // 唯一提交点:lossless-JSON 快照 + 深冻结 + seq 连续 + 重入 guard(重入抛错) + deriveMessages(): unknown[]; // 从有序 surface 投影模型历史,增量缓存(第二次调用命中缓存) + replayFromEntries(entries: ReadonlyArray<{type:string;data:unknown;seq?:number}>): PbaSession; // 从 log 重建(推广 hardware-state replayFromEntries 到全量事件) + assertModelVisibleLogged(visibleTypes: readonly string[]): void; // "model-visible⟺logged" 不变量:若 deriveMessages() 投影里有某 type 但 log 里没 append 过 → 抛错 +} +纯逻辑,注入 appendEntry(无 pi 运行时 import)。深冻结常量。`, + spec: `事件溯源底座。append 是唯一提交点(防旁路写)。lossless-JSON 快照 = 结构化克隆语义(处理 Date/Map/Set 折叠成 plain)。seq 单调连续,缺口即抛。deriveMessages 增量缓存(append 后失效)。replayFromEntries 从 entries 重建一个等价 PbaSession。model-visible⟺logged 不变量由 before_agent_start 钩子校验(本模块只暴露 assert 方法,钩子接线留给集成)。`, + refs: 'src/extensions/hardware-state.ts:134 replayFromEntries(重放范式)+ :99 makeHwEntry + :312 buildCompactionProtection;src/core/tool-pipeline.ts(深冻结/不变式范式)', + deps: [], + }, + { + key: 'T07', layer: 0, + title: 'PbaEventBus + ScopeKey 隔离', + files: ['src/core/pba-event-bus.ts'], + testFile: 'tests/pba-event-bus.test.ts', + contract: `type ScopeKey = string; // branded 语义:用 "a.b.c" 路径式 scope,祖先-后代关系 +interface PbaListener { (args: unknown, next: () => void): void; } +class PbaEventBus { + constructor(opts?: { emitter?: { on:(e:string,l:Function)=>(()=>void); emit:(e:string,a:unknown)=>void } }); // 注入 emitter 供单测;默认内存 emitter + on(event: string, listener: PbaListener, scope?: ScopeKey): () => void; // 返回 disposer + off(event: string, listener: PbaListener): void; + emit(event: string, args: unknown, scope?: ScopeKey): void; // 事件向上扩展到祖先 scope(后代监听器收到祖先发的事件?反:scope 匹配键或祖先键的监听器收事件) + waterfall(event: string, args: unknown, scope?: ScopeKey): unknown; // 顺序链:listener 收 (...args, next),调 next() 委托下一个;不调 next 即短路 + scopedScope(parent: ScopeKey, child: ScopeKey): ScopeKey; // 拼接 + listenerCount(event: string): number; +} +scope 规则:无 scope=全局监听收所有事件;注册时 scope=child,emit scope=child 则 child + 祖先监听器收(注册向下继承、事件向上扩展——子 agent 的事件冒泡到父 scope,父 scope 注册的监听也收)。typed event 名约定(文档化常量数组 KNOWN_EVENTS):verify:passed/build:done/boardlink:connect/glm:empty-output/xcompile:done/pdf-reader:page/debugger:attach/length-recovery:recovered。 +纯逻辑,emitter 可注入(无 pi 顶层 import)。`, + spec: `薄封装 pi.events 加 typed event bus。waterfall 链委托(next() 不调=短路)。scope 多 agent 隔离:子 agent 事件不串主 agent(子 scope 的事件冒泡到父,但父 scope emit 不下渗到子——单向冒泡)。21 域迁移留给集成阶段(本模块只提供 bus)。`, + refs: 'src/core/tool-pipeline.ts(waterfall/next 范式 + disposer 范式);src/extensions/index.ts:70 fail-soft 装配', + deps: [], + }, + { + key: 'T08', layer: 0, + title: '能力接缝三角色(board-link + flash)', + files: ['src/capabilities/board-link/types.ts', 'src/capabilities/board-link/index.ts', 'src/capabilities/board-link/providers/rdk-x5-ssh.ts', 'src/capabilities/board-link/providers/rdk-s100-serial.ts', 'src/capabilities/board-link/providers/local.ts', 'src/capabilities/flash/types.ts', 'src/capabilities/flash/index.ts', 'src/capabilities/flash/providers/dd.ts', 'src/capabilities/flash/providers/fastboot.ts', 'src/capabilities/flash/providers/dfu.ts', 'src/capabilities/flash/providers/openocd.ts'], + testFile: 'tests/capability-seams.test.ts', + contract: `// board-link +interface BoardLinkProvider { id: string; linkType: BoardLinkType; createExec(board: BoardSpec, underlying: ExecFn): ExecFn; healthCheck?(exec: ExecFn): Promise<{ok:boolean;reason?:string}>; } +class BoardLinkRegistry { register(p: BoardLinkProvider): () => void; resolve(board: BoardSpec): BoardLinkProvider; list(): readonly BoardLinkProvider[]; } // resolve fail-closed:无匹配 provider 抛错 +const RDK_X5_SSH_PROVIDER, RDK_S100_SERIAL_PROVIDER, LOCAL_PROVIDER: BoardLinkProvider; // 从 board-link.ts makeExec 抽 ssh/serial-stub/local 三实现 +// flash +interface FlashProvider { id: FlashMethod; plan(opts: FlashPlanOptions, ctx?: {lsblk?: LsblkRow[]}): FlashPlanEx; run(plan: FlashPlanEx, exec: ExecFn): Promise; verify(plan: FlashPlanEx, exec: ExecFn): Promise; } +class FlashRegistry { register(p: FlashProvider): () => void; resolve(method: FlashMethod): FlashProvider; list(): readonly FlashProvider[]; } +const DD_PROVIDER, FASTBOOT_PROVIDER, DFU_PROVIDER, OPENOCD_PROVIDER: FlashProvider; +BoardSpec(shared/types.ts:98)做 provider 配置。纯逻辑,import type 来自 shared/types + 现有 board-link.ts/flash.ts 的类型(re-export 或 import type)。 +❗不删 board-link.ts / flash.ts(仍在 barrel);本模块是新接缝层,provider 逻辑从那两文件抽出来。不修改原扩展文件。`, + spec: `Definition/Provider/Consumer 三角色。board-link 抽 BoardLinkProvider + Registry + 3 provider(rdk-x5-ssh/rdk-s100-serial/local)。flash 同理 4 provider(dd/fastboot/dfu/openocd)。验收:加 RdkS100Provider 后 resolve(S100 board) 无改动可用;register disposer 后 list 不见该 provider。fail-closed resolve。`, + refs: 'src/extensions/board-link.ts:250 makeExec(ssh/serial-stub/local 三分支逻辑搬到 provider)+:380 BoardRegistry(registry 范式)+:507 computeFingerprint;src/extensions/flash.ts:188 planFlash +:630 runFlash +:558 verifyFlash(按 method 分到 4 provider);src/shared/types.ts:75 FlashMethod/FlashPlan', + deps: [], + }, + { + key: 'T11', layer: 0, + title: '类型镜像漂移检测', + files: ['tsconfig.realpi.json', 'scripts/type-drift-check.ts'], + testFile: 'tests/type-drift-check.test.ts', + contract: `// tsconfig.realpi.json: extends ./tsconfig.json,paths 覆盖 @earendil-works/pi-coding-agent + pi-ai + pi-agent-core 指向 ../pi/packages/*/src/index.ts(真源码)。include src/ + scripts/。 +// scripts/type-drift-check.ts +interface TscResult { exitCode: number; stdout: string; stderr: string; } +function checkTypeDrift(opts: { tsconfigPath?: string; runTsc?: (args: string[]) => TscResult; pbaSrcPattern?: RegExp }): { + driftDetected: boolean; + pbaErrors: string[]; // 命中 src/**/*.ts 的错(真漂移) + piInternalErrors: string[]; // 仅 packages/ 内的错(pi 自家,忽略) +}; +默认 runTsc = spawnSync('npx tsc -p --noEmit')。过滤逻辑:每条 error 行按文件路径分类,src/ 下的进 pbaErrors,packages/ 下的进 piInternalErrors。driftDetected = pbaErrors.length>0。 +纯逻辑,runTsc 可注入(单测 mock)。`, + spec: `对真 pi 源码 tsc,检测 src/types/pi.d.ts 镜像漂移。已知 pi 自家 packages/agent/src 报错是 pi build 产物问题,非 pba,过滤掉只看 src/。CI 周期跑。`, + refs: '现有 tsconfig.json(看 paths 结构);src/types/pi.d.ts(被检测的镜像)', + deps: [], + }, + { + key: 'T16', layer: 0, + title: '多 LLM provider 适配', + files: ['src/core/provider-registry.ts'], + testFile: 'tests/provider-registry.test.ts', + contract: `interface ProviderDescriptor { + id: string; provider: string; baseUrl: string; apiKeyEnv: string; // key 占位变量名,值走 env,绝不入库 + thinkingFormat?: "qwen"|"none"; maxTokens: number; contextWindow: number; reasoning: boolean; + input?: ("text"|"image")[]; cost?: {input:number;output:number;cacheRead:number;cacheWrite:number}; +} +function buildProviderConfig(desc: ProviderDescriptor): { name: string; config: ProviderConfig }; // 泛化 glm-provider buildGlmModelConfig+toProviderConfig;thinkingFormat:"qwen" 触发 enable_thinking:false 兼容(THINKING_FORMAT_GATE 思路) +class ProviderRegistry { register(desc: ProviderDescriptor): () => void; resolve(modelId: string): ProviderDescriptor; list(): readonly ProviderDescriptor[]; } +const KNOWN_PROVIDERS: readonly ProviderDescriptor[]; // glm-5.2(默认)+ deepseek-native(stub) +const DEFAULT_GLM_DESCRIPTOR: ProviderDescriptor; // baseUrl=ai-api.d-robotics.cc/v1, apiKeyEnv=DROBOTICS_LLM_KEY, thinkingFormat:"qwen", maxTokens:8192 +纯逻辑,ProviderConfig 仅 import type。❗key 全程 \${DROBOTICS_LLM_KEY} 占位,绝不出现 sk- 明文。`, + spec: `换模型改配置行不改扩展。glm-provider 扩展支持多 provider。复用 dsh THINKING_FORMAT_GATE 思路支持 DeepSeek 原生+其他。本模块是新 core lib(不重度改 glm-provider.ts,glm-provider 可后续接进来)。`, + refs: 'src/extensions/glm-provider.ts:81 buildGlmModelConfig +:109 toProviderConfig(泛化这两函数)+:39 GlmCompat(thinkingFormat 范式)', + deps: [], + }, + { + key: 'T17', layer: 0, + title: '审批接缝 + credentials/settings + LSP', + files: ['src/capabilities/approval.ts', 'src/capabilities/credentials.ts', 'src/capabilities/settings.ts', 'src/capabilities/lsp.ts'], + testFile: 'tests/capabilities-misc.test.ts', + contract: `// approval.ts —— fail-closed 无人值守审批 +type ApprovalMode = "auto-deny" | "auto-approve" | "interactive"; +interface ApprovalRequest { action: string; risk: "low"|"medium"|"high"; timeoutMs?: number; context?: string; } +interface ApprovalResult { decision: "approve"|"deny"; reason: string; by: "auto"|"approver"|"timeout"; } +class ApprovalGate { + constructor(opts?: { mode?: ApprovalMode; timeoutMs?: number }); + setMode(m: ApprovalMode): void; + registerApprover(fn: (req: ApprovalRequest) => Promise): () => void; // disposer + request(req: ApprovalRequest): Promise; // auto-deny→直接 deny;auto-approve→approve;interactive→调注册的 approver,无 approver→deny(fail-closed),超时→deny +} +// credentials.ts —— 凭据 store,key 永不明文 echo +class CredentialsStore { + get(name: string): string | undefined; // 先 memory 后 process.env[name] + set(name: string, value: string): void; // 仅 memory,不落盘 + has(name: string): boolean; + redact(s: string): string; // 把形似 sk-xxx/长 token 的串替换成 +} +// settings.ts —— typed settings +class SettingsStore> { + constructor(defaults: T); + get(k: K): T[K]; + set(k: K, v: T[K]): void; + snapshot(): Readonly; +} +// lsp.ts —— 嵌入式 IDE 桥(on-demand stub) +interface LspBridge { initialize(opts: {rootUri: string}): Promise<{ok:boolean}>; shutdown(): Promise; } +class NoopLspBridge implements LspBridge; // 默认 no-op 实现(on-demand) +纯逻辑,无 pi import。`, + spec: `按需逐个。approval fail-closed 无人值守。credentials 永不 echo key。settings typed。lsp stub 接口。`, + refs: 'src/extensions/safety-gate.ts(fail-closed + hardGate 范式);src/core/sandbox-policy.ts(fail-closed unusable→拒绝 范式)', + deps: [], + }, + // ═══════════════════════ LAYER 1 ═══════════════════════ + { + key: 'T09', layer: 1, + title: 'compaction 完整工程', + files: ['src/compaction/token-meter.ts', 'src/compaction/tool-result-pruner.ts', 'src/compaction/summarizer.ts', 'src/compaction/spill.ts'], + testFile: 'tests/compaction.test.ts', + contract: `// token-meter.ts +function estimateTokens(text: string): number; // chars/4 启发 + 中文按 char 计 +function measureContext(messages: ReadonlyArray<{role:string;content:string}>): number; +// tool-result-pruner.ts +interface PruneOptions { tool: "i2cdump"|"gdb"|"dmesg"|"general"; maxLines?: number; } +interface PruneResult { pruned: string; dropped: number; preservedAddrs?: string[]; } +function pruneToolResult(content: string, opts: PruneOptions): PruneResult; // i2cdump 保留寄存器地址行(0xXX: 格式)+ 最后 dump 行;gdb 保留 #frame 行;dmesg 保留 error/critical/warn 行;general 截断 maxLines +// summarizer.ts +interface CompactionSummary { summary: string; reusedPrefix: boolean; droppedEntries: number; } +function buildCompactionSummary(opts: { prefix: string; recentEntries: ReadonlyArray<{type:string;data:unknown}>; maxTokens: number }): CompactionSummary; // 重放前缀 + append 压缩指令,标记 reusedPrefix(复用 KV prefix cache 语义) +// spill.ts +type SpillLocator = string & { readonly __brand: "SpillLocator" }; +class SpillStore { + spill(key: string, data: unknown): SpillLocator; // 大结果溢出,返 branded 句柄 + recall(locator: SpillLocator): unknown; // 取回 + has(locator: SpillLocator): boolean; + evict(olderThanBytes?: number): number; // 容量回收 +} +纯逻辑。import type 来自 ../core/pba-session.js(surface replace op 类型,T06 实际产出)。`, + spec: `compaction 完整:tokenMeter 压力触发 + tool-result prune(i2cdump/gdb/dmesg 大输出 model-free 压缩)+ spill(datasheet 大结果句柄)。验收:压力触发 summarize 标 reusedPrefix;i2cdump prune 寄存器地址不丢;spill 句柄可 recall。`, + refs: 'src/extensions/hardware-state.ts:295 buildCompactionProtection(compaction 保护范式);src/core/pba-session.ts(T06 产出,import type)', + deps: ['T06'], + }, + { + key: 'T13', layer: 1, + title: '上下文注入三段(inject/steer/followup)', + files: ['src/core/context-injector.ts'], + testFile: 'tests/context-injector.test.ts', + contract: `type InjectionPhase = "inject" | "steer" | "followup"; +interface Injection { phase: InjectionPhase; content: string; boardId?: string; nextStep: boolean; nextTurn: boolean; replacesSnapshot?: string; } +class ContextInjector { + inject(content: string): Injection; // 寄存器表 next-step,NO wake(nextStep=true 但不触发) + steer(content: string, boardId?: string): Injection; // 换板 next-step 唤醒 + followup(content: string): Injection; // 新任务 next-turn 唤醒 + snapshot(): { content: string; boardId?: string; ts: number }; // runtime-context 快照,取代更早快照 + deriveActiveContext(): { injections: Injection[]; active: Injection | null }; // 最新 snapshot 取代更早 + clear(phase?: InjectionPhase): void; +} +纯逻辑。import type 来自 ../core/pba-session.js(可选)。`, + spec: `inject(寄存器表 next-step 不唤醒)/steer(换板 next-step 唤醒)/followup(新任务 next-turn 唤醒)三段语义区分。runtime-context 快照"取代更早快照"。`, + refs: 'src/core/pba-session.ts(T06);src/extensions/env-probe.ts(注入范式参考)', + deps: ['T06', 'T07'], + }, + { + key: 'T14', layer: 1, + title: 'plan/goal/todo logged state', + files: ['src/core/checkpoint-state.ts'], + testFile: 'tests/checkpoint-state.test.ts', + contract: `class CheckpointRecorder { + constructor(opts: { append: (entry: {type:string;data:unknown}) => void }); // 注入 PbaSession.append 或独立 append + record(step: CheckpointStep, passed: boolean, timestamp: number): void; // 写进 session 事件(type="checkpoint-change") + current(): CheckpointState; // 读当前 + rebuild(entries: ReadonlyArray<{type:string;data:unknown}>): CheckpointState; // resume 从 log 重建 + fork(): CheckpointRecorder; // 从当前 fork(子任务) +} +CheckpointState(shared/types.ts:45 已存在:currentStep/stepPassed/history)。CheckpointStep(:43 已存在)。 +纯逻辑,append 注入。`, + spec: `checkpoint 进度写进 PbaSession 事件,resume/fork 从 log 重建。验收:session resume 后 checkpoint 状态从 log 重建。`, + refs: 'src/shared/types.ts:43 CheckpointStep +:45 CheckpointState(已存在,直接用);src/extensions/loop-orchestrator.ts(checkpoint 范式);src/core/pba-session.ts(T06 append)', + deps: ['T06'], + }, + { + key: 'T15', layer: 1, + title: 'profile/bundle 分层', + files: ['src/profiles/base.ts', 'src/profiles/repair-diagnosis.ts', 'src/profiles/embedded-dev.ts', 'src/profiles/index.ts'], + testFile: 'tests/profiles.test.ts', + contract: `interface Profile { id: string; extensions: readonly string[]; tools: readonly string[]; note?: string; } +const BASE_PROFILE: Profile; // 共享 base(safety-gate/glm-provider/persistent-shell/edit-length-recovery/subprocess-isolation/env-probe/mcp-bridge/server-runtime/hardware-state 等公共) +const REPAIR_DIAGNOSIS_PROFILE: Profile; // base + pdf-reader/datasheet-rag/peripheral-probe(维修诊断要的) +const EMBEDDED_DEV_PROFILE: Profile; // base + cross-compile/flash/jtag-debugger/device-tree/board-link/reg-tool(嵌入式开发要的) +function resolveProfile(id: string): Profile; // fail-closed:未知 id 抛错 +function mergeProfiles(base: Profile, delta: Pick): Profile; // 共享 base + 叠差异 +function diffProfiles(a: Profile, b: Profile): {added:string[];removed:string[]}; +纯逻辑。`, + spec: `维修诊断 profile vs 嵌入式开发 profile,共享 base + 叠差异。验收:两 profile 共享 base,各叠差异扩展。`, + refs: 'src/extensions/index.ts:39 extensionFactories(21 域名清单,照此选 extensions/tools 名)', + deps: ['T08'], + }, + { + key: 'T12', layer: 1, + title: '子代理 + 工作流编排', + files: ['src/capabilities/subagent/index.ts', 'src/capabilities/workflow/index.ts'], + testFile: 'tests/workflow.test.ts', + contract: `// subagent +interface SubagentResult { ok: boolean; value?: unknown; error?: string; scope: string; } +interface SubagentProvider { spawn(prompt: string, opts?: {scope?: string; timeoutMs?: number}): Promise; } +class InlineSubagentProvider implements SubagentProvider { // spawn-in-process:跑一个注入的 handler 函数(构造器收 (prompt,opts)=>Promise) + constructor(handler: (prompt: string, opts?: {scope?:string}) => Promise); + spawn(...): Promise; // scope 隔离:子 agent 事件不串主 agent(靠 ScopeKey,import type 自 T07) +} +class SubagentRegistry { register(p: SubagentProvider): ()=>void; resolve(id: string): SubagentProvider; } +// workflow +function parallel(thunks: ReadonlyArray<() => Promise>): Promise; // barrier:全等齐,单 thunk 抛错→该位 null(不 reject) +function pipeline(items: ReadonlyArray, ...stages: Array<(prev: unknown, item: T, i: number) => Promise>): Promise; // 每 item 过全 stage,stage 间无 barrier;stage 抛错→item 落 null 跳后续 +function phase(name: string): void; // 标记进度(no-op,仅记录) +const MAX_CONCURRENCY = 8; +纯逻辑。`, + spec: `loop-orchestrator 上层加 workflow:parallel(编译+探板+datasheet 三并发)/ pipeline(edit→compile→flash→verify 串行)。子 agent 事件不串主 agent。验收:parallel 三任务并发;pipeline 串行 stage 抛错 item 落 null。`, + refs: 'src/core/pba-event-bus.ts(T07 ScopeKey 隔离);src/extensions/loop-orchestrator.ts(闭环编排范式)', + deps: ['T07', 'T08'], + }, + { + key: 'T10', layer: 1, + title: 'CI 质量门 + snapshot + doc-sync', + files: ['.github/workflows/ci.yml', 'scripts/e2e-snapshot.ts', 'scripts/doc-sync.ts'], + testFile: 'tests/doc-sync.test.ts', + contract: `// scripts/doc-sync.ts —— 校验架构文档锚点 file:line 与代码对齐 +interface DocAnchor { docFile: string; docLine: number; codeFile: string; codeSymbol: string; } +function checkDocSync(opts: { readFile: (p: string) => string; anchors: readonly DocAnchor[]; grepSymbol: (file: string, symbol: string) => number; }): { ok: boolean; mismatches: Array<{anchor: DocAnchor; reason: string}> }; +// scripts/e2e-snapshot.ts —— 闭环 snapshot 回归对比(结构化) +interface SnapshotDiff { match: boolean; added: string[]; removed: string[]; changed: string[]; } +function compareSnapshot(actual: unknown, baseline: unknown): SnapshotDiff; +// .github/workflows/ci.yml —— test:coverage per-file 门 + doc-sync + type-drift-check(调 T11 的 scripts/type-drift-check.ts) +纯逻辑(readFile/grepSymbol 注入)。type-drift-check.ts 由 T11 拥有,本模块只在 ci.yml 里调它。`, + spec: `CI per-file 100% 覆盖门 + snapshot 漂移红 + doc-sync 锚点不一致红 + 类型漂移红。验收:doc-sync 锚点 file:line 与代码不符→红。`, + refs: 'scripts/type-drift-check.ts(T11 产出,ci.yml 调用);架构设计文档_v3.md(doc-sync 校验对象)', + deps: ['T11'], + }, +]; + +// ───────────────────────── prompt builders ───────────────────────── +function devPrompt(m) { + return [ + `你是 physical_byte_agent 项目模块 ${m.key}(${m.title})的【开发 Agent】。项目目录:${DIR}`, + ``, + `【目标】用最优雅的架构、最干净的代码实现本模块。禁止任何临时性妥协代码、禁止 bad smell(god object、隐式全局、魔法串、未处理边界、深嵌套、命名含糊)。纯逻辑、依赖可注入、JSDoc 注释(中文模块头 + 每导出 @param/@returns)。遵循现有风格:见 src/core/tool-pipeline.ts、src/core/sandbox-policy.ts、src/extensions/hardware-state.ts(命名导出 + 顶层仅 import type + 逻辑内联 + 深冻结常量 + fail-closed)。`, + ``, + `【独占文件——只创建/修改这些文件,严禁触碰任何其他文件(尤其 src/extensions/index.ts 不许动)】`, + m.files.map((f) => ' - ' + f).join('\n'), + ``, + `【契约——必须精确产出这些导出与签名,下游模块依赖这些名字,不得擅自改名】`, + m.contract, + ``, + `【SPEC】`, + m.spec, + ``, + `【参考文件(读这些学范式,勿盲抄)】`, + m.refs, + ...(m.deps.length ? [``, `【依赖模块已落地(Layer0 已完成)——读它们真实的导出再写 import,若实际导出名与契约不符以实际为准自适应】` + m.deps.join(', ')] : []), + ``, + `【密钥铁律】gateway key 一律用 \${DROBOTICS_LLM_KEY} 占位,绝不出现 sk- 开头明文,绝不写进 git-tr踪文件。`, + ``, + `【自检门——返回前必须过】`, + `1. 写一个最小冒烟测试 ${m.testFile}(3-6 用例:happy path + 一个边界 + 一个不变式),用 npx vitest 跑:`, + ` cd ${DIR} && npx vitest run ${m.testFile} # 必须 all green`, + ` 测试直接 import 你的命名导出,mock 注入依赖,无 pi 运行时无硬件。`, + `2. 确认你的文件顶层无 pi 运行时 import(仅 import type),以保离线可测。`, + `3. 违反独占文件/触碰 barrel/明文 key 一律算失败。`, + ``, + `返回 DEV_SCHEMA(module=${m.key},列出 files/exports/smokeTestCount/vitestGreen/notes)。`, + ].join('\n'); +} + +function testPrompt(m) { + return [ + `你是 physical_byte_agent 项目模块 ${m.key}(${m.title})的【测试 Agent】。项目目录:${DIR}`, + ``, + `【目标】为该模块的命名导出写一套严谨、多方法论、测试前置的测试套件。测试要严到植入的 bug 活不过。`, + ``, + `【测试文件——只写这一个,是你的独占】`, + ` ${m.testFile}`, + `先读开发 Agent 写的冒烟测试(如有),然后 REPLACE 成完整套件。`, + ``, + `【被测对象】读 ${m.files.join(' / ')} 的命名导出(按契约)。直接 import,mock 注入依赖(appendEntry/exec/emitter/runTsc/readFile 等),无 pi 运行时无硬件无网络。`, + ``, + `【必须应用的多测试方法论(每个 describe 块标注方法论名)】`, + `- 等价类划分(有效/无效/边界类)`, + `- 边界值分析(off-by-one、空、单元素、max、min)`, + `- 决策表(组合输入→期望,覆盖全分支)`, + `- 状态转换(若有状态:状态+迁移+不可达状态+重入)`, + `- 变异测试:至少植入 3 个 seeded bug(例:< 改 <=、off-by-one、错默认值、漏 freeze、漏 seq 校验、短路逻辑反),在测试内联一份带 bug 的逻辑副本/包装器,断言每个 bug 被【某条测试】杀死(植入后该测试失败=bug 被杀)。文档化每个植入 bug + 杀它的测试。最后确认真实(未植入 bug)代码全过。`, + `- 对抗/fuzz:畸形/滥用输入(null、undefined、巨大、NaN、循环引用、并发重入、负 seq)`, + `- 元蜕变/不变式:跨变换保持的性质(append 两次=replay 等价;freeze→篡改抛 TypeError;单调 deny;waterfall 不调 next=短路;fail-closed unusable=拒)`, + ``, + `【门】`, + `1. cd ${DIR} && npx vitest run ${m.testFile} # 真实代码必须 all green`, + `2. 每个植入 bug 变体单独跑,确认它 FAIL(bug 被杀)。`, + ``, + `若发现开发代码的真实 bug(非植入),列入 findings[](file+line+severity+failureScenario),【不要自己改】——留给 fix 阶段的开发 Agent。`, + `返回 TEST_SCHEMA(module=${m.key})。`, + ].join('\n'); +} + +function fixPrompt(m, test) { + return [ + `你是 physical_byte_agent 项目模块 ${m.key}(${m.title})的【修复 Agent】。项目目录:${DIR}`, + ``, + `测试 Agent 报告:allGreen=${test.allGreen}, testCount=${test.testCount}, mutationKilled=${test.mutationKilled}/${test.mutationBugsPlanted}`, + `findings:`, + JSON.stringify(test.findings, null, 2), + ``, + `【任务】逐条修复 findings 在你的独占文件里:`, + m.files.map((f) => ' - ' + f).join('\n'), + `严禁触碰其他文件。遵循现有风格 + JSDoc。密钥占位 \${DROBOTICS_LLM_KEY}。`, + ``, + `【门】cd ${DIR} && npx vitest run ${m.testFile} # 必须 all green 后再返回`, + `返回 DEV_SCHEMA(module=${m.key})。`, + ].join('\n'); +} + +// ───────────────────────── pipeline stages ───────────────────────── +async function devStage(m) { + return agent(devPrompt(m), { schema: DEV_SCHEMA, phase: m.layer === 0 ? 'Layer0' : 'Layer1', label: `dev:${m.key}` }); +} +async function testStage(_dev, m) { + return agent(testPrompt(m), { schema: TEST_SCHEMA, phase: m.layer === 0 ? 'Layer0' : 'Layer1', label: `test:${m.key}` }); +} +async function fixStage(test, m) { + let cur = test; + let attempts = 0; + const MAX = 3; + while (cur && (!cur.allGreen || (cur.findings && cur.findings.length > 0)) && attempts < MAX) { + attempts++; + await agent(fixPrompt(m, cur), { schema: DEV_SCHEMA, phase: m.layer === 0 ? 'Layer0' : 'Layer1', label: `fix:${m.key}#${attempts}` }); + cur = await agent(testPrompt(m), { schema: TEST_SCHEMA, phase: m.layer === 0 ? 'Layer0' : 'Layer1', label: `retest:${m.key}#${attempts}` }); + } + return { module: m.key, title: m.title, test: cur, fixAttempts: attempts, files: m.files }; +} + +// ───────────────────────── run ───────────────────────── +const layer0 = MODULES.filter((m) => m.layer === 0); +const layer1 = MODULES.filter((m) => m.layer === 1); + +phase('Layer0'); +log(`Layer0 并行:${layer0.map((m) => m.key).join(',')}(每模块 dev→test→fix≤3)`); +const l0 = await parallel( + layer0.map((m) => () => + pipeline([m], (mod) => devStage(mod), (dev, mod) => testStage(dev, mod), (test, mod) => fixStage(test, mod)).then((r) => r[0]) + ) +); +const l0r = l0.filter(Boolean); +log(`Layer0 完成:${l0r.length}/${layer0.length} 模块。绿:${l0r.filter((r) => r.test && r.test.allGreen && (!r.test.findings || !r.test.findings.length)).length}`); + +phase('Layer1'); +log(`Layer1 并行(依赖 Layer0 已落盘):${layer1.map((m) => m.key).join(',')}`); +const l1 = await parallel( + layer1.map((m) => () => + pipeline([m], (mod) => devStage(mod), (dev, mod) => testStage(dev, mod), (test, mod) => fixStage(test, mod)).then((r) => r[0]) + ) +); +const l1r = l1.filter(Boolean); +log(`Layer1 完成:${l1r.length}/${layer1.length} 模块。绿:${l1r.filter((r) => r.test && r.test.allGreen && (!r.test.findings || !r.test.findings.length)).length}`); + +return { + layer0: l0r.map((r) => ({ module: r.module, allGreen: r.test?.allGreen, testCount: r.test?.testCount, findings: r.test?.findings?.length ?? 0, fixAttempts: r.fixAttempts })), + layer1: l1r.map((r) => ({ module: r.module, allGreen: r.test?.allGreen, testCount: r.test?.testCount, findings: r.test?.findings?.length ?? 0, fixAttempts: r.fixAttempts })), +}; diff --git a/scripts/type-drift-check.ts b/scripts/type-drift-check.ts new file mode 100644 index 0000000..1abd930 --- /dev/null +++ b/scripts/type-drift-check.ts @@ -0,0 +1,199 @@ +/** + * @module type-drift-check + * + * 类型镜像漂移检测(T11)—— 对真 pi 源码跑 tsc --noEmit,检测 + * src/types/pi.d.ts 镜像是否与真 pi 扩展 API 面漂移。 + * + * 为什么需要:pba 在 src/types/pi.d.ts 维护了一份 pi 扩展 API 的类型镜像 + * (离线 tsc 用),pi 升级 API 后镜像可能过时。本模块用 tsconfig.realpi.json + * (paths 覆盖为真 pi 源码 ../pi/packages 下的 index.ts)跑 tsc,把报错按 + * 文件路径分类: + * - src/ 下的错 → pbaErrors(真漂移——镜像与真 pi 不一致,需修镜像) + * - packages/ 下的错 → piInternalErrors(pi 自家 build 产物问题,非 pba,忽略) + * + * 正交阶段(单一职责,确定性可测): + * extractErrorPath(纯解析:一行 tsc 输出 → 文件路径 | null) + * → checkTypeDrift(分类 + fail-closed 兜底) + * + * 纯逻辑 + runTsc 可注入(单测 mock),零 pi 运行时依赖,可离线单测。 + * CI 周期跑(非每次提交)。见架构设计文档_v3.md §type-drift。 + */ + +import { spawnSync } from "node:child_process"; + +// ============================================================================ +// 命名常量 —— 消灭魔法串 +// ============================================================================ + +/** 默认 tsconfig 路径(paths 指向真 pi 源码的覆盖配置)。 */ +const DEFAULT_TSCONFIG_PATH = "tsconfig.realpi.json"; + +/** + * pba 源码路径匹配模式。tsc 报错文件路径以此开头即为 pba 自身代码的错(真漂移)。 + * 默认匹配 src/ 下所有文件(tsc 只对 .ts/.tsx/.d.ts 报错,无需额外过滤扩展名)。 + */ +const DEFAULT_PBA_SRC_PATTERN = /^src\//; + +/** pi 自家源码路径匹配模式。报错文件路径含此片段即为 pi 内部错(忽略)。 */ +const PI_INTERNAL_PATTERN = /packages\//; + +/** + * tsc 报错行路径提取正则。 + * + * 匹配两种 tsc 输出格式(捕获组 1 = 文件路径,行/列标记之前的部分): + * - 非 pretty(CI 默认):src/foo.ts(23,5): error TS2322: msg + * - pretty(TTY): src/foo.ts:23:5 - error TS2322: msg + * + * 非贪婪 `(.+?)` 保证只取行/列标记之前的路径段;Unix 路径无冒号,首段 `:` 即 + * pretty 格式的 `:line:col` 分隔,不会误截路径内部。 + */ +const TSC_ERROR_PATH_RE = /^(.+?)(?:\(\d+,\d+\)|:\d+:\d+)/; + +/** tsc 错误码标记(用于判定一行是否为 tsc 报错行)。 */ +const TSC_ERROR_MARKER = /error\s+TS\d+:/; + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** tsc 执行结果。 */ +export interface TscResult { + /** 进程退出码(0=无错,非 0=有错或执行失败;-1=进程未正常退出)。 */ + readonly exitCode: number; + /** 标准输出(tsc 报错默认走 stdout)。 */ + readonly stdout: string; + /** 标准错误(tsc 启动失败 / spawn 错误走 stderr)。 */ + readonly stderr: string; +} + +/** 类型漂移检测结果。 */ +export interface TypeDriftResult { + /** 是否检测到真漂移(pbaErrors 非空即 true)。 */ + readonly driftDetected: boolean; + /** 命中 src/ 下文件的 tsc 报错行(真漂移——镜像与真 pi 不一致)。 */ + readonly pbaErrors: readonly string[]; + /** 仅 packages/ 下文件的 tsc 报错行(pi 自家问题,忽略)。 */ + readonly piInternalErrors: readonly string[]; +} + +/** tsc 执行器抽象(注入以便单测 mock,避免真 spawn)。 */ +export type TscRunner = (args: string[]) => TscResult; + +// ============================================================================ +// extractErrorPath —— 纯解析(导出供测试 + 调用方诊断) +// ============================================================================ + +/** + * 从一行 tsc 输出中提取报错文件路径。 + * + * 匹配两种 tsc 格式(见 {@link TSC_ERROR_PATH_RE}): + * - 非 pretty:src/foo.ts(23,5): error TS2322: msg → "src/foo.ts" + * - pretty: src/foo.ts:23:5 - error TS2322: msg → "src/foo.ts" + * + * 非报错行(不含 `error TSxxxx:`)返回 null,不误分类上下文行或摘要行。 + * + * @param line tsc 输出的一行。 + * @returns 文件路径,或 null(非报错行)。 + */ +export function extractErrorPath(line: string): string | null { + if (!TSC_ERROR_MARKER.test(line)) return null; + const match = line.match(TSC_ERROR_PATH_RE); + return match ? match[1].trim() : null; +} + +// ============================================================================ +// defaultRunTsc —— 默认 tsc 执行器(注入以便单测 mock) +// ============================================================================ + +/** + * 默认 tsc 执行器:同步 spawn `npx tsc `。 + * + * fail-tolerant:spawn 失败(npx 未安装、PATH 缺失等)时 exitCode=-1、 + * stderr 含 spawn 错误信息,由 {@link checkTypeDrift} 的 fail-closed 兜底。 + * + * @param args 传给 tsc 的参数(如 ["-p", "tsconfig.realpi.json", "--noEmit"])。 + * @returns tsc 执行结果。 + */ +export const defaultRunTsc: TscRunner = (args) => { + const res = spawnSync("npx", ["tsc", ...args], { encoding: "utf8" }); + const stderr = res.stderr ?? ""; + const spawnErr = res.error?.message ?? ""; + return { + exitCode: res.status ?? -1, + stdout: res.stdout ?? "", + stderr: stderr || spawnErr, + }; +}; + +// ============================================================================ +// checkTypeDrift —— 主入口 +// ============================================================================ + +/** + * 对真 pi 源码跑 tsc --noEmit,检测 src/types/pi.d.ts 镜像漂移。 + * + * 执行流程: + * 1. 构造 tsc 参数 `["-p", tsconfigPath, "--noEmit"]`(默认 tsconfig.realpi.json) + * 2. 调 `runTsc`(默认 `npx tsc`,可注入 mock) + * 3. 逐行解析 tsc 输出(stdout + stderr),按文件路径分类报错: + * - 匹配 `pbaSrcPattern`(默认 `^src/`)→ pbaErrors(真漂移) + * - 匹配 `packages/` → piInternalErrors(pi 自家,忽略) + * - 既非 src/ 亦非 packages/(如 scripts/)→ pbaErrors(fail-closed) + * + * fail-closed(安全不变式): + * - tsc 退出码非 0 但无可解析报错(如 npx 崩溃、tsconfig 不存在)→ + * 将原始 stderr 推入 pbaErrors,driftDetected=true + * (无法确认无漂移即视为有漂移,安全默认)。 + * + * 纯逻辑、runTsc 可注入、无 pi 运行时依赖、确定性可测。 + * + * @param opts.tsconfigPath tsconfig 路径(默认 "tsconfig.realpi.json")。 + * @param opts.runTsc tsc 执行器(默认 spawnSync npx tsc;单测注入 mock)。 + * @param opts.pbaSrcPattern pba 源码路径匹配正则(默认 `/^src\//`)。 + * @returns 漂移检测结果。 + */ +export function checkTypeDrift(opts: { + tsconfigPath?: string; + runTsc?: TscRunner; + pbaSrcPattern?: RegExp; +}): TypeDriftResult { + const tsconfigPath = opts.tsconfigPath ?? DEFAULT_TSCONFIG_PATH; + const pbaSrcPattern = opts.pbaSrcPattern ?? DEFAULT_PBA_SRC_PATTERN; + const runTsc = opts.runTsc ?? defaultRunTsc; + + const args = ["-p", tsconfigPath, "--noEmit"]; + const result = runTsc(args); + + // 合并 stdout + stderr(tsc 报错默认走 stdout,但启动失败走 stderr) + const output = [result.stdout, result.stderr].filter(Boolean).join("\n"); + const lines = output.split("\n"); + + const pbaErrors: string[] = []; + const piInternalErrors: string[] = []; + + for (const line of lines) { + const path = extractErrorPath(line); + if (path === null) continue; + + if (pbaSrcPattern.test(path)) { + pbaErrors.push(line); + } else if (PI_INTERNAL_PATTERN.test(path)) { + piInternalErrors.push(line); + } else { + // 既非 src/ 亦非 packages/(如 scripts/)—— fail-closed:视为 pba 漂移 + pbaErrors.push(line); + } + } + + // fail-closed:tsc 非零退出但无可解析报错 → 工具失败,无法确认无漂移 + if (result.exitCode !== 0 && pbaErrors.length === 0 && piInternalErrors.length === 0) { + const raw = result.stderr.trim() || result.stdout.trim() || "(no output)"; + pbaErrors.push(`tsc exited ${result.exitCode} with no parseable errors: ${raw}`); + } + + return { + driftDetected: pbaErrors.length > 0, + pbaErrors, + piInternalErrors, + }; +} diff --git a/src/capabilities/approval.ts b/src/capabilities/approval.ts new file mode 100644 index 0000000..0aca7d9 --- /dev/null +++ b/src/capabilities/approval.ts @@ -0,0 +1,184 @@ +/** + * @module approval + * + * 无人值守审批门 —— 物理字节 Agent 的风险动作裁决层。 + * + * 嵌入式开发场景里 agent 会发起高风险动作(烧录、dd、devmem 写寄存器)。 + * 无人值守(CI / 夜跑)时必须有 fail-closed 默认:无审批者即拒,绝不放行。 + * + * 三模式(ApprovalMode): + * - "auto-deny" —— 默认 fail-closed,所有请求直接拒(无人值守默认) + * - "auto-approve" —— 全部放行(仅受信任的隔离沙箱用,非默认) + * - "interactive" —— 委托注册的审批者;无审批者 → deny(fail-closed);超时 → deny + * + * 设计要点: + * - 纯逻辑 + 异步,零 pi 依赖,可离线单测。 + * - registerApprover 返回 disposer,可注销(session 结束清理);后注册者覆盖前者, + * disposer 只摘除自己(不误摘后来注册者)。 + * - 超时用 Promise.race,计时器在 finally 必 clear,防事件循环悬挂。 + * - 审批者抛错 → deny(fail-closed,绝不因审批者故障放行)。 + * - 未知 mode 一律按 auto-deny 处理(fail-closed 兜底)。 + * + * 见 src/extensions/safety-gate.ts 的 fail-closed 范式、src/core/sandbox-policy.ts + * 的 unusable→拒绝 范式。本模块是它们之上的"人类审批"裁决层。 + */ + +// ============================================================================ +// 命名常量 —— 消灭魔法串 +// ============================================================================ + +/** 默认审批模式:fail-closed 无人值守。 */ +export const DEFAULT_APPROVAL_MODE: ApprovalMode = "auto-deny"; +/** 默认超时(ms):interactive 模式无显式 timeoutMs 时的兜底。 */ +const DEFAULT_TIMEOUT_MS = 10_000; + +// ============================================================================ +// 类型契约 —— 下游依赖这些名字,不得改名 +// ============================================================================ + +/** 审批模式。 */ +export type ApprovalMode = "auto-deny" | "auto-approve" | "interactive"; + +/** 一次风险动作的审批请求。 */ +export interface ApprovalRequest { + /** 动作名(如 "flash" / "devmem-write")。 */ + action: string; + /** 风险等级。 */ + risk: "low" | "medium" | "high"; + /** 覆盖默认超时(ms);仅 interactive 模式生效。 */ + timeoutMs?: number; + /** 可选上下文(命令串 / 目标 / 原因)。 */ + context?: string; +} + +/** 审批裁决。 */ +export interface ApprovalResult { + /** 决定。 */ + decision: "approve" | "deny"; + /** 原因(诊断/审计用)。 */ + reason: string; + /** 裁决来源:auto=模式自动 / approver=注册审批者 / timeout=超时 fail-closed。 */ + by: "auto" | "approver" | "timeout"; +} + +/** 审批者签名:接收请求,返回裁决。 */ +export type ApproverFn = (req: ApprovalRequest) => Promise; + +// ============================================================================ +// ApprovalGate —— fail-closed 审批门 +// ============================================================================ + +/** + * 审批门。fail-closed 无人值守: + * - auto-deny → 直接 deny(by "auto") + * - auto-approve → approve(by "auto") + * - interactive → 调注册的 approver;无 approver → deny;approver 抛错 → deny;超时 → deny + * + * @example + * const gate = new ApprovalGate({ mode: "interactive" }); + * gate.registerApprover(async (req) => ({ decision: "approve", reason: "ok", by: "approver" })); + * const r = await gate.request({ action: "flash", risk: "high" }); + */ +export class ApprovalGate { + private mode: ApprovalMode; + private readonly timeoutMs: number | undefined; + private approver: ApproverFn | undefined; + + /** + * @param opts.mode 审批模式,默认 "auto-deny"(fail-closed)。 + * @param opts.timeoutMs interactive 模式默认超时;缺省用 DEFAULT_TIMEOUT_MS。 + */ + constructor(opts?: { mode?: ApprovalMode; timeoutMs?: number }) { + this.mode = opts?.mode ?? DEFAULT_APPROVAL_MODE; + this.timeoutMs = opts?.timeoutMs; + } + + /** 切换审批模式。 */ + setMode(m: ApprovalMode): void { + this.mode = m; + } + + /** + * 注册审批者。返回 disposer:调用即注销(仅摘除自己,不误摘后来注册者)。 + * + * @param fn 审批者函数。 + * @returns 注销函数。 + */ + registerApprover(fn: ApproverFn): () => void { + this.approver = fn; + return () => { + // 仅当仍是本 fn 时摘除,避免误摘后来注册者 + if (this.approver === fn) this.approver = undefined; + }; + } + + /** + * 请求审批。fail-closed 决策: + * - 非 auto-approve / 非 interactive(含 auto-deny 与未知)→ deny by "auto" + * - auto-approve → approve by "auto" + * - interactive + 无 approver → deny by "auto"(fail-closed) + * - interactive + approver:race 超时;approver 抛错 → deny;approver 正常 → 其裁决 + * + * 超时优先级:req.timeoutMs > 构造 timeoutMs > DEFAULT_TIMEOUT_MS。 + * + * @param req 审批请求。 + * @returns 审批裁决。 + */ + async request(req: ApprovalRequest): Promise { + // fail-closed 兜底:非 auto-approve / 非 interactive → deny(含 auto-deny 与未知) + if (this.mode !== "auto-approve" && this.mode !== "interactive") { + return { + decision: "deny", + reason: `mode "${this.mode}" → auto-deny`, + by: "auto", + } satisfies ApprovalResult; + } + if (this.mode === "auto-approve") { + return { + decision: "approve", + reason: "auto-approve mode", + by: "auto", + } satisfies ApprovalResult; + } + + // interactive + const approver = this.approver; + if (approver === undefined) { + return { + decision: "deny", + reason: "no approver registered (fail-closed)", + by: "auto", + } satisfies ApprovalResult; + } + + const timeoutMs = req.timeoutMs ?? this.timeoutMs ?? DEFAULT_TIMEOUT_MS; + let timer: ReturnType | undefined; + const timeoutP = new Promise((resolve) => { + timer = setTimeout( + () => + resolve({ + decision: "deny", + reason: `approval timed out after ${timeoutMs}ms`, + by: "timeout", + } satisfies ApprovalResult), + timeoutMs, + ); + }); + + try { + return await Promise.race([ + approver(req).catch( + (e: unknown): ApprovalResult => ({ + decision: "deny", + reason: `approver threw: ${String(e)}`, + by: "auto", + }), + ), + timeoutP, + ]); + } finally { + // 计时器务必 clear,防事件循环悬挂(即使 approver 先 resolve) + if (timer !== undefined) clearTimeout(timer); + } + } +} diff --git a/src/capabilities/board-link/index.ts b/src/capabilities/board-link/index.ts new file mode 100644 index 0000000..2709e03 --- /dev/null +++ b/src/capabilities/board-link/index.ts @@ -0,0 +1,170 @@ +/** + * @module capabilities/board-link + * + * 板链路能力接缝入口 —— Definition/Provider/Consumer 三角色之 Consumer 层。 + * + * BoardLinkRegistry:register provider(返回 disposer)→ resolve(board)(按 linkType + * 匹配 provider,fail-closed 无匹配抛错)→ list(只读快照)。 + * + * 验收不变式(见 tests/capability-seams.test.ts): + * ① register RDK_S100_SERIAL_PROVIDER 后 resolve(serial board) 无改动可用 + * ② register disposer 调用后 list 不见该 provider + * ③ resolve 无匹配 provider → 抛错(fail-closed) + * + * 纯逻辑,零 pi 运行时依赖。顶层仅 `import type`(esbuild 擦除)+ 同模块纯值导入, + * tests 直接 import 命名导出离线可测。 + * + * 见 Docs/T08_能力接缝三角色.md。 + */ + +import type { BoardSpec, BoardLinkType } from "../../shared/types.js"; +import type { BoardLinkProvider } from "./types.js"; + +// 三个 provider 是纯值(BoardLinkProvider 实例),不含 pi 运行时依赖,可值导入。 +import { RDK_X5_SSH_PROVIDER } from "./providers/rdk-x5-ssh.js"; +import { RDK_S100_SERIAL_PROVIDER } from "./providers/rdk-s100-serial.js"; +import { LOCAL_PROVIDER } from "./providers/local.js"; + +// 类型 + 共享健康检查 re-export(调用方一次性 import) +export type { + BoardLinkProvider, + BoardLinkHealthResult, + BoardSpec, + BoardLinkType, + ExecFn, + ExecResult, +} from "./types.js"; +export { defaultBoardHealthCheck } from "./types.js"; + +// provider 地址解析工具 re-export(调用方诊断/日志用) +export { + parseSshAddress, + buildSshArgs, + type SshTarget, +} from "./providers/rdk-x5-ssh.js"; +export { + parseSerialAddress, + SERIAL_STUB_RESULT, + type SerialTarget, +} from "./providers/rdk-s100-serial.js"; + +// ============================================================================ +// BoardLinkRegistry +// ============================================================================ + +/** + * 板链路 Provider 注册表。 + * + * - register(p): 按 p.id 存储,返回 disposer(调用后从注册表移除)。 + * disposer 只移除"仍是同一个 provider 实例"的条目——避免后注册的同 id provider + * 被前者的 disposer 误删(override 安全)。 + * - resolve(board): 按 board.linkType 匹配 provider,fail-closed 无匹配抛错。 + * - list(): 只读快照(调用方不可篡改内部状态)。 + * + * 与 BoardRegistry(板注册表)的区别:BoardRegistry 管理"板实例"(BoardSpec), + * 本注册表管理"链路 provider"(BoardLinkProvider)。一板一链路类型,一链路类型一 provider。 + */ +export class BoardLinkRegistry { + /** id → provider(插入序,Map 保证)。 */ + private readonly providers = new Map(); + + /** + * 注册一个 provider。id 唯一:重复 id 视为更新(替换),保证 barrel + * 重装配(测试多次装配 / session resume)幂等安全。返回 disposer。 + * + * @param provider 板链路 provider。 + * @returns disposer——调用后从注册表移除该 provider(仅当仍是同一实例时移除)。 + */ + register(provider: BoardLinkProvider): () => void { + this.providers.set(provider.id, provider); + return () => { + if (this.providers.get(provider.id) === provider) { + this.providers.delete(provider.id); + } + }; + } + + /** + * 按板规格解析 provider(按 linkType 匹配)。 + * + * fail-closed:无匹配 provider 抛错(绝不返回 undefined 让调用方裸调)。 + * 多个同 linkType provider 时取首个匹配(插入序)。 + * + * @param board 目标板规格。 + * @returns 匹配的 BoardLinkProvider。 + * @throws {Error} 无匹配 provider 时抛错。 + */ + resolve(board: BoardSpec): BoardLinkProvider { + for (const provider of this.providers.values()) { + if (provider.linkType === board.link) { + return provider; + } + } + throw new Error( + `board-link: no provider registered for link type "${board.link}" (board id="${board.id}")`, + ); + } + + /** + * 列出所有已注册 provider(只读快照)。 + * + * @returns 只读 provider 数组(按插入序)。 + */ + list(): readonly BoardLinkProvider[] { + return [...this.providers.values()]; + } +} + +// ============================================================================ +// 预置 provider 常量(调用方可直接 import 或 register 到自定义 registry) +// ============================================================================ + +export { RDK_X5_SSH_PROVIDER } from "./providers/rdk-x5-ssh.js"; +export { RDK_S100_SERIAL_PROVIDER } from "./providers/rdk-s100-serial.js"; +export { LOCAL_PROVIDER } from "./providers/local.js"; + +/** + * 递归深冻结对象/函数——冻结自身 + 所有自有属性值(递归)。 + * + * `Object.freeze([...])` 只冻结数组外壳,内部 provider 对象仍可被篡改 + * (`providers[0].id = "MUTATED"` 静默成功)。深冻结递归冻结每个 provider, + * 使 `.id = "MUTATED"` 在严格模式抛 TypeError(fail-closed 不变式)。 + * + * 与 flash/index.ts 的 deepFreeze 实现完全对称,保证 board-link 与 flash 两侧 + * 的不可变不变式行为一致。 + * + * 已冻结对象跳过(幂等安全),非对象/函数直透。 + * + * @param value 待冻结值。 + * @returns 冻结后的同一引用。 + */ +function deepFreeze(value: T): T { + if (value === null || value === undefined) return value; + if (typeof value !== "object" && typeof value !== "function") return value; + if (Object.isFrozen(value)) return value; + Object.freeze(value); + if (typeof value === "object") { + for (const key of Object.keys(value)) { + deepFreeze((value as Record)[key]); + } + } + return value; +} + +/** + * 全部预置 board-link provider(按 linkType 覆盖 ssh/serial/local)。 + * + * 消费方可用 `DEFAULT_BOARD_LINK_PROVIDERS.forEach(r => r.register(p))` 批量注册, + * 或按需挑选。解构后单独 register 亦可。 + * + * 深冻结,运行时不可变——数组外壳 + 每个 provider 对象均冻结, + * 篡改 provider 属性(如 `.id`)在严格模式抛 TypeError(fail-closed 不变式)。 + * 与 DEFAULT_FLASH_PROVIDERS 对称:flash 侧早已 deepFreeze 每个 provider, + * board-link 侧原先仅 Object.freeze([...]) 浅冻结数组外壳,provider 对象仍可被 + * 静默篡改(`RDK_X5_SSH_PROVIDER.id = "MUTATED"` 不报错),违反 fail-closed 不可变不变式。 + */ +export const DEFAULT_BOARD_LINK_PROVIDERS: readonly BoardLinkProvider[] = Object.freeze([ + deepFreeze(RDK_X5_SSH_PROVIDER), + deepFreeze(RDK_S100_SERIAL_PROVIDER), + deepFreeze(LOCAL_PROVIDER), +]); diff --git a/src/capabilities/board-link/providers/local.ts b/src/capabilities/board-link/providers/local.ts new file mode 100644 index 0000000..e571d99 --- /dev/null +++ b/src/capabilities/board-link/providers/local.ts @@ -0,0 +1,41 @@ +/** + * @module capabilities/board-link/providers/local + * + * 本地链路 Provider —— Definition/Provider/Consumer 三角色之 Provider。 + * + * 从 board-link.ts makeExec local 分支抽出:宿主即目标板,直透 underlying。 + * 纯逻辑,无 pi 运行时依赖。 + * + * 沙箱包装由消费方(扩展层)单独施加,本 provider 只负责 local 直透语义—— + * 单一职责,纯净可测。 + */ + +import type { ExecFn } from "../../../shared/types.js"; +import type { + BoardLinkProvider, + BoardLinkHealthResult, +} from "../types.js"; +import { defaultBoardHealthCheck } from "../types.js"; + +// ============================================================================ +// Provider 实例 +// ============================================================================ + +/** + * Local Provider。 + * + * createExec 产出直透 ExecFn:underlying(command, args, opts) —— 宿主即目标板。 + * healthCheck 委托 defaultBoardHealthCheck(在宿主跑 `true`,exit 0 = alive)。 + */ +export const LOCAL_PROVIDER: BoardLinkProvider = { + id: "local", + linkType: "local", + + createExec(_board, underlying: ExecFn): ExecFn { + return (command, args, opts) => underlying(command, args, opts); + }, + + async healthCheck(exec: ExecFn): Promise { + return defaultBoardHealthCheck(exec); + }, +}; diff --git a/src/capabilities/board-link/providers/rdk-s100-serial.ts b/src/capabilities/board-link/providers/rdk-s100-serial.ts new file mode 100644 index 0000000..fdcd6d1 --- /dev/null +++ b/src/capabilities/board-link/providers/rdk-s100-serial.ts @@ -0,0 +1,94 @@ +/** + * @module capabilities/board-link/providers/rdk-s100-serial + * + * RDK S100 串口链路 Provider —— Definition/Provider/Consumer 三角色之 Provider。 + * + * 从 board-link.ts makeExec serial 分支抽出:解析串口地址、返回 stub ExecFn。 + * 纯逻辑不能操作真实串口 fd,真实运行时由扩展层接 PTY / 子进程隔离层。 + * + * 沙箱包装由消费方(扩展层)单独施加,本 provider 只负责 serial stub 语义—— + * 单一职责,纯净可测。 + */ + +import type { ExecFn, ExecResult } from "../../../shared/types.js"; +import type { + BoardLinkProvider, + BoardLinkHealthResult, +} from "../types.js"; +import { defaultBoardHealthCheck } from "../types.js"; + +// ============================================================================ +// Serial 地址解析 +// ============================================================================ + +/** 串口地址解析结果。 */ +export interface SerialTarget { + /** 设备节点路径。 */ + dev: string; + /** 波特率。 */ + baudrate: number; +} + +/** 默认串口波特率。 */ +const DEFAULT_BAUDRATE = 115_200; + +/** + * 解析串口地址 /dev/ttyUSB0@115200 → { dev, baudrate }。 + * 无 @baudrate 后缀时默认 115200。 + * + * @param address 串口地址串。 + * @returns 解析出的 SerialTarget。 + */ +export function parseSerialAddress(address: string): SerialTarget { + const idx = address.lastIndexOf("@"); + if (idx >= 0) { + const baud = address.slice(idx + 1); + if (/^\d+$/.test(baud)) { + return { + dev: address.slice(0, idx), + baudrate: Number.parseInt(baud, 10), + }; + } + } + return { dev: address.trim(), baudrate: DEFAULT_BAUDRATE }; +} + +// ============================================================================ +// Serial stub 固定返回 +// ============================================================================ + +/** + * Serial stub 的固定返回。 + * + * 纯逻辑不能操作真实串口 fd,真实运行时由扩展层接 PTY / 子进程隔离层。 + */ +export const SERIAL_STUB_RESULT: ExecResult = { + stdout: + "[serial-stub] serial transport requires a real PTY; command not executed in pure-logic mode.\n", + stderr: "", + exitCode: 0, +}; + +// ============================================================================ +// Provider 实例 +// ============================================================================ + +/** + * RDK S100 Serial Provider。 + * + * createExec 产出 stub ExecFn:返回 SERIAL_STUB_RESULT(纯逻辑不能操作串口 fd)。 + * 真实运行时由扩展层接 PTY 替换此 stub。 + * healthCheck 委托 defaultBoardHealthCheck(stub 模式下 exitCode 0 = alive)。 + */ +export const RDK_S100_SERIAL_PROVIDER: BoardLinkProvider = { + id: "rdk-s100-serial", + linkType: "serial", + + createExec(_board, _underlying: ExecFn): ExecFn { + return async () => SERIAL_STUB_RESULT; + }, + + async healthCheck(exec: ExecFn): Promise { + return defaultBoardHealthCheck(exec); + }, +}; diff --git a/src/capabilities/board-link/providers/rdk-x5-ssh.ts b/src/capabilities/board-link/providers/rdk-x5-ssh.ts new file mode 100644 index 0000000..6a9fde9 --- /dev/null +++ b/src/capabilities/board-link/providers/rdk-x5-ssh.ts @@ -0,0 +1,131 @@ +/** + * @module capabilities/board-link/providers/rdk-x5-ssh + * + * RDK X5 SSH 链路 Provider —— Definition/Provider/Consumer 三角色之 Provider。 + * + * 从 board-link.ts makeExec ssh 分支抽出:解析 SSH 地址、拼接 ssh argv、 + * 委托 underlying("ssh", sshArgs, opts) 执行。纯逻辑,无 pi 运行时依赖。 + * + * 沙箱包装由消费方(扩展层)单独施加,本 provider 只负责 ssh 命令拼接—— + * 单一职责,纯净可测(createExec 无 env-var 全局状态依赖)。 + */ + +import type { BoardSpec, ExecFn } from "../../../shared/types.js"; +import type { + BoardLinkProvider, + BoardLinkHealthResult, +} from "../types.js"; +import { defaultBoardHealthCheck } from "../types.js"; + +// ============================================================================ +// SSH 地址解析 +// ============================================================================ + +/** SSH 地址解析结果。 */ +export interface SshTarget { + /** 登录用户名。 */ + user: string; + /** 主机名或 IP。 */ + host: string; + /** 端口。 */ + port: number; +} + +/** + * 解析 SSH 地址串。 + * + * - "root@192.168.1.100:2222" → { user:"root", host:"192.168.1.100", port:2222 } + * - "root@board" → { user:"root", host:"board", port:22 }(默认 22) + * - "board" → { user:"root"(默认), host:"board", port:22 } + * - "[::1]:2222" → IPv6 带端口 + * + * fail-tolerant:解析不出端口的默认 22,解析不出 user 的默认 root。 + * + * @param address SSH 地址串。 + * @returns 解析出的 SshTarget。 + */ +export function parseSshAddress(address: string): SshTarget { + let rest = address.trim(); + let user = "root"; + const atIdx = rest.indexOf("@"); + if (atIdx >= 0) { + user = rest.slice(0, atIdx); + rest = rest.slice(atIdx + 1); + } + let port = 22; + let host = rest; + // IPv6 [::1]:port 或普通 host:port + const lastColon = rest.lastIndexOf(":"); + if (lastColon >= 0) { + const after = rest.slice(lastColon + 1); + if (/^\d+$/.test(after)) { + port = Number.parseInt(after, 10); + host = rest.slice(0, lastColon); + } + } + // 去除 IPv6 方括号 + host = host.replace(/^\[/, "").replace(/\]$/, ""); + return { user, host, port }; +} + +// ============================================================================ +// SSH 命令拼接 +// ============================================================================ + +/** 默认 SSH 端口(不加 -p 参数,减少噪声)。 */ +const DEFAULT_SSH_PORT = 22; + +/** + * 构造 ssh 调用的参数数组(喂给 spawn("ssh", args))。 + * + * 例:board.address="root@192.168.1.100:2222", command="ls", args=["-la"] + * → ["-p", "2222", "root@192.168.1.100", "ls", "-la"] + * + * 默认端口 22 不加 -p(与 ssh 默认行为一致,减少参数噪声)。 + * + * @param board 目标板规格(取 .address 解析)。 + * @param command 要在板上执行的命令。 + * @param args 命令参数。 + * @returns ssh argv 数组。 + */ +export function buildSshArgs( + board: BoardSpec, + command: string, + args: string[], +): string[] { + const { user, host, port } = parseSshAddress(board.address); + const sshArgs: string[] = []; + if (port !== DEFAULT_SSH_PORT) { + sshArgs.push("-p", String(port)); + } + sshArgs.push(`${user}@${host}`); + sshArgs.push(command); + sshArgs.push(...args); + return sshArgs; +} + +// ============================================================================ +// Provider 实例 +// ============================================================================ + +/** + * RDK X5 SSH Provider。 + * + * createExec 产出 ExecFn:调 underlying("ssh", buildSshArgs(board, command, args), opts)。 + * healthCheck 委托 defaultBoardHealthCheck(在板上跑 `true`,exit 0 = alive)。 + */ +export const RDK_X5_SSH_PROVIDER: BoardLinkProvider = { + id: "rdk-x5-ssh", + linkType: "ssh", + + createExec(board: BoardSpec, underlying: ExecFn): ExecFn { + return (command, args, opts) => { + const sshArgs = buildSshArgs(board, command, args); + return underlying("ssh", sshArgs, opts); + }; + }, + + async healthCheck(exec: ExecFn): Promise { + return defaultBoardHealthCheck(exec); + }, +}; diff --git a/src/capabilities/board-link/types.ts b/src/capabilities/board-link/types.ts new file mode 100644 index 0000000..5fff9cf --- /dev/null +++ b/src/capabilities/board-link/types.ts @@ -0,0 +1,124 @@ +/** + * @module capabilities/board-link/types + * + * 板链路能力接缝 —— Definition/Provider/Consumer 三角色之 Definition 层。 + * + * 治原 board-link.ts makeExec 三分支(ssh / serial-stub / local)硬编码在单文件、 + * 新增链路类型需改主文件的缺陷。抽成 BoardLinkProvider 接口 + Registry, + * 每种链路一个 provider 文件,新增链路只 register 不改主逻辑(开闭原则)。 + * + * 三角色: + * - Definition —— 本文件:BoardLinkProvider 接口 + BoardLinkHealthResult 类型 + * - Provider —— providers/*.ts:ssh / serial / local 三实现(BoardLinkProvider 实例) + * - Consumer —— index.ts:BoardLinkRegistry(register/resolve/list,fail-closed resolve) + * + * 纯逻辑,零 pi 运行时依赖。顶层仅 `import type`(esbuild 擦除),tests 直接 import + * 命名导出离线可测,无 pi 运行时、无真实硬件。 + * + * 与原 board-link.ts 的关系:原 makeExec 把"链路类型命令包装"与"板侧沙箱包装"耦合在一起。 + * 本接缝层只负责链路类型命令包装(ssh 拼 args / serial stub / local 直透), + * 沙箱包装是正交安全关注点,由消费方(扩展层)用 core/sandbox-policy 单独施加。 + * 这使 provider 纯净可测——createExec 无 env-var 全局状态依赖。 + * + * 见 Docs/T08_能力接缝三角色.md。 + */ + +import type { + BoardSpec, + BoardLinkType, + ExecFn, + ExecResult, +} from "../../shared/types.js"; + +// 便于调用方一次性 import;类型本身定义在 shared/types.ts +export type { BoardSpec, BoardLinkType, ExecFn, ExecResult }; + +// ============================================================================ +// 常量 —— 消灭魔法串 +// ============================================================================ + +/** 健康探活默认命令(exit 0 = alive)。 */ +const DEFAULT_PROBE_COMMAND = "true"; + +/** 健康探活默认超时(毫秒)。 */ +const DEFAULT_HEALTH_TIMEOUT = 10_000; + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** 健康检查结果。 */ +export interface BoardLinkHealthResult { + /** 板是否在线。 */ + ok: boolean; + /** 离线/异常原因(诊断用)。 */ + reason?: string; +} + +/** + * 板链路 Provider —— Definition/Provider/Consumer 三角色之 Provider。 + * + * 每个 provider 封装一种链路类型(ssh / serial / local)的命令包装逻辑。 + * createExec 给定板规格 + 底层 exec,产出在该板执行命令的 ExecFn。 + * 新增链路类型只需新建一个 provider 文件并 register,不改已有逻辑(开闭原则)。 + */ +export interface BoardLinkProvider { + /** provider 唯一标识(如 "rdk-x5-ssh")。 */ + readonly id: string; + /** 该 provider 服务的链路类型。 */ + readonly linkType: BoardLinkType; + /** + * 给定板规格 + 底层 exec,产出在该板执行命令的 ExecFn。 + * + * ssh: 调 underlying("ssh", buildSshArgs(board, command, args), opts) + * serial: 返回 stub(纯逻辑不能操作串口 fd,真实运行时由扩展层接 PTY) + * local: 直透 underlying(command, args, opts) —— 宿主即目标板 + * + * @param board 目标板规格。 + * @param underlying 底层执行函数(宿主 spawn)。 + * @returns 该板专用的 ExecFn。 + */ + createExec(board: BoardSpec, underlying: ExecFn): ExecFn; + /** + * 健康探活(可选)。在板上跑探活命令,exit 0 = alive。 + * fail-closed:exec 抛异常或非 0 exit → false(板离线/不可达)。 + * + * @param exec 该板的 ExecFn(由 createExec 产出)。 + * @returns 健康检查结果。 + */ + healthCheck?(exec: ExecFn): Promise; +} + +// ============================================================================ +// 共享健康检查 —— 三 provider 共用,注入 exec 即可 +// ============================================================================ + +/** + * 默认健康检查:在板上跑探活命令(默认 `true`),exit 0 = alive。 + * + * fail-closed:exec 抛异常或非 0 exit → { ok:false }(板离线/不可达)。 + * 三 provider 共用此实现,注入各自的 exec 即可。 + * + * @param exec 该板的 ExecFn(由 createExec 产出)。 + * @param probeCommand 自定义探活命令(默认 "true")。 + * @param timeout 超时毫秒(默认 10000)。 + * @returns 健康检查结果。 + */ +export async function defaultBoardHealthCheck( + exec: ExecFn, + probeCommand: string = DEFAULT_PROBE_COMMAND, + timeout: number = DEFAULT_HEALTH_TIMEOUT, +): Promise { + try { + const result = await exec(probeCommand, [], { timeout }); + if (result.exitCode === 0) { + return { ok: true }; + } + return { + ok: false, + reason: `probe exit ${result.exitCode}: ${result.stderr.trim() || "(no stderr)"}`, + }; + } catch (e) { + return { ok: false, reason: `probe threw: ${String(e)}` }; + } +} diff --git a/src/capabilities/credentials.ts b/src/capabilities/credentials.ts new file mode 100644 index 0000000..912fc0e --- /dev/null +++ b/src/capabilities/credentials.ts @@ -0,0 +1,139 @@ +/** + * @module credentials + * + * 凭据 store —— 密钥永不明文 echo。 + * + * 治嵌入式 Agent 场景:LLM 网关 key(${DROBOTICS_LLM_KEY} 占位)、板侧 SSH 密码、 + * 烧录证书等。凭据只进进程内存,绝不落盘、绝不写进 git-tracked 文件、绝不在日志/ + * stdout 明文 echo。redact() 是日志脱敏兜底:任何形似 sk-xxx / 长不透明 token 的串 + * 一律替换成 。 + * + * 设计要点: + * - get:先查内存,后回退 process.env[name](只读 env,不写 env)。 + * - set:仅写内存 Map,不落盘、不写 env、不持久化。 + * - redact:纯正则脱敏,命名常量模式(非魔法正则),无副作用。 + * - 纯逻辑,零 pi 依赖,可离线单测。 + * + * 密钥铁律:gateway key 一律用 ${DROBOTICS_LLM_KEY} 占位,绝不出现 sk- 开头明文, + * 绝不写进 git-tracked 文件(见 glm-provider.ts:83 的占位范式)。 + */ + +// ============================================================================ +// 命名常量 —— 消灭魔法串 / 魔法正则 +// ============================================================================ + +/** redact 替换占位。导出供调用方 / 测试引用,杜绝散落魔法串。 */ +export const REDACTED_PLACEHOLDER = "" as const; + +/** + * 已知凭据前缀(OpenAI / GitHub / Slack / GitLab PAT 等)。匹配这些前缀 + 8 位以上 + * 字符即视为密钥。前缀均无正则特殊字符,故不需 escape。 + */ +const SECRET_PREFIXES = [ + "sk-", + "ghp_", + "gho_", + "ghs_", + "ghr_", + "ghu_", + "github_pat_", + "xoxb-", + "xoxp-", + "glpat-", +] as const; + +/** 长不透明 token 门槛:连续 40+ 位 [A-Za-z0-9_-] 视为 token(SHA-256=64、JWT 段等)。 */ +const LONG_TOKEN_MIN = 40; + +/** + * 凭据识别正则(全局):前缀密钥 或 长不透明 token。 + * + * 两支: + * ① (?:prefix)[A-Za-z0-9_-]{8,} —— 已知前缀 + 8 位以上 + * ② [A-Za-z0-9_-]{40,} —— 40+ 连续字符(通用长 token) + * + * 线性量词无嵌套回溯,无 catastrophic backtracking 风险。 + */ +const SECRET_PATTERN: RegExp = new RegExp( + `(?:${SECRET_PREFIXES.join("|")})[A-Za-z0-9_-]{8,}|[A-Za-z0-9_-]{${LONG_TOKEN_MIN},}`, + "g", +); + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** 凭据环境读取函数签名(注入以便单测,避免直接耦合 process.env)。 */ +export type EnvLookup = (name: string) => string | undefined; + +// ============================================================================ +// CredentialsStore —— 凭据 store +// ============================================================================ + +/** + * 凭据 store。key 永不明文 echo。 + * + * - get:先内存后 env(默认 process.env,可注入 envLookup 以便单测)。 + * - set:仅内存,不落盘、不写 env。 + * - redact:日志脱敏兜底,把形似 sk-xxx / 长 token 的串替换成 {@link REDACTED_PLACEHOLDER}。 + * + * @example + * const store = new CredentialsStore(); + * store.set("DROBOTICS_LLM_KEY", process.env.DROBOTICS_LLM_KEY!); + * store.redact("Authorization: Bearer sk-abcdef0123456789"); // → "Authorization: Bearer " + */ +export class CredentialsStore { + private readonly memory = new Map(); + private readonly envLookup: EnvLookup; + + /** + * @param envLookup env 读取函数,默认读 process.env。注入以便单测隔离。 + */ + constructor(envLookup: EnvLookup = (name) => process.env[name]) { + this.envLookup = envLookup; + } + + /** + * 取凭据。先内存后 env;均无返回 undefined。 + * + * @param name 凭据名。 + * @returns 凭据值或 undefined。 + */ + get(name: string): string | undefined { + const mem = this.memory.get(name); + if (mem !== undefined) return mem; + return this.envLookup(name); + } + + /** + * 存凭据。仅写内存,不落盘、不写 env。 + * + * @param name 凭据名。 + * @param value 凭据值。 + */ + set(name: string, value: string): void { + this.memory.set(name, value); + } + + /** + * 凭据是否存在(内存或 env)。 + * + * @param name 凭据名。 + * @returns true=存在。 + */ + has(name: string): boolean { + return this.get(name) !== undefined; + } + + /** + * 脱敏:把串里形似密钥 / 长 token 的子串替换成 {@link REDACTED_PLACEHOLDER}。 + * 用于日志 / 审计串的兜底过滤,保证 key 永不明文 echo。 + * + * @param s 待脱敏串。 + * @returns 脱敏后串(密钥子串被 替换)。 + */ + redact(s: string): string { + if (!s) return s; + return s.replace(SECRET_PATTERN, REDACTED_PLACEHOLDER); + } +} diff --git a/src/capabilities/flash/index.ts b/src/capabilities/flash/index.ts new file mode 100644 index 0000000..f3edcb4 --- /dev/null +++ b/src/capabilities/flash/index.ts @@ -0,0 +1,167 @@ +/** + * @module capabilities/flash + * + * 安全烧录能力接缝入口 —— Definition/Provider/Consumer 三角色之 Consumer 层。 + * + * FlashRegistry:register provider(返回 disposer)→ resolve(method)(按 id 匹配 + * provider,fail-closed 无匹配抛错)→ list(只读快照)。 + * + * 验收不变式(见 tests/capability-seams.test.ts): + * ① register DD_PROVIDER 后 resolve("dd") 无改动可用 + * ② register disposer 调用后 list 不见该 provider + * ③ resolve 无匹配 method → 抛错(fail-closed) + * + * 纯逻辑,零 pi 运行时依赖。顶层仅 `import type`(esbuild 擦除)+ 同模块纯值导入, + * tests 直接 import 命名导出离线可测。 + * + * 见 Docs/T08_能力接缝三角色.md + Docs/F13_安全烧录工具.md。 + */ + +import type { FlashMethod } from "../../shared/types.js"; +import type { FlashProvider } from "./types.js"; + +// 四个 provider 是纯值(FlashProvider 实例),不含 pi 运行时依赖,可值导入。 +import { DD_PROVIDER } from "./providers/dd.js"; +import { FASTBOOT_PROVIDER } from "./providers/fastboot.js"; +import { DFU_PROVIDER } from "./providers/dfu.js"; +import { OPENOCD_PROVIDER } from "./providers/openocd.js"; + +// 类型 + 共享纯函数 re-export(调用方一次性 import) +export type { + FlashProvider, + FlashPlanEx, + FlashPlanOptions, + DryRunResult, + VerifyResult, + RunFlashResult, + LsblkRow, + FlashMethod, + FlashPlan, + ExecFn, +} from "./types.js"; +export { + DD_BLOCK_SIZE, + ROOT_MOUNTPOINTS, + parseOffset, + parseLsblk, + isRootDiskTarget, + targetExistsInRows, + matchesDeviceName, + deviceBasename, + splitCommand, + orchestrateRun, + probeDryRun, + exitCodeVerify, +} from "./types.js"; + +// ============================================================================ +// FlashRegistry +// ============================================================================ + +/** + * 烧录 Provider 注册表。 + * + * - register(p): 按 p.id(= FlashMethod)存储,返回 disposer。 + * disposer 只移除"仍是同一 provider 实例"的条目——override 安全。 + * - resolve(method): 按 FlashMethod 匹配 provider,fail-closed 无匹配抛错。 + * - list(): 只读快照。 + * + * 与 FlashProvider 的关系:一 FlashMethod 一 provider。 + * 新增烧录方法只需新建 provider 文件并 register,不改已有逻辑(开闭原则)。 + */ +export class FlashRegistry { + /** FlashMethod → provider(插入序,Map 保证)。 */ + private readonly providers = new Map(); + + /** + * 注册一个 provider。id(= FlashMethod)唯一:重复视为更新(替换), + * 保证 barrel 重装配幂等安全。返回 disposer。 + * + * @param provider 烧录 provider。 + * @returns disposer——调用后从注册表移除该 provider(仅当仍是同一实例时移除)。 + */ + register(provider: FlashProvider): () => void { + this.providers.set(provider.id, provider); + return () => { + if (this.providers.get(provider.id) === provider) { + this.providers.delete(provider.id); + } + }; + } + + /** + * 按烧录方法解析 provider(按 FlashMethod 匹配)。 + * + * fail-closed:无匹配 provider 抛错(绝不返回 undefined 让调用方裸调)。 + * + * @param method 烧录方法。 + * @returns 匹配的 FlashProvider。 + * @throws {Error} 无匹配 provider 时抛错。 + */ + resolve(method: FlashMethod): FlashProvider { + const provider = this.providers.get(method); + if (!provider) { + throw new Error( + `flash: no provider registered for method "${method}"`, + ); + } + return provider; + } + + /** + * 列出所有已注册 provider(只读快照)。 + * + * @returns 只读 provider 数组(按插入序)。 + */ + list(): readonly FlashProvider[] { + return [...this.providers.values()]; + } +} + +// ============================================================================ +// 预置 provider 常量(调用方可直接 import 或 register 到自定义 registry) +// ============================================================================ + +export { DD_PROVIDER } from "./providers/dd.js"; +export { FASTBOOT_PROVIDER } from "./providers/fastboot.js"; +export { DFU_PROVIDER } from "./providers/dfu.js"; +export { OPENOCD_PROVIDER } from "./providers/openocd.js"; + +/** + * 递归深冻结对象/函数——冻结自身 + 所有自有属性值(递归)。 + * + * `Object.freeze([...])` 只冻结数组外壳,内部 provider 对象仍可被篡改 + * (`providers[0].id = "MUTATED"` 静默成功)。深冻结递归冻结每个 provider, + * 使 `.id = "MUTATED"` 在严格模式抛 TypeError(fail-closed 不变式)。 + * + * 已冻结对象跳过(幂等安全),非对象/函数直透。 + * + * @param value 待冻结值。 + * @returns 冻结后的同一引用。 + */ +function deepFreeze(value: T): T { + if (value === null || value === undefined) return value; + if (typeof value !== "object" && typeof value !== "function") return value; + if (Object.isFrozen(value)) return value; + Object.freeze(value); + if (typeof value === "object") { + for (const key of Object.keys(value)) { + deepFreeze((value as Record)[key]); + } + } + return value; +} + +/** + * 全部预置 flash provider(覆盖 dd/fastboot/dfu/openocd 四种方法)。 + * + * 消费方可用 `DEFAULT_FLASH_PROVIDERS.forEach(p => registry.register(p))` 批量注册, + * 或按需挑选。深冻结,运行时不可变——数组外壳 + 每个 provider 对象均冻结, + * 篡改 provider 属性(如 `.id`)在严格模式抛 TypeError。 + */ +export const DEFAULT_FLASH_PROVIDERS: readonly FlashProvider[] = Object.freeze([ + deepFreeze(DD_PROVIDER), + deepFreeze(FASTBOOT_PROVIDER), + deepFreeze(DFU_PROVIDER), + deepFreeze(OPENOCD_PROVIDER), +]); diff --git a/src/capabilities/flash/providers/dd.ts b/src/capabilities/flash/providers/dd.ts new file mode 100644 index 0000000..9e2fd90 --- /dev/null +++ b/src/capabilities/flash/providers/dd.ts @@ -0,0 +1,435 @@ +/** + * @module capabilities/flash/providers/dd + * + * dd 烧录 Provider —— Definition/Provider/Consumer 三角色之 Provider。 + * + * 从 flash.ts planFlash/dryRun/verifyFlash 的 dd 分支抽出: + * - plan(): `dd if= of= bs=4M conv=fsync [seek=]` + * - run(): dryRun(lsblk 根盘校验 + stat 镜像大小 + sha256 预计算 + 只读探针) + * → 写 → verify(读回 sha256 比对) + * - verify(): 读回 `dd if= bs=4M count=`,sha256 比对 + * + * fail-closed:target 不存在 / 是根盘 / offset+镜像越界 / 无 expectedSha256 → 拒绝。 + * 纯逻辑,ExecFn 注入,node:crypto 算 sha256,无真实硬件依赖。 + */ + +import { createHash } from "node:crypto"; +import type { ExecFn } from "../../../shared/types.js"; +import type { + FlashProvider, + FlashPlanEx, + FlashPlanOptions, + DryRunResult, + VerifyResult, + RunFlashResult, + LsblkRow, +} from "../types.js"; +import { + DD_BLOCK_SIZE, + parseOffset, + parseLsblk, + isRootDiskTarget, + targetExistsInRows, + matchesDeviceName, + deviceBasename, + ROOT_MOUNTPOINTS, + orchestrateRun, +} from "../types.js"; + +// ============================================================================ +// plan — 构建 dd 命令序列 +// ============================================================================ + +/** + * 构建 dd 烧录计划。 + * + * 命令:`dd if= of= bs=4M conv=fsync [seek=]` + * offset > 0 时 seek= 以 bs 为单位(字节偏移 → 块数)。 + * + * 注意:seek 用 Math.floor(offset / DD_BLOCK_SIZE) 将字节偏移转块数,非块对齐的 + * offset 会被截断(如 offset=16 → seek=0 → dd 从字节 0 写)。dryRun 会 fail-closed + * 拒绝非 DD_BLOCK_SIZE 整数倍的 offset,plan() 本身不做此校验(纯构建,校验归 dryRun)。 + * + * 若 ctx.lsblk 提供,做早期 fail-closed 根盘检查(target 不存在 / 是根盘 → 抛错)。 + * + * @param opts 烧录参数。 + * @param ctx 可选 lsblk 行数组(早期根盘校验)。 + * @returns FlashPlanEx。 + * @throws {Error} image/target 为空 / offset 不可解析 / target 是根盘。 + */ +function ddPlan(opts: FlashPlanOptions, ctx?: { lsblk?: LsblkRow[] }): FlashPlanEx { + if (!opts.image || opts.image.trim() === "") { + throw new Error("flash dd: image path required"); + } + if (!opts.target || opts.target.trim() === "") { + throw new Error("flash dd: target required"); + } + + const parsed = parseOffset(opts.offset); + if (parsed === null) { + throw new Error( + `flash dd: invalid offset "${opts.offset}" (expect decimal or 0x hex)`, + ); + } + + const parts = [ + "dd", + `if=${opts.image}`, + `of=${opts.target}`, + "bs=4M", + "conv=fsync", + ]; + if (parsed > 0) { + parts.push(`seek=${Math.floor(parsed / DD_BLOCK_SIZE)}`); + } + + const plan: FlashPlanEx = { + method: "dd", + commands: [parts.join(" ")], + target: opts.target, + image: opts.image, + offsetBytes: parsed, + dryRun: opts.dryRun, + verify: opts.verify, + }; + + // 早期 fail-closed 根盘校验(lsblk 行已提供时) + if (ctx?.lsblk && ctx.lsblk.length > 0) { + if (!targetExistsInRows(opts.target, ctx.lsblk)) { + throw new Error(`flash dd: target ${opts.target} not found in lsblk`); + } + if (isRootDiskTarget(opts.target, ctx.lsblk)) { + throw new Error( + `flash dd: target ${opts.target} is a mounted root disk — refusing`, + ); + } + } + + return plan; +} + +// ============================================================================ +// dryRun — lsblk 根盘校验 + stat 镜像大小 + sha256 预计算 + 只读探针 +// ============================================================================ + +/** + * dd dry-run:不写真写,只校验可烧条件。 + * + * 1. lsblk 确认 target 存在 + 非根盘 + * 2. stat 取镜像大小 + * 3. offset 越界校验(三段 fail-closed): + * a. offset >= 目标设备容量 → 拒绝(offset 单独越界) + * b. offset 非块对齐 → 拒绝(dd seek 截断) + * c. offset + imageSize > 目标设备容量 → 拒绝(镜像写过设备末尾) + * 4. sha256sum 预计算 + * 5. 只读验证镜像可读:dd if=image of=/dev/null bs=4M count=1 + * + * fail-closed:任一步失败 → ok:false。 + * + * @param plan 烧录计划。 + * @param exec 注入的执行函数。 + * @returns DryRunResult。 + */ +async function ddDryRun( + plan: FlashPlanEx, + exec: ExecFn, +): Promise { + const probeCommands: string[] = []; + + // 1. lsblk 确认 target 存在 + 非根盘 + const lsblkCmd = "lsblk"; + const lsblkArgs = ["-b", "-o", "NAME,SIZE,TYPE,MOUNTPOINT"]; + probeCommands.push(`${lsblkCmd} ${lsblkArgs.join(" ")}`); + const lsblkRes = await exec(lsblkCmd, lsblkArgs); + if (lsblkRes.exitCode !== 0) { + return { + ok: false, + reason: `lsblk failed: ${lsblkRes.stderr.trim() || `exit ${lsblkRes.exitCode}`}`, + plan, + targetExists: false, + isRootDisk: false, + probeCommands, + }; + } + const rows = parseLsblk(lsblkRes.stdout); + if (!targetExistsInRows(plan.target, rows)) { + return { + ok: false, + reason: `target ${plan.target} not found in lsblk`, + plan, + targetExists: false, + isRootDisk: false, + probeCommands, + }; + } + const base = deviceBasename(plan.target); + if (isRootDiskTarget(plan.target, rows)) { + const rootMounts = rows + .filter( + (r) => + matchesDeviceName(base, r.name) && + r.mountpoint && + ROOT_MOUNTPOINTS.has(r.mountpoint), + ) + .map((r) => `${r.name}:${r.mountpoint}`); + return { + ok: false, + reason: `target ${plan.target} has mounted ${rootMounts.join(", ")} — refusing`, + plan, + targetExists: true, + isRootDisk: true, + probeCommands, + }; + } + + // 2. stat 取镜像大小 + const statCmd = "stat"; + const statArgs = ["-c", "%s", plan.image]; + probeCommands.push(`${statCmd} ${statArgs.join(" ")}`); + const statRes = await exec(statCmd, statArgs); + if (statRes.exitCode !== 0) { + return { + ok: false, + reason: `stat image failed: ${statRes.stderr.trim() || `exit ${statRes.exitCode}`}`, + plan, + targetExists: true, + isRootDisk: false, + probeCommands, + }; + } + const imageSize = Number.parseInt(statRes.stdout.trim(), 10); + if (!Number.isFinite(imageSize) || imageSize <= 0) { + return { + ok: false, + reason: `invalid image size: "${statRes.stdout.trim()}"`, + plan, + targetExists: true, + isRootDisk: false, + probeCommands, + }; + } + plan.imageSizeBytes = imageSize; + plan.blockCount = Math.max(1, Math.ceil(imageSize / DD_BLOCK_SIZE)); + + // 3. offset 越界校验 + // 修正:旧逻辑把 target seek offset 与 source image size 比较(offset >= imageSize), + // 拒绝了合法的分区偏移烧录(如 4MB 镜像烧到 8MB 偏移分区)。 + // 正确语义:offset 不得超过目标设备容量(从 lsblk 行取 target 大小)。 + // 未知设备大小时回退到 offset >= imageSize 保守边界(fail-closed)。 + const targetRow = rows.find((r) => r.name === base); + const targetDeviceSize = targetRow?.size ?? 0; + if (plan.offsetBytes !== undefined) { + if (targetDeviceSize > 0) { + // 已知目标设备大小:offset 不得超过设备容量 + if (plan.offsetBytes >= targetDeviceSize) { + // 修正:实际比较的是 offset >= targetDeviceSize(设备容量),而非 image size。 + // 原消息 "offset X >= image size Y" 误导操作员去查镜像大小而非设备容量。 + // 现以 "exceeds target device size" 为主诊断,附带 image size 上下文—— + // offset 也 >= image size 时标注 ">= image size",否则标注 "< image size", + // 使操作员聚焦设备容量(真正越界的维度)。 + const exceedsImageToo = plan.offsetBytes >= imageSize; + return { + ok: false, + reason: `offset ${plan.offsetBytes} exceeds target device size ${targetDeviceSize} (offset ${exceedsImageToo ? ">= image size" : "< image size"} ${imageSize})`, + plan, + targetExists: true, + isRootDisk: false, + probeCommands, + }; + } + } else { + // 未知设备大小:回退到 offset 不超过镜像大小(保守边界) + if (plan.offsetBytes >= imageSize) { + return { + ok: false, + reason: `offset ${plan.offsetBytes} >= image size ${imageSize}`, + plan, + targetExists: true, + isRootDisk: false, + probeCommands, + }; + } + } + // 修正(非对齐 offset 静默截断):plan() 用 Math.floor(offset / DD_BLOCK_SIZE) + // 将字节偏移转成 dd seek= 块数。非块对齐的 offset 被静默截断——如 offset=16 + // → seek=0 → dd 从字节 0 开始写,而非字节 16,造成静默数据错位(可能损坏分区表)。 + // dryRun 的 offset 越界校验用字节语义(offset vs targetDeviceSize),但实际 seek + // 用块语义,形成 validation/execution mismatch。此处 fail-closed 拒绝非对齐 offset, + // 要求 offset 为 DD_BLOCK_SIZE (bs=4M) 的整数倍。 + if (plan.offsetBytes > 0 && plan.offsetBytes % DD_BLOCK_SIZE !== 0) { + return { + ok: false, + reason: `offset ${plan.offsetBytes} is not a multiple of block size ${DD_BLOCK_SIZE} (dd seek truncates non-aligned byte offsets; use a multiple of bs=4M)`, + plan, + targetExists: true, + isRootDisk: false, + probeCommands, + }; + } + // 修正(offset + imageSize 越界):模块 doc(types.ts:24)承诺 "offset + 镜像大小 + // 越过目标设备容量 → 拒绝"。上方旧检查只查 offset >= targetDeviceSize(offset 单独 + // 越界),漏掉 offset < targetDeviceSize 但 offset + imageSize > targetDeviceSize 的 + // 情形——如 8GB 设备 / 5GB 镜像 / 6GB 偏移(4MiB 对齐):6GB < 8GB 通过旧检查, + // 但 6GB + 5GB = 11GB > 8GB,dd 写过设备末尾,静默截断镜像数据,违反 fail-closed + // 安全不变式。此处补全:offset + imageSize 越过设备容量即拒绝。 + // guard offset > 0:offset=0 时 "0 + imageSize > deviceSize" 属 "镜像本身大于设备" + // 的独立语义,不在此 offset 越界检查中重复(避免误伤 imageSize > deviceSize 的 + // 合法 mock 场景);本检查聚焦 offset 促发的越界。 + // guard targetDeviceSize > 0:未知设备大小走上方 else 分支的保守边界,不重复。 + if ( + plan.offsetBytes > 0 && + targetDeviceSize > 0 && + plan.offsetBytes + imageSize > targetDeviceSize + ) { + return { + ok: false, + reason: `offset ${plan.offsetBytes} + image size ${imageSize} (${plan.offsetBytes + imageSize}) exceeds target device size ${targetDeviceSize}`, + plan, + targetExists: true, + isRootDisk: false, + probeCommands, + }; + } + } + + // 4. sha256sum 预计算 + const shaCmd = "sha256sum"; + const shaArgs = [plan.image]; + probeCommands.push(`${shaCmd} ${shaArgs.join(" ")}`); + const shaRes = await exec(shaCmd, shaArgs); + if (shaRes.exitCode !== 0) { + return { + ok: false, + reason: `sha256sum failed: ${shaRes.stderr.trim() || `exit ${shaRes.exitCode}`}`, + plan, + targetExists: true, + isRootDisk: false, + probeCommands, + }; + } + const hash = shaRes.stdout.trim().split(/\s+/)[0] ?? ""; + if (!/^[0-9a-f]{64}$/i.test(hash)) { + return { + ok: false, + reason: `unparsable sha256sum output: "${shaRes.stdout.trim().slice(0, 80)}"`, + plan, + targetExists: true, + isRootDisk: false, + probeCommands, + sha256sumOutput: shaRes.stdout, + }; + } + plan.expectedSha256 = hash; + + // 5. 只读验证镜像可读 + const ddProbe = "dd"; + const ddProbeArgs = [`if=${plan.image}`, "of=/dev/null", "bs=4M", "count=1"]; + probeCommands.push(`${ddProbe} ${ddProbeArgs.join(" ")}`); + const ddProbeRes = await exec(ddProbe, ddProbeArgs); + if (ddProbeRes.exitCode !== 0) { + return { + ok: false, + reason: `image read probe failed: ${ddProbeRes.stderr.trim() || `exit ${ddProbeRes.exitCode}`}`, + plan, + targetExists: true, + isRootDisk: false, + probeCommands, + sha256sumOutput: shaRes.stdout, + }; + } + + return { + ok: true, + plan, + targetExists: true, + isRootDisk: false, + probeCommands, + sha256sumOutput: shaRes.stdout, + }; +} + +// ============================================================================ +// verify — 读回 sha256 比对 +// ============================================================================ + +/** + * dd 烧后校验:读回 `dd if= bs=4M count=`, + * 对 stdout 算 sha256,与 plan.expectedSha256(dryRun 预计算)比对。 + * + * fail-closed:无 expectedSha256(未 dry-run)→ 拒绝;读回失败 → fail。 + * + * @param plan 烧录计划(dryRun 填充了 expectedSha256/blockCount)。 + * @param exec 注入的执行函数。 + * @returns VerifyResult。 + */ +async function ddVerify( + plan: FlashPlanEx, + exec: ExecFn, +): Promise { + if (!plan.expectedSha256) { + return { ok: false, reason: "no expectedSha256 in plan — run dryRun first" }; + } + const blockCount = plan.blockCount ?? 1; + const cmd = "dd"; + const args = [`if=${plan.target}`, "bs=4M", `count=${blockCount}`]; + const res = await exec(cmd, args); + if (res.exitCode !== 0) { + return { + ok: false, + expected: plan.expectedSha256, + reason: `readback dd failed: ${res.stderr.trim() || `exit ${res.exitCode}`}`, + verifyCommand: `${cmd} ${args.join(" ")}`, + }; + } + const actual = createHash("sha256").update(res.stdout).digest("hex"); + if (actual === plan.expectedSha256) { + return { + ok: true, + expected: plan.expectedSha256, + actual, + verifyCommand: `${cmd} ${args.join(" ")}`, + }; + } + return { + ok: false, + expected: plan.expectedSha256, + actual, + reason: "VERIFY FAILED: sha256 mismatch", + verifyCommand: `${cmd} ${args.join(" ")}`, + }; +} + +// ============================================================================ +// run — 三段式编排(委托 orchestrateRun) +// ============================================================================ + +/** + * dd 三段式编排:dryRun → 写 → verify。 + * 委托 orchestrateRun,注入 ddDryRun + ddVerify。 + * + * @param plan 烧录计划。 + * @param exec 注入的执行函数。 + * @returns RunFlashResult。 + */ +async function ddRun( + plan: FlashPlanEx, + exec: ExecFn, +): Promise { + return orchestrateRun(plan, exec, ddDryRun, ddVerify); +} + +// ============================================================================ +// Provider 实例 +// ============================================================================ + +/** + * dd 烧录 Provider。 + * + * 磁盘级烧录(SD 卡 / eMMC),强制 dry-run + sha256 校验,拒绝宿主系统盘。 + */ +export const DD_PROVIDER: FlashProvider = { + id: "dd", + plan: ddPlan, + run: ddRun, + verify: ddVerify, +}; diff --git a/src/capabilities/flash/providers/dfu.ts b/src/capabilities/flash/providers/dfu.ts new file mode 100644 index 0000000..b76abab --- /dev/null +++ b/src/capabilities/flash/providers/dfu.ts @@ -0,0 +1,122 @@ +/** + * @module capabilities/flash/providers/dfu + * + * dfu-util 烧录 Provider —— Definition/Provider/Consumer 三角色之 Provider。 + * + * 从 flash.ts planFlash/dryRun/verifyFlash 的 dfu 分支抽出: + * - plan(): `dfu-util -d [-a ] -D `(target = vid:pid) + * - run(): dryRun(dfu-util -l 列出 DFU 设备)→ 写 → verify(-l 再探活) + * - verify(): `dfu-util -l`,exit 0 为通过 + * + * 纯逻辑,ExecFn 注入,无真实硬件依赖。 + */ + +import type { ExecFn } from "../../../shared/types.js"; +import type { + FlashProvider, + FlashPlanEx, + FlashPlanOptions, +} from "../types.js"; +import { + orchestrateRun, + probeDryRun, + exitCodeVerify, +} from "../types.js"; + +// ============================================================================ +// plan — 构建 dfu-util 命令序列 +// ============================================================================ + +/** + * 构建 dfu-util 烧录计划。 + * + * - partition 提供(alt-setting):`dfu-util -d -a -D ` + * - partition 缺省:`dfu-util -d -D ` + * + * target = vid:pid(如 0483:df11)。 + * + * @param opts 烧录参数。 + * @returns FlashPlanEx。 + * @throws {Error} image/target 为空。 + */ +function dfuPlan(opts: FlashPlanOptions): FlashPlanEx { + if (!opts.image || opts.image.trim() === "") { + throw new Error("flash dfu: image path required"); + } + if (!opts.target || opts.target.trim() === "") { + throw new Error("flash dfu: target required"); + } + + const alt = opts.partition?.trim(); + const parts = ["dfu-util", `-d ${opts.target}`]; + if (alt) parts.push(`-a ${alt}`); + parts.push(`-D ${opts.image}`); + + return { + method: "dfu", + commands: [parts.join(" ")], + target: opts.target, + image: opts.image, + dryRun: opts.dryRun, + verify: opts.verify, + }; +} + +// ============================================================================ +// dryRun — dfu-util -l 列出 DFU 设备 +// ============================================================================ + +/** dfu 探活命令。 */ +const DFU_PROBE = { cmd: "dfu-util", args: ["-l"] }; + +// ============================================================================ +// verify — dfu-util -l 再探活 +// ============================================================================ + +/** + * dfu 烧后校验:`dfu-util -l`,exit 0 为通过。 + * dfu 无逐字节校验,只探设备仍在线。 + * + * @param plan 烧录计划。 + * @param exec 注入的执行函数。 + * @returns VerifyResult。 + */ +async function dfuVerify(plan: FlashPlanEx, exec: ExecFn) { + return exitCodeVerify(plan, exec, DFU_PROBE); +} + +// ============================================================================ +// run — 三段式编排 +// ============================================================================ + +/** + * dfu 三段式编排:dryRun(dfu-util -l 探活)→ 写 → verify(-l)。 + * + * @param plan 烧录计划。 + * @param exec 注入的执行函数。 + * @returns RunFlashResult。 + */ +async function dfuRun(plan: FlashPlanEx, exec: ExecFn) { + return orchestrateRun( + plan, + exec, + (p, e) => probeDryRun(p, e, DFU_PROBE), + dfuVerify, + ); +} + +// ============================================================================ +// Provider 实例 +// ============================================================================ + +/** + * dfu-util 烧录 Provider。 + * + * USB DFU 协议烧录(STM32 等),dfu-util -l 探活 + exitCode 校验。 + */ +export const DFU_PROVIDER: FlashProvider = { + id: "dfu", + plan: dfuPlan, + run: dfuRun, + verify: dfuVerify, +}; diff --git a/src/capabilities/flash/providers/fastboot.ts b/src/capabilities/flash/providers/fastboot.ts new file mode 100644 index 0000000..1155e31 --- /dev/null +++ b/src/capabilities/flash/providers/fastboot.ts @@ -0,0 +1,123 @@ +/** + * @module capabilities/flash/providers/fastboot + * + * fastboot 烧录 Provider —— Definition/Provider/Consumer 三角色之 Provider。 + * + * 从 flash.ts planFlash/dryRun/verifyFlash 的 fastboot 分支抽出: + * - plan(): `fastboot flash `(partition 缺省则 `fastboot flash `) + * - run(): dryRun(getvar all 探活)→ 写 → verify(getvar all 再探活) + * - verify(): `fastboot getvar all`,exit 0 为通过(fastboot 无逐字节校验) + * + * 纯逻辑,ExecFn 注入,无真实硬件依赖。 + */ + +import type { ExecFn } from "../../../shared/types.js"; +import type { + FlashProvider, + FlashPlanEx, + FlashPlanOptions, +} from "../types.js"; +import { + orchestrateRun, + probeDryRun, + exitCodeVerify, +} from "../types.js"; + +// ============================================================================ +// plan — 构建 fastboot 命令序列 +// ============================================================================ + +/** + * 构建 fastboot 烧录计划。 + * + * - partition 提供:`fastboot flash ` + * - partition 缺省:`fastboot flash ` + * + * @param opts 烧录参数。 + * @returns FlashPlanEx。 + * @throws {Error} image/target 为空。 + */ +function fastbootPlan(opts: FlashPlanOptions): FlashPlanEx { + if (!opts.image || opts.image.trim() === "") { + throw new Error("flash fastboot: image path required"); + } + if (!opts.target || opts.target.trim() === "") { + throw new Error("flash fastboot: target required"); + } + + const part = opts.partition?.trim(); + const cmd = part + ? `fastboot flash ${part} ${opts.image}` + : `fastboot flash ${opts.image}`; + + return { + method: "fastboot", + commands: [cmd], + target: opts.target, + image: opts.image, + dryRun: opts.dryRun, + verify: opts.verify, + }; +} + +// ============================================================================ +// dryRun — getvar all 探活 +// ============================================================================ + +/** fastboot 探活命令。 */ +const FASTBOOT_PROBE = { cmd: "fastboot", args: ["getvar", "all"] }; + +// ============================================================================ +// verify — getvar all 再探活 +// ============================================================================ + +/** + * fastboot 烧后校验:`fastboot getvar all`,exit 0 为通过。 + * fastboot 无逐字节校验,只探设备仍在线。 + * + * @param plan 烧录计划。 + * @param exec 注入的执行函数。 + * @returns VerifyResult。 + */ +async function fastbootVerify( + plan: FlashPlanEx, + exec: ExecFn, +) { + return exitCodeVerify(plan, exec, FASTBOOT_PROBE); +} + +// ============================================================================ +// run — 三段式编排 +// ============================================================================ + +/** + * fastboot 三段式编排:dryRun(getvar all 探活)→ 写 → verify(getvar all)。 + * + * @param plan 烧录计划。 + * @param exec 注入的执行函数。 + * @returns RunFlashResult。 + */ +async function fastbootRun(plan: FlashPlanEx, exec: ExecFn) { + return orchestrateRun( + plan, + exec, + (p, e) => probeDryRun(p, e, FASTBOOT_PROBE), + fastbootVerify, + ); +} + +// ============================================================================ +// Provider 实例 +// ============================================================================ + +/** + * fastboot 烧录 Provider。 + * + * Android/fastboot 协议烧录(USB),getvar all 探活 + exitCode 校验。 + */ +export const FASTBOOT_PROVIDER: FlashProvider = { + id: "fastboot", + plan: fastbootPlan, + run: fastbootRun, + verify: fastbootVerify, +}; diff --git a/src/capabilities/flash/providers/openocd.ts b/src/capabilities/flash/providers/openocd.ts new file mode 100644 index 0000000..bec5935 --- /dev/null +++ b/src/capabilities/flash/providers/openocd.ts @@ -0,0 +1,129 @@ +/** + * @module capabilities/flash/providers/openocd + * + * openocd 烧录 Provider —— Definition/Provider/Consumer 三角色之 Provider。 + * + * 从 flash.ts planFlash/dryRun/verifyFlash 的 openocd 分支抽出: + * - plan(): `openocd -f -c "program verify reset exit"`(target = cfg 路径) + * - run(): dryRun(openocd -f cfg -c init -c exit 探 JTAG 连通)→ 写 → verify + * - verify(): `openocd -f -c "verify_image " -c exit`,exit 0 为通过 + * + * 纯逻辑,ExecFn 注入,无真实硬件依赖。 + */ + +import type { ExecFn } from "../../../shared/types.js"; +import type { + FlashProvider, + FlashPlanEx, + FlashPlanOptions, +} from "../types.js"; +import { + orchestrateRun, + probeDryRun, + exitCodeVerify, +} from "../types.js"; + +// ============================================================================ +// plan — 构建 openocd 命令序列 +// ============================================================================ + +/** + * 构建 openocd 烧录计划。 + * + * 命令:`openocd -f -c "program verify reset exit"` + * target = openocd cfg 路径(如 interface/stlink.cfg)。 + * + * @param opts 烧录参数。 + * @returns FlashPlanEx。 + * @throws {Error} image/target 为空。 + */ +function openocdPlan(opts: FlashPlanOptions): FlashPlanEx { + if (!opts.image || opts.image.trim() === "") { + throw new Error("flash openocd: image path required"); + } + if (!opts.target || opts.target.trim() === "") { + throw new Error("flash openocd: target (cfg path) required"); + } + + return { + method: "openocd", + commands: [`openocd -f ${opts.target} -c "program ${opts.image} verify reset exit"`], + target: opts.target, + image: opts.image, + dryRun: opts.dryRun, + verify: opts.verify, + }; +} + +// ============================================================================ +// dryRun — openocd init/exit 探 JTAG 连通 +// ============================================================================ + +/** + * 构建 openocd 探活命令(依赖 plan.target = cfg 路径)。 + * + * @param plan 烧录计划。 + * @returns 探活命令 + 参数。 + */ +function openocdProbe(plan: FlashPlanEx): { cmd: string; args: string[] } { + return { + cmd: "openocd", + args: ["-f", plan.target, "-c", "init", "-c", "exit"], + }; +} + +// ============================================================================ +// verify — verify_image exitCode 校验 +// ============================================================================ + +/** + * openocd 烧后校验:`openocd -f -c "verify_image " -c exit`, + * exit 0 为通过。 + * + * @param plan 烧录计划。 + * @param exec 注入的执行函数。 + * @returns VerifyResult。 + */ +async function openocdVerify(plan: FlashPlanEx, exec: ExecFn) { + return exitCodeVerify(plan, exec, { + cmd: "openocd", + args: ["-f", plan.target, "-c", `verify_image ${plan.image}`, "-c", "exit"], + }); +} + +// ============================================================================ +// run — 三段式编排 +// ============================================================================ + +/** + * openocd 三段式编排:dryRun(init/exit 探 JTAG 连通)→ 写 → verify(verify_image)。 + * + * @param plan 烧录计划。 + * @param exec 注入的执行函数。 + * @returns RunFlashResult。 + */ +async function openocdRun(plan: FlashPlanEx, exec: ExecFn) { + const probe = openocdProbe(plan); + return orchestrateRun( + plan, + exec, + (p, e) => probeDryRun(p, e, probe), + openocdVerify, + ); +} + +// ============================================================================ +// Provider 实例 +// ============================================================================ + +/** + * openocd 烧录 Provider。 + * + * JTAG/SWD 协议烧录(MCU Flash),init/exit 探连通 + verify_image 校验。 + */ +export const OPENOCD_PROVIDER: FlashProvider = { + id: "openocd", + plan: openocdPlan, + run: openocdRun, + verify: openocdVerify, +}; diff --git a/src/capabilities/flash/types.ts b/src/capabilities/flash/types.ts new file mode 100644 index 0000000..551866b --- /dev/null +++ b/src/capabilities/flash/types.ts @@ -0,0 +1,572 @@ +/** + * @module capabilities/flash/types + * + * 安全烧录能力接缝 —— Definition/Provider/Consumer 三角色之 Definition 层。 + * + * 治原 flash.ts planFlash/dryRun/verifyFlash/runFlash 按 method switch 分派、 + * 新增烧录方法需改主文件的缺陷。抽成 FlashProvider 接口 + Registry, + * 每种烧录方法一个 provider 文件,新增方法只 register 不改主逻辑(开闭原则)。 + * + * 三角色: + * - Definition —— 本文件:FlashProvider 接口 + FlashPlanEx/FlashPlanOptions + + * RunFlashResult/VerifyResult/DryRunResult/LsblkRow 类型 + 共享纯函数(parseOffset / + * parseLsblk / isRootDiskTarget / splitCommand 等供各 provider 复用) + * - Provider —— providers/*.ts:dd / fastboot / dfu / openocd 四实现(FlashProvider 实例) + * - Consumer —— index.ts:FlashRegistry(register/resolve/list,fail-closed resolve) + * + * 纯逻辑,零 pi 运行时依赖。顶层仅 `import type`(esbuild 擦除)+ node:crypto(Node 内置), + * tests 直接 import 命名导出离线可测,无 pi 运行时、无真实硬件。 + * + * fail-closed 语义(安全不变式): + * - dryRun 默认 true(第一次必须先 dry-run 再写真写) + * - target 是宿主系统盘(挂载了 / /boot /home 等)或根分区 → 拒绝 + * - target 不存在 → 拒绝 + * - offset + 镜像大小 越过目标设备容量 → 拒绝(非 offset vs 镜像大小) + * - 烧后 sha256 不匹配 → VERIFY FAILED + * + * 见 Docs/T08_能力接缝三角色.md + Docs/F13_安全烧录工具.md。 + */ + +import type { + FlashMethod, + FlashPlan, + ExecFn, +} from "../../shared/types.js"; + +// 便于调用方一次性 import;类型本身定义在 shared/types.ts +export type { FlashMethod, FlashPlan, ExecFn }; + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** + * 扩展 FlashPlan:plan() 填充的偏移 + dryRun/verify 标记,dryRun()/verify() 填充的 + * 镜像大小 / 块数 / 预期 sha256(verify 用)。 + */ +export interface FlashPlanEx extends FlashPlan { + /** dd seek= 的字节偏移(解析自 opts.offset,十进制或 0x hex)。 */ + offsetBytes?: number; + /** 镜像字节数(dryRun 经 stat 填充,verify dd 读回 count 用)。 */ + imageSizeBytes?: number; + /** dd bs=4M 块数(ceil(imageSizeBytes / 4MiB)),verify 读回 count。 */ + blockCount?: number; + /** 是否先 dry-run(默认 true,fail-closed)。run() 据此决定是否跳过写。 */ + dryRun?: boolean; + /** 烧后是否 verify(默认 true)。run() 据此决定是否跳过 verify。 */ + verify?: boolean; +} + +/** + * flash provider plan() 的入参。method/image/target 必填,其余可选。 + */ +export interface FlashPlanOptions { + /** 烧录方法。 */ + method: FlashMethod; + /** 镜像/载荷文件路径。 */ + image: string; + /** 目标设备节点 / 串号 / cfg 路径。 */ + target: string; + /** dd seek= 字节偏移(十进制或 0x hex 字符串)。 */ + offset?: string; + /** fastboot 分区名(如 boot)或 dfu alt-setting。 */ + partition?: string; + /** 是否先 dry-run(默认 true,fail-closed)。 */ + dryRun?: boolean; + /** 烧后是否 verify(默认 true)。 */ + verify?: boolean; +} + +/** dryRun 结果。 */ +export interface DryRunResult { + /** 是否通过 dry-run 校验。 */ + ok: boolean; + /** 失败原因(fail-closed 诊断用)。 */ + reason?: string; + /** 烧录计划(dryRun 可能填充 imageSizeBytes/blockCount/expectedSha256)。 */ + plan: FlashPlanEx; + /** target 设备节点是否存在于 lsblk 输出。 */ + targetExists: boolean; + /** target 是否挂载了根/启动分区(→ 拒绝)。 */ + isRootDisk: boolean; + /** dry-run 阶段实际执行的探测命令(审计用)。 */ + probeCommands: string[]; + /** sha256sum 镜像原始输出(dd 方法)。 */ + sha256sumOutput?: string; +} + +/** verify 结果。 */ +export interface VerifyResult { + /** 是否通过烧后校验。 */ + ok: boolean; + /** 预期 sha256(dd 方法)。 */ + expected?: string; + /** 实际 sha256(dd 方法)。 */ + actual?: string; + /** 失败原因。 */ + reason?: string; + /** verify 阶段执行的命令。 */ + verifyCommand?: string; +} + +/** lsblk 行解析结果。 */ +export interface LsblkRow { + /** 设备名(如 sda1, mmcblk0p1)。 */ + name: string; + /** 字节大小。 */ + size: number; + /** 设备类型(disk/part)。 */ + type: string; + /** 挂载点(空串=未挂载)。 */ + mountpoint: string; +} + +/** run() 三段式编排结果。 */ +export interface RunFlashResult { + /** dry-run 阶段结果。 */ + dryRun: DryRunResult; + /** 是否真正执行了写命令。 */ + written: boolean; + /** 写命令执行结果(每条 command 的 exitCode)。 */ + writeExitCodes: number[]; + /** verify 阶段结果(跳过 verify 时 undefined)。 */ + verify?: VerifyResult; + /** 总体是否成功(dryRun ok + 写全 0 + verify ok)。 */ + ok: boolean; + /** 失败原因。 */ + reason?: string; +} + +// ============================================================================ +// 常量 —— 消灭魔法串 +// ============================================================================ + +/** dd 块大小(与文档一致 bs=4M)。 */ +export const DD_BLOCK_SIZE = 4 * 1024 * 1024; + +/** + * 深冻结 Set 包装器 —— 运行时不可变。 + * + * `Object.freeze(new Set(...))` 只冻结 Set 对象引用,不阻止 `.add()/.delete()` + * 修改集合内容(freeze 对 Set 内容无效果)。本包装器不暴露 add/delete/clear, + * 从运行时根除突变可能:调用方拿到的是只读视图,任何 `.add()/.delete()` 调用 + * 在运行时直接抛 TypeError(fail-closed)。 + * + * 实现 ReadonlySet 全部只读接口,类型与运行时双重不可变。 + */ +class FrozenSet implements ReadonlySet { + /** 私有底层 Set——外部不可达,无法通过 `.backing.delete()` 绕过。 */ + private readonly backing: Set; + + constructor(items: readonly T[]) { + this.backing = new Set(items); + } + + get size(): number { + return this.backing.size; + } + + has(value: T): boolean { + return this.backing.has(value); + } + + entries(): IterableIterator<[T, T]> { + return this.backing.entries(); + } + + keys(): IterableIterator { + return this.backing.keys(); + } + + values(): IterableIterator { + return this.backing.values(); + } + + forEach( + callback: (value: T, value2: T, set: ReadonlySet) => void, + thisArg?: unknown, + ): void { + this.backing.forEach((v) => callback.call(thisArg, v, v, this)); + } + + [Symbol.iterator](): IterableIterator { + return this.backing[Symbol.iterator](); + } +} + +/** 视为宿主系统盘的挂载点(命中任一即拒绝写)。深冻结,运行时不可变。 */ +export const ROOT_MOUNTPOINTS: ReadonlySet = new FrozenSet([ + "/", + "/boot", + "/boot/efi", + "/home", + "/var", + "/usr", + "/swap", + "[SWAP]", +]); + +/** lsblk 树形输出前缀字符(├─ └─ │ ─ 等非 ASCII 盒绘字符)。 */ +const LSBLK_TREE_CHARS = /[─-╼│├└─\s]+/; + +// ============================================================================ +// 共享纯函数 —— 各 provider 复用 +// ============================================================================ + +/** + * 把 offset 字符串(十进制或 0x hex)解析成字节数。 + * + * @param offset 十进制或 0x hex 字符串,undefined/空 → 0。 + * @returns 字节数;无法解析返回 null。 + */ +export function parseOffset(offset: string | undefined): number | null { + if (offset === undefined || offset === "") return 0; + const trimmed = offset.trim(); + if (/^0x[0-9a-fA-F]+$/.test(trimmed)) { + const n = Number(trimmed); + if (Number.isFinite(n) && n >= 0) return n; + return null; + } + if (/^\d+$/.test(trimmed)) { + try { + const big = BigInt(trimmed); + if (big > BigInt(Number.MAX_SAFE_INTEGER)) { + return Number.MAX_SAFE_INTEGER; + } + return Number(big); + } catch { + return null; + } + } + return null; +} + +/** + * 解析 `lsblk -b -o NAME,SIZE,TYPE,MOUNTPOINT` 的原始输出为行数组。 + * 处理树形盒绘字符前缀(├─ └─ │)与空 mountpoint。 + * + * @param raw lsblk 原始 stdout。 + * @returns 解析后的行数组。 + */ +export function parseLsblk(raw: string): LsblkRow[] { + const lines = raw.split("\n"); + const rows: LsblkRow[] = []; + let started = false; + for (const line of lines) { + if (!line.trim()) continue; + if (!started) { + if (/^NAME/i.test(line.trim())) { + started = true; + continue; + } + } + const cleaned = line.replace(LSBLK_TREE_CHARS, " ").trim(); + if (!cleaned) continue; + const cols = cleaned.split(/\s+/); + if (cols.length < 3) continue; + const name = cols[0] ?? ""; + const size = Number.parseInt(cols[1] ?? "0", 10); + const type = cols[2] ?? ""; + const mountpoint = cols.slice(3).join(" ") ?? ""; + rows.push({ + name, + size: Number.isFinite(size) ? size : 0, + type, + mountpoint, + }); + } + return rows; +} + +/** + * 从目标设备路径提取 basename(/dev/sda1 → sda1,/dev/mmcblk0p2 → mmcblk0p2)。 + * + * @param target 设备路径。 + * @returns basename。 + */ +export function deviceBasename(target: string): string { + const m = target.match(/\/dev\/(.+)$/); + return m ? m[1] : target.replace(/^\/+/, ""); +} + +/** + * 判断 lsblk 行名是否匹配目标设备(整盘自身或其分区)。 + * + * 匹配规则:`name === base` 或 `name === base + 分区后缀`。 + * 分区后缀模式为 `p?\d+`(覆盖 sda1 / mmcblk0p1 / nvme0n1p2 等命名约定)。 + * + * 替代旧的 `row.name.startsWith(base)`,后者会误匹配前缀相同但不同设备 + * (如 base "sda" 误匹配 "sdab";base "mmcblk0" 误匹配 "mmcblk0boot0")。 + * + * @param base 目标设备 basename(deviceBasename 提取)。 + * @param name lsblk 行的 NAME 字段。 + * @returns true 表示该行属于目标设备或其分区。 + */ +export function matchesDeviceName(base: string, name: string): boolean { + if (name === base) return true; + // 转义 base 中的正则元字符(设备名通常无元字符,但防御性转义) + const escaped = base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + // 分区后缀:p?\d+(sda1 / mmcblk0p1 / nvme0n1p2) + return new RegExp(`^${escaped}(?:p?\\d+)?$`).test(name); +} + +/** + * 判断 target 是否为宿主系统盘:target 自身或其任一分区挂载了根/启动目录。 + * + * @param target 设备路径。 + * @param rows lsblk 解析后的行数组。 + * @returns true 表示是宿主系统盘(应拒绝写)。 + */ +export function isRootDiskTarget( + target: string, + rows: LsblkRow[], +): boolean { + const base = deviceBasename(target); + for (const row of rows) { + if (matchesDeviceName(base, row.name)) { + if (row.mountpoint && ROOT_MOUNTPOINTS.has(row.mountpoint)) { + return true; + } + } + } + return false; +} + +/** + * 判断 target 是否出现在 lsblk 输出里(设备节点存在)。 + * + * @param target 设备路径。 + * @param rows lsblk 解析后的行数组。 + * @returns true 表示设备存在。 + */ +export function targetExistsInRows( + target: string, + rows: LsblkRow[], +): boolean { + const base = deviceBasename(target); + return rows.some((r) => matchesDeviceName(base, r.name)); +} + +/** + * 简易命令拆分:按空格切,但保留双引号内的整体 + * (openocd -c "program x verify reset exit")。 + * + * 仅供 run() 内部把 plan.commands 字符串拆回 command+args。 + * + * 空引号参数保留:`a -c ""` → `['a', '-c', '']`(空串是合法 argv, + * 不能因 `if (cur)` 丢弃)。靠 hadQuote 标记区分"空引号 token"与"未入 token"。 + * + * @param cmdStr 命令字符串。 + * @returns 拆分后的 token 数组(第一项为命令,其余为参数)。 + */ +export function splitCommand(cmdStr: string): string[] { + const tokens: string[] = []; + let cur = ""; + let inQuote = false; + let hadQuote = false; // 当前 token 是否进入过引号区域(空引号 "" 也算) + for (let i = 0; i < cmdStr.length; i++) { + const ch = cmdStr[i]; + if (ch === '"') { + inQuote = !inQuote; + hadQuote = true; + continue; + } + if (ch === " " && !inQuote) { + if (cur || hadQuote) tokens.push(cur); + cur = ""; + hadQuote = false; + continue; + } + cur += ch; + } + if (cur || hadQuote) tokens.push(cur); + return tokens; +} + +// ============================================================================ +// 共享编排 helper —— 各 provider 的 run() 复用(DRY,消灭三段式样板) +// ============================================================================ + +/** + * 三段式编排:dryRun(fail-closed)→ 写 → verify。 + * + * 各 provider 的 run() 委托此函数,注入自己的 dryRunFn / verifyFn 即可—— + * 编排逻辑(skipWrite 判定、逐条写、失败短路)只此一份,不复制到每个 provider。 + * + * - plan.dryRun !== false → 只 dry-run 不写真写(fail-closed 默认) + * - plan.verify === false → 跳过 verify + * + * @param plan 烧录计划(plan() 产出,dryRun/verify 标记已设)。 + * @param exec 注入的执行函数。 + * @param dryRunFn provider 的 dryRun 实现。 + * @param verifyFn provider 的 verify 实现。 + * @returns RunFlashResult。 + */ +export async function orchestrateRun( + plan: FlashPlanEx, + exec: ExecFn, + dryRunFn: (plan: FlashPlanEx, exec: ExecFn) => Promise, + verifyFn: (plan: FlashPlanEx, exec: ExecFn) => Promise, +): Promise { + // ① dry-run(fail-closed:不通过不写) + const dr = await dryRunFn(plan, exec); + if (!dr.ok) { + return { + dryRun: dr, + written: false, + writeExitCodes: [], + ok: false, + reason: dr.reason, + }; + } + + // dryRun 默认 true:未显式传 false 即只 dry-run + const dryOnly = plan.dryRun !== false; + if (dryOnly) { + return { dryRun: dr, written: false, writeExitCodes: [], ok: true }; + } + + // ② 写:逐条执行 plan.commands + const writeExitCodes: number[] = []; + for (const cmdStr of plan.commands) { + const parts = splitCommand(cmdStr); + const res = await exec(parts[0], parts.slice(1)); + writeExitCodes.push(res.exitCode); + if (res.exitCode !== 0) { + return { + dryRun: dr, + written: true, + writeExitCodes, + ok: false, + reason: `write command failed (${cmdStr}): ${res.stderr.trim() || `exit ${res.exitCode}`}`, + }; + } + } + + // ③ verify(verify !== false 时执行) + const vr = plan.verify === false ? undefined : await verifyFn(plan, exec); + const ok = vr ? vr.ok : true; + return { + dryRun: dr, + written: true, + writeExitCodes, + verify: vr, + ok, + reason: vr?.ok ? undefined : vr?.reason, + }; +} + +/** + * probe-based dryRun 通用实现(fastboot/dfu/openocd 共用)。 + * + * 跑一条探测命令,exit 0 = ok。fail-closed:非 0 → ok:false。 + * + * @param plan 烧录计划。 + * @param exec 注入的执行函数。 + * @param probe 探测命令 + 参数。 + * @returns DryRunResult。 + */ +export async function probeDryRun( + plan: FlashPlanEx, + exec: ExecFn, + probe: { cmd: string; args: string[] }, +): Promise { + const probeCommands = [`${probe.cmd} ${probe.args.join(" ")}`]; + const res = await exec(probe.cmd, probe.args); + if (res.exitCode !== 0) { + return { + ok: false, + reason: `${plan.method} probe failed: ${res.stderr.trim() || `exit ${res.exitCode}`}`, + plan, + targetExists: false, + isRootDisk: false, + probeCommands, + }; + } + return { + ok: true, + plan, + targetExists: true, + isRootDisk: false, + probeCommands, + }; +} + +/** + * exitCode-based verify 通用实现(fastboot/dfu/openocd 共用)。 + * + * 跑一条校验命令,exit 0 = ok。fail-closed:非 0 → ok:false。 + * + * @param plan 烧录计划。 + * @param exec 注入的执行函数。 + * @param verifyCmd 校验命令 + 参数。 + * @returns VerifyResult。 + */ +export async function exitCodeVerify( + plan: FlashPlanEx, + exec: ExecFn, + verifyCmd: { cmd: string; args: string[] }, +): Promise { + const res = await exec(verifyCmd.cmd, verifyCmd.args); + const cmdStr = `${verifyCmd.cmd} ${verifyCmd.args.join(" ")}`; + if (res.exitCode !== 0) { + return { + ok: false, + reason: `${plan.method} verify failed: ${res.stderr.trim() || `exit ${res.exitCode}`}`, + verifyCommand: cmdStr, + }; + } + return { ok: true, verifyCommand: cmdStr }; +} + +// ============================================================================ +// FlashProvider 接口 —— Definition/Provider/Consumer 三角色之 Provider 契约 +// ============================================================================ + +/** + * 安全烧录 Provider —— Definition/Provider/Consumer 三角色之 Provider。 + * + * 每个 provider 封装一种烧录方法(dd/fastboot/dfu/openocd)的三段式安全流程: + * - plan(): 构建命令序列(FlashPlanEx) + * - run(): dryRun → 写 → verify 三段式编排(fail-closed) + * - verify(): 烧后校验(dd sha256 比对 / 其他 exitCode 校验) + * + * 新增烧录方法只需新建一个 provider 文件并 register,不改已有逻辑(开闭原则)。 + */ +export interface FlashProvider { + /** provider 标识 = 烧录方法。 */ + readonly id: FlashMethod; + /** + * 由 method + image + target + opts 构建烧录计划。 + * + * 纯构建,不做 target 存在性/根盘校验(那是 dryRun 的职责)。 + * 若 ctx.lsblk 提供,可做早期 fail-closed 根盘检查。 + * + * @param opts 烧录参数(method/image/target 必填)。 + * @param ctx 可选上下文(lsblk 行数组,用于早期根盘校验)。 + * @returns FlashPlanEx。 + * @throws {Error} method 不合法 / image 或 target 为空 / offset 不可解析。 + */ + plan(opts: FlashPlanOptions, ctx?: { lsblk?: LsblkRow[] }): FlashPlanEx; + /** + * 三段式编排:dryRun(fail-closed)→ 写 → verify。 + * + * - plan.dryRun !== false → 只 dry-run 不写真写 + * - plan.verify === false → 跳过 verify + * + * @param plan 烧录计划(plan() 产出)。 + * @param exec 注入的执行函数。 + * @returns RunFlashResult。 + */ + run(plan: FlashPlanEx, exec: ExecFn): Promise; + /** + * 烧后校验。 + * + * dd: 读回 sha256 比对;其他: exitCode 校验。 + * + * @param plan 烧录计划(dryRun 填充了 expectedSha256/blockCount)。 + * @param exec 注入的执行函数。 + * @returns VerifyResult。 + */ + verify(plan: FlashPlanEx, exec: ExecFn): Promise; +} diff --git a/src/capabilities/lsp.ts b/src/capabilities/lsp.ts new file mode 100644 index 0000000..c52f183 --- /dev/null +++ b/src/capabilities/lsp.ts @@ -0,0 +1,85 @@ +/** + * @module lsp + * + * 嵌入式 IDE 桥(on-demand stub)—— LSP 协议的占位接口。 + * + * 场景:嵌入式 Agent 在交互式编辑(edit-strict / 交叉编译诊断回填)时需 LSP 能力 + * (定义跳转、诊断、补全)。但 LSP 服务进程重、且依赖具体板侧工具链(clangd + * 交叉编译参数),on-demand 启动。本模块只定义接口 + 提供 no-op 默认实现,真实 + * LSP 桥(spawn clangd / 持久 JSON-RPC)由后续模块接线,现以 NoopLspBridge 占位。 + * + * 设计要点: + * - LspBridge 接口:initialize(opts) + shutdown(),最小契约。 + * - NoopLspBridge:默认 no-op,initialize 永返回 {ok:true},shutdown 无副作用。 + * - 纯逻辑,零 pi 依赖,可离线单测。 + * - 不假装真实 LSP 能力(不做诊断/补全),只保证调用方在不接线时获得稳定 stub。 + */ + +// ============================================================================ +// 类型契约 —— 下游依赖这些名字,不得改名 +// ============================================================================ + +/** initialize 入参。 */ +export interface LspInitOptions { + /** 工作区根 URI(如 "file:///workspace")。 */ + rootUri: string; + /** 可选:额外初始化选项(透传给具体 LSP server)。 */ + initializationOptions?: Record; +} + +/** initialize 返回。 */ +export interface LspInitResult { + /** 是否成功。 */ + ok: boolean; + /** 失败原因(ok=false 时)。 */ + reason?: string; +} + +/** + * LSP 桥接口。on-demand:调用方按需 initialize,用完 shutdown。 + * 真实实现负责 spawn clangd / 持久 JSON-RPC;NoopLspBridge 为占位。 + */ +export interface LspBridge { + /** + * 初始化 LSP 会话。 + * + * @param opts 初始化参数(rootUri 必填)。 + * @returns 初始化结果。 + */ + initialize(opts: LspInitOptions): Promise; + /** + * 关闭 LSP 会话,释放资源。幂等。 + * + * @returns 关闭完成。 + */ + shutdown(): Promise; +} + +// ============================================================================ +// NoopLspBridge —— 默认 no-op 实现(on-demand stub) +// ============================================================================ + +/** + * no-op LSP 桥。默认实现:initialize 永成功、shutdown 无副作用。 + * + * 用于无真实 LSP 环境的占位,保证调用方代码路径在不接线时仍稳定运行。 + * 不做任何诊断 / 补全 / 跳转 —— 只满足 {@link LspBridge} 契约。 + */ +export class NoopLspBridge implements LspBridge { + /** + * 初始化:永返回 { ok: true }。 + * + * @param _opts 初始化参数(on-demand stub 不消费)。 + * @returns { ok: true }。 + */ + async initialize(_opts: LspInitOptions): Promise { + return { ok: true }; + } + + /** + * 关闭:无副作用,永 resolve。幂等。 + */ + async shutdown(): Promise { + // no-op —— on-demand stub 无资源需释放 + } +} diff --git a/src/capabilities/settings.ts b/src/capabilities/settings.ts new file mode 100644 index 0000000..9e0f5ca --- /dev/null +++ b/src/capabilities/settings.ts @@ -0,0 +1,184 @@ +/** + * @module settings + * + * typed settings store —— 类型安全的运行时配置。 + * + * 嵌入式 Agent 有大量运行时配置(超时、重试、寄存器表路径、板 ID……)。本 store + * 用泛型约束键集:构造时传入 defaults,get/set 的键被收窄到 defaults 的字面量键, + * 值类型跟随 defaults,杜绝魔法串键与类型漂移。 + * + * 设计要点: + * - 构造深拷贝 defaults(隔离外部对 defaults 的后续篡改,含嵌套对象引用)。 + * - get/set 由 keyof T 约束,编译期捕获未知键。 + * - snapshot 返回深冻结副本(运行时不可变),调用方可安全传递 / 缓存。 + * - 纯逻辑,零 pi 依赖,可离线单测。 + * + * 见 src/core/sandbox-policy.ts 的深冻结范式(DEFAULT_BOARD_SANDBOX_POLICY)。 + */ + +// ============================================================================ +// 内部工具 —— 深克隆 + 深冻结 +// ============================================================================ + +/** + * 深克隆对象(递归复制)。用于构造时深拷贝 defaults 与 snapshot 前复制:先复制再 + * 冻结,确保冻结不波及 store 内部状态。对非对象(string/number/...)原样返回; + * 数组逐元素递归克隆。 + * + * 内置引用类型显式处理,避免落入 plain-object 分支被掏空: + * - Date:用 `new Date(getTime())` 复制(Date 无可枚举自有键,plain-object 分支 + * 会产出空 `{}`,丢失值与类型)。 + * - RegExp:用 `new RegExp(source, flags)` 复制。 + * - Map:逐 entry 递归克隆键与值后重建。 + * - Set:逐元素递归克隆后重建。 + * + * @param obj 待克隆对象。 + * @returns 与原对象无共享引用的深副本。 + */ +function deepClone(obj: T): T { + if (obj === null || typeof obj !== "object") return obj; + if (Array.isArray(obj)) { + return obj.map((e) => deepClone(e)) as unknown as T; + } + // Date:plain-object 分支会得空 {},须用构造器保值保类型 + if (obj instanceof Date) { + return new Date(obj.getTime()) as unknown as T; + } + // RegExp:同上,source/flags 复制 + if (obj instanceof RegExp) { + return new RegExp(obj.source, obj.flags) as unknown as T; + } + // Map:逐 entry 递归克隆键值(键/值可能含嵌套引用) + if (obj instanceof Map) { + const map = new Map(); + for (const [k, v] of obj as Map) { + map.set(deepClone(k), deepClone(v)); + } + return map as unknown as T; + } + // Set:逐元素递归克隆 + if (obj instanceof Set) { + const set = new Set(); + for (const v of obj as Set) { + set.add(deepClone(v)); + } + return set as unknown as T; + } + const clone: Record = {}; + for (const key of Object.keys(obj as Record)) { + clone[key] = deepClone((obj as Record)[key]); + } + return clone as unknown as T; +} + +/** + * 深冻结对象(递归 Object.freeze)。用于 snapshot 输出,保证运行时不可变。 + * 调用方须确保传入的是独占副本(见 {@link deepClone}),否则会原地冻结共享引用。 + * 对非对象(string/number/...)原样返回。 + * + * 内置容器递归冻结以与 {@link deepClone} 对齐: + * - Map:冻结 Map 本身并递归冻结各键/值。 + * - Set:冻结 Set 本身并递归冻结各元素。 + * - Date/RegExp:冻结对象本身即可(无可变嵌套引用)。 + * + * @param obj 待冻结对象(须为独占副本)。 + * @returns 冻结后的对象(Readonly)。 + */ +function deepFreeze(obj: T): Readonly { + if (obj === null || typeof obj !== "object") return obj as Readonly; + if (obj instanceof Map) { + for (const [k, v] of obj as Map) { + if (k !== null && typeof k === "object" && !Object.isFrozen(k)) deepFreeze(k); + if (v !== null && typeof v === "object" && !Object.isFrozen(v)) deepFreeze(v); + } + Object.freeze(obj); + return obj as Readonly; + } + if (obj instanceof Set) { + for (const v of obj as Set) { + if (v !== null && typeof v === "object" && !Object.isFrozen(v)) deepFreeze(v); + } + Object.freeze(obj); + return obj as Readonly; + } + Object.freeze(obj); + for (const key of Object.keys(obj as Record)) { + const v = (obj as Record)[key]; + if (v !== null && typeof v === "object" && !Object.isFrozen(v)) { + deepFreeze(v); + } + } + return obj as Readonly; +} + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** 构造选项。 */ +export interface SettingsStoreOptions { + /** 初始 defaults(深拷贝隔离)。 */ + defaults: T; +} + +// ============================================================================ +// SettingsStore —— typed settings +// ============================================================================ + +/** + * 类型安全 settings store。 + * + * 泛型 T 约束键集与值类型:构造传入 defaults,后续 get/set 的键被收窄到 keyof T, + * 值类型为 T[K]。默认泛型 Record 兼容无强类型场景。 + * + * @example + * const s = new SettingsStore({ retries: 3, boardId: "x5" }); + * s.set("retries", 5); // ok + * s.get("boardId"); // "x5" + * s.snapshot(); // 深冻结只读副本 + */ +export class SettingsStore> { + private readonly store: T; + + /** + * @param defaults 初始默认值;深拷贝以隔离外部篡改(含嵌套对象引用)。 + */ + constructor(defaults: T) { + // 深拷贝:隔离外部对 defaults 任意层级(含嵌套对象)的后续 mutation, + // 避免调用方篡改 defaults 嵌套字段回渗污染 store 内部状态。 + this.store = deepClone(defaults); + } + + /** + * 取某项配置。 + * + * @param k 配置键(keyof T)。 + * @returns 配置值。 + */ + get(k: K): T[K] { + return this.store[k]; + } + + /** + * 设某项配置。键由 keyof T 约束,编译期拒绝未知键。 + * + * @param k 配置键。 + * @param v 配置值(类型跟随 T[K])。 + */ + set(k: K, v: T[K]): void { + this.store[k] = v; + } + + /** + * 返回当前全部配置的深冻结只读副本。调用方可安全传递 / 缓存,不影响内部状态。 + * + * 实现先 {@link deepClone} 复制全部嵌套引用,再 {@link deepFreeze} 冻结副本, + * 确保冻结不波及内部 store 的嵌套对象。构造亦已深拷贝 defaults,故内部 store + * 与调用方传入的 defaults 无共享嵌套引用。 + * + * @returns 深冻结只读副本(与内部状态无共享引用)。 + */ + snapshot(): Readonly { + return deepFreeze(deepClone({ ...this.store })); + } +} diff --git a/src/capabilities/subagent/index.ts b/src/capabilities/subagent/index.ts new file mode 100644 index 0000000..116b6ab --- /dev/null +++ b/src/capabilities/subagent/index.ts @@ -0,0 +1,278 @@ +/** + * @module capabilities/subagent + * + * 子代理能力接缝(T12)—— spawn-in-process 子 agent + 作用域隔离注册表。 + * + * 治嵌入式开发场景下"主 agent 单线推进、无法把可并行的子任务(编译/探板/ + * datasheet RAG)分派给隔离子 agent"的缺陷。本模块提供: + * ① SubagentProvider 抽象 + InlineSubagentProvider(spawn-in-process 实现) + * ② SubagentRegistry(register/resolve,fail-closed 无匹配抛错) + * ③ isolatedSubagentScope —— 把任意 scope 挂到 "subagent" 命名空间根下, + * 使子 agent 作用域与主 agent 作用域互不为祖孙(T07 scopeReceives 双向 + * 不匹配),故子 agent 事件不串主 agent(核心隔离不变式)。 + * + * 作用域隔离不变式(靠 T07 ScopeKey,见 tests/workflow.test.ts ⑥): + * - 主 agent 监听 scope=M,子 agent emit scope="subagent…": + * "subagent…" 不以 M 为段前缀(除非 M 恰为 "subagent",但主 agent 不应监听 + * 此根)→ scopeReceives 返回 false → 主 agent 不收子 agent 事件(不串)。 + * - 主 agent emit scope=M,子 agent 监听 scope="subagent…": + * M 非 "subagent…" 的祖先后缀 → scopeReceives 返回 false → 子 agent 不收 + * 主 agent 事件(不下渗)。 + * - 双向不串:子 agent 事件不污染主 agent,主 agent 事件不下渗子 agent。 + * 需要观测子 agent 的集成层可在 scope="subagent"(根)注册监听收全部子 agent + * 事件,这不破坏隔离——主 agent 仍只监听自己的 scope。 + * + * 纯逻辑:顶层仅 `import type`(esbuild 擦除),零 pi 运行时依赖,无硬件。 + * tests 直接 import 命名导出即可离线单测。与 tool-pipeline / sandbox-policy / + * board-link 的注册器范式同源(disposer + fail-closed resolve + 深冻结常量)。 + * + * 见架构设计文档_v3.md §7(T12)/ Docs/T08_能力接缝三角色.md。 + */ + +import type { ScopeKey } from "../../core/pba-event-bus.js"; + +// ============================================================================ +// 命名常量 —— 消灭魔法串(隔离根 / 默认 provider id) +// ============================================================================ + +/** + * 子代理事件隔离根作用域前缀。 + * + * 所有子 agent 作用域都挂在此根下("subagent.<…>"),与主 agent 作用域 + * (任意非 "subagent" 前缀的路径)互不为祖孙,实现双向事件不串。深冻结。 + */ +export const SUBAGENT_SCOPE_ROOT = "subagent" as const; + +/** + * InlineSubagentProvider 的默认 id。 + * + * 单实例 spawn-in-process 场景的默认注册键;需注册多个 inline provider 时 + * 构造器显式传不同 id 即可。深冻结。 + */ +export const INLINE_SUBAGENT_ID = "inline-subagent" as const; + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** + * 子代理 spawn 结果。 + * + * - ok=true 时 value 携带 handler 返回值;error 缺省。 + * - ok=false 时 error 携带失败原因(handler 抛错 / 超时);value 缺省。 + * - scope 始终为子 agent 实际运行所在的隔离作用域键(经 isolatedSubagentScope 派生)。 + * + * fail-closed:handler 抛错或超时绝不向上传播,统一转成 ok:false 结果, + * 由调用方决定如何处理(与 tool-pipeline 的 timeout around 容器同道)。 + */ +export interface SubagentResult { + /** true=handler 正常返回;false=抛错或超时。 */ + readonly ok: boolean; + /** handler 返回值(ok=true 时)。 */ + readonly value?: unknown; + /** 失败原因(ok=false 时)。 */ + readonly error?: string; + /** 子 agent 实际运行的隔离作用域键("subagent…" 形式)。 */ + readonly scope: string; +} + +/** + * spawn 选项。 + */ +export interface SubagentSpawnOptions { + /** + * 语义作用域提示。经 isolatedSubagentScope 挂到 "subagent" 根下后作为子 agent + * 的隔离作用域;缺省则用序号派生唯一键。无论传什么,最终 scope 都隔离于主 agent。 + */ + readonly scope?: string; + /** 超时毫秒;超时转 ok:false(fail-closed,不抛)。缺省=不限。 */ + readonly timeoutMs?: number; +} + +/** + * 子代理 Provider —— Definition/Provider/Consumer 三角色之 Provider。 + * + * 每个封装一种 spawn 后端(in-process / 真 pi subagent / 远程 agent)。 + * id 是注册键(与 BoardLinkProvider / ProviderDescriptor 同道)。 + */ +export interface SubagentProvider { + /** provider 唯一标识(注册键)。 */ + readonly id: string; + /** + * 派生一个子 agent 执行 prompt,返回隔离结果。 + * + * @param prompt 子 agent 的任务提示。 + * @param opts scope 提示 + 超时。 + * @returns SubagentResult(fail-closed,绝不 reject)。 + */ + spawn(prompt: string, opts?: SubagentSpawnOptions): Promise; +} + +// ============================================================================ +// isolatedSubagentScope —— 作用域隔离(纯函数,确定性可测) +// ============================================================================ + +/** + * 把任意 scope 挂到 "subagent" 命名空间根下,保证与主 agent 作用域双向不串。 + * + * 归一(按 "." 切段、滤空段)后前缀 SUBAGENT_SCOPE_ROOT: + * - undefined / "" / " " → "subagent"(仅根,仍隔离) + * - "compile" → "subagent.compile" + * - "main.task" → "subagent.main.task" + * - "a..b" / ".b" → "subagent.a.b"(滤空段) + * + * 隔离保证(T07 scopeReceives):派生后的 scope 恒以 "subagent" 为段前缀, + * 任何非 "subagent" 前缀的主 agent 作用域 M 都不是它的祖先也不是后代, + * 故主 agent emit/监听 与 子 agent emit/监听 互不派发(双向不串)。 + * + * @param scope 原始作用域提示(可 undefined)。 + * @returns 挂在 "subagent" 根下的隔离作用域键。 + */ +export function isolatedSubagentScope(scope: string | undefined): ScopeKey { + const segs = (scope ?? "").split(".").filter((s) => s.length > 0); + return segs.length === 0 ? SUBAGENT_SCOPE_ROOT : `${SUBAGENT_SCOPE_ROOT}.${segs.join(".")}`; +} + +// ============================================================================ +// InlineSubagentProvider —— spawn-in-process 实现 +// ============================================================================ + +/** + * spawn-in-process 子代理 provider —— 跑一个注入的 handler 函数。 + * + * - 构造器收 handler:`(prompt, opts?) => Promise`。opts 只含 scope + * (handler 不负责超时,超时由 provider 在外层 race 包裹)。 + * - spawn 派生隔离 scope(isolatedSubagentScope),把派生后的 scope 透传给 handler, + * 使 handler 在隔离作用域上下文内运行;记录 scope 进 SubagentResult。 + * - 超时(opts.timeoutMs):handler 与 timer 竞速,超时转 ok:false(fail-closed)。 + * - handler 抛错:转 ok:false + error 串(绝不向上传播 reject)。 + * + * @param handler 在进程内跑子 agent 任务的函数(注入以便单测 mock)。 + * @param id 注册键;缺省 INLINE_SUBAGENT_ID。需注册多个 inline provider 时传不同 id。 + */ +export class InlineSubagentProvider implements SubagentProvider { + readonly id: string; + private readonly handler: (prompt: string, opts?: { scope?: string }) => Promise; + + constructor( + handler: (prompt: string, opts?: { scope?: string }) => Promise, + id: string = INLINE_SUBAGENT_ID, + ) { + this.handler = handler; + this.id = id; + } + + /** @inheritdoc */ + async spawn(prompt: string, opts?: SubagentSpawnOptions): Promise { + const scope = isolatedSubagentScope(opts?.scope); + try { + const value = await runWithTimeout(this.handler(prompt, { scope }), opts?.timeoutMs); + return { ok: true, value, scope }; + } catch (e) { + return { ok: false, error: errorMessage(e), scope }; + } + } +} + +// ============================================================================ +// SubagentRegistry —— 可注册/解析的子代理表 +// ============================================================================ + +/** + * 子代理 Provider 注册表 —— 维护 id → provider 映射。 + * + * - register(p): 按 p.id 存储,返回 disposer。disposer 只在"仍是同一 provider 实例" + * 时移除——避免后注册的同 id provider 被前者的 disposer 误删(override 安全, + * 与 BoardLinkRegistry / ProviderRegistry 同道)。 + * - resolve(id): fail-closed,未知 id 抛错(无 provider = 拒绝 spawn,不静默回退)。 + * - list(): 只读快照(调用方不可篡改内部状态)。 + * + * 重复 id 视为更新(替换),保证 barrel 重装配 / session resume 幂等安全。 + */ +export class SubagentRegistry { + /** id → provider(插入序,Map 保证)。 */ + private readonly providers = new Map(); + + /** + * 注册一个 provider。重复 id 视为更新(替换),旧 disposer 失效。 + * + * @param provider 子代理 provider。 + * @returns disposer——调用后从注册表移除该 provider(仅当仍是同一实例时移除)。 + */ + register(provider: SubagentProvider): () => void { + this.providers.set(provider.id, provider); + return () => { + if (this.providers.get(provider.id) === provider) { + this.providers.delete(provider.id); + } + }; + } + + /** + * 按 id 解析 provider。 + * + * fail-closed:未知 id 抛错(绝不返回 undefined 让调用方裸调,避免误用未配置子代理)。 + * + * @param id provider 注册键。 + * @returns 匹配的 SubagentProvider。 + * @throws {Error} 未注册该 id。 + */ + resolve(id: string): SubagentProvider { + const provider = this.providers.get(id); + if (!provider) { + throw new Error(`[subagent] no provider registered for id "${id}" (fail-closed)`); + } + return provider; + } + + /** + * 列出全部已注册 provider(只读快照,按插入序)。 + * + * @returns 只读 provider 数组。 + */ + list(): readonly SubagentProvider[] { + return [...this.providers.values()]; + } +} + +// ============================================================================ +// 内部工具 —— 超时竞速 + 错误归一(纯逻辑,无副作用泄漏) +// ============================================================================ + +/** + * handler 与超时竞速。超时 reject(由 spawn 的 catch 转成 ok:false)。 + * + * - ms 缺省/非有限正 → 不限时,直透 promise。 + * - 超时 reject Error("subagent spawn timeout after ms")。 + * - finally 清 timer,防句柄泄漏。 + * + * @param p handler promise。 + * @param ms 超时毫秒(可选)。 + * @returns handler 的值;超时则 reject。 + */ +function runWithTimeout(p: Promise, ms: number | undefined): Promise { + if (ms === undefined || !Number.isFinite(ms) || ms <= 0) return p; + let timer: ReturnType | undefined; + return Promise.race([ + p, + new Promise((_resolve, reject) => { + timer = setTimeout( + () => reject(new Error(`subagent spawn timeout after ${ms}ms`)), + ms, + ); + }), + ]).finally(() => { + if (timer !== undefined) clearTimeout(timer); + }); +} + +/** + * 把 unknown 错误归一为可读串。 + * + * @param e 抛出的值。 + * @returns Error.message 或 String(e)。 + */ +function errorMessage(e: unknown): string { + if (e instanceof Error) return e.message; + return String(e); +} diff --git a/src/capabilities/workflow/index.ts b/src/capabilities/workflow/index.ts new file mode 100644 index 0000000..70f0059 --- /dev/null +++ b/src/capabilities/workflow/index.ts @@ -0,0 +1,172 @@ +/** + * @module capabilities/workflow + * + * 工作流编排原语(T12)—— loop-orchestrator 上层的并发/串行编排引擎。 + * + * 三个纯逻辑原语,正交、单一职责: + * ① parallel —— barrier 原语:全等齐(Promise.allSettled 语义),单 thunk 抛错 + * → 该位落 null(不 reject)。用于编译(宿主)+ 探板(板)+ datasheet RAG + * (宿主)三并发。 + * ② pipeline —— 流水线原语:每 item 过全 stage,stage 间无全局 barrier(item 在 + * 有界并发下独立流过 stage 链),stage 抛错 → item 落 null 跳后续 stage。 + * 用于 edit→compile→flash→verify 串行(单板物理约束下 items 长度=1)。 + * ③ phase —— 进度标记锚点(no-op;记录委托给集成层 T07 事件总线 / pi UI)。 + * + * 设计决策: + * - parallel 不限并发("barrier:全等齐"= 等全部 settle,不是限流)。需限流的 + * 调用方自行分片或用 pipeline(pipeline 按 MAX_CONCURRENCY 限 item 并发)。 + * - pipeline 按 MAX_CONCURRENCY 限 item 并发;每 item 串行过 stage(stage[i+1] + * 需 stage[i] 的 prev)。stage 间无全局 barrier = item 不在 stage 边界等齐 + * 其余 item,可同时处于不同 stage(streaming 语义)。 + * - 结果保序:result[i] 恒对应 items[i](pipeline)/ thunks[i](parallel)。 + * - 无顶层可变状态:runWithConcurrency 是纯函数式并发限制器(cursor 在单线程 + * 事件循环内单调推进,无真并行竞态);phase 是无副作用锚点,绝不持模块级 + * 可变集合(禁隐式全局)。 + * + * 纯逻辑:顶层零 import(无 pi 运行时、无 node 内置依赖),确定性可测。 + * 见架构设计文档_v3.md §7(T12)/ §11(G7 上层 workflow)。 + */ + +// ============================================================================ +// 命名常量 —— 消灭魔法串(并发上限) +// ============================================================================ + +/** + * pipeline 的默认 item 并发上限。 + * + * 物理单板串行场景调用方传 items 长度=1(loop-orchestrator 已强制单板串行); + * 非硬件批处理场景(如多源 datasheet 并行解析)用 8 作合理上限,防 promise 风暴。 + * 深冻结,运行时不可变。 + */ +export const MAX_CONCURRENCY: Readonly = Object.freeze(8) as number; + +// ============================================================================ +// ① parallel —— barrier 原语 +// ============================================================================ + +/** + * 并发执行全部 thunk,等齐后返回(barrier 语义)。 + * + * - 全部 thunk 立即并发启动(map 内调 t())。 + * - 用 Promise.allSettled 等全部 settle:fulfilled → 取 value;rejected → 该位 null。 + * - 单 thunk 抛错绝不向上传播(不 reject),只把对应位落 null;其余位不受影响。 + * - 结果保序:result[i] 对应 thunks[i]。 + * - 空 thunk 数组 → 空结果数组。 + * + * @param thunks 待并发执行的零参 async 函数数组(只读)。 + * @returns 与 thunks 同序的结果数组;rejected thunk 位为 null。 + */ +export async function parallel( + thunks: ReadonlyArray<() => Promise>, +): Promise { + // 用 Promise.resolve().then(t) 包裹每个 thunk:把同步 throw 转成被 allSettled + // 吸收的 rejection(落 null),兑现"单 thunk 抛错绝不向上传播"的不变式—— + // 否则 t() 同步抛错会逃逸 map,allSettled 从未执行,parallel 整体 reject。 + const settled = await Promise.allSettled( + thunks.map((t) => Promise.resolve().then(t)), + ); + return settled.map((s) => (s.status === "fulfilled" ? s.value : null)); +} + +// ============================================================================ +// ② pipeline —— 流水线原语 +// ============================================================================ + +/** + * 把每个 item 串行流过全部 stage,返回每 item 的终态。 + * + * 语义: + * - 每 item 依次过 stage[0] → stage[1] → … → stage[n-1];stage[i+1] 收 stage[i] + * 的返回值作 prev(stage[0] 收 undefined 作 prev)。 + * - stage 间无全局 barrier:item 在 MAX_CONCURRENCY 有界并发下独立流过 stage + * 链,不等待其余 item 在 stage 边界对齐(streaming 语义)。 + * - stage 抛错 → 该 item 落 null,跳过其后续 stage(fail-soft per-item)。 + * - 结果保序:result[i] 恒对应 items[i];未失败 item 的终态 = 末 stage 返回值 + * (stages 为空时终态 = item 本身,identity 语义)。 + * - 空 items → 空结果数组。 + * + * @param items 待流水线处理的 item 数组(只读)。 + * @param stages 有序 stage 函数:`(prev, item, i) => Promise`。 + * @returns 与 items 同序的结果数组;stage 抛错的 item 位为 null。 + */ +export async function pipeline( + items: ReadonlyArray, + ...stages: Array<(prev: unknown, item: T, i: number) => Promise> +): Promise { + const results: unknown[] = new Array(items.length).fill(null); + await runWithConcurrency(items, MAX_CONCURRENCY, async (item, i) => { + let prev: unknown = undefined; + for (const stage of stages) { + try { + prev = await stage(prev, item, i); + } catch { + // stage 抛错:该 item 落 null(results[i] 已初始化为 null),跳后续 stage。 + return; + } + } + // stages 为空 → identity(终态 = item 本身);否则终态 = 末 stage 返回值。 + results[i] = stages.length === 0 ? item : prev; + }); + return results; +} + +// ============================================================================ +// ③ phase —— 进度标记锚点(no-op) +// ============================================================================ + +/** + * 标记一个编排阶段进度。no-op:不影响控制流,无返回值,无副作用。 + * + * "仅记录"= 逻辑上标记阶段边界,但实际记录(日志/UI notify/事件总线 emit) + * 委托给集成层(T07 PbaEventBus emit / pi UI notify)。本函数作为编排代码中 + * 稳定的阶段锚点存在——集成层可在调用点外包 phase 调用来观测进度,而 + * parallel/pipeline 原语本身不耦合观测(保持纯逻辑、可离线单测)。 + * + * 不持模块级可变集合(禁隐式全局);故多次调用彼此独立,无累积状态。 + * + * @param name 阶段名(如 "compile-phase")。 + */ +export function phase(name: string): void { + // no-op 锚点:void name 消费参数防 lint unused 警告,无运行时效果。 + void name; +} + +// ============================================================================ +// 内部:有界并发执行器(纯函数式,cursor 在单线程事件循环内单调推进) +// ============================================================================ + +/** + * 在有界并发下对 items 跑 fn,全部完成后 resolve(barrier)。 + * + * - limit 经 Math.max(1, min(limit, items.length)) 钳制;items 为空立即 resolve。 + * - 起 effectiveLimit 个 worker,每个循环从 cursor 取下一个未处理 item; + * cursor 在单线程事件循环内 ++ 单调推进(await 切点间无真并行,无竞态)。 + * - fn 抛错不阻断其余 item(fn 内部应自行 try/catch 或让 pipeline 的 per-item + * 语义吸收;此执行器把 fn 视为已封装)。 + * + * @param items 待处理 item 数组(只读)。 + * @param limit 并发上限。 + * @param fn 处理单个 item 的函数(收 item + index)。 + */ +async function runWithConcurrency( + items: ReadonlyArray, + limit: number, + fn: (item: T, index: number) => Promise, +): Promise { + if (items.length === 0) return; + const effectiveLimit = Math.max(1, Math.min(limit, items.length)); + let cursor = 0; + const worker = async (): Promise => { + while (cursor < items.length) { + const idx = cursor; + cursor++; + if (idx >= items.length) return; + await fn(items[idx], idx); + } + }; + const workers: Promise[] = []; + for (let w = 0; w < effectiveLimit; w++) { + workers.push(worker()); + } + await Promise.all(workers); +} diff --git a/src/compaction/spill.ts b/src/compaction/spill.ts new file mode 100644 index 0000000..3a13a14 --- /dev/null +++ b/src/compaction/spill.ts @@ -0,0 +1,178 @@ +/** + * @module compaction/spill + * + * 大结果溢出句柄库(T09 第四件)—— 治 datasheet/大回包占爆上下文。 + * + * datasheet RAG 命中的整页文本、i2cdump 全量寄存器表动辄数十 KB,若原样塞进 LLM 上下文 + * 会瞬间超压。spill 把这些大结果暂存进带 brand 的句柄,模型上下文里只留一个不透明 locator, + * 需要时 recall 取回。句柄是 nominal brand(外部不可伪造),只由 SpillStore 发放。 + * + * 纯逻辑:数据存内存 Map(注入式存储可测);TextEncoder 算字节(web 标准,无 pi 依赖); + * evict 按序列化字节大小回收容量。零 pi 运行时依赖,离线可单测。 + * + * 范式:纯逻辑,零依赖,零副作用(除内部 Map 状态),确定性可测。 + * 见架构设计文档_v3.md §6.2。 + */ + +// ============================================================================ +// 命名常量 —— 消灭魔法串 +// ============================================================================ + +/** locator 前缀(brand 之外的明文命名空间,便于诊断)。 */ +const LOCATOR_PREFIX = "pba-spill"; +/** locator 各段分隔符。 */ +const LOCATOR_SEP = ":"; + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** + * 溢出句柄(nominal brand,外部不可伪造)。 + * + * 仅 SpillStore.spill 能产出合法 SpillLocator;recall/has 只认此类型。 + * 运行时底层是字符串,但 TS brand 阻止外部直接构造(brand 字段不导出构造器)。 + */ +export type SpillLocator = string & { readonly __brand: "SpillLocator" }; + +/** 内部存储条目:原始数据 + 序列化字节大小。 */ +interface SpillEntry { + readonly data: unknown; + readonly bytes: number; +} + +// ============================================================================ +// 内部纯函数:locator 构造 + 字节度量 +// ============================================================================ + +/** + * 把 key + 序号封成 SpillLocator(brand 注入,仅本模块可调)。 + * + * @param key 调用方语义键。 + * @param seq 单调序号(同 key 唯一化)。 + * @returns branded locator 句柄。 + */ +function makeLocator(key: string, seq: number): SpillLocator { + return `${LOCATOR_PREFIX}${LOCATOR_SEP}${key}${LOCATOR_SEP}${seq}` as SpillLocator; +} + +/** 全局 TextEncoder(复用,避免反复构造)。 */ +const encoder = new TextEncoder(); + +/** + * 度量任意值的 UTF-8 序列化字节大小(evict 容量回收依据)。 + * + * fail-soft:不可 JSON 序列化(循环)→ 退回 String(value) 的字节长度,不抛错。 + * 注意 JSON.stringify(undefined) 返回 undefined(非字符串、且不抛),故对 try 块 + * 结果做 typeof string 守卫:非字符串一律退回 String(value),杜绝把 undefined 赋给 + * text 后 `text.length` 解引用抛 TypeError(破坏文档化 fail-soft 契约)。 + * + * @param value 任意值。 + * @returns UTF-8 字节长度(≥ 0)。 + */ +function measureBytes(value: unknown): number { + let text: string; + try { + text = JSON.stringify(value); + } catch { + text = String(value); + } + // JSON.stringify 对 undefined/function/symbol 返 undefined(非字符串、不抛), + // 必须退回 String(value) 守卫,否则 text.length 解引用抛 TypeError。 + if (typeof text !== "string") { + text = String(value); + } + if (text.length === 0) return 0; + return encoder.encode(text).length; +} + +// ============================================================================ +// SpillStore +// ============================================================================ + +/** + * 大结果溢出句柄库。 + * + * - spill(key, data):暂存大结果,返 branded locator(上下文里只留 locator)。 + * - recall(locator):取回原数据;未知 locator → undefined(fail-closed)。 + * - has(locator):存在性查询。 + * - evict(olderThanBytes?):容量回收;undefined → 清空全部;否则回收字节 > 阈值的条目。 + * + * 内部用 Map 保持插入序,evict 在超阈值集合内按插入序回收(FIFO 语义)。 + */ +export class SpillStore { + /** 句柄 → 条目(插入序)。 */ + private readonly store = new Map(); + /** key → 已发序号(同 key 的自增计数)。 */ + private readonly seqByKey = new Map(); + + /** + * 暂存大结果,返 branded locator 句柄。 + * + * 同一 key 可多次 spill(序号自增),每次返不同 locator。 + * + * @param key 调用方语义键(如 "datasheet:rmii")。 + * @param data 任意可序列化大结果。 + * @returns branded locator 句柄。 + */ + spill(key: string, data: unknown): SpillLocator { + const seq = (this.seqByKey.get(key) ?? 0) + 1; + this.seqByKey.set(key, seq); + const locator = makeLocator(key, seq); + this.store.set(locator, { data, bytes: measureBytes(data) }); + return locator; + } + + /** + * 取回溢出数据。 + * + * fail-closed:未知 locator(含被 evict 回收的)→ undefined。 + * + * @param locator SpillStore 发放的 branded 句柄。 + * @returns 原数据;不存在时 undefined。 + */ + recall(locator: SpillLocator): unknown { + return this.store.get(locator)?.data; + } + + /** + * 查询 locator 是否仍存活(未被 evict 回收)。 + * + * @param locator branded 句柄。 + * @returns 存在 true;否则 false。 + */ + has(locator: SpillLocator): boolean { + return this.store.has(locator); + } + + /** + * 容量回收。 + * + * - olderThanBytes 缺省:清空全部条目,返回被清条数(full reclaim)。 + * 注意:full reclaim 只清 store,不清 seqByKey —— seq 必须单调续号, + * 否则 evict 后同 key 再 spill 会让 seq 重置为 1,复用刚被回收的 locator 字符串, + * 致已 evict 的旧 locator 引用静默解析为新数据(违反 fail-closed 不变式)。 + * - olderThanBytes 给定:回收序列化字节 > olderThanBytes 的条目(大 blob 优先回收), + * 返回回收条数。阈值用 ">" 而非 ">=" —— 恰等于阈值的条目保留(边界值友好)。 + * + * @param olderThanBytes 字节阈值(可选)。 + * @returns 被回收的条数(≥ 0)。 + */ + evict(olderThanBytes?: number): number { + if (olderThanBytes === undefined) { + const n = this.store.size; + this.store.clear(); + // 故意不清 seqByKey:让 seq 单调续号,evict 后同 key 再 spill 用新 seq, + // 不复用已回收的 locator 字符串(fail-closed 不变式)。 + return n; + } + let evicted = 0; + for (const [loc, entry] of this.store) { + if (entry.bytes > olderThanBytes) { + this.store.delete(loc); + evicted++; + } + } + return evicted; + } +} diff --git a/src/compaction/summarizer.ts b/src/compaction/summarizer.ts new file mode 100644 index 0000000..84bed96 --- /dev/null +++ b/src/compaction/summarizer.ts @@ -0,0 +1,159 @@ +/** + * @module compaction/summarizer + * + * 上下文压缩摘要构建器(T09 第三件)—— compaction 压力触发后的 model-free 摘要。 + * + * 当 token-meter 测出上下文超压时,compaction 需把近期 entry 压成一段摘要喂回模型。 + * 本模块重放稳定前缀(prefix,命中 KV prefix cache)+ append 一条压缩指令(近期 entry 的 + * 结构化摘要),全程不调 LLM(model-free 确定性摘要),故离线可单测。 + * + * reusedPrefix 语义:prefix 非空 → 标记 true(前缀是已缓存段的逐字重放,模型 KV prefix + * cache 可复用,不重算);prefix 空 → false(冷启动,无前缀可复用)。 + * + * 范式:纯逻辑,仅 import type 自 T06 surface + import 同仓 token-meter; + * 零 pi 运行时依赖,零副作用,确定性可测。见架构设计文档_v3.md §5.1 / §6.2。 + */ + +import type { PbaSessionEntry } from "../core/pba-session.js"; +import { estimateTokens } from "./token-meter.js"; + +// ============================================================================ +// 命名常量 —— 消灭魔法串/魔法数 +// ============================================================================ + +/** 压缩指令的标题(摘要正文里标记压缩段起点)。 */ +const DIRECTIVE_HEADER = "## Compaction Summary"; +/** 单条 entry 摘要的最大字符数(超出加省略号,控制摘要体积)。 */ +const DIGEST_MAX_CHARS = 120; +/** 摘要省略号。 */ +const ELLIPSIS = "…"; + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** + * compaction 摘要结果。 + * + * @property summary 重放前缀 + 压缩指令 + 近期 entry 摘要(受 maxTokens 约束)。 + * @property reusedPrefix 是否复用了非空前缀(KV prefix cache 命中语义)。 + * @property droppedEntries 被压缩进摘要、从活跃上下文移除的 entry 数。 + */ +export interface CompactionSummary { + readonly summary: string; + readonly reusedPrefix: boolean; + readonly droppedEntries: number; +} + +/** recentEntries 元素形状:取自 T06 surface entry 的 {type,data} 投影。 */ +type RecentEntry = Pick; + +// ============================================================================ +// 内部纯函数:entry 摘要 + token 预算裁剪 +// ============================================================================ + +/** + * 把单条 entry 压成一行摘要(type + 截断后的 data JSON)。 + * + * fail-soft:data 不可 JSON 序列化(含循环)→ 退回 "[unserializable]"。 + * + * @param entry 会话 entry(type + data)。 + * @returns 形如 `- tool-result: {"name":"i2cdump",...}` 的摘要行。 + */ +function digestEntry(entry: RecentEntry): string { + let body: string; + try { + body = JSON.stringify(entry.data); + } catch { + body = "[unserializable]"; + } + if (body.length > DIGEST_MAX_CHARS) { + body = body.slice(0, DIGEST_MAX_CHARS) + ELLIPSIS; + } + return `- ${entry.type}: ${body}`; +} + +/** + * 在 token 预算内从最新端保留尽可能多的摘要行(drop 最旧的)。 + * + * 摘要行按时间顺序 oldest→newest;超预算时从头部丢弃最旧行,保留最新上下文。 + * base(前缀+指令)始终保留不被裁剪(前缀是 KV cache 复用段,不可截断)。 + * + * @param digestLines entry 摘要行数组(oldest→newest)。 + * @param base 基础文本(前缀 + 指令头,始终保留)。 + * @param maxTokens token 预算上限。 + * @returns 保留的摘要行数组 + 是否裁剪过。 + */ +function fitDigestsToBudget( + digestLines: readonly string[], + base: string, + maxTokens: number, +): { kept: string[]; trimmed: boolean } { + const kept = [...digestLines]; + let trimmed = false; + // 估算 base + 当前 kept 的总 token;超预算则从最旧端(头部)逐行丢弃。 + const estimateAll = (): number => + estimateTokens(base) + + (kept.length > 0 ? estimateTokens(kept.join("\n")) : 0); + + while (kept.length > 0 && estimateAll() > maxTokens) { + kept.shift(); + trimmed = true; + } + // base 自身超预算时:不再加摘要行(前缀不可截断,仅记录裁剪)。 + if (kept.length === 0 && estimateTokens(base) > maxTokens) { + trimmed = digestLines.length > 0; + } + return { kept, trimmed }; +} + +// ============================================================================ +// 主入口 +// ============================================================================ + +/** + * 构建 compaction 摘要:重放前缀 + append 压缩指令 + 近期 entry 摘要。 + * + * 流程(确定性、model-free): + * 1. reusedPrefix = prefix.trim() 非空; + * 2. base = [prefix?, DIRECTIVE_HEADER + 计数说明]; + * 3. 为每条 recentEntry 生成一行摘要(type + 截断 data JSON); + * 4. 在 maxTokens 预算内从最新端保留尽可能多摘要行(drop 最旧); + * 5. summary = base + 保留摘要行;droppedEntries = recentEntries.length。 + * + * 前缀始终保留(KV prefix cache 复用语义,不可截断);超预算只裁摘要行。 + * + * @param opts.prefix 稳定前缀(已缓存段的逐字重放)。 + * @param opts.recentEntries 近期会话 entry(type + data,oldest→newest)。 + * @param opts.maxTokens 摘要 token 预算上限。 + * @returns compaction 摘要结果。 + */ +export function buildCompactionSummary(opts: { + prefix: string; + recentEntries: ReadonlyArray; + maxTokens: number; +}): CompactionSummary { + const { prefix, recentEntries, maxTokens } = opts; + const reusedPrefix = prefix.trim().length > 0; + + const directiveLine = + `${DIRECTIVE_HEADER}\n` + + `${recentEntries.length} recent entries compacted (model-free digest):`; + + const baseParts: string[] = []; + if (reusedPrefix) baseParts.push(prefix); + baseParts.push(directiveLine); + const base = baseParts.join("\n\n"); + + const digestLines = recentEntries.map(digestEntry); + const { kept } = fitDigestsToBudget(digestLines, base, maxTokens); + + const summary = + kept.length > 0 ? `${base}\n${kept.join("\n")}` : base; + + return { + summary, + reusedPrefix, + droppedEntries: recentEntries.length, + }; +} diff --git a/src/compaction/token-meter.ts b/src/compaction/token-meter.ts new file mode 100644 index 0000000..21dc50d --- /dev/null +++ b/src/compaction/token-meter.ts @@ -0,0 +1,88 @@ +/** + * @module compaction/token-meter + * + * 上下文 token 估算 —— compaction 的压力触发器(T09 第一件)。 + * + * 嵌入式 agent 的工具输出(i2cdump/gdb/dmesg)动辄数 KB,会快速吃满模型上下文窗。 + * token-meter 给 compaction 一个 model-free 的 token 估算,供 summarizer 判断"何时压" + * 与"压完多大"。不依赖任何 tokenizer(pi 运行时无依赖),故离线可单测。 + * + * 启发式(文档化、确定性): + * - ASCII/拉丁部分:chars/4(OpenAI 系 tokenizer 的经验上界,glm-5.2 同量级) + * - CJK 统一表意部分:每 char 计 1 token(CJK 常被逐字切分,char 计更准) + * - 二者叠加取整上界,空串返回 0 + * + * 范式:纯逻辑,零依赖,零副作用,确定性可测。见架构设计文档_v3.md §5.1 / §6.2。 + */ + +// ============================================================================ +// 命名常量 —— 消灭魔法数 +// ============================================================================ + +/** 非部分每 N 字符折算 1 token(OpenAI/glm 经验上界)。 */ +const LATIN_CHARS_PER_TOKEN = 4; +/** 每条消息的角色/结构开销 token(role tag + 分隔符的保守估算)。 */ +const PER_MESSAGE_OVERHEAD_TOKENS = 4; + +/** + * CJK 统一表意 + 扩展 A + 兼容表意的字符集(逐字计 1 token)。 + * 深冻结:仅作为 RegExp 源字符范围,不运行时改写。 + */ +const CJK_PATTERN = /[一-鿿㐀-䶿豈-﫿]/g; + +// ============================================================================ +// 估算原语 +// ============================================================================ + +/** + * 统计文本中的 CJK 表意字符数(逐字计 token 的来源)。 + * + * @param text 任意文本。 + * @returns CJK 字符出现次数(非 CJK 计 0)。 + */ +function countCjk(text: string): number { + let n = 0; + for (const _ of text.matchAll(CJK_PATTERN)) n++; + return n; +} + +/** + * 估算一段文本的 token 数(model-free 启发)。 + * + * - 空串 → 0 + * - CJK 部分:每 char 计 1 token + * - 非 CJK 部分:⌈len/4⌉ token + * - 二者相加 + * + * 确定性:同一输入恒同输出;不调任何 tokenizer,离线可测。 + * + * @param text 待估文本。 + * @returns token 估算值(≥ 0 整数)。 + */ +export function estimateTokens(text: string): number { + if (text.length === 0) return 0; + const cjk = countCjk(text); + const nonCjk = text.length - cjk; + const nonCjkTokens = Math.ceil(nonCjk / LATIN_CHARS_PER_TOKEN); + return cjk + nonCjkTokens; +} + +/** + * 估算一组消息的总上下文 token 数(含每条消息的结构开销)。 + * + * 对每条消息累加 `estimateTokens(content) + PER_MESSAGE_OVERHEAD_TOKENS`, + * 反映 role 标签/分隔符在真实上下文里的固定开销。空消息数组 → 0。 + * + * @param messages 模型消息序列(只读,不修改)。 + * @returns 总 token 估算值(≥ 0 整数)。 + */ +export function measureContext( + messages: ReadonlyArray<{ role: string; content: string }>, +): number { + let total = 0; + for (const m of messages) { + if (!m) continue; + total += estimateTokens(m.content ?? "") + PER_MESSAGE_OVERHEAD_TOKENS; + } + return total; +} diff --git a/src/compaction/tool-result-pruner.ts b/src/compaction/tool-result-pruner.ts new file mode 100644 index 0000000..c05db2d --- /dev/null +++ b/src/compaction/tool-result-pruner.ts @@ -0,0 +1,227 @@ +/** + * @module compaction/tool-result-pruner + * + * 工具大输出 model-free 压缩(T09 第二件)—— 治嵌入式场景的工具回包爆窗。 + * + * i2cdump 一片寄存器表 ~256 行、gdb backtrace 数十帧、dmesg 滚屏数百行, + * 原样喂模型既吃 token 又模糊重点。本模块按工具语义保留诊断关键行、丢弃噪声, + * 全程不调 LLM(model-free),确定性可离线单测。 + * + * 四类工具的保留语义(fail-soft:格式不符时退回首尾行,绝不丢全部上下文): + * - i2cdump 保留寄存器地址行(0xXX:/XX: 格式)+ 最后 dump 行;preservedAddrs 回传地址标签 + * - gdb 保留 #frame 行(#0/#1… 栈帧头) + * - dmesg 保留 error/critical/warn 行(含 dmesg 级别标记 <0..4>) + * - general 截断到 maxLines(默认 200 行) + * + * 范式:纯逻辑,零依赖,零副作用,确定性可测。见架构设计文档_v3.md §6.2。 + */ + +// ============================================================================ +// 命名常量 —— 消灭魔法串/魔法数 +// ============================================================================ + +/** general 工具未指定 maxLines 时的默认截断行数。 */ +const DEFAULT_GENERAL_MAX_LINES = 200; +/** 单条 entry 摘要截断字符数(summarizer 用,本模块引用统一来源)。 */ + +/** i2cdump 寄存器地址行:可选 0x 前缀 + 1~4 位十六进制 + 冒号。 */ +const I2C_ADDR_LINE = /^(?:0x[0-9a-fA-F]+|[0-9a-fA-F]{1,4}):/; +/** i2cdump 地址标签提取(冒号前的部分,含 0x 前缀)。 */ +const I2C_ADDR_LABEL = /^(0x[0-9a-fA-F]+|[0-9a-fA-F]{1,4}):/; +/** gdb 栈帧行:#数字 开头。 */ +const GDB_FRAME_LINE = /^#\d+\b/; +/** dmesg 级别标记 <0..4>(emerg/alert/crit/err/warn)。 */ +const DMESG_LEVEL = /<[0-4]>/; +/** dmesg 关键字(error/critical/warn 及常见缩写,大小写不敏感)。 */ +const DMESG_KEYWORD = /error|critical|warn/i; + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** 可剪枝的工具类别(每类有独立保留语义)。 */ +export type PruneToolKind = "i2cdump" | "gdb" | "dmesg" | "general"; + +/** + * 剪枝选项。 + * + * @property tool 工具类别(决定保留语义)。 + * @property maxLines 仅 general 用:保留的最大行数(缺省 DEFAULT_GENERAL_MAX_LINES)。 + */ +export interface PruneOptions { + readonly tool: PruneToolKind; + readonly maxLines?: number; +} + +/** + * 剪枝结果。 + * + * @property pruned 剪枝后的内容(保留行用 \n 连接)。 + * @property dropped 被丢弃的行数(原总行数 - 保留行数)。 + * @property preservedAddrs 仅 i2cdump:被保留的寄存器地址标签列表(0xXX/XX)。 + */ +export interface PruneResult { + readonly pruned: string; + readonly dropped: number; + readonly preservedAddrs?: string[]; +} + +// ============================================================================ +// 内部纯函数:行切割 + 首尾兜底 +// ============================================================================ + +/** + * 按行切割文本,保留行序(不去空行,计数忠实于原始结构)。 + * + * @param content 原始文本。 + * @returns 行数组(空串 → [""];统一不返回尾随空元素除非原文本以换行结尾)。 + */ +function splitLines(content: string): string[] { + if (content.length === 0) return [""]; + return content.split("\n"); +} + +/** + * 取最后一个非空行(i2cdump 的"最后 dump 行")。 + * + * @param lines 行数组。 + * @returns 最后一个 trim 后非空的行;全空 → null。 + */ +function lastNonEmptyLine(lines: readonly string[]): string | null { + for (let i = lines.length - 1; i >= 0; i--) { + const ln = lines[i]; + if (ln && ln.trim().length > 0) return ln; + } + return null; +} + +/** + * fail-soft 兜底:当按工具语义一行都没保留到时,退回首尾行,避免上下文全丢。 + * + * @param lines 行数组。 + * @returns 兜底保留行集合(去重后的行,保持原序)。 + */ +function fallbackBookends(lines: readonly string[]): string[] { + const first = lines[0] ?? ""; + const last = lastNonEmptyLine(lines); + if (first.length === 0 && last === null) return []; + if (last === null || last === first) return [first]; + return [first, last]; +} + +/** + * 按谓词过滤行,记录被保留行下标,返回保留行 + 保留下标集合。 + * + * @param lines 行数组。 + * @param pred 保留谓词。 + * @returns 保留行数组、保留下标 Set。 + */ +function selectBy( + lines: readonly string[], + pred: (ln: string) => boolean, +): { kept: string[]; keptIdx: Set } { + const kept: string[] = []; + const keptIdx = new Set(); + for (let i = 0; i < lines.length; i++) { + const ln = lines[i]; + if (pred(ln)) { + kept.push(ln); + keptIdx.add(i); + } + } + return { kept, keptIdx }; +} + +// ============================================================================ +// 四类工具的保留谓词 +// ============================================================================ + +/** i2cdump 寄存器地址行谓词。 */ +const isI2cAddrLine = (ln: string): boolean => I2C_ADDR_LINE.test(ln); +/** gdb 栈帧行谓词。 */ +const isGdbFrameLine = (ln: string): boolean => GDB_FRAME_LINE.test(ln); +/** dmesg error/critical/warn 行谓词(级别标记或关键字)。 */ +const isDmesgSevereLine = (ln: string): boolean => + DMESG_LEVEL.test(ln) || DMESG_KEYWORD.test(ln); + +/** + * 从 i2cdump 地址行提取地址标签(冒号前部分)。 + * + * @param ln 地址行。 + * @returns 地址标签(如 "00"/"0x10");不匹配时 null。 + */ +function extractAddr(ln: string): string | null { + const m = I2C_ADDR_LABEL.exec(ln); + return m ? m[1] ?? null : null; +} + +// ============================================================================ +// 主入口 +// ============================================================================ + +/** + * 按工具语义剪枝工具回包,保留诊断关键行、丢弃噪声。 + * + * - i2cdump:保留寄存器地址行 + 最后 dump 行;preservedAddrs 回传地址标签; + * 一行都没匹配则退回首尾行(fail-soft,不丢全部上下文)。 + * - gdb:保留 #frame 行;无帧则退回首尾行。 + * - dmesg:保留 error/critical/warn 行;benign dmesg 无匹配 → pruned 为空(正确语义)。 + * - general:截断到 maxLines(默认 200);超出即丢弃。 + * + * 不变量:`dropped === lines.length - preservedLines`;空内容 → { pruned:"", dropped:0 }。 + * + * @param content 工具原始回包文本。 + * @param opts 剪枝选项(tool 必填,maxLines 仅 general 用)。 + * @returns 剪枝结果。 + */ +export function pruneToolResult(content: string, opts: PruneOptions): PruneResult { + if (content.length === 0) { + return { pruned: "", dropped: 0, preservedAddrs: opts.tool === "i2cdump" ? [] : undefined }; + } + const lines = splitLines(content); + + if (opts.tool === "general") { + const limit = opts.maxLines ?? DEFAULT_GENERAL_MAX_LINES; + const max = Math.max(0, limit); + const kept = lines.slice(0, max); + const dropped = lines.length - kept.length; + return { pruned: kept.join("\n"), dropped }; + } + + if (opts.tool === "i2cdump") { + const { kept, keptIdx } = selectBy(lines, isI2cAddrLine); + const addrs: string[] = []; + for (const ln of kept) { + const a = extractAddr(ln); + if (a !== null && !addrs.includes(a)) addrs.push(a); + } + // 最后 dump 行:取最后一个非空行,若未被地址谓词保留则补入(去重)。 + const tail = lastNonEmptyLine(lines); + let preserved = kept; + const preservedIdx = new Set(keptIdx); + if (tail !== null) { + const tailIdx = lines.lastIndexOf(tail); + if (tailIdx >= 0 && !preservedIdx.has(tailIdx)) { + preserved = [...kept, tail]; + preservedIdx.add(tailIdx); + } + } + if (preserved.length === 0) preserved = fallbackBookends(lines); + return { + pruned: preserved.join("\n"), + dropped: lines.length - preserved.length, + preservedAddrs: addrs, + }; + } + + if (opts.tool === "gdb") { + const { kept } = selectBy(lines, isGdbFrameLine); + const preserved = kept.length > 0 ? kept : fallbackBookends(lines); + return { pruned: preserved.join("\n"), dropped: lines.length - preserved.length }; + } + + // dmesg + const { kept } = selectBy(lines, isDmesgSevereLine); + // benign dmesg(无 error/warn)→ pruned 为空是正确语义,不兜底。 + return { pruned: kept.join("\n"), dropped: lines.length - kept.length }; +} diff --git a/src/core/checkpoint-state.ts b/src/core/checkpoint-state.ts new file mode 100644 index 0000000..d5983fb --- /dev/null +++ b/src/core/checkpoint-state.ts @@ -0,0 +1,284 @@ +/** + * @module checkpoint-state + * + * plan/goal/todo logged state(T14)—— 闭环 checkpoint 进度的事件溯源记录器。 + * + * 治嵌入式开发场景缺陷:闭环每轮(edit→compile→flash→verify→check→done) + * 的进度状态须持久化进 session 事件 log,使 session resume / fork 子任务后 + * 能从 log 重建 checkpoint 状态,不丢进度、不重跑已通过步骤。 + * + * 三件事(纯逻辑,append 注入,零 pi 运行时依赖,离线可单测): + * ① record —— 推进 checkpoint 状态 + 写一条 "checkpoint-change" 事件 + * (data = 全量 CheckpointState 快照,含完整 history)。 + * ② current —— 读当前 CheckpointState(深拷贝,防外部篡改)。 + * ③ rebuild —— 从 log entries 重建状态(resume 用:取最后一条 + * checkpoint-change 快照,回填内部状态)。 + * fork —— 从当前状态 fork 出子记录器(子任务独立推进,共享 append sink)。 + * + * 与 loop-orchestrator(src/extensions/loop-orchestrator.ts)的关系: + * loop-orchestrator 的 CheckpointMachine 是扩展层的同进程状态机单例, + * advance + serialize + restore 全在扩展内。本模块把 checkpoint 进度的 + * 持久化下沉为可注入的核心层记录器——append 注入 PbaSession.append(T06), + * 事件 type="checkpoint-change" 与 PbaSessionEventMap 对齐 + * (src/core/pba-session.ts:92),resume 时从 PbaSession.getEntries() 重建。 + * + * 推进逻辑复用 CheckpointMachine.advance 的已证范式(src/extensions/loop-orchestrator.ts:200): + * - passed + 末步(done) → 停在 done,stepPassed=true。 + * - passed + 非末步且 nextStep 在 currentStep 之后 → 前进,stepPassed 重置 false。 + * - passed + 已到/已过 → 不回退(重入补跑仅记 history)。 + * - failed → 停在该步(退回重试),stepPassed=false。 + * 差异:timestamp 由调用方注入(确定性可测),不内部取 Date.now()。 + * + * 范式:纯逻辑模块,顶层仅 import type(shared/types),无 pi 运行时依赖; + * 深冻结常量;fail-closed(非法 step 兜底;rebuild 缺 checkpoint-change 则回初始态)。 + * 见架构设计文档_v3.md §5.1。 + */ + +import type { CheckpointState, CheckpointStep } from "../shared/types.js"; + +// ============================================================================ +// 命名常量 —— 消灭魔法串(事件 type / 步骤序 / 初始态) +// ============================================================================ + +/** checkpoint 进度写入 session 的事件类型(与 PbaSessionEventMap 对齐)。 */ +export const CHECKPOINT_CHANGE_TYPE = "checkpoint-change" as const; + +/** + * 闭环 6 步顺序(与 loop-orchestrator STEP_ORDER 一致,深冻结)。 + * + * edit → compile → flash → verify → check → done。 + */ +export const STEP_ORDER: readonly CheckpointStep[] = Object.freeze([ + "edit", + "compile", + "flash", + "verify", + "check", + "done", +] as const); + +/** 初始 checkpoint 状态(深冻结,运行时不可变)。 */ +export const INITIAL_CHECKPOINT_STATE: CheckpointState = Object.freeze({ + currentStep: "edit", + stepPassed: false, + history: Object.freeze([]) as readonly { step: CheckpointStep; passed: boolean; timestamp: number }[], +} as CheckpointState); + +// ============================================================================ +// 类型守卫 —— rebuild 时校验 log entry data 形状 +// ============================================================================ + +/** + * 判定一个值是否是合法的 CheckpointState(rebuild 前校验,fail-tolerant 跳过坏条)。 + * + * @param value 任意值。 + * @returns true=合法 CheckpointState。 + */ +function isCheckpointState(value: unknown): value is CheckpointState { + if (value === null || typeof value !== "object") return false; + const s = value as Record; + if (typeof s.currentStep !== "string") return false; + // 拒绝越界 currentStep:须为 STEP_ORDER 内的合法步骤串,防篡改/坏快照。 + // 否则 advanceState 以 state.currentStep 算 curIdx=STEP_ORDER.indexOf(...)=-1, + // 使后续 record 的 targetIdx>-1 恒成立,可从被篡改/损坏的快照 + // (currentStep='bogus' 等)向前跳过 edit→compile→flash→verify→check→done + // 的正常推进门——例如 rebuild({currentStep:'bogus'}) 后 record('check',true) + // 会把 currentStep 直接跳到 'done',再 record('done',true) 即伪造完成态。 + // 坏快照在此被拒 → rebuild 回初始态(fail-closed)。 + if (!STEP_ORDER.includes(s.currentStep as CheckpointStep)) return false; + if (typeof s.stepPassed !== "boolean") return false; + if (!Array.isArray(s.history)) return false; + return s.history.every( + (h) => + h !== null && + typeof h === "object" && + typeof (h as Record).step === "string" && + typeof (h as Record).passed === "boolean" && + typeof (h as Record).timestamp === "number", + ); +} + +// ============================================================================ +// 内部纯函数:状态推进 + 深拷贝 +// ============================================================================ + +/** + * 深拷贝 CheckpointState(防外部/内部引用共享)。 + * + * @param s 源状态。 + * @returns 独立拷贝(history 每条也浅拷贝)。 + */ +function cloneState(s: CheckpointState): CheckpointState { + return { + currentStep: s.currentStep, + stepPassed: s.stepPassed, + history: Array.isArray(s.history) + ? s.history.map((h) => ({ step: h.step, passed: h.passed, timestamp: h.timestamp })) + : [], + }; +} + +/** + * 推进 checkpoint 状态(复用 CheckpointMachine.advance 已证范式)。 + * + * 语义见模块头。纯函数:修改传入的 state 对象(调用方负责传入可变拷贝)。 + * + * @param state 要推进的状态(原地修改)。 + * @param step 执行的步骤。 + * @param passed 该步骤是否通过。 + * @param timestamp 记录时刻(epoch ms)。 + */ +function advanceState( + state: CheckpointState, + step: CheckpointStep, + passed: boolean, + timestamp: number, +): void { + state.history.push({ step, passed, timestamp }); + + const idx = STEP_ORDER.indexOf(step); + if (idx < 0) return; // 未知 step:仅记 history,不动 currentStep + const curIdx = STEP_ORDER.indexOf(state.currentStep); + + if (passed) { + if (idx === STEP_ORDER.length - 1) { + // done 通过:停在 done。守卫 idx <= curIdx:终态通过只在已抵达 done 时生效, + // 禁止从早期步骤(如 edit)向前跳伪造到达终态 done 的完成表象。 + // 与 failed 分支(下文 idx <= curIdx)对称——失败不向前跳伪造进度, + // 通过亦不向前跳伪造完成态。idx > curIdx 时仅记 history,不置 stepPassed=true。 + if (idx <= curIdx) { + state.currentStep = step; + state.stepPassed = true; + } + } else { + const targetIdx = idx + 1; + // 只前进不回退:target 在 currentStep 之后才推进 + if (targetIdx > curIdx) { + state.currentStep = STEP_ORDER[targetIdx] as CheckpointStep; + state.stepPassed = false; + } + // targetIdx <= curIdx:已到或已过,不回退(重入补跑仅记 history) + } + } else { + // 失败:退回该步重试。守卫 idx <= curIdx:失败只退回/停留,不向前跳 + // (与 passed 路径的单调不变式对称——禁止经失败到达尚未抵达的步骤, + // 尤其禁止经失败伪造到达终态 done 的进度表象)。 + if (idx <= curIdx) { + state.currentStep = step; + state.stepPassed = false; + } + // idx > curIdx:失败一个在 currentStep 之后的步骤,不前进(仅记 history) + } +} + +// ============================================================================ +// CheckpointRecorder —— 事件溯源记录器 +// ============================================================================ + +/** append 注入函数的入参形状(与 PbaSession.append 一致)。 */ +export interface CheckpointAppendEntry { + /** 事件类型(开放 string)。 */ + type: string; + /** 事件载荷。 */ + data: unknown; +} + +/** + * 闭环 checkpoint 进度的事件溯源记录器。 + * + * append 注入 PbaSession.append(或独立 sink);record 推进状态并写一条 + * "checkpoint-change" 事件;current 返回深拷贝;rebuild 从 log 重建(resume); + * fork 从当前状态派生子记录器(子任务独立推进)。 + * + * 纯逻辑:append 注入,无 pi 运行时依赖,离线可单测。 + */ +export class CheckpointRecorder { + /** 注入的提交下沉(PbaSession.append 或测试 mock)。record 经此写出事件。 */ + private readonly appendFn: (entry: CheckpointAppendEntry) => void; + /** 可变内部状态(record/rebuild 修改,current 返回拷贝)。 */ + private state: CheckpointState; + + /** + * @param opts.append 注入的提交下沉(PbaSession.append 或 mock)。record 唯一提交点经此写出。 + */ + constructor(opts: { append: (entry: CheckpointAppendEntry) => void }) { + this.appendFn = opts.append; + this.state = cloneState(INITIAL_CHECKPOINT_STATE); + } + + /** + * 推进 checkpoint 状态并写一条 "checkpoint-change" 事件进 session。 + * + * 推进语义见模块头(复用 CheckpointMachine.advance 范式,timestamp 注入)。 + * 写出的 data 是推进后的全量 CheckpointState 快照(含完整 history)。 + * + * @param step 执行的步骤。 + * @param passed 该步骤是否通过。 + * @param timestamp 记录时刻(epoch ms,注入以保确定性可测)。 + */ + record(step: CheckpointStep, passed: boolean, timestamp: number): void { + advanceState(this.state, step, passed, timestamp); + const snapshot = cloneState(this.state); + this.appendFn({ type: CHECKPOINT_CHANGE_TYPE, data: snapshot }); + } + + /** + * 读当前 checkpoint 状态(深拷贝,防外部篡改内部状态)。 + * + * @returns 当前 CheckpointState 的独立拷贝。 + */ + current(): CheckpointState { + return cloneState(this.state); + } + + /** + * 从 log entries 重建 checkpoint 状态(resume 用)。 + * + * 扫描 entries,取最后一条 type="checkpoint-change" 且 data 合法的快照, + * 回填内部状态。无 checkpoint-change 条目时回初始态(全新 session)。 + * + * fail-tolerant:缺字段/乱序/坏条静默跳过,不抛异常(旧 session 不崩)。 + * entries 非数组(null/undefined/number/object 等)时静默回初始态, + * 不抛 TypeError(与 fail-tolerant 姿态一致)。重建后 current() 返回重建 + * 状态,record() 在重建基础上继续推进。 + * + * @param entries pi session 的 entry 列表(只读,不修改)。 + * @returns 重建后的 CheckpointState(独立拷贝)。 + */ + rebuild(entries: ReadonlyArray<{ type: string; data: unknown }>): CheckpointState { + let rebuilt: CheckpointState | null = null; + // 非数组(null/undefined/number/object 等):静默回初始态,不抛 TypeError + if (!Array.isArray(entries)) { + this.state = cloneState(INITIAL_CHECKPOINT_STATE); + return cloneState(this.state); + } + for (const entry of entries) { + if (!entry || typeof entry.type !== "string") continue; + if (entry.type !== CHECKPOINT_CHANGE_TYPE) continue; + if (isCheckpointState(entry.data)) { + // 每条 checkpoint-change 是全量快照,取最后一条胜出 + rebuilt = cloneState(entry.data); + } + } + if (rebuilt !== null) { + this.state = rebuilt; + } else { + this.state = cloneState(INITIAL_CHECKPOINT_STATE); + } + return cloneState(this.state); + } + + /** + * 从当前状态 fork 出子记录器(子任务独立推进)。 + * + * 子记录器共享父的 append sink(写进同一 session),但拥有父状态的独立拷贝。 + * 子的 record 不影响父的 current(),反之亦然。 + * + * @returns 从当前状态派生的新 CheckpointRecorder。 + */ + fork(): CheckpointRecorder { + const child = new CheckpointRecorder({ append: this.appendFn }); + child.state = cloneState(this.state); + return child; + } +} diff --git a/src/core/context-injector.ts b/src/core/context-injector.ts new file mode 100644 index 0000000..30f796f --- /dev/null +++ b/src/core/context-injector.ts @@ -0,0 +1,418 @@ +/** + * @module context-injector + * + * 上下文注入三段(T13)—— inject / steer / followup 三段语义区分的 + * runtime-context 注入器 + 快照"取代更早快照"不变量。 + * + * 场景锚定:嵌入式闭环 agent 跨 turn / 跨 step 的上下文干预有三类截然不同的意图, + * pi 的 sendMessage 只给 deliverAs("steer"/"followUp"/"nextTurn") 开关,缺语义层抽象: + * + * ① inject —— 寄存器表 next-step,NO wake:把寄存器映射表 / 设备树片段 / datasheet + * 摘要登记进 runtime-context,下一 step 生效,但不主动唤醒 agent(被动补料, + * 不打断当前工具流水线)。对应 deliverAs 不触发。 + * ② steer —— 换板 next-step 唤醒:切到另一块目标板(X5→S100),标记 replacesSnapshot + * 取代更早快照,下一 step 唤醒 agent 重新定向。对应 deliverAs:"steer"。 + * ③ followup—— 新任务 next-turn 唤醒:用户派新任务("烧新 bootloader"),next-turn 唤醒, + * 取代更早快照。对应 deliverAs:"followUp"/"nextTurn"。 + * + * "runtime-context 快照取代更早快照":每次 snapshot() 全量捕获当前 live 注入集合, + * 新快照即刻取代所有更早快照(仅最新快照为"the"runtime-context)。steer/followup + * 通过 replacesSnapshot 指向被取代的快照 id,显式声明取代关系。live 注入集合 = + * 最近一次 steer/followup(含)之后的所有 inject 累积(无 steer/followup 则全部 live), + * 体现"寄存器表累积 + 换板/新任务刷新"语义。 + * + * 纯逻辑:appendEntry 下沉由构造注入(PbaSession.append 适配或测试 mock),顶层仅 + * `import type`(esbuild 擦除),无 pi 运行时依赖,离线可单测。深冻结常量 + fail-closed + * (空 content / 未知 phase 抛错)。见架构设计文档_v3.md §6.3 T13。 + */ + +import type { PbaSessionEntry } from "../core/pba-session.js"; + +// ============================================================================ +// 命名常量 —— 消灭魔法串(phase 合法集 / 注入事件 type / 快照 id 前缀) +// ============================================================================ + +/** + * 三段注入 phase 合法集合。深冻结。 + * + * inject=寄存器表被动补料 / steer=换板 next-step 唤醒 / followup=新任务 next-turn 唤醒。 + */ +export const INJECTION_PHASES = Object.freeze(["inject", "steer", "followup"] as const) as readonly InjectionPhase[]; + +/** appendEntry 下沉用的事件 type(落 PbaSession 后跨 session resume 可重放)。 */ +export const CONTEXT_INJECTION_TYPE = "context-injection" as const; + +/** 内部快照 id 前缀(不外泄,仅供 replacesSnapshot 引用)。 */ +const SNAPSHOT_ID_PREFIX = "snap-" as const; + +/** + * trim() 不剥离的 Unicode Default_Ignorable / 零宽字符集。 + * + * String.prototype.trim() 只剥 Unicode White_Space 属性(含 U+FEFF BOM/ZWNBSP, + * 自 ES2019 起并入 WhiteSpace production),不剥其余 Default_Ignorable_Code_Point: + * U+200B 零宽空格 / U+200C ZWNJ / U+200D ZWJ / U+2060 WORD JOINER / + * U+2061–206F 不可见数学/格式符。这些字符视觉上不可见,纯由其组成的 content + * 等价于空串,会绕过 fail-closed 掩盖调用方 bug,故 assertContent 须先手动 + * 剥除再判空(见 findings[]:trim-only 判空被 U+200B 绕过)。 + * + * 注:U+FEFF 不在此列——trim() 已剥离它(见 findings[]:列入 regex 为冗余覆盖, + * 行为虽正确但属 dead-branch,故移除以保持集合语义为"trim 真正不剥的字符")。 + */ +const INVISIBLE_CHARS = /[\u200B\u200C\u200D\u2060-\u206F]/g; + +// ============================================================================ +// 类型契约 —— 下游模块依赖这些名字,不得擅自改名 +// ============================================================================ + +/** 注入阶段。 */ +export type InjectionPhase = "inject" | "steer" | "followup"; + +/** + * 一条上下文注入。 + * + * - phase —— inject / steer / followup 三段之一。 + * - content —— 注入文本(寄存器表片段 / 换板指令 / 新任务 prompt)。 + * - boardId —— steer 携带目标板 id;inject/followup 不带(undefined)。 + * - nextStep —— true=下一 step 生效(inject/steer);false=不绑 step(followup)。 + * - nextTurn —— true=下一 turn 唤醒(followup);false=不绑 turn(inject/steer)。 + * - replacesSnapshot —— 声明取代的更早快照 id(steer/followup 取代 prior runtime-context; + * inject 不取代,undefined)。仅在 prior snapshot 存在时填充。 + */ +export interface Injection { + readonly phase: InjectionPhase; + readonly content: string; + readonly boardId?: string; + readonly nextStep: boolean; + readonly nextTurn: boolean; + readonly replacesSnapshot?: string; +} + +/** + * runtime-context 快照:某一时刻 live 注入集合的全量捕获。每次调用取代更早快照。 + */ +export interface RuntimeSnapshot { + /** 合并后的 live 注入文本(live 注入按序 "\n\n" 拼接;空集合 → "")。 */ + readonly content: string; + /** live 注入中最新 boardId(steer 的板;无 steer → undefined)。 */ + readonly boardId?: string; + /** 捕获时刻(epoch ms)。 */ + readonly ts: number; +} + +/** appendEntry 下沉类型(与 PbaSession.append 注入的 appendEntry 同构)。 */ +export type InjectionSink = (type: string, data: unknown) => void; + +/** deriveActiveContext 产物:完整寄存器表 + 当前 active 注入。 */ +export interface ActiveContext { + /** 全量寄存器表(所有曾注入的 Injection,按序)。 */ + readonly injections: ReadonlyArray; + /** 当前 active 注入 = live 集合最新一条(无 live 注入 → null)。 */ + readonly active: Injection | null; +} + +// ============================================================================ +// 内部工具:深冻结 + phase 校验 + live 集合计算 +// ============================================================================ + +/** + * 递归冻结对象/数组(原始值原样返回)。与 pba-session / sandbox-policy 范式一致: + * 运行时任何篡改抛 TypeError。 + * + * @param value 任意值。 + * @returns 冻结后的同一引用。 + */ +function deepFreeze(value: T): T { + if (value === null || typeof value !== "object") return value; + if (Array.isArray(value)) { + for (const v of value) deepFreeze(v); + } else { + for (const v of Object.values(value as Record)) deepFreeze(v); + } + Object.freeze(value); + return value; +} + +/** + * fail-closed phase 校验:非合法 phase 抛错。 + * @param phase 待校验 phase。 + */ +function assertPhase(phase: InjectionPhase): void { + if (!INJECTION_PHASES.includes(phase)) { + throw new Error( + `ContextInjector: invalid injection phase "${phase}" — must be one of ${INJECTION_PHASES.join("/")}`, + ); + } +} + +/** + * fail-closed content 校验:非非空字符串抛错。 + * + * 嵌入式注入的 content 是寄存器表/换板指令/任务 prompt,空串无意义且掩盖调用方 bug, + * 故 fail-closed 拒绝而非静默吞。trim() 只剥 Unicode White_Space,不剥零宽 + * Default_Ignorable(U+200B 零宽空格 / U+200D ZWJ 等),纯零宽字符串视觉为空却 + * 绕过 trim-only 判空;故先以 INVISIBLE_CHARS 剥除零宽字符再 trim 判空。 + * + * @param content 待校验内容。 + */ +function assertContent(content: string): void { + // 嵌入式注入的 content 是寄存器表/换板指令/任务 prompt,空串与纯空白均无意义 + // 且掩盖调用方 bug,故 fail-closed 拒绝而非静默吞。trim() 只剥 White_Space, + // 不剥零宽 Default_Ignorable(U+200B 等),须先手动剥除再判空,否则纯零宽 + // 字符串视觉为空却绕过 fail-closed(见 findings[])。 + if (typeof content !== "string" || content.replace(INVISIBLE_CHARS, "").trim().length === 0) { + throw new Error("ContextInjector: injection content must be a non-empty string (fail-closed)"); + } +} + +/** + * 计算当前 live 注入集合:最近一次 steer/followup(含)之后的所有注入按序累积; + * 无 steer/followup 则全部注入 live。体现"寄存器表累积 + 换板/新任务刷新"语义。 + * + * @param injections 全量寄存器表。 + * @returns live 注入子集(保持原序,原引用)。 + */ +function computeLiveInjections(injections: ReadonlyArray): Injection[] { + let pivot = -1; + for (let i = injections.length - 1; i >= 0; i--) { + const phase = injections[i]?.phase; + if (phase === "steer" || phase === "followup") { + pivot = i; + break; + } + } + return pivot === -1 ? [...injections] : injections.slice(pivot); +} + +// ============================================================================ +// ContextInjector —— 三段注入器 + 快照取代不变量 +// ============================================================================ + +/** + * 上下文注入三段注入器。 + * + * 纯逻辑:appendEntry 下沉由构造注入(PbaSession.append 适配或测试 mock),无 pi 运行时依赖。 + * 维护 append-only 寄存器表 + append-only 快照历史;每次 snapshot() 取代更早快照。 + * steer/followup 通过 replacesSnapshot 声明取代关系。live 集合由 computeLiveInjections 推导。 + */ +export class ContextInjector { + /** 注入下沉(落 PbaSession 跨 session resume);无则 undefined(纯内存模式)。 */ + private readonly appendEntry: InjectionSink | undefined; + /** 是否深冻结产物(默认 true,运行时不可变;测试可关)。 */ + private readonly useFreeze: boolean; + /** append-only 寄存器表。 */ + private readonly injections: Injection[] = []; + /** append-only 快照历史(仅最新一条为 live runtime-context)。 */ + private readonly snapshots: InternalSnapshot[] = []; + /** 快照 id 自增计数(供 replacesSnapshot 引用)。 */ + private snapshotSeq = 0; + + /** + * @param opts.appendEntry 注入下沉(与 PbaSession 构造注入的 appendEntry 同构)。 + * 每条注入经此落库;省略则纯内存(测试默认)。 + * @param opts.deepFreeze 是否深冻结产物(默认 true)。 + */ + constructor(opts: { appendEntry?: InjectionSink; deepFreeze?: boolean } = {}) { + this.appendEntry = opts.appendEntry; + this.useFreeze = opts.deepFreeze ?? true; + } + + /** + * inject —— 寄存器表 next-step,NO wake。 + * + * 把寄存器映射表 / 设备树片段 / datasheet 摘要登记进 runtime-context,下一 step 生效, + * 但不主动唤醒 agent(被动补料)。不取代更早快照(replacesSnapshot=undefined)。 + * + * @param content 注入文本(非空)。 + * @returns Injection{ phase:"inject", nextStep:true, nextTurn:false }。 + */ + inject(content: string): Injection { + assertContent(content); + return this.register({ + phase: "inject", + content, + nextStep: true, + nextTurn: false, + }); + } + + /** + * steer —— 换板 next-step 唤醒。 + * + * 切到另一块目标板,下一 step 唤醒 agent 重新定向。标记 replacesSnapshot 取代当前 + * runtime-context 快照(若已存在快照),声明换板刷新语义。 + * + * @param content 换板指令文本(非空)。 + * @param boardId 目标板 id(可选,省略则不绑定特定板)。 + * @returns Injection{ phase:"steer", nextStep:true, nextTurn:false, boardId?, replacesSnapshot? }。 + */ + steer(content: string, boardId?: string): Injection { + assertContent(content); + return this.register({ + phase: "steer", + content, + boardId, + nextStep: true, + nextTurn: false, + replacesSnapshot: this.currentSnapshotId(), + }); + } + + /** + * followup —— 新任务 next-turn 唤醒。 + * + * 用户派新任务,下一 turn 唤醒。标记 replacesSnapshot 取代当前 runtime-context 快照 + * (若已存在快照),声明新任务刷新语义。不绑 step(nextStep=false)。 + * + * @param content 新任务 prompt(非空)。 + * @returns Injection{ phase:"followup", nextStep:false, nextTurn:true, replacesSnapshot? }。 + */ + followup(content: string): Injection { + assertContent(content); + return this.register({ + phase: "followup", + content, + nextStep: false, + nextTurn: true, + replacesSnapshot: this.currentSnapshotId(), + }); + } + + /** + * runtime-context 快照:全量捕获当前 live 注入集合,新快照即刻取代所有更早快照。 + * + * - content = live 注入按序 "\n\n" 拼接(空 live → "")。 + * - boardId = live 注入中最新 boardId(steer 的板;无 → undefined)。 + * - ts = Date.now()。 + * + * 新快照 append 进历史,成为唯一 live runtime-context(更早快照被取代)。 + * + * @returns 当前 runtime-context 快照。 + */ + snapshot(): RuntimeSnapshot { + const live = computeLiveInjections(this.injections); + const content = live.map((i) => i.content).join("\n\n"); + let boardId: string | undefined; + for (let i = live.length - 1; i >= 0; i--) { + if (live[i]?.boardId !== undefined) { + boardId = live[i]?.boardId; + break; + } + } + this.snapshotSeq += 1; + const internal: InternalSnapshot = { + id: `${SNAPSHOT_ID_PREFIX}${this.snapshotSeq}`, + content, + boardId, + ts: Date.now(), + }; + this.snapshots.push(internal); + const external: RuntimeSnapshot = { + content: internal.content, + boardId: internal.boardId, + ts: internal.ts, + }; + return this.useFreeze ? (deepFreeze(external) as RuntimeSnapshot) : external; + } + + /** + * 推导当前 active 上下文:全量寄存器表 + 当前 active 注入。 + * + * active 注入 = live 集合最新一条(最近 steer/followup 之后累积的最新注入); + * 无 live 注入 → null。体现"最新 snapshot 取代更早"——live 集合随快照刷新而刷新, + * 更早被取代的注入不参与 active。 + * + * @returns { injections: 全量表, active: live 最新一条或 null }。 + */ + deriveActiveContext(): ActiveContext { + const live = computeLiveInjections(this.injections); + const active = live.length > 0 ? (live[live.length - 1] as Injection) : null; + const view: ActiveContext = { + injections: this.useFreeze ? (deepFreeze([...this.injections]) as ReadonlyArray) : [...this.injections], + active, + }; + return this.useFreeze ? (deepFreeze(view) as ActiveContext) : view; + } + + /** + * 清除寄存器表。phase 给定则只清该 phase;省略则全清(含快照历史,完整重置)。 + * + * @param phase 可选,仅清该 phase 的注入。 + */ + clear(phase?: InjectionPhase): void { + if (phase !== undefined) { + assertPhase(phase); + for (let i = this.injections.length - 1; i >= 0; i--) { + if (this.injections[i]?.phase === phase) { + this.injections.splice(i, 1); + } + } + return; + } + this.injections.length = 0; + this.snapshots.length = 0; + this.snapshotSeq = 0; + } + + // ---- 内部 ---- + + /** + * 统一注册:校验 phase → 冻结 Injection → 追加寄存器表 → 经 appendEntry 下沉。 + * @param partial 待注册注入(缺 replacesSnapshot/boardId 由调用方按 phase 填)。 + * @returns 冻结后的 Injection。 + */ + private register(partial: Omit & { replacesSnapshot?: string }): Injection { + assertPhase(partial.phase); + const injection: Injection = { + phase: partial.phase, + content: partial.content, + boardId: partial.boardId, + nextStep: partial.nextStep, + nextTurn: partial.nextTurn, + replacesSnapshot: partial.replacesSnapshot, + }; + const frozen = this.useFreeze ? (deepFreeze(injection) as Injection) : injection; + this.injections.push(frozen); + if (this.appendEntry) { + this.appendEntry(CONTEXT_INJECTION_TYPE, frozen); + } + return frozen; + } + + /** + * 当前(最新)快照 id,供 steer/followup 填 replacesSnapshot。无快照 → undefined。 + * @returns 最新快照 id 或 undefined。 + */ + private currentSnapshotId(): string | undefined { + return this.snapshots.length > 0 ? (this.snapshots[this.snapshots.length - 1]?.id) : undefined; + } +} + +/** 内部快照(带 id,供 replacesSnapshot 引用;id 不外泄到 RuntimeSnapshot)。 */ +interface InternalSnapshot { + readonly id: string; + readonly content: string; + readonly boardId?: string; + readonly ts: number; +} + +/** + * 把一条 Injection 序列化成 PbaSession appendEntry 兼容的 entry 形状(供集成层 T07/T09 + * 跨 session resume 重放)。纯函数,无副作用。 + * + * @param injection 注入。 + * @param seq 序号(调用方自增)。 + * @param ts 提交时刻(省略取 Date.now())。 + * @returns PbaSessionEntry 形状 { type, data, seq, ts }。 + */ +export function toSessionEntry( + injection: Injection, + seq: number, + ts: number = Date.now(), +): PbaSessionEntry { + return { + type: CONTEXT_INJECTION_TYPE, + data: injection, + seq, + ts, + }; +} diff --git a/src/core/pba-event-bus.ts b/src/core/pba-event-bus.ts new file mode 100644 index 0000000..b736afe --- /dev/null +++ b/src/core/pba-event-bus.ts @@ -0,0 +1,393 @@ +/** + * @module pba-event-bus + * + * 物理字节 Agent 类型化事件总线(T07)—— 薄封装 pi.events,叠加三层能力: + * ① typed event 名约定(KNOWN_EVENTS)—— 消灭魔法串,集中文档化领域事件 + * ② ScopeKey 隔离 —— 路径式 scope("a.b.c")做祖先-后代关系,子 agent 事件 + * 单向冒泡到父 scope(父监听收子事件),但父 emit 不下渗到子(单向冒泡) + * ③ waterfall 链委托 —— listener 收 (args, next),调 next() 委托下一个; + * 不调 next 即短路(与 tool-pipeline 的 pre/around/post 中间件范式同源) + * + * scope 语义不变式(见 tests/pba-event-bus.test.ts ⑥): + * - 无 scope(global)监听收所有事件(根节点,一切冒泡到根) + * - 注册 scope=L,emit scope=S:L 收 ⟺ L===S 或 L 是 S 的祖先(S=L+"…" 前缀) + * - global emit(scope 缺省)只达 global 监听,不下渗到任何子 scope(单向冒泡) + * + * 与 pi.events 的关系:bus 自持作用域监听注册表(Map), + * 作用域匹配/冒泡在 bus 内完成(pi.events 的 emit 不带 scope,无法承载)。 + * emit 在派发完 bus 监听后向 emitter.emit 转发(outbound 薄封装), + * 让仍用 pi.events.on 的原始监听在迁移过渡期也能收到事件。 + * emitter 可注入(默认内存 emitter);inbound 桥接(pi.events.emit → bus 监听) + * 留给集成阶段,本模块只提供 bus。 + * + * 纯逻辑,顶层零 pi 运行时 import(仅 import type,esbuild 擦除), + * tests 直接 import 命名导出即可离线单测,无 pi 运行时无硬件。 + * 见架构设计文档_v3.md §5.2 / §7(T07)。 + */ + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** + * 作用域键 —— branded 语义的路径式字符串 "a.b.c"。 + * + * 以 "." 分段,祖先-后代关系靠段前缀("a" 是 "a.b" 的祖先,但 "a" 不是 "ab" 的祖先, + * 因段边界对齐)。空串/undefined 归一为 global(根作用域)。 + */ +export type ScopeKey = string; + +/** + * 事件监听器。收 (args, next): + * - 在 emit(广播)语义下,next 是 no-op(广播不短路,全部监听独立触发) + * - 在 waterfall(链式)语义下,调 next() 委托下一个监听;不调即短路 + * + * @param args 事件载荷(按引用传递,监听可读可改,waterfall 下改后下游可见) + * @param next 委托下一个监听(waterfall 语义;emit 下为 no-op) + */ +export interface PbaListener { + (args: unknown, next: () => void): void; +} + +/** + * 可注入的事件传输层(pi.events 的 disposer 变体)。 + * + * pi.events.on 返回 void,本接口要求 on 返回 disposer(供单测清理 / 未来 inbound 桥接)。 + * 集成阶段用 adapter 包 pi.events 即可(on 返回 () => pi.events.off(...))。 + * 本模块仅用 emit(outbound 转发);on 供默认内存 emitter 自洽 + 集成阶段 inbound 桥接。 + */ +export interface PbaEmitter { + /** + * 注册原始监听。返回 disposer(卸载该监听)。 + * @param event 事件名 + * @param handler 原始监听(收 data) + * @returns 卸载函数 + */ + on(event: string, handler: (data: unknown) => void): () => void; + /** + * 派发事件到该传输层注册的原始监听。 + * @param event 事件名 + * @param data 载荷 + */ + emit(event: string, data: unknown): void; +} + +/** + * PbaEventBus 构造选项。 + */ +export interface PbaEventBusOptions { + /** + * 注入的事件传输层(默认内存 emitter)。 + * 单测注入 spy emitter 可断言 outbound 转发;集成阶段注入 pi.events adapter。 + */ + readonly emitter?: PbaEmitter; +} + +// ============================================================================ +// 命名常量 —— 消灭魔法串(typed event 名约定) +// ============================================================================ + +/** + * 领域事件名约定 —— 全 Agent 共享的 typed event 集合(深冻结,运行时不可变)。 + * + * bus 不强制只能用这些事件名(开放扩展),但所有 21 域扩展约定只用 KNOWN_EVENTS + * 内的名字,避免魔法串散落各处。新增事件改这里一处。 + * + * 成员(与现有扩展 pi.events.emit 调用对齐): + * - verify:passed 硬件验证通过(hardware-verify) + * - build:done 构建完成(build-tracker) + * - boardlink:connect 板链路连通(board-link) + * - glm:empty-output glm 零输出命门(glm-provider) + * - xcompile:done 交叉编译完成(cross-compile) + * - pdf-reader:page PDF 单页抽取(pdf-reader) + * - debugger:attach 调试器附着(jtag-debugger) + * - length-recovery:recovered 长度截断恢复(length-recovery) + */ +export const KNOWN_EVENTS = Object.freeze([ + "verify:passed", + "build:done", + "boardlink:connect", + "glm:empty-output", + "xcompile:done", + "pdf-reader:page", + "debugger:attach", + "length-recovery:recovered", +] as const); + +// ============================================================================ +// 内部:作用域归一 + 冒泡判定(纯函数,确定性可测) +// ============================================================================ + +/** + * 归一化作用域键:按 "." 切段、滤空段、重连。 + * + * - undefined / "" / " " → undefined(global) + * - "a.b.c" → "a.b.c" + * - "a..b" / "a." / ".b" → 滤空段后 "a.b" / "a" / "b" + * + * 归一保证段边界对齐,使祖先判定不靠裸前缀("a" 不会误匹配 "ab")。 + * + * @param scope 原始作用域键(可 undefined) + * @returns 归一后的作用域字符串,或 undefined(global) + */ +function normalizeScope(scope: ScopeKey | undefined): string | undefined { + if (scope === undefined) return undefined; + const segs = scope.split(".").filter((s) => s.length > 0); + return segs.length === 0 ? undefined : segs.join("."); +} + +/** + * 判定注册于 listenerScope 的监听是否应收到 emit 于 emitScope 的事件。 + * + * 冒泡不变式(单向向上): + * - listenerScope=undefined(global)→ 恒收(根节点,一切冒泡到根) + * - emitScope=undefined(global emit)→ 非 global 监听恒不收(不下渗到子) + * - listenerScope === emitScope → 收 + * - emitScope 以 listenerScope + "." 为段前缀 → 收(listenerScope 是祖先) + * - 否则 → 不收(listenerScope 是后代或旁支,事件不向下/旁冒泡) + * + * @param listenerScope 监听注册时的归一作用域(undefined=global) + * @param emitScope emit 时的归一作用域(undefined=global emit) + * @returns 是否派发 + */ +function scopeReceives( + listenerScope: string | undefined, + emitScope: string | undefined, +): boolean { + if (listenerScope === undefined) return true; // global 收所有 + if (emitScope === undefined) return false; // global emit 不下渗到子 + if (listenerScope === emitScope) return true; + return emitScope.startsWith(listenerScope + "."); +} + +/** no-op next —— emit(广播)语义下传入监听的 next,调它无副作用。 */ +const NOOP_NEXT: () => void = Object.freeze(() => {}) as () => void; + +// ============================================================================ +// 内部:默认内存 emitter(无 pi 依赖,单测默认可用) +// ============================================================================ + +/** + * 默认内存 emitter —— 极简 pub/sub,on 返回 disposer,emit 快照派发(防迭代中增删)。 + * + * bus 自身不在 emitter 上注册(作用域派发在 bus 内),故默认 emitter 的 handler 集常态空, + * emit 转发在此为 no-op;单测可直接在默认 emitter 上 on 来断言 outbound 转发。 + */ +class InMemoryEmitter { + private readonly handlers = new Map void>>(); + + on(event: string, handler: (data: unknown) => void): () => void { + let set = this.handlers.get(event); + if (!set) { + set = new Set(); + this.handlers.set(event, set); + } + set.add(handler); + return () => { + const s = this.handlers.get(event); + if (!s) return; + s.delete(handler); + if (s.size === 0) this.handlers.delete(event); + }; + } + + emit(event: string, data: unknown): void { + const set = this.handlers.get(event); + if (!set) return; + for (const h of [...set]) { + try { + h(data); + } catch { + // 传输层单监听失败不阻断其余(fail-soft,与 bus emit 同道) + } + } + } +} + +// ============================================================================ +// 监听注册表条目 +// ============================================================================ + +/** 一条注册:监听引用 + 归一作用域。按引用比 `===`(disposer 精确卸载单条)。 */ +interface ListenerEntry { + readonly listener: PbaListener; + readonly scope: string | undefined; +} + +// ============================================================================ +// PbaEventBus +// ============================================================================ + +/** + * 类型化事件总线 —— pi.events 的薄封装 + scope 隔离 + waterfall 链委托。 + * + * 自持 `Map` 注册表,作用域冒泡在 bus 内判定(pi.events 的 + * emit 不带 scope,无法承载)。emit 先按 scope 冒泡派发 bus 监听,再向 emitter.emit + * 转发(outbound,过渡期原始 pi.events 监听仍可收)。waterfall 构造 next 链,不调 + * next 即短路。 + * + * 故障语义: + * - emit(广播):单监听抛错被隔离(fail-soft,其余监听照派发),不阻断 emitter 转发 + * - waterfall(链):监听抛错向上传播(链即断,调用方显式处理),不静默吞 + * - emitter 转发失败不阻断 bus(传输层故障与 bus 监听解耦) + */ +export class PbaEventBus { + private readonly registry = new Map(); + private readonly emitter: PbaEmitter; + + /** + * @param opts emitter 注入(默认内存 emitter)。单测注入 spy 可断言 outbound 转发。 + */ + constructor(opts?: PbaEventBusOptions) { + this.emitter = opts?.emitter ?? new InMemoryEmitter(); + } + + /** + * 注册监听。返回 disposer(卸载该条注册,幂等)。 + * + * 同一 (event, listener) 可多次注册(不同 scope 各占一条);disposer 仅卸载自身那一条。 + * 重复注册不抛(barrel 重装配 / session resume 幂等安全,与 tool-pipeline 同道)。 + * + * @param event 事件名(约定用 KNOWN_EVENTS 内名字,但不强制) + * @param listener 监听器(收 args + next) + * @param scope 作用域键(缺省=global,收所有事件;路径式 "a.b.c") + * @returns 卸载函数(调一次即移除该条;再调 no-op) + */ + on(event: string, listener: PbaListener, scope?: ScopeKey): () => void { + const norm = normalizeScope(scope); + const entry: ListenerEntry = { listener, scope: norm }; + let list = this.registry.get(event); + if (!list) { + list = []; + this.registry.set(event, list); + } + list.push(entry); + return () => { + const arr = this.registry.get(event); + if (!arr) return; + const idx = arr.indexOf(entry); + if (idx >= 0) arr.splice(idx, 1); + if (arr.length === 0) this.registry.delete(event); + }; + } + + /** + * 按 listener 引用卸载某事件的所有注册(跨所有 scope)。 + * + * 不触 emitter(bus 自持注册表)。未注册/事件不存在为 no-op(不抛)。 + * + * @param event 事件名 + * @param listener 待卸监听引用(`===` 比对) + */ + off(event: string, listener: PbaListener): void { + const arr = this.registry.get(event); + if (!arr) return; + for (let i = arr.length - 1; i >= 0; i--) { + if (arr[i].listener === listener) arr.splice(i, 1); + } + if (arr.length === 0) this.registry.delete(event); + } + + /** + * 广播派发事件:按 scope 冒泡选匹配监听,各独立触发(不短路),再向 emitter 转发。 + * + * 冒泡规则(见 {@link scopeReceives}): + * - emit scope=S → global 监听 + 注册 scope 为 S 或其祖先的监听收 + * - emit 无 scope → 仅 global 监听收(不下渗子 scope) + * + * fail-soft:单监听抛错被隔离(catch 后续派发照常),emitter 转发失败亦不阻断 bus。 + * + * @param event 事件名 + * @param args 载荷(按引用传,监听可读可改) + * @param scope emit 作用域(缺省=global emit,仅达 global 监听) + */ + emit(event: string, args: unknown, scope?: ScopeKey): void { + const norm = normalizeScope(scope); + const arr = this.registry.get(event); + if (arr) { + // 快照防迭代中增删(监听内 on/off 自身或同事件) + const snapshot = arr.slice(); + for (const entry of snapshot) { + if (scopeReceives(entry.scope, norm)) { + try { + entry.listener(args, NOOP_NEXT); + } catch { + // fail-soft:单监听崩溃不阻断其余监听 + 转发 + } + } + } + } + // outbound 薄封装:bus emit 同步转发到传输层,过渡期原始 pi.events 监听可收 + try { + this.emitter.emit(event, args); + } catch { + // 传输层故障与 bus 监听解耦 + } + } + + /** + * 链式派发事件:按 scope 冒泡选匹配监听,构造 next 链顺序执行。 + * + * listener 收 (args, next):调 next() 委托下一个监听;不调即短路(下游不跑)。 + * 链末(无更多监听)next 为 no-op。返回穿线后的 args(监听 void,按引用可改后下游可见)。 + * + * 与 emit 的区别:waterfall 是顺序链(可短路),emit 是并行广播(不可短路)。 + * 故障语义不同:waterfall 监听抛错向上传播(链断,调用方显式处理); + * 不向 emitter 转发(链是请求语义,非广播,原始 pi.events 监听不应介入链中)。 + * + * 同步语义:listener 必须同步调 next() 才能续链;异步调 next 链在 waterfall 返回前不完成。 + * + * @param event 事件名 + * @param args 载荷(按引用穿线,下游监听见上游改动) + * @param scope emit 作用域(冒泡规则同 emit) + * @returns 穿线后的 args(短路点或链末的 args) + */ + waterfall(event: string, args: unknown, scope?: ScopeKey): unknown { + const norm = normalizeScope(scope); + const arr = this.registry.get(event); + const matched: ListenerEntry[] = arr + ? arr.filter((e) => scopeReceives(e.scope, norm)) + : []; + let i = 0; + const next = (): void => { + if (i >= matched.length) return; // 链末 + const entry = matched[i]; + i++; + // 抛错向上传播(链断),不静默吞 —— 与 emit fail-soft 区别 + entry.listener(args, next); + }; + next(); + return args; + } + + /** + * 拼接父子作用域键(路径式,段边界对齐)。 + * + * 归一两侧(滤空段)后按序连 "parent.child"。空侧归一为 global,故: + * - scopedScope("a", "b") → "a.b" + * - scopedScope("", "b") → "b"(父空=global) + * - scopedScope("a", "") → "a" + * - scopedScope("", "") → ""(global) + * + * @param parent 父作用域键 + * @param child 子作用域键 + * @returns 拼接后的作用域键 + */ + scopedScope(parent: ScopeKey, child: ScopeKey): ScopeKey { + const ps = normalizeScope(parent); + const cs = normalizeScope(child); + if (ps === undefined) return cs ?? ""; + if (cs === undefined) return ps; + return `${ps}.${cs}`; + } + + /** + * 返回某事件注册监听总数(跨所有 scope)。 + * + * @param event 事件名 + * @returns 注册条数(未注册返回 0) + */ + listenerCount(event: string): number { + return this.registry.get(event)?.length ?? 0; + } +} diff --git a/src/core/pba-session.ts b/src/core/pba-session.ts new file mode 100644 index 0000000..7112402 --- /dev/null +++ b/src/core/pba-session.ts @@ -0,0 +1,437 @@ +/** + * @module pba-session + * + * Physical Byte Agent 会话事件溯源底座(T06)—— 全量事件 log 的唯一提交点 + + * 模型历史投影 + "model-visible⟺logged" 不变量。 + * + * 推广 hardware-state 的 replayFromEntries(src/extensions/hardware-state.ts:134) + * 从硬件状态子集到全量事件:turn / step / user-message / assistant-message / + * tool-call / tool-result / hw:state / flash-log / verify-record / checkpoint-change。 + * + * 三件事(纯逻辑,注入 appendEntry,零 pi 运行时依赖,离线可单测): + * ① append —— 唯一提交点:lossless-JSON 快照(Date/Map/Set 折叠成 plain + * 标记对象,结构化克隆语义)+ 深冻结 + seq 单调连续 + + * 重入 guard(重入抛错,防 appendEntry 回调旁路写)。 + * ② deriveMessages —— 从有序 surface(user-message / assistant-message / + * tool-call / tool-result)投影模型历史,增量缓存 + * (append 后失效,第二次调用命中缓存)。 + * ③ replayFromEntries —— 从 log 重建等价 PbaSession(seq 连续性校验,缺口即抛; + * 推广 hardware-state replayFromEntries 到全量事件)。 + * + * "model-visible⟺logged" 不变量由 assertModelVisibleLogged 暴露: + * 声明喂模型的每个 type 必须在 log 里 append 过,否则抛错(fail-closed, + * 防止旁路喂模型未 log 的消息)。before_agent_start 钩子接线留给集成层(T07/T09)。 + * + * 范式:纯逻辑模块,顶层仅 import type(shared/types),无 pi 运行时依赖; + * 深冻结常量;fail-closed(重入 / seq 缺口 / 未 log 均抛错)。 + * 见架构设计文档_v3.md §5.1。 + */ + +import type { CheckpointState, VerifyRecord } from "../shared/types.js"; + +// ============================================================================ +// 命名常量 —— 消灭魔法串(lossless 标记 / 模型可见类型集) +// ============================================================================ + +/** lossless 快照的类型标记命名空间(折叠 Date/Map/Set 成 plain 时打标签,保 round-trip 无损)。 */ +const LOSSLESS_TAG = "__pbaType" as const; + +/** + * 模型可见事件类型集合(deriveMessages 的投影源)。深冻结。 + * + * 只有这四种 type 参与 deriveMessages 投影;turn/step/hw:state 等是非投影事件 + * (持久化但不直接进模型历史)。assertModelVisibleLogged 的典型入参即此集合的子集。 + */ +export const MODEL_VISIBLE_TYPES = Object.freeze([ + "user-message", + "assistant-message", + "tool-call", + "tool-result", +] as const) as readonly string[]; + +// ============================================================================ +// 事件 Map —— 类型契约(merge-extensible:append 接受任意 string type,此 Map 供类型化调用方) +// ============================================================================ + +/** hw:state 事件 data 形状(与 hardware-state 扩展的 HwStateData 结构兼容)。 */ +export interface PbaHwStateData { + /** 状态/事件类别。 */ + type: string; + /** 任意状态载荷。 */ + data: Record; + /** 捕获时刻(epoch ms)。 */ + ts: number; +} + +/** flash-log 事件 data 形状(与 hardware-state 扩展的 FlashLogEntry 结构兼容)。 */ +export interface PbaFlashLogData { + method: string; + target: string; + image: string; + sha256?: string; + result: "ok" | "fail"; + ts: number; +} + +/** + * PbaSession 全量事件 Map —— 每个 key 映射到该事件的 data 形状。 + * + * merge-extensible:append 的入参 type 是开放 string(不强制在此枚举内), + * 故新事件类型无需改本 Map 即可 append;此 Map 仅供类型化调用方与文档化不变量。 + */ +export interface PbaSessionEventMap { + "turn": { turn: number; phase: "start" | "end"; reason?: string }; + "step": { turn: number; step: number; phase: "start" | "end" }; + "user-message": { role: "user"; content: string }; + "assistant-message": { role: "assistant"; content: string }; + "tool-call": { name: string; args: unknown; turn?: number; step?: number }; + "tool-result": { name: string; result: unknown; turn?: number; step?: number }; + "hw:state": PbaHwStateData; + "flash-log": PbaFlashLogData; + "verify-record": VerifyRecord; + "checkpoint-change": CheckpointState; +} + +/** 内部持久化的一条会话事件(append / replay 共用)。 */ +export interface PbaSessionEntry { + /** 事件类型(开放 string)。 */ + readonly type: string; + /** lossless-JSON 快照后的 data(plain,可深冻结)。 */ + readonly data: unknown; + /** 单调连续序号(从 1 起,append 自增 / replay 校验)。 */ + readonly seq: number; + /** 提交时刻(epoch ms)。 */ + readonly ts: number; +} + +// ============================================================================ +// deriveMessages 投影产物 +// ============================================================================ + +/** + * deriveMessages 投影出的单条模型消息。 + * + * - user-message → { role:"user", content } + * - assistant-message → { role:"assistant", content } + * - tool-call → { role:"assistant", toolCalls:[{name,args}] } + * - tool-result → { role:"tool", name, content: result } + */ +export interface DerivedMessage { + readonly role: "user" | "assistant" | "tool"; + readonly content: unknown; + /** tool-result 的工具名(role:"tool" 时)。 */ + readonly name?: string; + /** tool-call 的调用列表(role:"assistant" 且为工具调用时)。 */ + readonly toolCalls?: ReadonlyArray<{ name: string; args: unknown }>; +} + +// ============================================================================ +// 内部纯函数:lossless-JSON 快照 + 深冻结 +// ============================================================================ + +/** + * 把任意值折叠成 lossless-JSON plain 快照(结构化克隆语义)。 + * + * - Date → { __pbaType:"Date", value: iso }(保 round-trip 无损) + * - Map → { __pbaType:"Map", value: [[k,v],...] }(键值递归快照) + * - Set → { __pbaType:"Set", value: [...] }(元素递归快照) + * - Array/Object → 递归每个元素/值 + * - 原始值 → 原样 + * - 循环引用 → 抛错(fail-closed:循环结构不可 JSON 序列化,拒绝快照) + * + * 产物是纯 plain 对象/数组/原始值,JSON.stringify 安全 + 可深冻结。 + * + * @param value 任意值。 + * @returns plain JSON-safe 快照。 + */ +function toLosslessSnapshot(value: unknown): unknown { + return snapshotValue(value, new WeakSet()); +} + +function snapshotValue(value: unknown, seen: WeakSet): unknown { + if (value === null || typeof value !== "object") return value; + const ref = value as object; + if (seen.has(ref)) { + throw new Error("PbaSession: cannot snapshot cyclic object (lossless-JSON invariant)"); + } + seen.add(ref); + if (value instanceof Date) { + return { [LOSSLESS_TAG]: "Date", value: value.toISOString() }; + } + if (value instanceof Map) { + const entries = [...value.entries()].map(([k, v]) => [ + snapshotValue(k, seen), + snapshotValue(v, seen), + ]); + return { [LOSSLESS_TAG]: "Map", value: entries }; + } + if (value instanceof Set) { + return { [LOSSLESS_TAG]: "Set", value: [...value].map((v) => snapshotValue(v, seen)) }; + } + if (Array.isArray(value)) { + return value.map((v) => snapshotValue(v, seen)); + } + const out: Record = {}; + for (const [k, v] of Object.entries(value)) { + out[k] = snapshotValue(v, seen); + } + return out; +} + +/** + * 递归冻结对象/数组(原始值原样返回)。 + * + * 与 sandbox-policy / tool-pipeline 的深冻结范式一致:运行时任何篡改抛 TypeError。 + * + * @param value 任意值。 + * @returns 冻结后的同一引用。 + */ +function deepFreeze(value: T): T { + if (value === null || typeof value !== "object") return value; + if (Array.isArray(value)) { + for (const v of value) deepFreeze(v); + } else { + for (const v of Object.values(value as Record)) deepFreeze(v); + } + Object.freeze(value); + return value; +} + +// ============================================================================ +// deriveMessages 投影:单条事件 → 模型消息(非投影类型返回 null) +// ============================================================================ + +/** + * 把一条会话事件投影成模型消息。非 MODEL_VISIBLE 类型返回 null(跳过)。 + * + * @param entry 会话事件。 + * @returns 投影消息或 null。 + */ +function projectMessage(entry: PbaSessionEntry): DerivedMessage | null { + const data = (entry.data ?? null) as Record | null; + switch (entry.type) { + case "user-message": + return { role: "user", content: data?.content ?? "" }; + case "assistant-message": + return { role: "assistant", content: data?.content ?? "" }; + case "tool-call": + return { + role: "assistant", + content: null, + toolCalls: [{ name: String(data?.name ?? ""), args: data?.args ?? null }], + }; + case "tool-result": + return { + role: "tool", + name: String(data?.name ?? ""), + content: data?.result ?? null, + }; + default: + return null; + } +} + +// ============================================================================ +// PbaSession —— 事件溯源底座 +// ============================================================================ + +/** + * 会话事件溯源底座。append 是唯一提交点(防旁路写);deriveMessages 从有序 surface + * 投影模型历史并增量缓存;replayFromEntries 从 log 重建等价会话。 + * + * 纯逻辑:appendEntry 由构造注入(pi 的 appendEntry 或测试 mock),无 pi 运行时依赖。 + */ +export class PbaSession { + private readonly appendEntry: (type: string, data: unknown) => void; + private readonly useFreeze: boolean; + private seq = 0; + private readonly log: PbaSessionEntry[] = []; + private readonly loggedTypes = new Set(); + private messagesCache: ReadonlyArray | null = null; + /** getEntries 的冻结快照缓存(append/loadEntries 后失效,二次调用命中同引用)。 */ + private entriesView: readonly PbaSessionEntry[] | null = null; + private appending = false; + + /** + * @param opts.appendEntry 注入的提交下沉(pi appendEntry 或 mock)。append 唯一提交点经此写出。 + * @param opts.deepFreeze 是否深冻结快照(默认 true,运行时不可变;测试可关)。 + */ + constructor(opts: { appendEntry: (type: string, data: unknown) => void; deepFreeze?: boolean }) { + this.appendEntry = opts.appendEntry; + this.useFreeze = opts.deepFreeze ?? true; + } + + /** + * 唯一提交点:lossless-JSON 快照 + 深冻结 + seq 自增 + 调 appendEntry 下沉 + + * 本地 log 追加 + 缓存失效。 + * + * 重入 guard:若 appendEntry 回调再次进入 append(旁路写),立即抛错(fail-closed, + * 防 seq 乱序 / 双写)。下沉抛错时回滚 seq,保持状态一致。 + * + * @param event { type, data } —— type 开放 string;data 任意(Date/Map/Set 折叠成 plain)。 + */ + append(event: { type: string; data: unknown }): void { + if (this.appending) { + throw new Error( + "PbaSession: reentrant append detected — appendEntry must not re-enter append (唯一提交点 guard)", + ); + } + this.appending = true; + try { + const snap = toLosslessSnapshot(event.data); + const stored = this.useFreeze ? deepFreeze(snap) : snap; + this.seq += 1; + const entry: PbaSessionEntry = { + type: event.type, + data: stored, + seq: this.seq, + ts: Date.now(), + }; + if (this.useFreeze) Object.freeze(entry); + try { + this.appendEntry(event.type, stored); + } catch (err) { + // 下沉失败:回滚 seq,保持单调连续不变量(此条未真正提交)。 + this.seq -= 1; + throw err; + } + this.log.push(entry); + this.loggedTypes.add(event.type); + this.messagesCache = null; // 失效增量缓存 + this.entriesView = null; // 失效 getEntries 冻结快照缓存 + } finally { + this.appending = false; + } + } + + /** + * 从有序 surface(user-message / assistant-message / tool-call / tool-result) + * 投影模型历史。增量缓存:append 后失效,第二次调用命中缓存(同引用)。 + * + * @returns 投影消息数组(深冻结若 useFreeze;缓存命中时返回同一引用)。 + */ + deriveMessages(): unknown[] { + if (this.messagesCache !== null) return this.messagesCache as unknown[]; + const messages: DerivedMessage[] = []; + for (const entry of this.log) { + const m = projectMessage(entry); + if (m) messages.push(m); + } + const out = this.useFreeze ? (deepFreeze(messages) as unknown[]) : (messages as unknown[]); + this.messagesCache = out; + return out; + } + + /** + * 只读访问内部 log 的冻结快照(entry 与数组容器均冻结)。供 compaction(T09)等下游读取。 + * + * 返回数组容器的 Object.freeze 视图(与 stored data 的深冻结防线对称):下游 push/splice + * 等结构性篡改会抛 TypeError,无法旁路 append 唯一提交点 guard。增量缓存:append/loadEntries + * 后失效,第二次调用命中同引用。entry 本身已在 append 时深冻结。 + * + * @returns 内部 log 的冻结只读快照(数组容器冻结;entry 已冻结;append 后返回新引用)。 + */ + getEntries(): readonly PbaSessionEntry[] { + if (this.entriesView !== null) return this.entriesView; + this.entriesView = Object.freeze([...this.log]); + return this.entriesView; + } + + /** + * 从 log entries 重建一个等价 PbaSession(推广 hardware-state replayFromEntries 到全量事件)。 + * + * seq 连续性校验(fail-closed,缺口即抛): + * - entries 带 seq 时,必须严格 +1 递增(首条为基线,非 1 起亦可,支持 compaction 续写); + * - entries 不带 seq 时,按序赋 1..n; + * - 混合时:带 seq 的校验连续,不带 seq 的按 lastSeq+1 填充。 + * 重建后新会话沿用本会话的 appendEntry / useFreeze,seq 续 lastSeq,可继续 append。 + * + * @param entries log entry 列表(只读,不修改)。 + * @returns 等价的新 PbaSession。 + */ + replayFromEntries( + entries: ReadonlyArray<{ type: string; data: unknown; seq?: number }>, + ): PbaSession { + const next = new PbaSession({ appendEntry: this.appendEntry, deepFreeze: this.useFreeze }); + next.loadEntries(entries); + return next; + } + + /** + * "model-visible⟺logged" 不变量校验:声明喂模型的每个 type 必须在 log 里 append 过。 + * + * fail-closed:若 visibleTypes 中某 type 从未 append 过(loggedTypes 无此 type)→ 抛错 + * (防止旁路喂模型未 log 的消息——唯一提交点被绕过)。 + * + * 反向(logged 但未声明 visible)不在本方法职责内,由集成层保证声明完整。 + * + * @param visibleTypes 声明为模型可见的 type 列表(典型为 MODEL_VISIBLE_TYPES 子集)。 + */ + assertModelVisibleLogged(visibleTypes: readonly string[]): void { + for (const t of visibleTypes) { + if (!this.loggedTypes.has(t)) { + throw new Error( + `PbaSession: type "${t}" declared model-visible but never logged (model-visible⟺logged invariant violated)`, + ); + } + } + } + + /** + * 内部:从 entries 校验 seq 连续性并装载进本会话(replayFromEntries 用)。 + * + * seq 校验(fail-closed,违例即抛): + * - 下界:带 seq 的 entry 必须 seq >= 1(0/负数/NaN 不可作为 compaction 基线; + * PbaSessionEntry.seq 文档化“从 1 起”不变量;NaN 因 typeof===\"number\" 通过类型门, + * 故用 !(seq>=1) 一并拒绝)。 + * - 连续性:带 seq 的 entry 必须严格 +1 递增(首条为基线,非 1 起亦可,支持 compaction 续写); + * 不带 seq 的按序赋 1..n;混合时带 seq 的校验连续,不带 seq 的按 lastSeq+1 填充。 + * + * 私有:仅供同类实例跨实例调用(TS private 跨实例可访问)。 + */ + private loadEntries(entries: ReadonlyArray<{ type: string; data: unknown; seq?: number }>): void { + let lastSeq: number | null = null; + const loaded: PbaSessionEntry[] = []; + for (let i = 0; i < entries.length; i++) { + const e = entries[i]; + if (!e || typeof e.type !== "string") { + throw new Error(`PbaSession: replay entry[${i}] missing string type`); + } + let seq: number; + if (typeof e.seq === "number") { + seq = e.seq; + // 下界校验:seq >= 1(NaN/0/负数拒绝;compaction 续写可非 1 起,但不可低于 1) + if (!(seq >= 1)) { + throw new Error( + `PbaSession: replay entry[${i}] seq ${seq} violates lower bound — must be >= 1 (PbaSessionEntry.seq 从 1 起不变量)`, + ); + } + if (lastSeq !== null && seq !== lastSeq + 1) { + throw new Error( + `PbaSession: seq discontinuity at entry[${i}] — expected ${lastSeq + 1}, got ${seq}`, + ); + } + } else { + seq = lastSeq === null ? 1 : lastSeq + 1; + } + lastSeq = seq; + const snap = toLosslessSnapshot(e.data); + const stored = this.useFreeze ? deepFreeze(snap) : snap; + const entry: PbaSessionEntry = { + type: e.type, + data: stored, + seq, + ts: Date.now(), + }; + if (this.useFreeze) Object.freeze(entry); + loaded.push(entry); + } + for (const e of loaded) { + this.log.push(e); + this.loggedTypes.add(e.type); + } + this.seq = lastSeq ?? 0; + this.messagesCache = null; + this.entriesView = null; + } +} diff --git a/src/core/provider-registry.ts b/src/core/provider-registry.ts new file mode 100644 index 0000000..ce20a86 --- /dev/null +++ b/src/core/provider-registry.ts @@ -0,0 +1,474 @@ +/** + * @module provider-registry + * + * 多 LLM provider 适配核心库(T16)—— 换模型改配置行不改扩展。 + * + * glm-provider 扩展当前硬编码 glm-5.2 单 provider。本模块把"描述一个 provider" + * 抽象成 {@link ProviderDescriptor},泛化 glm-provider 的 buildGlmModelConfig + + * toProviderConfig 两函数为单一 {@link buildProviderConfig},并维护一个可注册/解析 + * 的 provider 表({@link ProviderRegistry})。glm-provider 扩展可后续改为先查 + * registry 再 registerProvider,从而支持 DeepSeek 原生及其他 provider。 + * + * 复用 dsh THINKING_FORMAT_GATE 思路:thinkingFormat:"qwen" 触发 pi + * openai-completions 的 enable_thinking:false 兼容分支(治命门一"thinking 吃光 + * max_tokens 零输出");thinkingFormat:"none" 或缺省则不注入 qwen compat,留给 + * provider 原生 reasoning 语义。 + * + * 纯逻辑:顶层仅 `import type`(esbuild 擦除),ProviderConfig/ProviderModelConfig + * 仅作类型,运行时不解析 pi。tests 直接 import 命名导出即可离线单测,无 pi 运行时 + * 依赖、无硬件。 + * + * 密钥铁律:gateway key 一律用 `${DROBOTICS_LLM_KEY}` 形式占位(env 变量名来自 + * desc.apiKeyEnv),绝不出现 sk- 开头明文,绝不写进 git-tracked 文件。 + */ + +import type { ProviderConfig, ProviderModelConfig } from "@earendil-works/pi-coding-agent"; + +// ============================================================================ +// 命名常量 —— 消灭魔法串(网关 / provider 名 / 思考格式 / 默认窗口) +// ============================================================================ + +/** d-robotics 内部 LLM 网关 base url(glm-5.2 默认走此网关,实测见缺陷分析 §3 #7)。 */ +const DROBOTICS_GATEWAY_URL = "https://ai-api.d-robotics.cc/v1"; +/** glm-5.2 经网关的 provider 名(pi.registerProvider 第一参数)。 */ +const GLM_PROVIDER_NAME = "drobotics-glm"; +/** glm-5.2 真实模型 id(带中划线,实测见缺陷分析 §3 #7)。 */ +const GLM_MODEL_ID = "glm-5.2"; +/** DeepSeek 原生 provider 名(stub,后续接线真实网关)。 */ +const DEEPSEEK_PROVIDER_NAME = "deepseek-native"; +/** DeepSeek 原生模型 id(官方 chat 模型)。 */ +const DEEPSEEK_MODEL_ID = "deepseek-chat"; +/** DeepSeek 原生官方网关 base url(stub,可被私有网关覆盖)。 */ +const DEEPSEEK_GATEWAY_URL = "https://api.deepseek.com/v1"; +/** DeepSeek 原生官方 key 的环境变量名(占位,值走 env)。 */ +const DEEPSEEK_API_KEY_ENV = "DEEPSEEK_API_KEY"; +/** glm-5.2 默认 key 的环境变量名(占位,值走 env)。 */ +const GLM_API_KEY_ENV = "DROBOTICS_LLM_KEY"; +/** glm-5.2 默认 max_tokens(治命门一:从缺陷默认 2048 提到 8192,防 thinking 吃光)。 */ +const GLM_MAX_TOKENS = 8192; +/** glm-5.2 上下文窗口(1M token)。 */ +const GLM_CONTEXT_WINDOW = 1_000_000; +/** DeepSeek 上下文窗口(128K token,官方文档)。 */ +const DEEPSEEK_CONTEXT_WINDOW = 128_000; +/** DeepSeek 默认 max_tokens。 */ +const DEEPSEEK_MAX_TOKENS = 8192; + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** + * 思考格式门 —— 复用 dsh THINKING_FORMAT_GATE 思路。 + * + * - "qwen" —— 注入 compat.thinkingFormat:"qwen" + thinkingLevelMap 全 null + + * supportsReasoningEffort:false,触发 pi openai-completions 的 enable_thinking:false + * 分支(治命门一:glm-5.2 默认开 thinking 吃光 max_tokens 致零输出)。 + * - "none" —— 不注入 qwen compat,留给 provider 原生 reasoning 语义。 + */ +export type ThinkingFormat = "qwen" | "none"; + +/** + * provider 描述符 —— 声明式描述一个 LLM provider 的全部接线信息。 + * + * 设计为纯数据(可深冻结、可序列化、可 diff)。key 不入库:只记环境变量名 + * (apiKeyEnv),运行时由 {@link buildProviderConfig} 展开成 `${VAR}` 占位交 pi。 + * + * 下游模块(glm-provider 扩展、配置加载器)依赖这些字段名,不得擅自改名。 + */ +export interface ProviderDescriptor { + /** 模型 id(带中划线如 "glm-5.2",pi 模型匹配键)。 */ + readonly id: string; + /** pi provider 名(pi.registerProvider 第一参数)。 */ + readonly provider: string; + /** 网关 base url(含 /v1 后缀)。 */ + readonly baseUrl: string; + /** key 占位变量名,值走 env,绝不入库(展开为 `${VAR}`)。 */ + readonly apiKeyEnv: string; + /** 思考格式门;缺省视为 "none"。 */ + readonly thinkingFormat?: ThinkingFormat; + /** 最大输出 token 数。 */ + readonly maxTokens: number; + /** 上下文窗口(token 数)。 */ + readonly contextWindow: number; + /** 是否支持 reasoning(thinking)输出。 */ + readonly reasoning: boolean; + /** 支持的输入模态;缺省 ["text"]。 */ + readonly input?: readonly ("text" | "image")[]; + /** 计费(每百万 token,美元);缺省全 0(内部网关不计费)。 */ + readonly cost?: { + readonly input: number; + readonly output: number; + readonly cacheRead: number; + readonly cacheWrite: number; + }; +} + +// ============================================================================ +// 内部:思考格式门 —— 把 thinkingFormat 展开成 pi compat/thinkingLevelMap +// ============================================================================ + +/** thinkingLevelMap 全 null 形态(关掉 reasoning effort 映射,配合 qwen compat)。 */ +const NULL_THINKING_LEVEL_MAP = Object.freeze({ + off: null, + low: null, + medium: null, + high: null, +}); +/** thinkingLevelMap 默认直通形态(effort 名原样透传给 provider 原生 reasoning)。 */ +const PASSTHROUGH_THINKING_LEVEL_MAP = Object.freeze({ + off: null, + low: "low", + medium: "medium", + high: "high", +}); + +/** + * 把 thinkingFormat 展开成 pi 的 compat + thinkingLevelMap + supportsReasoningEffort。 + * + * THINKING_FORMAT_GATE:thinkingFormat:"qwen" 注入 compat.thinkingFormat:"qwen" + * 触发 pi enable_thinking:false 分支;"none"/缺省则用直通 map,留原生语义。 + * + * none 分支 quirk(文档化,见 {@link buildProviderConfig} JSDoc):返回 compat=undefined, + * 故返回的 supportsReasoningEffort(= desc.reasoning)在 buildProviderConfig 中因 compat + * 不存在而被丢弃——pi 仅从 compat.supportsReasoningEffort 读此字段。当前无 none+ + * reasoning:true 的已知 provider,故无实际影响;未来若需为这类 provider 暴露 + * reasoning-effort 控制,应在此分支产出携带 supportsReasoningEffort 的 compat 对象。 + * + * @param desc provider 描述符。 + * @returns { thinkingLevelMap, compat, supportsReasoningEffort } 三元组。 + */ +function applyThinkingFormatGate(desc: ProviderDescriptor): { + thinkingLevelMap: Record; + compat: Record | undefined; + supportsReasoningEffort: boolean; +} { + if (desc.thinkingFormat === "qwen") { + return { + thinkingLevelMap: NULL_THINKING_LEVEL_MAP, + compat: { thinkingFormat: "qwen", supportsReasoningEffort: false }, + supportsReasoningEffort: false, + }; + } + return { + thinkingLevelMap: PASSTHROUGH_THINKING_LEVEL_MAP, + compat: undefined, + supportsReasoningEffort: desc.reasoning, + }; +} + +// ============================================================================ +// buildProviderConfig —— 泛化 glm-provider buildGlmModelConfig + toProviderConfig +// ============================================================================ + +/** + * 把 {@link ProviderDescriptor} 转成 pi.registerProvider(name, config) 的入参。 + * + * 泛化 glm-provider 的 buildGlmModelConfig + toProviderConfig 两函数:descriptor 是 + * 纯数据,本函数把它展开成 pi 能消费的 { name, config }。thinkingFormat:"qwen" + * 触发 enable_thinking:false 兼容(THINKING_FORMAT_GATE 思路,治命门一)。 + * + * 密钥铁律:apiKey 展开为 `${desc.apiKeyEnv}` 占位,绝不出现 sk- 明文。 + * + * 低层信任契约(finding 2 文档化硬约束):本函数信任入参、**不**调用 + * {@link assertDescriptorValid},留给上层决定校验时机——glm-provider 扩展传入已知良好的 + * 冻结常量(KNOWN_PROVIDERS),无需再校验。但这是一条 fail-open 路径:畸形 descriptor + * (如 `{}`)**不被拒绝**,而会产出 `apiKey="${undefined}"`、`name=undefined` 的半成品 config + * (pi.registerProvider 会接受,但运行时报晦涩的 auth 错而非注册期 fail-closed 清晰错)。 + * 不能在此加校验——若干对抗/变异测试(buildProviderConfig({}) 不抛而产 ${undefined}、 + * M5 mutant)显式 pin 此 fail-open 行为作为低层信任 quirk。故任何传入外部/用户构造的 + * descriptor 的 caller(配置加载器、用户配置路径)**必须**走 fail-closed 入口 + * {@link buildProviderConfigValidated}(先校验再构建),绝不可直接调本函数。 + * + * cost 防篡改硬化(治 finding 1):`cost: desc.cost ? Object.freeze(desc.cost) + * : Object.freeze({...})`。原实现直接别名 `desc.cost` 进 model(与 `input` 的 + * spread-copy 不一致),caller 在 build 后改写 `desc.cost.input` 会**静默**腐蚀已构建 + * config 的 cost(input 因已拷贝无此害)。本函数不能改成 spread-copy——等价类/对抗 + * 测试(model.cost === desc.cost 同引用 quirk、循环引用 cost 不爆栈)显式 pin 此同引用 + * 契约。改用 Object.freeze 原地冻结 desc.cost:保留同引用(toBe 不破),同时 caller 再 + * 改写 `desc.cost.input` 会**loudly** 抛 TypeError 而非静默腐蚀——把静默 bug 变成显式崩溃。 + * 冻结对已知良好入参(KNOWN_PROVIDERS 已 deepFreeze)是 no-op;仅对 mutable descriptor + * caller 生效,而 mutable descriptor 本就违反"纯数据/可深冻结"设计不变式(见 + * {@link ProviderDescriptor} JSDoc),故此冻结是硬化而非副作用污染。 + * + * none 分支思考格式门 quirk(文档化):thinkingFormat:"none"/缺省时, + * {@link applyThinkingFormatGate} 返回 compat=undefined(不注入 qwen shim,留给 provider + * 原生 reasoning 语义),故 supportsReasoningEffort(= desc.reasoning)计算后被丢弃—— + * pi 只从 compat.supportsReasoningEffort 读此字段,compat 缺省即不暴露 reasoning-effort + * 控制。当前 DeepSeek stub(reasoning:false)不受影响(丢弃的值本就是 false);仅当未来 + * 出现 none+reasoning:true 的 provider 且需要 reasoning-effort 控制时,需扩展 gate 在 none + * 分支产出携带 supportsReasoningEffort 的 compat 对象(会改变 compat=undefined 契约, + * 须同步更新测试)。 + * + * @param desc provider 描述符(低层信任,不校验)。 + * @returns { name, config } 供 pi.registerProvider 使用。 + */ +export function buildProviderConfig(desc: ProviderDescriptor): { + name: string; + config: ProviderConfig; +} { + const apiKey = `\${${desc.apiKeyEnv}}`; + const { thinkingLevelMap, compat, supportsReasoningEffort } = applyThinkingFormatGate(desc); + + const model: ProviderModelConfig = { + id: desc.id, + name: desc.id, + reasoning: desc.reasoning, + thinkingLevelMap, + input: [...(desc.input ?? ["text"])] as ("text" | "image")[], + // 治 finding 1:原别名 `desc.cost` 与 input 的 spread-copy 不一致,build 后改写 + // desc.cost.input 会静默腐蚀此 model.cost。Object.freeze 原地冻结保留同引用 + // (model.cost === desc.cost 契约不破),改写改抛 TypeError(静默→显式)。 + // 不用 spread-copy:会破坏同引用 quirk 测试;冻结对已冻结的 KNOWN_PROVIDERS 是 no-op。 + cost: desc.cost ? Object.freeze(desc.cost) : Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }), + contextWindow: desc.contextWindow, + maxTokens: desc.maxTokens, + compat, + }; + // supportsReasoningEffort 是 pi ProviderModelConfig.compat 的可选子字段(镜像 glm-provider), + // 透传进 compat 以兼容 pi 当前 schema(compat 为 Record)。 + // 注意:none 分支 compat=undefined 时此处跳过——见上 JSDoc 的 quirk 文档化。 + if (compat) { + compat.supportsReasoningEffort = supportsReasoningEffort; + } + + return { + name: desc.provider, + config: { + name: desc.id, + baseUrl: desc.baseUrl, + apiKey, + api: "openai", + authHeader: true, + models: [model], + }, + }; +} + +/** + * fail-closed 入口:先 {@link assertDescriptorValid} 校验,再 {@link buildProviderConfig} 构建。 + * + * 治 finding:buildProviderConfig 低层信任不校验,配置加载器等外部 caller 直接传畸形 + * descriptor 会产出半成品 config(apiKey="${undefined}"、name=undefined),违反密钥铁律/ + * fail-closed 契约。本函数给外部 caller 一个一步到位的 fail-closed 路径——缺字段直接抛错, + * 绝不产出半成品 provider config 交 pi.registerProvider。 + * + * glm-provider 扩展传已知良好常量时可直接用 {@link buildProviderConfig}(免重复校验); + * 配置加载器/用户配置路径务必用本函数。 + * + * @param desc 待校验+构建的 provider 描述符。 + * @returns { name, config } 供 pi.registerProvider 使用。 + * @throws {Error} id/provider/baseUrl/apiKeyEnv 为空串或 maxTokens/contextWindow 非有限正。 + */ +export function buildProviderConfigValidated(desc: ProviderDescriptor): { + name: string; + config: ProviderConfig; +} { + assertDescriptorValid(desc); + return buildProviderConfig(desc); +} + +// ============================================================================ +// 描述符校验 —— fail-closed(缺字段拒绝注册,不静默吞错) +// ============================================================================ + +/** + * 校验描述符必填字段。fail-closed:缺字段抛错,绝不注册半成品 provider。 + * + * 导出供外部 caller(配置加载器、{@link buildProviderConfigValidated})复用同一套校验 + * 契约——buildProviderConfig 低层信任不校验(见其 JSDoc),外部 descriptor 入站时务必 + * 先过本函数或直接走 {@link buildProviderConfigValidated}。 + * + * @param desc 待校验描述符。 + * @throws {Error} id/provider/baseUrl/apiKeyEnv 为空串或 maxTokens<=0。 + */ +export function assertDescriptorValid(desc: ProviderDescriptor): void { + const required: ReadonlyArray = [ + [desc.id, "id"], + [desc.provider, "provider"], + [desc.baseUrl, "baseUrl"], + [desc.apiKeyEnv, "apiKeyEnv"], + ]; + for (const [value, label] of required) { + if (typeof value !== "string" || value.trim() === "") { + throw new Error(`[provider-registry] invalid descriptor: ${label} must be non-empty string`); + } + } + if (!Number.isFinite(desc.maxTokens) || desc.maxTokens <= 0) { + throw new Error(`[provider-registry] invalid descriptor: maxTokens must be finite positive (got ${desc.maxTokens})`); + } + if (!Number.isFinite(desc.contextWindow) || desc.contextWindow <= 0) { + throw new Error(`[provider-registry] invalid descriptor: contextWindow must be finite positive (got ${desc.contextWindow})`); + } +} + +// ============================================================================ +// ProviderRegistry —— 可注册/解析的 provider 表 +// ============================================================================ + +/** + * provider 注册表 —— 维护 id → descriptor 映射,支持 register/resolve/list。 + * + * 设计为模块内可实例化的纯逻辑类(非单例,便于测试与多配置隔离)。register 返回 + * disposer(与 tool-pipeline/sandbox-policy 的注册器范式一致),重复 id 视为更新 + * (替换 descriptor,旧 disposer 失效),保证 barrel 重装配幂等。 + * + * fail-closed:resolve 未知 id 抛错(无 descriptor = 无 provider = 拒绝使用, + * 不静默回退到默认,避免误用未配置模型)。 + * + * 代际计数器单调不重置(治 finding):disposer 仅移除 descriptor,不删 generations[id], + * 计数器单调递增永不回退,确保 dispose→re-register 同 id 周期后旧 disposer 永久 no-op + * (见 {@link ProviderRegistry.register} disposer 注释)。 + */ +export class ProviderRegistry { + private readonly descriptors = new Map(); + /** id → 单调递增的代际号(永不重置/删除,旧 disposer 的代际号过期则 no-op)。 */ + private readonly generations = new Map(); + + /** + * 注册一个 provider 描述符。重复 id 视为更新(替换),旧 disposer 失效。 + * + * 不可变存储(治 finding):先校验,再 {@link cloneDescriptor} 拷贝 + {@link deepFreezeDescriptor} + * 深冻结后存入表。调用方原对象不被冻结/不持同引用——resolve 返回的是 registry 自己的 + * 深冻结副本,调用方无法通过 resolved 对象篡改内部状态,注册后改写原对象也不会让 Map + * key 与存储条目状态分裂,守住"纯数据/可深冻结"不变式。 + * + * @param desc provider 描述符(先校验,fail-closed;存储深冻结副本)。 + * @returns disposer:调用即移除本次注册(若已被同 id 后续注册覆盖则 no-op)。 + */ + register(desc: ProviderDescriptor): () => void { + assertDescriptorValid(desc); + const id = desc.id; + const stored = deepFreezeDescriptor(cloneDescriptor(desc)); + const generation = (this.generations.get(id) ?? 0) + 1; + this.generations.set(id, generation); + this.descriptors.set(id, stored); + return () => { + // 只有当前代际的 disposer 才真移除 descriptor;被覆盖后的旧 disposer no-op。 + // 治 finding:disposer 不删 generations[id]——保留单调递增计数器,永不回退。 + // 原实现同时 generations.delete(id),致 dispose→re-register 同 id 周期后 generation + // 重算为 `(undefined ?? 0)+1 = 1`,与已触发(应永久 no-op)的旧 disposer 捕获的 + // 代际号 1 碰撞,旧 disposer 复活误删新注册条目,破坏 dispose 幂等性与 fail-closed。 + // 保留 generations[id] 后,旧 disposer 代际号恒小于当前代际号 → 永久 no-op。 + if (this.generations.get(id) === generation) { + this.descriptors.delete(id); + } + }; + } + + /** + * 按 model id 解析 provider 描述符。 + * + * fail-closed:未知 id 抛错(绝不静默回退默认,防误用未配置模型)。 + * + * @param modelId 模型 id(如 "glm-5.2")。 + * @returns 对应描述符。 + * @throws {Error} 未注册该 id。 + */ + resolve(modelId: string): ProviderDescriptor { + const desc = this.descriptors.get(modelId); + if (!desc) { + throw new Error(`[provider-registry] no provider registered for model id "${modelId}" (fail-closed)`); + } + return desc; + } + + /** + * 列出全部已注册描述符(按注册序,只读快照)。 + * + * @returns 只读数组(调用方不可篡改表内状态)。 + */ + list(): readonly ProviderDescriptor[] { + return [...this.descriptors.values()]; + } +} + +// ============================================================================ +// 内部:深冻结描述符(运行时不可变,防意外篡改) +// ============================================================================ + +/** + * 深拷贝一个描述符(顶层浅拷贝 + cost/input 副本),不冻结调用方原对象。 + * + * 供 {@link ProviderRegistry.register} 存储前隔离用——registry 持有自己的纯数据副本, + * 调用方注册后仍可安全复用/改写原对象,不会让 Map key 与存储条目状态分裂。 + * + * @param desc 待拷贝描述符。 + * @returns 全新对象(cost/input 为新引用,顶层字段从原对象复制)。 + */ +function cloneDescriptor(desc: ProviderDescriptor): ProviderDescriptor { + return { + id: desc.id, + provider: desc.provider, + baseUrl: desc.baseUrl, + apiKeyEnv: desc.apiKeyEnv, + thinkingFormat: desc.thinkingFormat, + maxTokens: desc.maxTokens, + contextWindow: desc.contextWindow, + reasoning: desc.reasoning, + input: desc.input ? [...desc.input] as ("text" | "image")[] : undefined, + cost: desc.cost ? { ...desc.cost } : undefined, + }; +} + +/** + * 深冻结一个描述符及其嵌套 cost/input 数组。 + * + * @param desc 待冻结描述符。 + * @returns 同一对象(已深冻结,运行时篡改抛 TypeError)。 + */ +function deepFreezeDescriptor(desc: T): Readonly { + if (desc.cost) Object.freeze(desc.cost); + if (desc.input) Object.freeze(desc.input); + return Object.freeze(desc); +} + +// ============================================================================ +// 已知 provider 常量 —— glm-5.2(默认)+ deepseek-native(stub) +// ============================================================================ + +/** + * glm-5.2 默认描述符 —— 经 d-robotics 内部网关,thinkingFormat:"qwen" 治命门一。 + * + * baseUrl=ai-api.d-robotics.cc/v1, apiKeyEnv=DROBOTICS_LLM_KEY, thinkingFormat:"qwen", + * maxTokens=8192。深冻结,运行时不可变。 + */ +export const DEFAULT_GLM_DESCRIPTOR: Readonly = deepFreezeDescriptor({ + id: GLM_MODEL_ID, + provider: GLM_PROVIDER_NAME, + baseUrl: DROBOTICS_GATEWAY_URL, + apiKeyEnv: GLM_API_KEY_ENV, + thinkingFormat: "qwen", + maxTokens: GLM_MAX_TOKENS, + contextWindow: GLM_CONTEXT_WINDOW, + reasoning: true, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, +}); + +/** + * DeepSeek 原生 stub 描述符 —— 走官方网关,thinkingFormat:"none"(原生 reasoning 语义)。 + * + * stub:baseUrl/apiKeyEnv 指官方端点,后续接线真实私有网关时覆盖即可。深冻结。 + */ +const DEEPSEEK_DESCRIPTOR: Readonly = deepFreezeDescriptor({ + id: DEEPSEEK_MODEL_ID, + provider: DEEPSEEK_PROVIDER_NAME, + baseUrl: DEEPSEEK_GATEWAY_URL, + apiKeyEnv: DEEPSEEK_API_KEY_ENV, + thinkingFormat: "none", + maxTokens: DEEPSEEK_MAX_TOKENS, + contextWindow: DEEPSEEK_CONTEXT_WINDOW, + reasoning: false, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, +}); + +/** + * 已知 provider 列表 —— glm-5.2(默认)+ deepseek-native(stub)。 + * + * 深冻结只读。配置加载器默认把这组注册进 ProviderRegistry;用户配置可覆盖/追加。 + */ +export const KNOWN_PROVIDERS: readonly ProviderDescriptor[] = Object.freeze([ + DEFAULT_GLM_DESCRIPTOR, + DEEPSEEK_DESCRIPTOR, +]); diff --git a/src/index.ts b/src/index.ts index 6966fb4..5a1cf73 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,3 +16,45 @@ export type { LaunchResult, } from "./agent.js"; export * from "./shared/types.js"; + +// ============================================================================ +// v3 P1+P2 公共 API(T06–T17)—— 核心库导出,供 agent 层与外部消费者使用。 +// board-link / flash 能力 barrel 各自也 re-export 了 shared 类型(BoardSpec/FlashPlan +// 等),为避免与上方 `export * from "./shared/types.js"` 重名冲突,这两者只用具名 +// re-export 它们的【新增】符号(Registry/Provider/默认 provider),共享类型继续由 +// shared/types 单一事实源导出。 +// ============================================================================ + +// T06 事件溯源 + T07 typed event bus + T13 上下文注入 + T14 checkpoint + T16 provider +export * from "./core/pba-session.js"; +export * from "./core/pba-event-bus.js"; +export * from "./core/provider-registry.js"; +export * from "./core/context-injector.js"; +export * from "./core/checkpoint-state.js"; + +// T09 compaction 完整工程 +export * from "./compaction/token-meter.js"; +export * from "./compaction/tool-result-pruner.js"; +export * from "./compaction/summarizer.js"; +export * from "./compaction/spill.js"; + +// T17 审批 / 凭据 / settings / lsp +export * from "./capabilities/approval.js"; +export * from "./capabilities/credentials.js"; +export * from "./capabilities/settings.js"; +export * from "./capabilities/lsp.js"; + +// T12 子代理 + 工作流编排 +export * from "./capabilities/subagent/index.js"; +export * from "./capabilities/workflow/index.js"; + +// T15 profile/bundle 分层 +export * from "./profiles/index.js"; + +// T08 能力接缝 —— board-link + flash(具名 re-export 新增符号,共享类型走 shared/types) +export { BoardLinkRegistry, DEFAULT_BOARD_LINK_PROVIDERS } from "./capabilities/board-link/index.js"; +export { RDK_X5_SSH_PROVIDER, RDK_S100_SERIAL_PROVIDER, LOCAL_PROVIDER } from "./capabilities/board-link/index.js"; +export type { BoardLinkProvider, BoardLinkHealthResult } from "./capabilities/board-link/index.js"; +export { FlashRegistry, DEFAULT_FLASH_PROVIDERS } from "./capabilities/flash/index.js"; +export { DD_PROVIDER, FASTBOOT_PROVIDER, DFU_PROVIDER, OPENOCD_PROVIDER } from "./capabilities/flash/index.js"; +export type { FlashProvider } from "./capabilities/flash/index.js"; diff --git a/src/profiles/base.ts b/src/profiles/base.ts new file mode 100644 index 0000000..9f10f55 --- /dev/null +++ b/src/profiles/base.ts @@ -0,0 +1,273 @@ +/** + * @module profiles/base + * + * Physical Byte Agent —— profile/bundle 分层基座(T15)。 + * + * 两个业务方向各自一个 profile,共享 base + 叠差异: + * - 维修诊断(repair-diagnosis):base + pdf-reader / datasheet-rag / peripheral-probe + * - 嵌入式开发(embedded-dev):base + cross-compile / flash / jtag-debugger / + * device-tree / board-link / reg-tool + * + * 单一事实源:{@link DOMAIN_TOOLS} 把每个扩展域映射到它真实注册的工具名 + * (取自各扩展 `defineTool({ name })` 的真实串,非臆造)。profiles 的 `tools` + * 由 `toolsFor(extensions)` 派生,扩展域改工具只改这一处,杜绝重复与魔法串。 + * + * 三个纯函数(fail-closed / 确定性 / 无副作用 / 可离线单测): + * ① mergeProfiles —— 共享 base + 叠差异(并集、去重、稳定序) + * ② diffProfiles —— 两 profile 的扩展域差异(added / removed) + * ③ toolsFor —— 由扩展域列表派生其暴露的工具名 + * + * 范式:纯逻辑模块,顶层无 pi 运行时依赖(零 import type 以外的 pi 引用), + * 无副作用,确定性可测。深冻结所有导出常量。见架构设计文档_v3.md。 + */ + +// ============================================================================ +// 类型契约 +// ============================================================================ + +/** + * 一个 profile —— 一组扩展域 + 它们暴露给 LLM 的工具,附 id 与可选说明。 + * + * `extensions`:要装配的扩展域 kebab 名(对应 src/extensions/index.ts 的 + * extensionFactories 域名清单,如 "glm-provider" / "safety-gate")。 + * `tools`:上述扩展真实注册的工具名(取自各扩展 `defineTool({ name })`, + * 如 "glm_status" / "pshell"),由 {@link toolsFor} 从 {@link DOMAIN_TOOLS} + * 派生,保证每个串都有真实 referent,无魔法串。 + * + * 全字段 readonly + 深冻结,运行时不可变。 + */ +export interface Profile { + /** profile 标识(resolveProfile 据此查表,fail-closed)。 */ + readonly id: string; + /** 要装配的扩展域 kebab 名清单(稳定序:base 在前,差异在后)。 */ + readonly extensions: readonly string[]; + /** 上述扩展暴露给 LLM 的真实工具名清单(稳定序,去重)。 */ + readonly tools: readonly string[]; + /** 可选:profile 用途说明(诊断/文档用)。 */ + readonly note?: string; +} + +// ============================================================================ +// 单一事实源 —— 扩展域 → 真实注册工具名(取自各扩展 defineTool name) +// ============================================================================ + +/** + * 扩展域 → 该扩展真实注册的工具名(取自 src/extensions/<域>.ts 的 + * `defineTool({ name })`,逐条核对,非臆造)。 + * + * 只挂工具名(safety-gate 是守护规则、edit-strict 是 hook,均不注册工具 → 空数组)。 + * 深冻结:每个数组也冻结,运行时篡改抛 TypeError。 + * + * 这是 `tools` 的唯一来源:profiles 的 tools 全部由 `toolsFor` 从此表派生, + * 扩展改工具名只需改本表,所有 profile 自动同步,杜绝重复清单与魔法串。 + */ +export const DOMAIN_TOOLS: Readonly> = Object.freeze({ + "glm-provider": Object.freeze(["glm_status"]), + "safety-gate": Object.freeze([]), // 守护规则(blocklist),不注册工具 + "persistent-shell": Object.freeze(["pshell"]), + "pdf-reader": Object.freeze(["read_pdf"]), + "edit-strict": Object.freeze([]), // hook(before/after),不注册工具 + "length-recovery": Object.freeze(["length_recovery_status"]), + "subprocess-isolation": Object.freeze(["isolated_exec"]), + "env-probe": Object.freeze(["env_status"]), + "mcp-bridge": Object.freeze(["mcp_list", "mcp_call"]), + "server-runtime": Object.freeze(["server_session"]), + "hardware-state": Object.freeze(["hw_state"]), + "cross-compile": Object.freeze(["xcompile"]), + flash: Object.freeze(["flash"]), + "peripheral-probe": Object.freeze(["bus_probe"]), + "jtag-debugger": Object.freeze(["debugger"]), + "device-tree": Object.freeze(["dt"]), + "board-link": Object.freeze([ + "board_connect", + "board_exec", + "board_scp", + "board_console", + ]), + "datasheet-rag": Object.freeze(["datasheet_query"]), + "hardware-verify": Object.freeze(["verify"]), + "loop-orchestrator": Object.freeze(["loop_status"]), + "build-tracker": Object.freeze(["build", "build_status"]), + "reg-tool": Object.freeze(["reg"]), +}); + +// ============================================================================ +// 内部纯工具 —— 深冻结 / 稳定并集 / 派生工具 +// ============================================================================ + +/** + * 冻结一个字符串数组并返回其 readonly 视图(深冻结辅助)。 + * + * @param xs 待冻结数组。 + * @returns 冻结后的 readonly 数组(运行时篡改抛 TypeError)。 + */ +function frozen(xs: readonly string[]): readonly string[] { + return Object.freeze([...xs]) as readonly string[]; +} + +/** + * 稳定并集:base 在前(保序),其后追加 base 中没有的 delta 项(保序去重)。 + * + * 纯逻辑、确定性、无副作用。用作 mergeProfiles 的并集核心。 + * + * @param base 基底数组(顺序保留)。 + * @param delta 差异数组(仅追加 base 未含项,保序)。 + * @returns 去重并集(深冻结)。 + */ +function unionStable( + base: readonly string[], + delta: readonly string[], +): readonly string[] { + const seen = new Set(base); + const out: string[] = [...base]; + for (const x of delta) { + if (!seen.has(x)) { + seen.add(x); + out.push(x); + } + } + return frozen(out); +} + +// ============================================================================ +// toolsFor —— 由扩展域派生其暴露的工具名(单一事实源派生) +// ============================================================================ + +/** + * 由扩展域清单派生其暴露的工具名(从 {@link DOMAIN_TOOLS} 查表,保序去重)。 + * + * 未知域 fail-closed:抛错(防止 profile 引入不存在的扩展域,早暴露拼写错误)。 + * 这是 `tools` 的唯一来源,杜绝工具名与扩展域脱钩的魔法串。 + * + * @param domains 扩展域 kebab 名清单。 + * @returns 这些扩展真实注册的工具名(去重保序,深冻结)。 + * @throws {Error} 当 domains 含 {@link DOMAIN_TOOLS} 未收录的域时(fail-closed)。 + */ +export function toolsFor(domains: readonly string[]): readonly string[] { + const out: string[] = []; + const seen = new Set(); + for (const d of domains) { + const tools = DOMAIN_TOOLS[d]; + if (tools === undefined) { + throw new Error( + `toolsFor: unknown extension domain "${d}" — not in DOMAIN_TOOLS (fail-closed)`, + ); + } + for (const t of tools) { + if (!seen.has(t)) { + seen.add(t); + out.push(t); + } + } + } + return frozen(out); +} + +// ============================================================================ +// BASE_PROFILE —— 两业务方向共享的扩展基座 +// ============================================================================ + +/** + * base 扩展域清单 —— 两业务方向共享的公共基座。 + * + * 来源:契约 base 项(safety-gate / glm-provider / persistent-shell / + * edit-length-recovery / subprocess-isolation / env-probe / mcp-bridge / + * server-runtime / hardware-state)。其中 "edit-length-recovery" 是契约简写, + * 实际无此单一扩展,展开为真实的 edit-strict + length-recovery 两扩展 + * (均为 hook/恢复类公共基座,T08 已按真实名自适应)。 + */ +export const BASE_EXTENSIONS: readonly string[] = Object.freeze([ + "glm-provider", + "safety-gate", + "persistent-shell", + "edit-strict", + "length-recovery", + "subprocess-isolation", + "env-probe", + "mcp-bridge", + "server-runtime", + "hardware-state", +]); + +/** + * base profile —— 两业务方向共享的扩展 + 工具基座。 + * + * tools 由 {@link toolsFor} 从 {@link BASE_EXTENSIONS} 派生(含 pshell / + * glm_status / isolated_exec / env_status / mcp_list / mcp_call / + * server_session / hw_state / length_recovery_status;safety-gate 与 + * edit-strict 不注册工具,故 base 工具数 < 扩展数)。深冻结,运行时不可变。 + */ +export const BASE_PROFILE: Profile = Object.freeze({ + id: "base", + extensions: BASE_EXTENSIONS, + tools: toolsFor(BASE_EXTENSIONS), + note: "共享基座:provider / 安全门 / 持久 shell / 编辑恢复 / 子进程隔离 / 环境探针 / MCP 桥 / 服务运行时 / 硬件状态", +}) as Profile; + +// ============================================================================ +// mergeProfiles —— 共享 base + 叠差异(并集去重,稳定序) +// ============================================================================ + +/** + * 共享 base + 叠差异:返回 base 与 delta 的扩展/工具并集(去重,base 序在前)。 + * + * 契约签名 delta: Pick —— delta 不带 id/note, + * 故结果继承 base 的 id/note;具体命名 profile(repair-diagnosis / + * embedded-dev)在调用处用对象展开覆盖 id/note,复用本函数做并集重活。 + * + * 纯逻辑、确定性、无副作用。结果深冻结。 + * + * @param base 基底 profile(extensions/tools 序保留在前)。 + * @param delta 差异(仅 extensions/tools;追加 base 未含项)。 + * @returns 合并后的新 profile(id/note 继承 base,深冻结)。 + */ +export function mergeProfiles( + base: Profile, + delta: Pick, +): Profile { + return Object.freeze({ + id: base.id, + extensions: unionStable(base.extensions, delta.extensions), + tools: unionStable(base.tools, delta.tools), + note: base.note, + }) as Profile; +} + +// ============================================================================ +// diffProfiles —— 两 profile 扩展域差异(added / removed) +// ============================================================================ + +/** + * 两 profile 的扩展域差异:b 比 a 多的 = added,b 比 a 少的 = removed。 + * + * 按 SPEC "各叠差异扩展" 只 diff `extensions`(profile 选择主轴,工具随扩展派生, + * 避免扩展域名与工具名同形如 "flash" 的碰撞歧义)。工具差异调用方可直接 diff + * `.tools`。added/removed 各保序(不主动去重;遍历 a/b.extensions 逐条比对, + * 重复由输入驱动 —— 真实 profile 无重复扩展条目,故输出无重复;若传入含重复 + * 的畸形 profile,输出会保留重复条目,调用方负责输入归一)。 + * + * 纯逻辑、确定性、无副作用。结果数组深冻结。 + * + * @param a 基准 profile。 + * @param b 对比 profile。 + * @returns { added: b 有 a 无;removed: a 有 b 无 }(均深冻结 readonly)。 + */ +export function diffProfiles( + a: Profile, + b: Profile, +): { added: readonly string[]; removed: readonly string[] } { + const aSet = new Set(a.extensions); + const bSet = new Set(b.extensions); + const added: string[] = []; + for (const x of b.extensions) { + if (!aSet.has(x)) added.push(x); + } + const removed: string[] = []; + for (const x of a.extensions) { + if (!bSet.has(x)) removed.push(x); + } + return Object.freeze({ + added: frozen(added), + removed: frozen(removed), + }) as { added: readonly string[]; removed: readonly string[] }; +} diff --git a/src/profiles/embedded-dev.ts b/src/profiles/embedded-dev.ts new file mode 100644 index 0000000..f317629 --- /dev/null +++ b/src/profiles/embedded-dev.ts @@ -0,0 +1,60 @@ +/** + * @module profiles/embedded-dev + * + * 嵌入式开发 profile —— base + cross-compile / flash / jtag-debugger / + * device-tree / board-link / reg-tool。 + * + * 第二个业务方向(嵌入式 C 层开发)要的能力:交叉编译(cross-compile 的 + * xcompile)、三段式烧录(flash 的 flash)、JTAG 调试(jtag-debugger 的 + * debugger)、设备树解析(device-tree 的 dt)、板链路连接与执行(board-link + * 的 board_connect/board_exec/board_scp/board_console)、寄存器读写(reg-tool + * 的 reg)。 + * + * 由 {@link mergeProfiles}(BASE_PROFILE, EMBEDDED_DELTA) 复用 base 并集重活, + * 仅覆盖 id / note —— 单一事实源,无重复清单。深冻结,运行时不可变。 + * + * 范式:纯逻辑,顶层仅 import type + 命名导出,零 pi 运行时依赖。 + */ + +import type { Profile } from "./base.js"; +import { BASE_PROFILE, mergeProfiles, toolsFor } from "./base.js"; + +/** + * 嵌入式开发差异扩展域(base 之上叠加)。 + * tools 由 {@link toolsFor} 从本域派生 → xcompile / flash / debugger / dt / + * board_connect / board_exec / board_scp / board_console / reg。 + */ +export const EMBEDDED_DEV_DELTA: Readonly< + Pick +> = Object.freeze({ + extensions: Object.freeze([ + "cross-compile", + "flash", + "jtag-debugger", + "device-tree", + "board-link", + "reg-tool", + ]), + tools: toolsFor([ + "cross-compile", + "flash", + "jtag-debugger", + "device-tree", + "board-link", + "reg-tool", + ]), +}) as Readonly>; + +/** + * 嵌入式开发 profile —— base + cross-compile / flash / jtag-debugger / + * device-tree / board-link / reg-tool。 + * + * 复用 {@link mergeProfiles} 做 extensions/tools 并集(去重保序),仅覆盖 id/note。 + * 工具集 = base 工具 + xcompile + flash + debugger + dt + board_connect + + * board_exec + board_scp + board_console + reg。 + */ +export const EMBEDDED_DEV_PROFILE: Profile = Object.freeze({ + ...mergeProfiles(BASE_PROFILE, EMBEDDED_DEV_DELTA), + id: "embedded-dev", + note: "嵌入式开发:base + 交叉编译 + 烧录 + JTAG 调试 + 设备树 + 板链路 + 寄存器读写", +}) as Profile; diff --git a/src/profiles/index.ts b/src/profiles/index.ts new file mode 100644 index 0000000..2a56662 --- /dev/null +++ b/src/profiles/index.ts @@ -0,0 +1,77 @@ +/** + * @module profiles + * + * profile/bundle 分层 barrel(T15)。 + * + * 职责: + * - re-export 三 profile 常量 + Profile 类型 + mergeProfiles / diffProfiles / + * toolsFor / DOMAIN_TOOLS / BASE_EXTENSIONS(命名导出,下游可深引用) + * - {@link resolveProfile}:fail-closed 按 id 查表,未知 id 抛错 + * + * 范式:纯逻辑,顶层仅 import type + 命名 re-export,零 pi 运行时依赖。 + * 不注册任何扩展、不改 src/extensions/index.ts barrel(独占文件边界)。 + */ + +import type { Profile } from "./base.js"; + +// 仅把注册表(PROFILE_REGISTRY)实际引用的三个 profile 常量作值导入; +// 纯函数 / 类型 / delta 用 `export ... from` 直通 re-export,避免重复值导入。 +import { BASE_PROFILE } from "./base.js"; +import { REPAIR_DIAGNOSIS_PROFILE } from "./repair-diagnosis.js"; +import { EMBEDDED_DEV_PROFILE } from "./embedded-dev.js"; + +// 类型 re-export(import type 擦除,下游类型侧统一从本 barrel 取) +export type { Profile } from "./base.js"; +// 域→工具表 + base 扩展清单 re-export(下游诊断/装配用) +export { DOMAIN_TOOLS, BASE_EXTENSIONS } from "./base.js"; +// 纯函数 re-export(直通,不经本模块值绑定) +export { mergeProfiles, diffProfiles, toolsFor } from "./base.js"; +// 差异清单 re-export +export { REPAIR_DIAGNOSIS_DELTA } from "./repair-diagnosis.js"; +export { EMBEDDED_DEV_DELTA } from "./embedded-dev.js"; +// 三 profile 常量 re-export +export { BASE_PROFILE } from "./base.js"; +export { REPAIR_DIAGNOSIS_PROFILE } from "./repair-diagnosis.js"; +export { EMBEDDED_DEV_PROFILE } from "./embedded-dev.js"; + +// ============================================================================ +// PROFILE_REGISTRY + resolveProfile —— fail-closed 按 id 查表 +// ============================================================================ + +/** + * id → profile 注册表(深冻结,运行时不可变)。 + * + * resolveProfile 据此查表。新增 profile 只需在此注册一行,resolveProfile 自动覆盖。 + */ +const PROFILE_REGISTRY: Readonly> = Object.freeze({ + [BASE_PROFILE.id]: BASE_PROFILE, + [REPAIR_DIAGNOSIS_PROFILE.id]: REPAIR_DIAGNOSIS_PROFILE, + [EMBEDDED_DEV_PROFILE.id]: EMBEDDED_DEV_PROFILE, +}) as Readonly>; + +/** + * 按 id 解析 profile —— fail-closed:未知 id 抛错(不返回 undefined/默认值, + * 防止调用方静默拿到错 profile 后装配出错扩展)。 + * + * 用 {@link Object.hasOwn} 判定而非 `id in PROFILE_REGISTRY` 或下标取值后 + * `!== undefined`:后两者走原型链,对 "toString" / "constructor" / "__proto__" + * 等 Object.prototype 继承键会取到继承的函数/对象(!== undefined → 不抛 → + * 返回继承成员当 Profile 用,调用方后续访问 .extensions/.tools 行为不可预期)。 + * `Object.hasOwn` 只认自身属性,继承键一律判为未注册 → fail-closed 抛错。 + * + * 纯逻辑、确定性、无副作用。返回注册表中的冻结实例(引用共享,不复制)。 + * + * @param id profile 标识("base" / "repair-diagnosis" / "embedded-dev")。 + * @returns 对应的冻结 profile。 + * @throws {Error} 当 id 未在 {@link PROFILE_REGISTRY} 注册时(fail-closed)。 + */ +export function resolveProfile(id: string): Profile { + if (!Object.hasOwn(PROFILE_REGISTRY, id)) { + throw new Error( + `resolveProfile: unknown profile id "${id}" — registered: ${Object.keys( + PROFILE_REGISTRY, + ).join(", ")} (fail-closed)`, + ); + } + return PROFILE_REGISTRY[id]; +} diff --git a/src/profiles/repair-diagnosis.ts b/src/profiles/repair-diagnosis.ts new file mode 100644 index 0000000..bbaee8c --- /dev/null +++ b/src/profiles/repair-diagnosis.ts @@ -0,0 +1,44 @@ +/** + * @module profiles/repair-diagnosis + * + * 维修诊断 profile —— base + pdf-reader / datasheet-rag / peripheral-probe。 + * + * 第一个业务方向(电子维修诊断 9 阶段 SOP)要的能力:读器件 datasheet PDF + * (pdf-reader 的 read_pdf)、按器件型号 RAG 查 datasheet 段落(datasheet-rag + * 的 datasheet_query)、探外设总线(peripheral-probe 的 bus_probe)。 + * + * 由 {@link mergeProfiles}(BASE_PROFILE, REPAIR_DELTA) 复用 base 并集重活, + * 仅覆盖 id / note —— 单一事实源,无重复清单。深冻结,运行时不可变。 + * + * 范式:纯逻辑,顶层仅 import type + 命名导出,零 pi 运行时依赖。 + */ + +import type { Profile } from "./base.js"; +import { BASE_PROFILE, mergeProfiles, toolsFor } from "./base.js"; + +/** + * 维修诊断差异扩展域(base 之上叠加)。 + * tools 由 {@link toolsFor} 从本域派生 → read_pdf / datasheet_query / bus_probe。 + */ +export const REPAIR_DIAGNOSIS_DELTA: Readonly< + Pick +> = Object.freeze({ + extensions: Object.freeze([ + "pdf-reader", + "datasheet-rag", + "peripheral-probe", + ]), + tools: toolsFor(["pdf-reader", "datasheet-rag", "peripheral-probe"]), +}) as Readonly>; + +/** + * 维修诊断 profile —— base + pdf-reader / datasheet-rag / peripheral-probe。 + * + * 复用 {@link mergeProfiles} 做 extensions/tools 并集(去重保序),仅覆盖 id/note。 + * 工具集 = base 工具 + read_pdf + datasheet_query + bus_probe。 + */ +export const REPAIR_DIAGNOSIS_PROFILE: Profile = Object.freeze({ + ...mergeProfiles(BASE_PROFILE, REPAIR_DIAGNOSIS_DELTA), + id: "repair-diagnosis", + note: "维修诊断:base + PDF datasheet 阅读 + datasheet RAG 检索 + 外设总线探针", +}) as Profile; diff --git a/tests/capabilities-misc.test.ts b/tests/capabilities-misc.test.ts new file mode 100644 index 0000000..7203953 --- /dev/null +++ b/tests/capabilities-misc.test.ts @@ -0,0 +1,1320 @@ +/** + * capabilities-misc 完整测试套件 —— T17(approval + credentials + settings + lsp)。 + * + * 被测模块均为纯逻辑(零 pi 依赖、无硬件、无网络),可直接 import 命名导出。 + * 唯一可注入依赖是 CredentialsStore 的 envLookup;approval 的计时器用 + * vi.useFakeTimers() 注入控制。无 appendEntry/exec/emitter/runTsc/readFile 依赖 + * (这四个模块设计上不触碰它们)。 + * + * 应用的测试方法论(每个 describe 块以【方法论】标签标注): + * - 等价类划分(有效/无效/边界类) + * - 边界值分析(off-by-one、空、单元素、min/max) + * - 决策表(组合输入→期望,覆盖全分支) + * - 状态转换(mode + approver 注册/注销迁移 + 重入 + 不可达状态兜底) + * - 变异测试:6 个 seeded bug 内联副本,每个断言被某测试杀死(植入后该测试失败=被杀) + * - 对抗/fuzz:null/undefined/巨大/NaN/负 timeout/并发重入 + * - 元蜕变/不变式:fail-closed 单调 deny、freeze→篡改抛 TypeError、 + * redact 不残留明文、snapshot 副本隔离内部状态、waterfall 不调 next=短路 + * + * 门: + * 1. 真实代码全绿(npx vitest run tests/capabilities-misc.test.ts) + * 2. 每个 seeded bug 变体内联副本断言被某测试杀死(buggyResult ≠ correctResult → 杀) + * + * 见架构设计文档 §6.1 T17。 + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { + ApprovalGate, + DEFAULT_APPROVAL_MODE, + type ApprovalMode, + type ApprovalRequest, + type ApprovalResult, + type ApproverFn, +} from "../src/capabilities/approval.js"; +import { + CredentialsStore, + REDACTED_PLACEHOLDER, +} from "../src/capabilities/credentials.js"; +import { SettingsStore } from "../src/capabilities/settings.js"; +import { + NoopLspBridge, + type LspBridge, + type LspInitOptions, +} from "../src/capabilities/lsp.js"; + +// ---------------------------------------------------------------------------- +// 共用工厂 +// ---------------------------------------------------------------------------- + +/** 立即 approver:按 decision 字面量返回。 */ +function makeApprover( + decision: "approve" | "deny", + reason = "mock", +): ApproverFn { + return async (): Promise => ({ + decision, + reason, + by: "approver", + }); +} + +/** 慢 approver:延迟 delayMs 后 resolve(配合 fake timers)。 */ +function makeSlowApprover( + delayMs: number, + decision: "approve" | "deny" = "approve", +): ApproverFn { + return () => + new Promise((resolve) => + setTimeout( + () => resolve({ decision, reason: "late", by: "approver" }), + delayMs, + ), + ); +} + +/** 记录是否被调用的 approver(用于短路断言)。 */ +function makeRecordingApprover( + decision: "approve" | "deny" = "approve", +): { fn: ApproverFn; called: () => boolean } { + let called = false; + return { + fn: async (): Promise => { + called = true; + return { decision, reason: "rec", by: "approver" }; + }, + called: () => called, + }; +} + +// ============================================================================ +// 【等价类划分】approval —— 三模式有效类 + 未知/缺省无效类 +// ============================================================================ + +describe("【等价类划分】approval mode 有效/无效类", () => { + it("auto-deny 类:任意 risk/action/context 一律 deny by auto", async () => { + const gate = new ApprovalGate({ mode: "auto-deny" }); + const reqs: ApprovalRequest[] = [ + { action: "flash", risk: "high" }, + { action: "devmem-write", risk: "low", context: "0x40020000" }, + { action: "dd", risk: "medium" }, + { action: "rm", risk: "high", context: "/lib" }, + ]; + for (const req of reqs) { + const r = await gate.request(req); + expect(r.decision).toBe("deny"); + expect(r.by).toBe("auto"); + expect(r.reason).toContain("auto-deny"); + } + }); + + it("auto-approve 类:任意请求 approve by auto,reason 固定", async () => { + const gate = new ApprovalGate({ mode: "auto-approve" }); + for (const req of [ + { action: "read", risk: "low" }, + { action: "flash", risk: "high" }, + ] as ApprovalRequest[]) { + const r = await gate.request(req); + expect(r).toMatchObject({ decision: "approve", by: "auto" }); + expect(r.reason).toBe("auto-approve mode"); + } + }); + + it("interactive 有效类:有 approver → approver 裁决透传(approve/deny 均可)", async () => { + for (const decision of ["approve", "deny"] as const) { + const gate = new ApprovalGate({ mode: "interactive" }); + gate.registerApprover(makeApprover(decision, `mock-${decision}`)); + const r = await gate.request({ action: "flash", risk: "high" }); + expect(r.decision).toBe(decision); + expect(r.by).toBe("approver"); + expect(r.reason).toBe(`mock-${decision}`); + } + }); + + it("无效类:未知 mode 一律按 fail-closed deny(含 'zzz'/'AUTO-DENY' 大写/'deny'/'')", async () => { + const gate = new ApprovalGate(); + // 默认就是 auto-deny + expect(DEFAULT_APPROVAL_MODE).toBe("auto-deny"); + for (const m of ["zzz", "AUTO-DENY", "deny", ""] as unknown as ApprovalMode[]) { + gate.setMode(m); + const r = await gate.request({ action: "x", risk: "low" }); + expect(r.decision).toBe("deny"); + expect(r.by).toBe("auto"); + expect(r.reason).toContain("auto-deny"); + } + }); + + it("缺省类:不传 opts → 默认 auto-deny(fail-closed 无人值守默认)", async () => { + const gate = new ApprovalGate(); + const r = await gate.request({ action: "flash", risk: "high" }); + expect(r).toMatchObject({ decision: "deny", by: "auto" }); + }); + + it("DEFAULT_APPROVAL_MODE 常量值=auto-deny(下游契约不得改名)", () => { + expect(DEFAULT_APPROVAL_MODE).toBe("auto-deny"); + }); +}); + +// ============================================================================ +// 【边界值分析】approval timeout —— 优先级、off-by-one、0、负、NaN、缺省 +// ============================================================================ + +describe("【边界值分析】approval timeout 优先级与边界", () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it("req.timeoutMs > 构造 timeoutMs(更短者):用 req → timeout deny", async () => { + const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 10_000 }); + gate.registerApprover(makeSlowApprover(10_000, "approve")); + const p = gate.request({ action: "flash", risk: "high", timeoutMs: 50 }); + vi.advanceTimersByTime(50); + const r = await p; + expect(r).toMatchObject({ decision: "deny", by: "timeout" }); + expect(r.reason).toContain("50ms"); + }); + + it("构造 timeoutMs 生效(缺 req.timeoutMs)→ timeout deny", async () => { + const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 30 }); + gate.registerApprover(makeSlowApprover(10_000)); + const p = gate.request({ action: "flash", risk: "high" }); + vi.advanceTimersByTime(30); + const r = await p; + expect(r).toMatchObject({ decision: "deny", by: "timeout" }); + expect(r.reason).toContain("30ms"); + }); + + it("DEFAULT_TIMEOUT_MS 兜底(两者均缺省=10000)", async () => { + const gate = new ApprovalGate({ mode: "interactive" }); + gate.registerApprover(makeSlowApprover(10_010)); + const p = gate.request({ action: "flash", risk: "high" }); + vi.advanceTimersByTime(10_000); + const r = await p; + expect(r).toMatchObject({ decision: "deny", by: "timeout" }); + expect(r.reason).toContain("10000ms"); + }); + + it("approver 先于超时 resolve → approver 裁决胜出(边界:恰好不超时)", async () => { + const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 100 }); + gate.registerApprover(makeSlowApprover(10, "approve")); + const p = gate.request({ action: "flash", risk: "high" }); + vi.advanceTimersByTime(10); + const r = await p; + expect(r).toMatchObject({ decision: "approve", by: "approver" }); + }); + + it("timeoutMs=0 边界:req 显式 0 → 立即超时 deny(0 非 null/undefined)", async () => { + const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 10_000 }); + gate.registerApprover(makeSlowApprover(10_000)); + const p = gate.request({ action: "flash", risk: "high", timeoutMs: 0 }); + vi.advanceTimersByTime(1); + const r = await p; + expect(r.by).toBe("timeout"); + expect(r.decision).toBe("deny"); + }); + + it("负 timeoutMs 边界:setTimeout 视同 0 → 仍 timeout deny(不报错)", async () => { + const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 10_000 }); + gate.registerApprover(makeSlowApprover(10_000)); + const p = gate.request({ action: "flash", risk: "high", timeoutMs: -5 }); + vi.advanceTimersByTime(1); + const r = await p; + expect(r.by).toBe("timeout"); + expect(r.decision).toBe("deny"); + }); + + it("NaN timeoutMs 边界:setTimeout(NaN) 视同 0 → timeout deny(不报错)", async () => { + const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 10_000 }); + gate.registerApprover(makeSlowApprover(10_000)); + const p = gate.request({ + action: "flash", + risk: "high", + timeoutMs: NaN, + }); + vi.advanceTimersByTime(1); + const r = await p; + expect(r.by).toBe("timeout"); + expect(r.decision).toBe("deny"); + }); +}); + +// ============================================================================ +// 【决策表】approval —— mode × approver存在性 × approver行为 → 期望 +// ============================================================================ + +describe("【决策表】approval mode×approver×行为 → decision/by", () => { + type Row = { + name: string; + mode: ApprovalMode; + registerApprover: boolean; + approverThrows?: boolean; + approverSlow?: boolean; + approverDecision?: "approve" | "deny"; + timeoutMs?: number; + expectDecision: "approve" | "deny"; + expectBy: "auto" | "approver" | "timeout"; + expectApproverCalled: boolean; + }; + + const rows: Row[] = [ + { name: "auto-deny / no approver", mode: "auto-deny", registerApprover: false, expectDecision: "deny", expectBy: "auto", expectApproverCalled: false }, + { name: "auto-deny / has approver (短路不调)", mode: "auto-deny", registerApprover: true, approverDecision: "approve", expectDecision: "deny", expectBy: "auto", expectApproverCalled: false }, + { name: "auto-approve / no approver", mode: "auto-approve", registerApprover: false, expectDecision: "approve", expectBy: "auto", expectApproverCalled: false }, + { name: "auto-approve / has approver (短路不调)", mode: "auto-approve", registerApprover: true, approverDecision: "deny", expectDecision: "approve", expectBy: "auto", expectApproverCalled: false }, + { name: "interactive / no approver → fail-closed", mode: "interactive", registerApprover: false, expectDecision: "deny", expectBy: "auto", expectApproverCalled: false }, + { name: "interactive / approver approve", mode: "interactive", registerApprover: true, approverDecision: "approve", expectDecision: "approve", expectBy: "approver", expectApproverCalled: true }, + { name: "interactive / approver deny", mode: "interactive", registerApprover: true, approverDecision: "deny", expectDecision: "deny", expectBy: "approver", expectApproverCalled: true }, + { name: "interactive / approver throws → deny fail-closed", mode: "interactive", registerApprover: true, approverThrows: true, expectDecision: "deny", expectBy: "auto", expectApproverCalled: true }, + { name: "interactive / approver slow → timeout", mode: "interactive", registerApprover: true, approverSlow: true, approverDecision: "approve", timeoutMs: 50, expectDecision: "deny", expectBy: "timeout", expectApproverCalled: true }, + ]; + + for (const row of rows) { + it(row.name, async () => { + const useFake = row.approverSlow === true; + if (useFake) vi.useFakeTimers(); + try { + const gate = new ApprovalGate({ mode: row.mode, timeoutMs: 10_000 }); + let approverCalled = false; + if (row.registerApprover) { + if (row.approverThrows) { + gate.registerApprover(async () => { + approverCalled = true; + throw new Error("approver boom"); + }); + } else if (row.approverSlow) { + gate.registerApprover( + () => { + approverCalled = true; // 同步标记:approver 已被调用 + return new Promise((resolve) => + setTimeout( + () => + resolve({ decision: row.approverDecision ?? "approve", reason: "ok", by: "approver" }), + 10_000, + ), + ); + }, + ); + } else { + gate.registerApprover(async () => { + approverCalled = true; + return { decision: row.approverDecision ?? "approve", reason: "ok", by: "approver" } as ApprovalResult; + }); + } + } + const p = gate.request({ action: "flash", risk: "high", timeoutMs: row.timeoutMs }); + if (useFake) vi.advanceTimersByTime(row.timeoutMs ?? 0); + const r = await p; + expect(r.decision).toBe(row.expectDecision); + expect(r.by).toBe(row.expectBy); + expect(approverCalled).toBe(row.expectApproverCalled); + if (row.approverThrows) { + expect(r.reason).toContain("approver threw"); + } + } finally { + if (useFake) vi.useRealTimers(); + } + }); + } +}); + +// ============================================================================ +// 【状态转换】approval —— mode/approver 注册/注销迁移 + 重入 + 不可达态兜底 +// ============================================================================ + +describe("【状态转换】approval mode & approver 注册/注销迁移", () => { + it("初始态=auto-deny;setMode 迁移后行为随之变;再迁回 auto-deny", async () => { + const gate = new ApprovalGate(); // 初始 auto-deny + expect(await gate.request({ action: "x", risk: "low" })).toMatchObject({ + decision: "deny", + by: "auto", + }); + gate.setMode("auto-approve"); + expect(await gate.request({ action: "x", risk: "low" })).toMatchObject({ + decision: "approve", + by: "auto", + }); + // 迁到 interactive 无 approver(不可达态兜底 → deny) + gate.setMode("interactive"); + expect(await gate.request({ action: "x", risk: "low" })).toMatchObject({ + decision: "deny", + by: "auto", + }); + gate.setMode("auto-deny"); + expect(await gate.request({ action: "x", risk: "low" })).toMatchObject({ + decision: "deny", + by: "auto", + }); + }); + + it("registerApprover→request→dispose→request 状态迁移闭环", async () => { + const gate = new ApprovalGate({ mode: "interactive" }); + // 态 A:无 approver → deny + expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({ + decision: "deny", + by: "auto", + }); + // 态 B:注册 → approve + const dispose = gate.registerApprover(makeApprover("approve")); + expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({ + decision: "approve", + by: "approver", + }); + // 态 C:dispose → 回 deny + dispose(); + expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({ + decision: "deny", + by: "auto", + }); + }); + + it("disposer 幂等重入:dispose 两次不报错", async () => { + const gate = new ApprovalGate({ mode: "interactive" }); + const dispose = gate.registerApprover(makeApprover("approve")); + expect(() => { + dispose(); + dispose(); // 重入幂等 + }).not.toThrow(); + expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({ + decision: "deny", + by: "auto", + }); + }); + + it("后注册者覆盖前者;旧 disposer 不误摘后来注册者", async () => { + const gate = new ApprovalGate({ mode: "interactive" }); + const disposeA = gate.registerApprover(makeApprover("deny", "A")); + const disposeB = gate.registerApprover(makeApprover("approve", "B")); // B 覆盖 A + // 当前应 B:approve + expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({ + decision: "approve", + by: "approver", + }); + // 旧 disposer(A)调用:approver 现是 B≠A,不应摘除 B + disposeA(); + expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({ + decision: "approve", + by: "approver", + }); + // B 的 disposer 才摘除 + disposeB(); + expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({ + decision: "deny", + by: "auto", + }); + }); + + it("同一 fn 注册两次后 dispose 一次即清空(=== 自摘除语义)", async () => { + const gate = new ApprovalGate({ mode: "interactive" }); + const fn = makeApprover("approve", "same"); + const d1 = gate.registerApprover(fn); + const d2 = gate.registerApprover(fn); // 同一引用覆盖 + // d1 此时已不再 === 当前 approver? 当前 approver===fn,d1 的 disposer 检查 ===fn 仍真 + // dispose d1:因 this.approver===fn → 摘除 + d1(); + expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({ + decision: "deny", + by: "auto", + }); + // d2 再 dispose 幂等 + expect(() => d2()).not.toThrow(); + }); + + it("并发重入:同一 gate 多个 request 并发不互相干扰(各自 race)", async () => { + vi.useFakeTimers(); + try { + const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 100 }); + let callCount = 0; + gate.registerApprover( + () => + new Promise((resolve) => + setTimeout(() => { + callCount++; + resolve({ decision: "approve", reason: "ok", by: "approver" }); + }, 10), + ), + ); + const p1 = gate.request({ action: "a", risk: "low" }); + const p2 = gate.request({ action: "b", risk: "low" }); + const p3 = gate.request({ action: "c", risk: "low" }); + vi.advanceTimersByTime(10); + const [r1, r2, r3] = await Promise.all([p1, p2, p3]); + for (const r of [r1, r2, r3]) { + expect(r).toMatchObject({ decision: "approve", by: "approver" }); + } + expect(callCount).toBe(3); + } finally { + vi.useRealTimers(); + } + }); +}); + +// ============================================================================ +// 【对抗/fuzz】approval —— 畸形 req、approver 抛非 Error、超长 context +// ============================================================================ + +describe("【对抗/fuzz】approval 畸形/滥用输入", () => { + it("approver 抛非 Error 值(null/string/NaN/undefined/42/{})→ 仍 fail-closed deny by auto", async () => { + const gate = new ApprovalGate({ mode: "interactive" }); + for (const thrown of [null, "string-err", NaN, undefined, 42, {}]) { + gate.registerApprover(async () => { + throw thrown; + }); + const r = await gate.request({ action: "f", risk: "high" }); + expect(r.decision).toBe("deny"); + expect(r.by).toBe("auto"); + expect(r.reason).toContain("approver threw"); + } + }); + + it("approver 返回非法 decision 字面量 → 原样透传(gate 不做白名单校验,契约由调用方保证)", async () => { + const gate = new ApprovalGate({ mode: "interactive" }); + gate.registerApprover( + async () => + ({ decision: "maybe", reason: "x", by: "approver" }) as unknown as ApprovalResult, + ); + const r = await gate.request({ action: "f", risk: "high" }); + expect(r.by).toBe("approver"); + expect(r.decision as string).toBe("maybe"); + }); + + it("超长 context 字符串不致崩溃/超时", async () => { + const gate = new ApprovalGate({ mode: "interactive" }); + const big = "x".repeat(1_000_000); + gate.registerApprover(makeApprover("approve")); + const r = await gate.request({ action: "dd", risk: "high", context: big }); + expect(r).toMatchObject({ decision: "approve", by: "approver" }); + }); + + it("risk/action 为空串 → 仍正常裁决(不校验枚举)", async () => { + const gate = new ApprovalGate({ mode: "auto-approve" }); + const r = await gate.request({ action: "", risk: "" } as unknown as ApprovalRequest); + expect(r).toMatchObject({ decision: "approve", by: "auto" }); + }); +}); + +// ============================================================================ +// 【元蜕变/不变式】approval —— fail-closed 单调 deny、计时器不悬挂、短路 +// ============================================================================ + +describe("【元蜕变/不变式】approval fail-closed 单调性 + 计时器清理 + 短路", () => { + it("不变式:auto-deny 模式对任意 N 个不同请求恒 deny(单调)", async () => { + const gate = new ApprovalGate({ mode: "auto-deny" }); + const decisions = new Set(); + const bys = new Set(); + for (let i = 0; i < 20; i++) { + const r = await gate.request({ action: `act${i}`, risk: "low", context: `c${i}` }); + decisions.add(r.decision); + bys.add(r.by); + } + expect(decisions).toEqual(new Set(["deny"])); + expect(bys).toEqual(new Set(["auto"])); + }); + + it("不变式:approver 先 resolve 后计时器必 clear(无悬挂 timer)", async () => { + vi.useFakeTimers(); + const clearSpy = vi.spyOn(globalThis, "clearTimeout"); + try { + const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 10_000 }); + gate.registerApprover(makeSlowApprover(10, "approve")); + const p = gate.request({ action: "f", risk: "high" }); + vi.advanceTimersByTime(10); + await p; + // 再推过超时点:若计时器未 clear,残留超时回调会触发 + vi.advanceTimersByTime(10_000); + expect(clearSpy).toHaveBeenCalled(); + } finally { + clearSpy.mockRestore(); + vi.useRealTimers(); + } + }); + + it("不变式:timeout 路径也必 clear 计时器(finally 不分胜负均执行)", async () => { + vi.useFakeTimers(); + const clearSpy = vi.spyOn(globalThis, "clearTimeout"); + try { + const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 50 }); + gate.registerApprover(makeSlowApprover(10_000, "approve")); // 超时胜 + const p = gate.request({ action: "f", risk: "high" }); + vi.advanceTimersByTime(50); + const r = await p; + expect(r.by).toBe("timeout"); + expect(clearSpy).toHaveBeenCalled(); + } finally { + clearSpy.mockRestore(); + vi.useRealTimers(); + } + }); + + it("不变式:auto-* 模式 waterfall 不调 next=短路(approver 永不被调)", async () => { + for (const mode of ["auto-deny", "auto-approve"] as const) { + const gate = new ApprovalGate({ mode }); + const rec = makeRecordingApprover("approve"); + gate.registerApprover(rec.fn); + await gate.request({ action: "f", risk: "high" }); + expect(rec.called()).toBe(false); // 短路:approver 永不被调 + } + }); + + it("元蜕变:approver 同一裁决在有无 timeoutMs(足够大)下等价(变换保持)", async () => { + const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 10_000 }); + gate.registerApprover(makeApprover("approve", "stable")); + const r1 = await gate.request({ action: "f", risk: "high" }); // 无 req.timeoutMs + const r2 = await gate.request({ action: "f", risk: "high", timeoutMs: 10_000 }); // 大 timeoutMs + expect(r1).toEqual(r2); + }); +}); + +// ============================================================================ +// 【等价类 + 边界值】credentials —— redact 匹配类与边界 +// ============================================================================ + +describe("【等价类划分】credentials redact 有效/无效类", () => { + const store = new CredentialsStore(); + + it("有效类:所有已知前缀密钥(8+ 后缀)→ ", () => { + for (const prefix of [ + "sk-", + "ghp_", + "gho_", + "ghs_", + "ghr_", + "ghu_", + "github_pat_", + "xoxb-", + "xoxp-", + "glpat-", + ]) { + const tok = prefix + "abcdefgh"; // 前缀 + 恰好 8 位 + expect(store.redact(tok)).toBe(REDACTED_PLACEHOLDER); + } + }); + + it("有效类:长不透明 token(40+ 连续 [A-Za-z0-9_-])→ ", () => { + expect(store.redact("a".repeat(40))).toBe(REDACTED_PLACEHOLDER); + expect(store.redact("a".repeat(64))).toBe(REDACTED_PLACEHOLDER); // SHA-256 长度 + expect(store.redact("A1-b_C2-d".repeat(5))).toBe(REDACTED_PLACEHOLDER); // 含 _- 的 50 位 + }); + + it("无效类:普通短串/配置/无密钥串 → 原样不动", () => { + for (const s of ["board=x5 retries=3", "hello world", "Authorization", "no secret here"]) { + expect(store.redact(s)).toBe(s); + } + }); + + it("无效类:sk- 后缀 < 8 位 → 不脱敏(按设计阈值,非密钥)", () => { + expect(store.redact("sk-abcd123")).toBe("sk-abcd123"); // sk- + 7 位 + }); + + it("REDACTED_PLACEHOLDER 常量=(下游契约不得改名)", () => { + expect(REDACTED_PLACEHOLDER).toBe(""); + }); +}); + +describe("【边界值分析】credentials redact 长度边界(off-by-one)", () => { + const store = new CredentialsStore(); + + it("长 token 边界:39 位不脱敏 / 40 位脱敏 / 41 位脱敏", () => { + expect(store.redact("a".repeat(39))).toBe("a".repeat(39)); + expect(store.redact("a".repeat(40))).toBe(REDACTED_PLACEHOLDER); + expect(store.redact("a".repeat(41))).toBe(REDACTED_PLACEHOLDER); + }); + + it("前缀后缀边界:8 位脱敏 / 7 位不脱敏", () => { + expect(store.redact("sk-abcdefgh")).toBe(REDACTED_PLACEHOLDER); // 8 + expect(store.redact("sk-abcdefg")).toBe("sk-abcdefg"); // 7 + }); + + it("空串/单字符边界:redact('')='' / redact('x')='x'", () => { + expect(store.redact("")).toBe(""); + expect(store.redact("x")).toBe("x"); + }); + + it("多个密钥同时出现:全部替换,明文零残留", () => { + const log = "k1=sk-abcdefghij k2=" + "b".repeat(45) + " k3=ghp_xxxxxxxxxx"; + const out = store.redact(log); + expect(out).not.toContain("sk-abcdef"); + expect(out).not.toContain("bbbbb"); + expect(out).not.toContain("ghp_xxx"); + expect(out.split(REDACTED_PLACEHOLDER).length - 1).toBe(3); + }); + + it("密钥后接非匹配字符:密钥部分脱敏,后缀保留(部分匹配)", () => { + // sk- + 8 位后接点号(点不在 [A-Za-z0-9_-]) + expect(store.redact("sk-abcdefgh.tail")).toBe(`${REDACTED_PLACEHOLDER}.tail`); + }); +}); + +// ============================================================================ +// 【决策表】credentials get/set/has —— 内存×env 组合 +// ============================================================================ + +describe("【决策表】credentials get/has 内存×env 组合", () => { + type Row = { + name: string; + mem?: string; + env?: string; + expectGet: string | undefined; + expectHas: boolean; + }; + const rows: Row[] = [ + { name: "仅内存有", mem: "mem-val", expectGet: "mem-val", expectHas: true }, + { name: "仅 env 有", env: "env-val", expectGet: "env-val", expectHas: true }, + { name: "内存+env(内存优先)", mem: "mem-val", env: "env-val", expectGet: "mem-val", expectHas: true }, + { name: "两者皆无", expectGet: undefined, expectHas: false }, + { name: "内存有但空串(区分 undefined 与 '')", mem: "", env: "env-val", expectGet: "", expectHas: true }, + { name: "env 有但空串", env: "", expectGet: "", expectHas: true }, + ]; + for (const row of rows) { + it(row.name, () => { + const env = new Map(); + if (row.env !== undefined) env.set("K", row.env); + const store = new CredentialsStore((n) => env.get(n)); + if (row.mem !== undefined) store.set("K", row.mem); + expect(store.get("K")).toBe(row.expectGet); + expect(store.has("K")).toBe(row.expectHas); + }); + } +}); + +// ============================================================================ +// 【对抗/fuzz】credentials —— null/undefined/巨大/非字符串 +// ============================================================================ + +describe("【对抗/fuzz】credentials 畸形输入", () => { + it("redact(null/undefined/0/false) → 原样返回(!s 短路,不抛)", () => { + const store = new CredentialsStore(); + expect(store.redact(null as unknown as string)).toBe(null); + expect(store.redact(undefined as unknown as string)).toBe(undefined); + // @ts-expect-error 故意传非串 + expect(store.redact(0)).toBe(0); + // @ts-expect-error 故意传 false + expect(store.redact(false)).toBe(false); + }); + + it("redact 巨大串(1MB)不崩溃且替换密钥", () => { + const store = new CredentialsStore(); + const big = "sk-abcdefgh".repeat(100_000); // ~1.1MB 含 10 万密钥 + const out = store.redact(big); + expect(out).not.toContain("sk-abc"); + expect(out.length).toBeGreaterThan(0); + }); + + it("redact 含 _- 与字母数字混合的长 token 边界(不误伤短 token)", () => { + const store = new CredentialsStore(); + const t39 = "a1_b2-c3_d4-e5_f6-g7_h8-i9_j0-k1_l2-m3_n4".slice(0, 39); + expect(t39.length).toBe(39); + expect(store.redact(t39)).toBe(t39); + // 幂等 + expect(store.redact(t39)).toBe(store.redact(t39)); + }); + + it("get(undefined/空名) → undefined,不抛", () => { + const store = new CredentialsStore(() => undefined); + expect(store.get("")).toBeUndefined(); + expect(store.get(undefined as unknown as string)).toBeUndefined(); + expect(store.has("")).toBe(false); + }); + + it("set 不落盘不写 env:set 后 envLookup 不见该 key", () => { + const env = new Map([["K", "env-only"]]); + const spy = vi.fn((n: string) => env.get(n)); + const store = new CredentialsStore(spy); + store.set("K", "mem-val"); + // get 走内存优先,不触发 envLookup + expect(store.get("K")).toBe("mem-val"); + expect(spy).not.toHaveBeenCalled(); + // 未 set 的 key 才查 env + expect(store.get("OTHER")).toBeUndefined(); + expect(spy).toHaveBeenCalledWith("OTHER"); + }); +}); + +// ============================================================================ +// 【元蜕变/不变式】credentials —— key 永不 echo、redact 幂等、set→get 等价 +// ============================================================================ + +describe("【元蜕变/不变式】credentials key 永不 echo", () => { + it("不变式:任意含密钥串 redact 后不含原密钥子串", () => { + const store = new CredentialsStore(); + const secrets = ["sk-abcdefghijkl", "ghp_abcdefghijkl", "x".repeat(50)]; + for (const s of secrets) { + const out = store.redact(`log: ${s} done`); + expect(out).not.toContain(s); + expect(out).toContain(REDACTED_PLACEHOLDER); + } + }); + + it("元蜕变:redact(redact(s)) == redact(s)(幂等)", () => { + const store = new CredentialsStore(); + for (const s of [ + "a sk-abcdefghij b", + "x".repeat(50), + "plain text only", + "multi sk-aaaa1111 and ghp_bbbb2222", + ]) { + const once = store.redact(s); + const twice = store.redact(once); + expect(twice).toBe(once); + } + }); + + it("元蜕变:set(k,v) 后 get(k)==v 恒成立(replay 等价:多次 get 等价)", () => { + const store = new CredentialsStore(() => undefined); + store.set("K", "v1"); + const g1 = store.get("K"); + const g2 = store.get("K"); + const g3 = store.get("K"); + expect(g1).toBe("v1"); + expect(g1).toBe(g2); + expect(g2).toBe(g3); + }); +}); + +// ============================================================================ +// 【等价类 + 边界值】settings —— defaults 类、深冻结、键约束 +// ============================================================================ + +describe("【等价类划分】settings defaults 有效/边界类", () => { + it("有效类:多类型值(number/string/boolean/对象/数组/null)get/set", () => { + type Cfg = { + n: number; + s: string; + b: boolean; + o: { x: number }; + arr: number[]; + z: null; + }; + const s = new SettingsStore({ + n: 1, + s: "x", + b: true, + o: { x: 2 }, + arr: [1, 2], + z: null, + }); + expect(s.get("n")).toBe(1); + expect(s.get("s")).toBe("x"); + expect(s.get("b")).toBe(true); + expect(s.get("o")).toEqual({ x: 2 }); + expect(s.get("arr")).toEqual([1, 2]); + expect(s.get("z")).toBe(null); + s.set("n", 99); + s.set("s", "y"); + s.set("b", false); + expect(s.get("n")).toBe(99); + expect(s.get("s")).toBe("y"); + expect(s.get("b")).toBe(false); + }); + + it("边界类:空对象 defaults → snapshot 为 {}(深冻结空对象)", () => { + const s = new SettingsStore({}); + const snap = s.snapshot(); + expect(snap).toEqual({}); + expect(Object.isFrozen(snap)).toBe(true); + }); + + it("边界类:单键 defaults", () => { + const s = new SettingsStore({ only: 42 }); + expect(s.get("only")).toBe(42); + s.set("only", 0); + expect(s.get("only")).toBe(0); + }); + + it("隔离类:构造后篡改外部 defaults 顶层属性不影响 store(浅拷贝顶层隔离)", () => { + // defaults 带索引签名以便后续加键;store 泛型显式收窄到 {a,b} 以便 get("c") 报错。 + const defaults: { a: number; b: number; [k: string]: number } = { + a: 1, + b: 2, + }; + const s = new SettingsStore<{ a: number; b: number }>(defaults); + defaults.a = 999; // 篡改外部顶层(原对象,非副本) + defaults.c = 3; // 加键 + expect(s.get("a")).toBe(1); // 顶层不受影响(浅拷贝复制了原语值) + // @ts-expect-error c 不在收窄键集 {a,b} + expect(s.get("c")).toBeUndefined(); + }); + + it("隔离类:构造后篡改外部 defaults 嵌套对象不影响 store(深拷贝隔离)", () => { + const defaults = { o: { x: 1 } }; + const s = new SettingsStore(defaults); + defaults.o.x = 999; // 篡改嵌套引用 + expect(s.get("o").x).toBe(1); // 深拷贝隔离,不受影响 + }); +}); + +// ============================================================================ +// 【边界值分析】settings snapshot 深冻结 —— off-by-one 层级 +// ============================================================================ + +describe("【边界值分析】settings snapshot 深冻结层级", () => { + it("顶层冻结:篡改 snapshot 顶层属性抛 TypeError", () => { + const s = new SettingsStore({ a: 1, b: { x: 1 } }); + const snap = s.snapshot(); + expect(Object.isFrozen(snap)).toBe(true); + expect(() => { + (snap as { a: number }).a = 999; + }).toThrow(TypeError); + }); + + it("一层嵌套冻结:篡改 snapshot.b.x 抛 TypeError", () => { + const s = new SettingsStore({ b: { x: 1 } }); + const snap = s.snapshot(); + expect(Object.isFrozen(snap.b)).toBe(true); + expect(() => { + (snap as { b: { x: number } }).b.x = 999; + }).toThrow(TypeError); + }); + + it("两层嵌套冻结:篡改 snapshot.b.c.x 抛 TypeError(深递归 off-by-one 防漏)", () => { + const s = new SettingsStore({ b: { c: { x: 1 } } }); + const snap = s.snapshot(); + expect(Object.isFrozen(snap.b.c)).toBe(true); + expect(() => { + (snap as { b: { c: { x: number } } }).b.c.x = 999; + }).toThrow(TypeError); + }); + + it("数组元素冻结:snapshot.arr 冻结,元素不可变", () => { + const s = new SettingsStore({ arr: [1, 2, 3] }); + const snap = s.snapshot(); + expect(Object.isFrozen(snap.arr)).toBe(true); + expect(() => { + (snap as { arr: number[] }).arr[0] = 999; + }).toThrow(TypeError); + }); + + it("snapshot 不冻结内部 store(store 仍可 set)", () => { + const s = new SettingsStore({ a: 1 }); + const snap = s.snapshot(); + expect(Object.isFrozen(snap)).toBe(true); + // 内部 store 仍可写 + expect(() => s.set("a", 5)).not.toThrow(); + expect(s.get("a")).toBe(5); + // 旧 snapshot 不受影响 + expect(snap.a).toBe(1); + }); + + it("Map 值深冻结:snapshot 含 Map 时 Map 与键值均冻结", () => { + const s = new SettingsStore({ m: new Map([["k", { v: 1 }]]) }); + const snap = s.snapshot(); + expect(Object.isFrozen(snap.m)).toBe(true); + // Map.set 在冻结的 Map 上静默失败(非 strict),但深层值对象应已冻结 + // 篡改 Map 内的 value 对象应抛 TypeError + const inner = (snap as { m: Map }).m.get("k")!; + expect(Object.isFrozen(inner)).toBe(true); + expect(() => { + inner.v = 999; + }).toThrow(TypeError); + }); + + it("Set 值深冻结:snapshot 含 Set 时 Set 与元素均冻结", () => { + const s = new SettingsStore({ set: new Set([{ v: 1 }]) }); + const snap = s.snapshot(); + expect(Object.isFrozen(snap.set)).toBe(true); + const elem = (snap as { set: Set<{ v: number }> }).set.values().next().value!; + expect(Object.isFrozen(elem)).toBe(true); + expect(() => { + elem.v = 999; + }).toThrow(TypeError); + }); +}); + +// ============================================================================ +// 【状态转换】settings —— set 迁移与 snapshot 时序 +// ============================================================================ + +describe("【状态转换】settings set 迁移与 snapshot 时序", () => { + it("初始态=get defaults;set 迁移值;snapshot 反映当时态", () => { + const s = new SettingsStore({ a: 1 }); + expect(s.get("a")).toBe(1); // 初始态 + const snap0 = s.snapshot(); + s.set("a", 2); // 迁移 + const snap1 = s.snapshot(); + expect(snap0.a).toBe(1); // 旧态冻结不变 + expect(snap1.a).toBe(2); // 新态反映 + expect(s.get("a")).toBe(2); + }); + + it("多次 set 覆盖:最后值胜出(单调迁移)", () => { + const s = new SettingsStore({ a: 0 }); + for (let i = 1; i <= 5; i++) s.set("a", i); + expect(s.get("a")).toBe(5); + }); +}); + +// ============================================================================ +// 【元蜕变/不变式】settings —— snapshot 副本隔离内部状态 +// ============================================================================ + +describe("【元蜕变/不变式】settings snapshot 副本隔离", () => { + it("不变式:snapshot 不影响内部 store 顶层值(set 后再 snapshot 反映新值)", () => { + const s = new SettingsStore({ a: 1 }); + const snap1 = s.snapshot(); + s.set("a", 2); + const snap2 = s.snapshot(); + expect(snap1.a).toBe(1); // 旧快照不变 + expect(snap2.a).toBe(2); // 新快照反映 + expect(s.get("a")).toBe(2); + }); + + it("不变式:snapshot 嵌套对象与内部 store 嵌套对象无共享引用(深克隆隔离)", () => { + const s = new SettingsStore({ b: { x: 1 } }); + const snap = s.snapshot(); + // snapshot 的 b 与 store 内部 b 不是同一引用 + expect(snap.b).not.toBe(s.get("b")); + // 篡改 snapshot.b(会抛,因为已冻结)—— 先确认已冻结 + expect(Object.isFrozen(snap.b)).toBe(true); + // 内部 store 仍可经 set 替换整个对象 + s.set("b", { x: 2 }); + expect(s.get("b").x).toBe(2); + expect(snap.b.x).toBe(1); // 旧 snapshot 不受影响 + }); + + it("元蜕变:两次 snapshot 同状态等价(replay 等价)", () => { + const s = new SettingsStore({ a: 1, b: { x: 1 } }); + const snap1 = s.snapshot(); + const snap2 = s.snapshot(); + expect(snap1).toEqual(snap2); + }); + + it("不变式:Date 值深克隆隔离(构造后篡改外部 Date 不影响 store)", () => { + const d = new Date(2020, 0, 1); + const s = new SettingsStore({ when: d }); + d.setFullYear(2099); // 篡改外部 Date + expect(s.get("when").getTime()).toBe(new Date(2020, 0, 1).getTime()); + }); +}); + +// ============================================================================ +// 【等价类 + 状态转换】lsp NoopLspBridge —— 初始化/关闭/幂等 +// ============================================================================ + +describe("【等价类划分】lsp noop initialize/shutdown", () => { + it("有效类:initialize 任意 rootUri → {ok:true}", async () => { + const bridge: LspBridge = new NoopLspBridge(); + for (const rootUri of [ + "file:///workspace", + "file:///abs/path", + "", + ] as LspInitOptions["rootUri"][]) { + const r = await bridge.initialize({ rootUri }); + expect(r.ok).toBe(true); + expect(r.reason).toBeUndefined(); + } + }); + + it("有效类:含 initializationOptions 透传不报错", async () => { + const bridge: LspBridge = new NoopLspBridge(); + const r = await bridge.initialize({ + rootUri: "file:///w", + initializationOptions: { clangd: { fallbackFlags: ["--target=aarch64"] } }, + }); + expect(r.ok).toBe(true); + }); +}); + +describe("【状态转换】lsp shutdown 幂等 + 顺序无关", () => { + it("shutdown 前未 initialize 也可直接 shutdown(无状态前置)", async () => { + const bridge: LspBridge = new NoopLspBridge(); + await expect(bridge.shutdown()).resolves.toBeUndefined(); + }); + + it("shutdown 多次调用幂等(重入不报错)", async () => { + const bridge: LspBridge = new NoopLspBridge(); + await bridge.initialize({ rootUri: "file:///w" }); + await bridge.shutdown(); + await bridge.shutdown(); + await bridge.shutdown(); + }); + + it("initialize→shutdown→initialize 可循环(无残留状态)", async () => { + const bridge: LspBridge = new NoopLspBridge(); + const r1 = await bridge.initialize({ rootUri: "file:///a" }); + await bridge.shutdown(); + const r2 = await bridge.initialize({ rootUri: "file:///b" }); + await bridge.shutdown(); + expect(r1.ok).toBe(true); + expect(r2.ok).toBe(true); + }); +}); + +describe("【元蜕变/不变式】lsp noop 契约", () => { + it("不变式:NoopLspBridge.initialize 永返回 ok=true(不假装诊断能力)", async () => { + const bridge: LspBridge = new NoopLspBridge(); + for (let i = 0; i < 10; i++) { + const r = await bridge.initialize({ rootUri: `file:///w${i}` }); + expect(r.ok).toBe(true); + } + }); + + it("元蜕变:initialize(a) 与 initialize(b) 结果等价(rootUri 不影响 noop 结果)", async () => { + const bridge: LspBridge = new NoopLspBridge(); + const ra = await bridge.initialize({ rootUri: "file:///aaa" }); + const rb = await bridge.initialize({ rootUri: "file:///bbb" }); + expect(ra).toEqual(rb); + }); +}); + +// ============================================================================ +// 【变异测试】6 个 seeded bug 内联副本 —— 每个断言被某测试杀死 +// ============================================================================ +// +// 约定:每个 seeded bug 内联一份带 bug 的逻辑副本(不动真实源码)。 +// 杀伤断言模式(双断言): +// - 真实逻辑满足 correctness 期望 → expect(() => expect(real).toEqual(correct)).not.toThrow() +// - 带 bug 副本不满足 correctness 期望 → expect(() => expect(buggy).toEqual(correct)).toThrow() +// (后者抛 AssertionError = buggy≠correct = bug 被杀) +// +// 植入 bug 清单(文档化): +// B1 approval:fail-closed 守卫 `&&` 改 `||` → auto-approve 永远 deny +// 杀手:"auto-approve 应 approve(真实 approve / buggy deny)" +// B2 credentials:LONG_TOKEN_MIN 40 → 41(off-by-one)→ 恰好 40 位 token 漏脱 +// 杀手:"恰好 40 位长 token 应脱敏(真实脱敏 / buggy 漏脱)" +// B3 settings:snapshot 漏 freeze 递归(只冻顶层)→ 嵌套对象可被篡改不抛 +// 杀手:"snapshot 嵌套属性篡改应抛 TypeError(真实抛 / buggy 不抛)" +// B4 approval:timeout 优先级漏 req.timeoutMs(恒用 ctor ?? DEFAULT) +// 杀手:"req.timeoutMs=50, ctor=10000 → 应用 50(真实 50 / buggy 10000)" +// B5 credentials:前缀后缀量词 {8,} → {9,}(off-by-one)→ sk-+8 位后缀漏脱 +// 杀手:"sk-+8 位后缀应脱敏(真实脱敏 / buggy 漏脱)" +// B6 approval:registerApprover disposer 无代际校验(直接置 undefined) +// 杀手:"旧 disposer 不误摘后来注册者(真实保留 B / buggy 误删 B)" +// --------------------------------------------------------------------------- + +describe("【变异测试】seeded bug 1:approval fail-closed && → || 短路反", () => { + // BUG:把 `mode !== "auto-approve" && mode !== "interactive"` 改成 `||`。 + // 效果:mode="auto-approve" 时第一支为真(auto-approve≠interactive)→ 永远 deny。 + function buggyDecide(mode: ApprovalMode): ApprovalResult { + // BUG: || 而非 &&。注意:此 mutation 亦被 tsc 检出(TS2367 无重叠比较), + // 此处 @ts-expect-error 压制以保留 buggy 副本供运行时杀伤断言。 + // @ts-expect-error bug: || 短路反, TS 亦检出 '"auto-approve"' 与 '"interactive"' 无重叠 + if (mode !== "auto-approve" || mode !== "interactive") { + return { decision: "deny", reason: `mode "${mode}" → auto-deny`, by: "auto" }; + } + if (mode === "auto-approve") { + return { decision: "approve", reason: "auto-approve mode", by: "auto" }; + } + return { decision: "deny", reason: "interactive stub", by: "auto" }; + } + + it("杀 bug1:auto-approve 应 approve(真实 approve / buggy deny)", async () => { + const correct: ApprovalResult = { + decision: "approve", + reason: "auto-approve mode", + by: "auto", + }; + const real = await new ApprovalGate({ mode: "auto-approve" }).request({ + action: "x", + risk: "low", + }); + const buggy = buggyDecide("auto-approve"); + // 真实满足 + expect(() => expect(real).toEqual(correct)).not.toThrow(); + // buggy 不满足 = bug 被杀 + expect(() => expect(buggy).toEqual(correct)).toThrow(); + }); +}); + +describe("【变异测试】seeded bug 2:credentials LONG_TOKEN_MIN 40 → 41(off-by-one)", () => { + // BUG:长 token 阈值从 40 改成 41 → 恰好 40 位 token 不再脱敏。 + const PREFIXES = [ + "sk-", + "ghp_", + "gho_", + "ghs_", + "ghr_", + "ghu_", + "github_pat_", + "xoxb-", + "xoxp-", + "glpat-", + ]; + const BUGGY_PATTERN = new RegExp( + `(?:${PREFIXES.join("|")})[A-Za-z0-9_-]{8,}|[A-Za-z0-9_-]{41}`, + "g", + ); + function buggyRedact(s: string): string { + if (!s) return s; + return s.replace(BUGGY_PATTERN, REDACTED_PLACEHOLDER); + } + + it("杀 bug2:恰好 40 位长 token 应脱敏(真实脱敏 / buggy 漏脱)", () => { + const store = new CredentialsStore(); + const tok = "a".repeat(40); + const correct = REDACTED_PLACEHOLDER; + const real = store.redact(tok); + const buggy = buggyRedact(tok); + expect(() => expect(real).toBe(correct)).not.toThrow(); + expect(() => expect(buggy).toBe(correct)).toThrow(); // buggy 漏脱 = 被杀 + }); +}); + +describe("【变异测试】seeded bug 3:settings snapshot 漏 freeze 递归(只冻顶层)", () => { + // BUG:snapshot 只 Object.freeze 顶层,不递归 → 嵌套对象可被篡改。 + function buggyShallowFreeze(obj: T): Readonly { + if (obj === null || typeof obj !== "object") return obj as Readonly; + Object.freeze(obj); + // BUG:漏掉递归 + return obj as Readonly; + } + function buggySnapshot(store: T): Readonly { + return buggyShallowFreeze({ ...store }); + } + // 尝试篡改嵌套属性,返回是否抛错。 + function tryMutateNested(snap: Readonly<{ b: { c: { x: number } } }>): boolean { + try { + (snap as { b: { c: { x: number } } }).b.c.x = 999; + return false; // 未抛 = 未冻结 + } catch { + return true; // 抛 = 已冻结 + } + } + + it("杀 bug3:snapshot 嵌套属性篡改应抛 TypeError(真实抛 / buggy 不抛)", () => { + const s = new SettingsStore({ b: { c: { x: 1 } } }); + const realSnap = s.snapshot(); + const buggySnap = buggySnapshot({ b: { c: { x: 1 } } }); + const correct = true; // 期望抛(已冻结) + expect(() => expect(tryMutateNested(realSnap)).toBe(correct)).not.toThrow(); + expect(() => expect(tryMutateNested(buggySnap)).toBe(correct)).toThrow(); // buggy 不抛 = 被杀 + }); +}); + +describe("【变异测试】seeded bug 4:approval timeout 优先级忽略 req.timeoutMs", () => { + // BUG:计算 timeoutMs 时漏掉 req.timeoutMs,恒用 ctor ?? DEFAULT。 + function realTimeoutMs( + reqT: number | undefined, + ctorT: number | undefined, + ): number { + return reqT ?? ctorT ?? 10_000; + } + function buggyTimeoutMs( + reqT: number | undefined, + ctorT: number | undefined, + ): number { + // BUG:漏 reqT + void reqT; + return ctorT ?? 10_000; + } + + it("杀 bug4:req.timeoutMs=50, ctor=10000 → 应用 50(真实 50 / buggy 10000)", () => { + const correct = 50; + expect(() => expect(realTimeoutMs(50, 10_000)).toBe(correct)).not.toThrow(); + expect(() => expect(buggyTimeoutMs(50, 10_000)).toBe(correct)).toThrow(); // buggy=10000 + }); + + it("杀 bug4(补充):req.timeoutMs=0 应生效(0 非 null)(真实 0 / buggy 10000)", () => { + expect(() => expect(realTimeoutMs(0, 10_000)).toBe(0)).not.toThrow(); + expect(() => expect(buggyTimeoutMs(0, 10_000)).toBe(0)).toThrow(); // buggy 忽略 0 + }); +}); + +describe("【变异测试】seeded bug 5:credentials 前缀后缀 {8,} → {9,}(off-by-one)", () => { + // BUG:前缀密钥后缀量词从 {8,} 改成 {9,} → 恰好 8 位后缀不再脱敏。 + const PREFIXES = [ + "sk-", + "ghp_", + "gho_", + "ghs_", + "ghr_", + "ghu_", + "github_pat_", + "xoxb-", + "xoxp-", + "glpat-", + ]; + const BUGGY_PATTERN = new RegExp( + `(?:${PREFIXES.join("|")})[A-Za-z0-9_-]{9,}|[A-Za-z0-9_-]{40}`, + "g", + ); + function buggyRedact(s: string): string { + if (!s) return s; + return s.replace(BUGGY_PATTERN, REDACTED_PLACEHOLDER); + } + + it("杀 bug5:sk-+8 位后缀应脱敏(真实脱敏 / buggy 漏脱)", () => { + const store = new CredentialsStore(); + const tok = "sk-abcdefgh"; // 恰好 8 位后缀,总长 11(<40,长 token 分支不救) + const correct = REDACTED_PLACEHOLDER; + const real = store.redact(tok); + const buggy = buggyRedact(tok); + expect(() => expect(real).toBe(correct)).not.toThrow(); + expect(() => expect(buggy).toBe(correct)).toThrow(); // buggy 漏脱 = 被杀 + }); +}); + +describe("【变异测试】seeded bug 6:approval disposer 无代际校验(直接置 undefined)", () => { + // BUG:registerApprover 的 disposer 直接 `this.approver = undefined`, + // 不检查 === fn → 旧 disposer 调用会误摘后来注册者。 + class BuggyApprovalGate { + private mode: ApprovalMode = "interactive"; + private approver: ApproverFn | undefined; + setMode(m: ApprovalMode): void { this.mode = m; } + registerApprover(fn: ApproverFn): () => void { + this.approver = fn; + return () => { + // BUG:无 `if (this.approver === fn)` 代际校验,直接清空 + this.approver = undefined; + }; + } + async request(req: ApprovalRequest): Promise { + if (this.mode !== "auto-approve" && this.mode !== "interactive") { + return { decision: "deny", reason: "auto-deny", by: "auto" }; + } + if (this.mode === "auto-approve") { + return { decision: "approve", reason: "auto-approve mode", by: "auto" }; + } + const approver = this.approver; + if (approver === undefined) { + return { decision: "deny", reason: "no approver", by: "auto" }; + } + return approver(req).catch( + (): ApprovalResult => ({ decision: "deny", reason: "threw", by: "auto" }), + ); + } + } + + it("杀 bug6:旧 disposer 不误摘后来注册者(真实保留 B / buggy 误删 B)", async () => { + // 真实 gate:B 覆盖 A,disposeA 不影响 B + const realGate = new ApprovalGate({ mode: "interactive" }); + const realDispA = realGate.registerApprover(makeApprover("deny", "A")); + realGate.registerApprover(makeApprover("approve", "B")); + realDispA(); + const realR = await realGate.request({ action: "f", risk: "high" }); + const realCorrect: ApprovalResult = { decision: "approve", reason: "B", by: "approver" }; + + // buggy gate:disposeA 直接清空 → B 被误删 → deny + const buggyGate = new BuggyApprovalGate(); + const buggyDispA = buggyGate.registerApprover(makeApprover("deny", "A")); + buggyGate.registerApprover(makeApprover("approve", "B")); + buggyDispA(); + const buggyR = await buggyGate.request({ action: "f", risk: "high" }); + // 期望(正确)行为是 approve;buggy 会 deny + expect(() => expect(realR).toMatchObject(realCorrect)).not.toThrow(); + // buggy 不满足 correct(decision=deny ≠ approve)→ 断言抛 = bug 被杀 + expect(() => expect(buggyR).toMatchObject(realCorrect)).toThrow(); + }); +}); + +// ============================================================================ +// 【集成不变式】跨模块 fail-closed 一致性 +// ============================================================================ + +describe("【集成不变式】跨模块 fail-closed / unusable 拒绝一致性", () => { + it("approval 未知 mode + credentials 未注入 key + lsp stub:全链路 fail-closed/unusable 不放行", async () => { + // approval:未知 mode → deny + const gate = new ApprovalGate(); + gate.setMode("unknown-mode" as unknown as ApprovalMode); + const ar = await gate.request({ action: "flash", risk: "high" }); + expect(ar.decision).toBe("deny"); + + // credentials:未注入的 key → get 返回 undefined(unusable) + const store = new CredentialsStore(() => undefined); + expect(store.get("MISSING_GATEWAY_KEY")).toBeUndefined(); + expect(store.has("MISSING_GATEWAY_KEY")).toBe(false); + + // lsp:noop stub 永不假装真实能力,但 initialize ok(占位稳定) + const bridge: LspBridge = new NoopLspBridge(); + const lr = await bridge.initialize({ rootUri: "file:///w" }); + expect(lr.ok).toBe(true); + await expect(bridge.shutdown()).resolves.toBeUndefined(); + }); +}); diff --git a/tests/capability-seams.test.ts b/tests/capability-seams.test.ts new file mode 100644 index 0000000..7390f93 --- /dev/null +++ b/tests/capability-seams.test.ts @@ -0,0 +1,2523 @@ +/** + * @module tests/capability-seams + * + * T08 能力接缝三角色(board-link + flash)完整测试套件。 + * + * 被测对象(按契约直 import 命名导出): + * - board-link: BoardLinkRegistry / DEFAULT_BOARD_LINK_PROVIDERS / + * RDK_X5_SSH_PROVIDER / RDK_S100_SERIAL_PROVIDER / LOCAL_PROVIDER / + * parseSshAddress / buildSshArgs / parseSerialAddress / SERIAL_STUB_RESULT / + * defaultBoardHealthCheck + * - flash: FlashRegistry / DEFAULT_FLASH_PROVIDERS / DD_PROVIDER / FASTBOOT_PROVIDER / + * DFU_PROVIDER / OPENOCD_PROVIDER / parseOffset / parseLsblk / deviceBasename / + * matchesDeviceName / isRootDiskTarget / targetExistsInRows / splitCommand / + * orchestrateRun / probeDryRun / exitCodeVerify / DD_BLOCK_SIZE / ROOT_MOUNTPOINTS + * + * 多测试方法论(每个 describe 块标题标注方法论名): + * - 等价类划分(有效/无效/边界类) + * - 边界值分析(off-by-one、空、单元素、max、min) + * - 决策表(组合输入→期望,覆盖全分支) + * - 状态转换(register→resolve→dispose→resolve 不可达;重入/再注册) + * - 变异测试(7 个 seeded bug 内联副本,每个被某条真实测试杀死; + * kill verification:每个 mutant 通过真实断言确认 FAIL) + * - 对抗/fuzz(空串/undefined/null/巨大数/畸形引号/并发重入/负 seq/NaN) + * - 元蜕变/不变式(快照独立性、freeze→篡改抛 TypeError、单调 deny、 + * waterfall 写失败短路=不调 next、fail-closed unusable=拒) + * + * mock 注入 ExecFn(scriptedExec / mockExec),无 pi 运行时、无真实硬件、无网络。 + * + * 变异测试方法论说明: + * 每个 mutant 是真实逻辑的"单点变异"内联副本。我们对每个 mutant 做两层验证: + * ① 偏离验证:断言 mutant 输出 ≠ 真实输出(mutant 确实改变了行为) + * ② kill verification:把 mutant 喂给与真实代码完全相同的断言(expect(...).toBe(...)), + * 断言该断言抛错(即 mutant 在真实测试下 FAIL → bug 被杀)。 + * 套件本身保持全绿(mutant 测试断言 mutant 确实偏离/确实 FAIL,而非断言 mutant 对)。 + * 每个 mutant 标注:变异点 + 杀它的真实测试名。 + */ + +import { describe, it, expect, vi } from "vitest"; +import { createHash } from "node:crypto"; + +import { + BoardLinkRegistry, + DEFAULT_BOARD_LINK_PROVIDERS, + RDK_X5_SSH_PROVIDER, + RDK_S100_SERIAL_PROVIDER, + LOCAL_PROVIDER, + parseSshAddress, + buildSshArgs, + parseSerialAddress, + SERIAL_STUB_RESULT, + defaultBoardHealthCheck, +} from "../src/capabilities/board-link/index.js"; +import { + FlashRegistry, + DEFAULT_FLASH_PROVIDERS, + DD_PROVIDER, + FASTBOOT_PROVIDER, + DFU_PROVIDER, + OPENOCD_PROVIDER, + DD_BLOCK_SIZE, + ROOT_MOUNTPOINTS, + parseOffset, + parseLsblk, + deviceBasename, + matchesDeviceName, + isRootDiskTarget, + targetExistsInRows, + splitCommand, + orchestrateRun, + probeDryRun, + exitCodeVerify, +} from "../src/capabilities/flash/index.js"; +import type { + BoardSpec, + ExecFn, + ExecResult, + ExecOpts, + FlashMethod, +} from "../src/shared/types.js"; +import type { + FlashPlanEx, + DryRunResult, + VerifyResult, + LsblkRow, +} from "../src/capabilities/flash/types.js"; + +// ============================================================================ +// mock 工厂 +// ============================================================================ + +/** 构造 mock ExecFn:记录调用,返回固定结果(所有命令同结果)。 */ +function mockExec( + overrides?: Partial, +): ExecFn & { calls: { command: string; args: string[]; opts?: ExecOpts }[] } { + const calls: { command: string; args: string[]; opts?: ExecOpts }[] = []; + const fn = async ( + command: string, + args: string[], + opts?: ExecOpts, + ): Promise => { + calls.push({ command, args, opts }); + return { + stdout: overrides?.stdout ?? "", + stderr: overrides?.stderr ?? "", + exitCode: overrides?.exitCode ?? 0, + }; + }; + return Object.assign(fn, { calls }) as ExecFn & { + calls: { command: string; args: string[]; opts?: ExecOpts }[]; + }; +} + +/** + * 构造 scripted ExecFn:按 (command,args) 路由到不同结果。 + * responder 返回 undefined 时默认 exit 0 空输出。 + */ +function scriptedExec( + responder: (cmd: string, args: string[]) => ExecResult | undefined, +): ExecFn & { calls: { command: string; args: string[]; opts?: ExecOpts }[] } { + const calls: { command: string; args: string[]; opts?: ExecOpts }[] = []; + const fn = async ( + command: string, + args: string[], + opts?: ExecOpts, + ): Promise => { + calls.push({ command, args, opts }); + const r = responder(command, args); + return r ?? { stdout: "", stderr: "", exitCode: 0 }; + }; + return Object.assign(fn, { calls }) as ExecFn & { + calls: { command: string; args: string[]; opts?: ExecOpts }[]; + }; +} + +const ok = (stdout = "", stderr = ""): ExecResult => ({ stdout, stderr, exitCode: 0 }); +const fail = (exitCode: number, stderr = ""): ExecResult => ({ stdout: "", stderr, exitCode }); + +/** 构造 ssh BoardSpec。 */ +function sshBoard(id = "x5", address = "root@192.168.1.100:22"): BoardSpec { + return { id, name: `Board ${id}`, link: "ssh", address, fingerprint: `ssh:${address}` }; +} +/** 构造 serial BoardSpec。 */ +function serialBoard(id = "s100", address = "/dev/ttyUSB0@115200"): BoardSpec { + return { id, name: `Board ${id}`, link: "serial", address, fingerprint: `serial:${address}` }; +} +/** 构造 local BoardSpec。 */ +function localBoard(id = "host"): BoardSpec { + return { id, name: `Board ${id}`, link: "local", address: "localhost", fingerprint: "local" }; +} + +// ============================================================================ +// BoardLinkRegistry —— 等价类 + 边界 + 决策表 + 状态转换 + 不变式 +// ============================================================================ + +describe("BoardLinkRegistry — 等价类/决策表:register→resolve→list", () => { + it("register 单 provider 后 resolve 同 linkType 返回该 provider", () => { + const reg = new BoardLinkRegistry(); + reg.register(RDK_S100_SERIAL_PROVIDER); + const p = reg.resolve(serialBoard()); + expect(p.id).toBe("rdk-s100-serial"); + expect(p.linkType).toBe("serial"); + }); + + it("register 三 provider 覆盖 ssh/serial/local 全 linkType(决策表)", () => { + const reg = new BoardLinkRegistry(); + reg.register(RDK_X5_SSH_PROVIDER); + reg.register(RDK_S100_SERIAL_PROVIDER); + reg.register(LOCAL_PROVIDER); + expect(reg.resolve(sshBoard()).id).toBe("rdk-x5-ssh"); + expect(reg.resolve(serialBoard()).id).toBe("rdk-s100-serial"); + expect(reg.resolve(localBoard()).id).toBe("local"); + }); + + it("空注册表 resolve 任意 board 抛错(fail-closed unusable=拒)", () => { + const reg = new BoardLinkRegistry(); + expect(() => reg.resolve(sshBoard())).toThrow(/no provider registered/); + expect(() => reg.resolve(serialBoard())).toThrow(/no provider registered/); + }); + + it("已注册 ssh+local 但缺 serial → resolve serial 抛错(决策表缺项)", () => { + const reg = new BoardLinkRegistry(); + reg.register(RDK_X5_SSH_PROVIDER); + reg.register(LOCAL_PROVIDER); + expect(() => reg.resolve(serialBoard())).toThrow( + /no provider registered for link type "serial"/, + ); + }); + + it("list 空注册表返回空数组(边界 min)", () => { + const reg = new BoardLinkRegistry(); + const snap = reg.list(); + expect(snap).toHaveLength(0); + }); + + it("list 单元素注册表返回长度 1(边界单元素)", () => { + const reg = new BoardLinkRegistry(); + reg.register(RDK_X5_SSH_PROVIDER); + expect(reg.list()).toHaveLength(1); + }); + + it("linkType 为畸形值(wifi)→ 抛错含该值(对抗/fuzz)", () => { + const reg = new BoardLinkRegistry(); + reg.register(RDK_X5_SSH_PROVIDER); + const bogus = { ...sshBoard(), link: "wifi" as never }; + expect(() => reg.resolve(bogus)).toThrow(/no provider registered for link type "wifi"/); + }); + + it("resolve 抛错消息含 board id(诊断不变式)", () => { + const reg = new BoardLinkRegistry(); + const b = sshBoard("myboard"); + expect(() => reg.resolve(b)).toThrow(/board id="myboard"/); + }); + + it("重复 register 同 id provider → 替换,list 长度不变(等价类:override)", () => { + const reg = new BoardLinkRegistry(); + const p1 = { ...RDK_X5_SSH_PROVIDER, id: "rdk-x5-ssh" }; + const p2 = { ...RDK_X5_SSH_PROVIDER, id: "rdk-x5-ssh" }; + reg.register(p1); + reg.register(p2); + expect(reg.list()).toHaveLength(1); + expect(reg.resolve(sshBoard())).toBe(p2); + }); +}); + +describe("BoardLinkRegistry — 状态转换:register→resolve→dispose→resolve(不可达)", () => { + it("dispose 后该 provider 不可再 resolve(状态迁移到 absent)", () => { + const reg = new BoardLinkRegistry(); + const dispose = reg.register(RDK_X5_SSH_PROVIDER); + expect(reg.list()).toHaveLength(1); + expect(reg.resolve(sshBoard()).id).toBe("rdk-x5-ssh"); + + dispose(); + expect(reg.list()).toHaveLength(0); + expect(() => reg.resolve(sshBoard())).toThrow(); + }); + + it("dispose 幂等:二次调用无副作用(重入安全)", () => { + const reg = new BoardLinkRegistry(); + const dispose = reg.register(RDK_X5_SSH_PROVIDER); + dispose(); + dispose(); // 不抛 + expect(reg.list()).toHaveLength(0); + }); + + it("再注册同 provider 后 resolve 复活(状态 absent→present)", () => { + const reg = new BoardLinkRegistry(); + const dispose = reg.register(RDK_X5_SSH_PROVIDER); + dispose(); + expect(() => reg.resolve(sshBoard())).toThrow(); + reg.register(RDK_X5_SSH_PROVIDER); + expect(reg.resolve(sshBoard()).id).toBe("rdk-x5-ssh"); + }); + + it("override 安全:disposer 只删仍是同一实例的条目,不误删后注册的同 id provider", () => { + const reg = new BoardLinkRegistry(); + const p1: typeof RDK_X5_SSH_PROVIDER = { ...RDK_X5_SSH_PROVIDER, id: "rdk-x5-ssh" }; + const p2: typeof RDK_X5_SSH_PROVIDER = { ...RDK_X5_SSH_PROVIDER, id: "rdk-x5-ssh" }; + const dispose1 = reg.register(p1); + reg.register(p2); // 同 id 替换 + dispose1(); // p1 的 disposer:get(id)===p1? 否(是 p2)→不删 + expect(reg.list()).toHaveLength(1); + expect(reg.resolve(sshBoard())).toBe(p2); + }); + + it("同 linkType 多 provider 取插入序首个(决策表)", () => { + const reg = new BoardLinkRegistry(); + const first = { ...RDK_X5_SSH_PROVIDER, id: "ssh-a" }; + const second = { ...RDK_X5_SSH_PROVIDER, id: "ssh-b" }; + reg.register(first); + reg.register(second); + expect(reg.resolve(sshBoard()).id).toBe("ssh-a"); + }); + + it("先 dispose 第一个后第二个同 linkType 升首(状态转换)", () => { + const reg = new BoardLinkRegistry(); + const first = { ...RDK_X5_SSH_PROVIDER, id: "ssh-a" }; + const second = { ...RDK_X5_SSH_PROVIDER, id: "ssh-b" }; + const d1 = reg.register(first); + reg.register(second); + expect(reg.resolve(sshBoard()).id).toBe("ssh-a"); + d1(); + expect(reg.resolve(sshBoard()).id).toBe("ssh-b"); + }); + + it("完整生命周期:register→resolve→dispose→re-register→resolve(状态环)", () => { + const reg = new BoardLinkRegistry(); + const d1 = reg.register(RDK_X5_SSH_PROVIDER); + expect(reg.resolve(sshBoard()).id).toBe("rdk-x5-ssh"); + d1(); + expect(() => reg.resolve(sshBoard())).toThrow(); + // re-register with different provider instance same id + const p2 = { ...RDK_X5_SSH_PROVIDER, id: "rdk-x5-ssh" }; + const d2 = reg.register(p2); + expect(reg.resolve(sshBoard())).toBe(p2); + d2(); + expect(() => reg.resolve(sshBoard())).toThrow(); + }); + + it("交错 register/dispose 多 provider 不互相腐蚀(状态转换复杂序列)", () => { + const reg = new BoardLinkRegistry(); + const dSsh = reg.register(RDK_X5_SSH_PROVIDER); + const dSerial = reg.register(RDK_S100_SERIAL_PROVIDER); + reg.register(LOCAL_PROVIDER); + dSsh(); + expect(reg.list().map((p) => p.id).sort()).toEqual(["local", "rdk-s100-serial"]); + dSerial(); + expect(reg.list().map((p) => p.id)).toEqual(["local"]); + reg.register(RDK_X5_SSH_PROVIDER); + expect(reg.list().map((p) => p.id).sort()).toEqual(["local", "rdk-x5-ssh"]); + }); +}); + +describe("BoardLinkRegistry — 并发重入/对抗(fuzz)", () => { + it("并发 register + dispose 互不腐蚀(无共享状态竞争)", () => { + const reg = new BoardLinkRegistry(); + const dispose = reg.register(RDK_X5_SSH_PROVIDER); + reg.register(LOCAL_PROVIDER); + dispose(); + reg.register(RDK_S100_SERIAL_PROVIDER); + expect(reg.list().map((p) => p.id).sort()).toEqual(["local", "rdk-s100-serial"]); + }); + + it("dispose 已空注册表不抛(空状态重入)", () => { + const reg = new BoardLinkRegistry(); + const d = reg.register(RDK_X5_SSH_PROVIDER); + d(); + const d2 = reg.register(RDK_X5_SSH_PROVIDER); + d2(); + d2(); + expect(reg.list()).toHaveLength(0); + }); + + it("多注册表实例互不干扰(隔离不变式)", () => { + const reg1 = new BoardLinkRegistry(); + const reg2 = new BoardLinkRegistry(); + reg1.register(RDK_X5_SSH_PROVIDER); + // reg2 空 → resolve 抛错 + expect(() => reg2.resolve(sshBoard())).toThrow(); + // reg1 仍可用 + expect(reg1.resolve(sshBoard()).id).toBe("rdk-x5-ssh"); + // 在 reg2 注册后不影响 reg1 + reg2.register(LOCAL_PROVIDER); + expect(reg1.list()).toHaveLength(1); + expect(reg2.list()).toHaveLength(1); + }); +}); + +describe("BoardLinkRegistry — 元蜕变/不变式:list 快照独立性", () => { + it("两次 list() 返回独立数组,mutate 一个不影响注册表与另一快照", () => { + const reg = new BoardLinkRegistry(); + reg.register(RDK_X5_SSH_PROVIDER); + const a = reg.list() as unknown[]; + const b = reg.list() as unknown[]; + expect(a).not.toBe(b); + a.push({} as never); + expect(reg.list()).toHaveLength(1); + expect(b).toHaveLength(1); + }); + + it("list 返回顺序稳定(插入序不变式,元蜕变)", () => { + const reg = new BoardLinkRegistry(); + reg.register(RDK_X5_SSH_PROVIDER); + reg.register(RDK_S100_SERIAL_PROVIDER); + reg.register(LOCAL_PROVIDER); + const ids1 = reg.list().map((p) => p.id); + const ids2 = reg.list().map((p) => p.id); + expect(ids1).toEqual(ids2); + expect(ids1).toEqual(["rdk-x5-ssh", "rdk-s100-serial", "local"]); + }); +}); + +// ============================================================================ +// parseSshAddress —— 等价类 + 边界值 + 对抗/fuzz +// ============================================================================ + +describe("parseSshAddress — 等价类/边界值", () => { + it("user@host:port 全字段", () => { + expect(parseSshAddress("root@192.168.1.100:2222")).toEqual({ + user: "root", + host: "192.168.1.100", + port: 2222, + }); + }); + it("user@host 无端口 → 默认 22", () => { + expect(parseSshAddress("root@board")).toEqual({ user: "root", host: "board", port: 22 }); + }); + it("仅 host 无 user → 默认 root", () => { + expect(parseSshAddress("board")).toEqual({ user: "root", host: "board", port: 22 }); + }); + it("IPv6 带端口 [::1]:2222", () => { + expect(parseSshAddress("[::1]:2222")).toEqual({ user: "root", host: "::1", port: 2222 }); + }); + it("IPv6 带括号无端口 → 默认 22", () => { + expect(parseSshAddress("root@[::1]")).toEqual({ user: "root", host: "::1", port: 22 }); + }); + it("空白字符被 trim", () => { + expect(parseSshAddress(" root@host:2222 ")).toEqual({ + user: "root", + host: "host", + port: 2222, + }); + }); + it("端口 0 被解析为 0(边界 min)", () => { + expect(parseSshAddress("host:0").port).toBe(0); + }); + it("端口带前导零 → parseInt 去零(边界)", () => { + expect(parseSshAddress("host:0022").port).toBe(22); + }); + it("非数字端口后缀 → 不当端口,host 保留(fail-tolerant)", () => { + const r = parseSshAddress("host:abc"); + expect(r.host).toBe("host:abc"); + expect(r.port).toBe(22); + }); + it("多 @ 取第一个(user 在第一个 @ 前)", () => { + const r = parseSshAddress("a@b@host:2222"); + expect(r.user).toBe("a"); + expect(r.host).toBe("b@host"); + expect(r.port).toBe(2222); + }); +}); + +describe("parseSshAddress — 对抗/fuzz", () => { + it("空串 → user root / host 空 / port 22", () => { + expect(parseSshAddress("")).toEqual({ user: "root", host: "", port: 22 }); + }); + it("仅 @ → user 空 / host 空", () => { + const r = parseSshAddress("@"); + expect(r.user).toBe(""); + expect(r.host).toBe(""); + }); + it("user@ 无 host → host 空", () => { + const r = parseSshAddress("root@"); + expect(r.user).toBe("root"); + expect(r.host).toBe(""); + }); + it("仅冒号 → host 保留为 ':' 且 port 22(after 空非数字)", () => { + const r = parseSshAddress(":"); + expect(r.host).toBe(":"); + expect(r.port).toBe(22); + }); + it("巨大端口号 → Number 仍解析(不校验 65535 上界)", () => { + const r = parseSshAddress("host:999999999999"); + expect(r.port).toBe(999999999999); + }); + it("仅空格 → trim 后空串 → host 空", () => { + const r = parseSshAddress(" "); + expect(r.user).toBe("root"); + expect(r.host).toBe(""); + expect(r.port).toBe(22); + }); + it("host 含多个冒号但尾部非数字(IPv6 无端口)", () => { + const r = parseSshAddress("root@[fe80::1]"); + expect(r.host).toBe("fe80::1"); + expect(r.port).toBe(22); + }); +}); + +// ============================================================================ +// buildSshArgs —— 决策表 + 边界 +// ============================================================================ + +describe("buildSshArgs — 决策表(port 22 vs 非 22 × args 空/非空)", () => { + it("非默认端口 → 带 -p ", () => { + const board = sshBoard("x5", "root@192.168.1.100:2222"); + expect(buildSshArgs(board, "ls", ["-la"])).toEqual([ + "-p", "2222", "root@192.168.1.100", "ls", "-la", + ]); + }); + it("默认端口 22 → 不带 -p(减噪)", () => { + const board = sshBoard("x5", "root@192.168.1.100:22"); + expect(buildSshArgs(board, "ls", ["-la"])).toEqual([ + "root@192.168.1.100", "ls", "-la", + ]); + }); + it("默认端口 + 空 args → 仅 user@host + command(边界)", () => { + const board = sshBoard("x5", "root@board"); + expect(buildSshArgs(board, "uname", [])).toEqual(["root@board", "uname"]); + }); + it("非默认端口 + 空 args → -p + user@host + command", () => { + const board = sshBoard("x5", "root@board:2222"); + expect(buildSshArgs(board, "uname", [])).toEqual(["-p", "2222", "root@board", "uname"]); + }); + it("多个 args 原序展开", () => { + const board = sshBoard("x5", "root@board"); + expect(buildSshArgs(board, "echo", ["a", "b", "c"])).toEqual([ + "root@board", "echo", "a", "b", "c", + ]); + }); + it("端口 0 → 带 -p 0(非 22 即带 -p,边界 min)", () => { + const board = sshBoard("x5", "host:0"); + const args = buildSshArgs(board, "ls", []); + expect(args).toContain("-p"); + expect(args).toContain("0"); + }); + it("空 command + 空 args → 仅 user@host(边界)", () => { + const board = sshBoard("x5", "root@board"); + expect(buildSshArgs(board, "", [])).toEqual(["root@board", ""]); + }); +}); + +// ============================================================================ +// BoardLinkProvider createExec —— 等价类 + 不变式 +// ============================================================================ + +describe("RDK_X5_SSH_PROVIDER createExec — 等价类:包装命令委托 underlying", () => { + it("createExec 产出 ExecFn 调 underlying('ssh', sshArgs, opts)", async () => { + const underlying = mockExec(); + const board = sshBoard("x5", "root@192.168.1.100:2222"); + const exec = RDK_X5_SSH_PROVIDER.createExec(board, underlying); + await exec("ls", ["-la"], { timeout: 5000 }); + + expect(underlying.calls).toHaveLength(1); + expect(underlying.calls[0].command).toBe("ssh"); + expect(underlying.calls[0].args).toEqual(["-p", "2222", "root@192.168.1.100", "ls", "-la"]); + expect(underlying.calls[0].opts?.timeout).toBe(5000); + }); + + it("opts 透传:无 opts 时 underlying 收到 undefined", async () => { + const underlying = mockExec(); + const exec = RDK_X5_SSH_PROVIDER.createExec(sshBoard("x5", "root@host"), underlying); + await exec("uname", []); + expect(underlying.calls[0].opts).toBeUndefined(); + }); + + it("createExec 返回的 ExecFn 每次调均包装(不变式:委托恒定)", async () => { + const underlying = mockExec(); + const exec = RDK_X5_SSH_PROVIDER.createExec(sshBoard("x5", "root@host"), underlying); + await exec("ls", []); + await exec("pwd", []); + expect(underlying.calls).toHaveLength(2); + expect(underlying.calls.every((c) => c.command === "ssh")).toBe(true); + }); + + it("id/linkType 契约", () => { + expect(RDK_X5_SSH_PROVIDER.id).toBe("rdk-x5-ssh"); + expect(RDK_X5_SSH_PROVIDER.linkType).toBe("ssh"); + }); +}); + +describe("RDK_S100_SERIAL_PROVIDER createExec — 不变式:stub 不调 underlying", () => { + it("createExec 返回 stub,underlying 永不被调用,exitCode 0", async () => { + const underlying = mockExec(); + const exec = RDK_S100_SERIAL_PROVIDER.createExec(serialBoard(), underlying); + const r = await exec("uname", ["-a"]); + expect(underlying.calls).toHaveLength(0); + expect(r.exitCode).toBe(0); + expect(r.stdout).toContain("serial-stub"); + expect(r).toBe(SERIAL_STUB_RESULT); // 同一引用(恒等不变式) + }); + + it("SERIAL_STUB_RESULT 内容契约:stderr 空 + stdout 标注 stub", () => { + expect(SERIAL_STUB_RESULT.stderr).toBe(""); + expect(SERIAL_STUB_RESULT.exitCode).toBe(0); + expect(SERIAL_STUB_RESULT.stdout).toMatch(/serial-stub/); + }); + + it("多次调用 stub 返回同一引用(元蜕变:恒等不变式)", async () => { + const underlying = mockExec(); + const exec = RDK_S100_SERIAL_PROVIDER.createExec(serialBoard(), underlying); + const r1 = await exec("a", []); + const r2 = await exec("b", ["x"]); + expect(r1).toBe(r2); + expect(r1).toBe(SERIAL_STUB_RESULT); + }); + + it("id/linkType 契约", () => { + expect(RDK_S100_SERIAL_PROVIDER.id).toBe("rdk-s100-serial"); + expect(RDK_S100_SERIAL_PROVIDER.linkType).toBe("serial"); + }); +}); + +describe("LOCAL_PROVIDER createExec — 等价类:直透 underlying", () => { + it("createExec 产出 ExecFn 原样转发 command/args/opts", async () => { + const underlying = mockExec(); + const exec = LOCAL_PROVIDER.createExec(localBoard(), underlying); + await exec("echo", ["hi"], { cwd: "/tmp" }); + expect(underlying.calls[0]).toEqual({ + command: "echo", args: ["hi"], opts: { cwd: "/tmp" }, + }); + }); + + it("无 opts 直透 undefined", async () => { + const underlying = mockExec(); + const exec = LOCAL_PROVIDER.createExec(localBoard(), underlying); + await exec("uname", []); + expect(underlying.calls[0].command).toBe("uname"); + expect(underlying.calls[0].opts).toBeUndefined(); + }); + + it("id/linkType 契约", () => { + expect(LOCAL_PROVIDER.id).toBe("local"); + expect(LOCAL_PROVIDER.linkType).toBe("local"); + }); +}); + +// ============================================================================ +// defaultBoardHealthCheck —— 决策表 + fail-closed 不变式 +// ============================================================================ + +describe("defaultBoardHealthCheck — 决策表(exit 0 / 非 0 / 抛异常)", () => { + it("exit 0 → ok true", async () => { + const exec = mockExec({ exitCode: 0 }); + const r = await defaultBoardHealthCheck(exec); + expect(r.ok).toBe(true); + expect(r.reason).toBeUndefined(); + }); + it("exit 非 0 + stderr 有文 → ok false + reason 含 stderr", async () => { + const exec = mockExec({ exitCode: 1, stderr: "boom" }); + const r = await defaultBoardHealthCheck(exec); + expect(r.ok).toBe(false); + expect(r.reason).toContain("probe exit 1"); + expect(r.reason).toContain("boom"); + }); + it("exit 非 0 + stderr 空 → reason 含 (no stderr)(边界)", async () => { + const exec = mockExec({ exitCode: 2, stderr: "" }); + const r = await defaultBoardHealthCheck(exec); + expect(r.ok).toBe(false); + expect(r.reason).toContain("(no stderr)"); + }); + it("exec 抛异常 → ok false + reason 含 probe threw(fail-closed)", async () => { + const exec = (async () => { throw new Error("network unreachable"); }) as ExecFn; + const r = await defaultBoardHealthCheck(exec); + expect(r.ok).toBe(false); + expect(r.reason).toContain("probe threw"); + expect(r.reason).toContain("network unreachable"); + }); + it("exec 抛非 Error 对象 → reason 含 String(e)(fail-closed 兜底)", async () => { + const exec = (async () => { throw "string error"; }) as ExecFn; + const r = await defaultBoardHealthCheck(exec); + expect(r.ok).toBe(false); + expect(r.reason).toContain("string error"); + }); + it("exec 抛 undefined → reason 含 'undefined'(fail-closed 兜底)", async () => { + const exec = (async () => { throw undefined; }) as ExecFn; // eslint-disable-line no-throw-literal + const r = await defaultBoardHealthCheck(exec); + expect(r.ok).toBe(false); + expect(r.reason).toContain("probe threw"); + }); +}); + +describe("defaultBoardHealthCheck — 边界/不变式:默认探活命令与超时", () => { + it("默认探活命令 'true' + 默认超时 10000 透传给 exec", async () => { + const exec = mockExec({ exitCode: 0 }); + await defaultBoardHealthCheck(exec); + expect(exec.calls[0].command).toBe("true"); + expect(exec.calls[0].args).toEqual([]); + expect(exec.calls[0].opts?.timeout).toBe(10_000); + }); + it("自定义探活命令 + 自定义超时透传", async () => { + const exec = mockExec({ exitCode: 0 }); + await defaultBoardHealthCheck(exec, "ls", 5000); + expect(exec.calls[0].command).toBe("ls"); + expect(exec.calls[0].opts?.timeout).toBe(5000); + }); + it("超时 0 透传(边界 min)", async () => { + const exec = mockExec({ exitCode: 0 }); + await defaultBoardHealthCheck(exec, "true", 0); + expect(exec.calls[0].opts?.timeout).toBe(0); + }); + it("负超时透传(对抗:不校验,调用方负责)", async () => { + const exec = mockExec({ exitCode: 0 }); + await defaultBoardHealthCheck(exec, "true", -1); + expect(exec.calls[0].opts?.timeout).toBe(-1); + }); +}); + +describe("Provider healthCheck 集成 — 不变式:经 createExec 包装后探活", () => { + it("ssh healthCheck 在板上跑 'true' → underlying 收到 ssh argv 含 'true'", async () => { + const underlying = mockExec({ exitCode: 0 }); + const exec = RDK_X5_SSH_PROVIDER.createExec(sshBoard("x5", "root@host:2222"), underlying); + const r = await RDK_X5_SSH_PROVIDER.healthCheck!(exec); + expect(r.ok).toBe(true); + expect(underlying.calls[0].command).toBe("ssh"); + expect(underlying.calls[0].args).toContain("true"); + expect(underlying.calls[0].opts?.timeout).toBe(10_000); + }); + it("local healthCheck 直透 underlying('true', [], {timeout})", async () => { + const underlying = mockExec({ exitCode: 0 }); + const exec = LOCAL_PROVIDER.createExec(localBoard(), underlying); + const r = await LOCAL_PROVIDER.healthCheck!(exec); + expect(r.ok).toBe(true); + expect(underlying.calls[0].command).toBe("true"); + }); + it("serial healthCheck:stub 永远 exitCode 0 → ok true(stub 恒活)", async () => { + const underlying = mockExec({ exitCode: 0 }); + const exec = RDK_S100_SERIAL_PROVIDER.createExec(serialBoard(), underlying); + const r = await RDK_S100_SERIAL_PROVIDER.healthCheck!(exec); + expect(r.ok).toBe(true); + expect(underlying.calls).toHaveLength(0); + }); + it("ssh healthCheck underlying 抛异常 → ok false(fail-closed 端到端)", async () => { + const underlying = (async () => { throw new Error("ssh unreachable"); }) as ExecFn; + const exec = RDK_X5_SSH_PROVIDER.createExec(sshBoard("x5", "root@host"), underlying); + const r = await RDK_X5_SSH_PROVIDER.healthCheck!(exec); + expect(r.ok).toBe(false); + expect(r.reason).toContain("probe threw"); + }); +}); + +// ============================================================================ +// parseSerialAddress —— 等价类 + 边界 +// ============================================================================ + +describe("parseSerialAddress — 等价类/边界值", () => { + it("dev@baudrate 全字段", () => { + expect(parseSerialAddress("/dev/ttyUSB0@115200")).toEqual({ + dev: "/dev/ttyUSB0", + baudrate: 115_200, + }); + }); + it("无 @ 后缀 → 默认 115200", () => { + expect(parseSerialAddress("/dev/ttyUSB0")).toEqual({ + dev: "/dev/ttyUSB0", + baudrate: 115_200, + }); + }); + it("@ 后非数字 → 整串作 dev(fail-tolerant)", () => { + expect(parseSerialAddress("/dev/ttyUSB0@fast")).toEqual({ + dev: "/dev/ttyUSB0@fast", + baudrate: 115_200, + }); + }); + it("baudrate 0(边界 min)", () => { + expect(parseSerialAddress("/dev/ttyUSB0@0").baudrate).toBe(0); + }); + it("多 @ 取最后一个", () => { + expect(parseSerialAddress("/dev/@ttyUSB0@9600")).toEqual({ + dev: "/dev/@ttyUSB0", + baudrate: 9600, + }); + }); + it("空串 → dev 空 / 默认 baudrate(边界)", () => { + expect(parseSerialAddress("")).toEqual({ dev: "", baudrate: 115_200 }); + }); + it("仅 @ → dev '@' / 默认 baudrate(边界)", () => { + const r = parseSerialAddress("@"); + expect(r.dev).toBe("@"); + expect(r.baudrate).toBe(115_200); + }); + it("baudrate 带前导零 → parseInt 去零(边界)", () => { + expect(parseSerialAddress("/dev/ttyUSB0@009600").baudrate).toBe(9600); + }); + it("仅空格 → dev 空 / 默认 baudrate(边界)", () => { + expect(parseSerialAddress(" ")).toEqual({ dev: "", baudrate: 115_200 }); + }); +}); + +// ============================================================================ +// FlashRegistry —— 等价类 + 状态转换 + 不变式(对称 BoardLinkRegistry) +// ============================================================================ + +describe("FlashRegistry — 等价类/决策表:register→resolve→list", () => { + it("register 四 provider 覆盖 dd/fastboot/dfu/openocd(决策表)", () => { + const reg = new FlashRegistry(); + reg.register(DD_PROVIDER); + reg.register(FASTBOOT_PROVIDER); + reg.register(DFU_PROVIDER); + reg.register(OPENOCD_PROVIDER); + expect(reg.resolve("dd").id).toBe("dd"); + expect(reg.resolve("fastboot").id).toBe("fastboot"); + expect(reg.resolve("dfu").id).toBe("dfu"); + expect(reg.resolve("openocd").id).toBe("openocd"); + }); + it("空注册表 resolve 任意 method 抛错(fail-closed unusable=拒)", () => { + const reg = new FlashRegistry(); + expect(() => reg.resolve("dd")).toThrow(/no provider registered for method "dd"/); + }); + it("已注册 dd+fastboot 但缺 openocd → resolve openocd 抛错", () => { + const reg = new FlashRegistry(); + reg.register(DD_PROVIDER); + reg.register(FASTBOOT_PROVIDER); + expect(() => reg.resolve("openocd")).toThrow(/no provider registered for method "openocd"/); + }); + it("list 空注册表返回空数组(边界 min)", () => { + expect(new FlashRegistry().list()).toHaveLength(0); + }); + it("重复 register 同 method → 替换不增(等价类:override)", () => { + const reg = new FlashRegistry(); + const p1 = { ...DD_PROVIDER, id: "dd" as FlashMethod }; + const p2 = { ...DD_PROVIDER, id: "dd" as FlashMethod }; + reg.register(p1); + reg.register(p2); + expect(reg.list()).toHaveLength(1); + expect(reg.resolve("dd")).toBe(p2); + }); +}); + +describe("FlashRegistry — 状态转换:dispose→不可达 + 重入", () => { + it("dispose 后不可 resolve,再注册复活", () => { + const reg = new FlashRegistry(); + const dispose = reg.register(DD_PROVIDER); + expect(reg.resolve("dd").id).toBe("dd"); + dispose(); + expect(() => reg.resolve("dd")).toThrow(); + reg.register(DD_PROVIDER); + expect(reg.resolve("dd").id).toBe("dd"); + }); + it("dispose 幂等", () => { + const reg = new FlashRegistry(); + const d = reg.register(DD_PROVIDER); + d(); d(); + expect(reg.list()).toHaveLength(0); + }); + it("override 安全:同 method 后注册不被前者 disposer 误删", () => { + const reg = new FlashRegistry(); + const p1 = { ...DD_PROVIDER, id: "dd" as FlashMethod }; + const p2 = { ...DD_PROVIDER, id: "dd" as FlashMethod }; + const d1 = reg.register(p1); + reg.register(p2); + d1(); + expect(reg.list()).toHaveLength(1); + expect(reg.resolve("dd")).toBe(p2); + }); + it("list 快照独立(元蜕变)", () => { + const reg = new FlashRegistry(); + reg.register(DD_PROVIDER); + const a = reg.list() as unknown[]; + const b = reg.list() as unknown[]; + expect(a).not.toBe(b); + a.pop(); + expect(reg.list()).toHaveLength(1); + expect(b).toHaveLength(1); + }); + it("完整生命周期:register→resolve→dispose→re-register→resolve(状态环)", () => { + const reg = new FlashRegistry(); + const d1 = reg.register(DD_PROVIDER); + expect(reg.resolve("dd").id).toBe("dd"); + d1(); + expect(() => reg.resolve("dd")).toThrow(); + reg.register(FASTBOOT_PROVIDER); + expect(reg.resolve("fastboot").id).toBe("fastboot"); + expect(() => reg.resolve("dd")).toThrow(); + reg.register(DD_PROVIDER); + expect(reg.resolve("dd").id).toBe("dd"); + }); + it("交错 register/dispose 多 provider 不互相腐蚀(状态转换复杂序列)", () => { + const reg = new FlashRegistry(); + const dDd = reg.register(DD_PROVIDER); + const dFb = reg.register(FASTBOOT_PROVIDER); + reg.register(OPENOCD_PROVIDER); + dDd(); + expect(reg.list().map((p) => p.id).sort()).toEqual(["fastboot", "openocd"]); + dFb(); + expect(reg.list().map((p) => p.id)).toEqual(["openocd"]); + reg.register(DFU_PROVIDER); + expect(reg.list().map((p) => p.id).sort()).toEqual(["dfu", "openocd"]); + }); +}); + +describe("FlashRegistry — 隔离/对抗(fuzz)", () => { + it("多注册表实例互不干扰(隔离不变式)", () => { + const reg1 = new FlashRegistry(); + const reg2 = new FlashRegistry(); + reg1.register(DD_PROVIDER); + expect(() => reg2.resolve("dd")).toThrow(); + expect(reg1.resolve("dd").id).toBe("dd"); + reg2.register(FASTBOOT_PROVIDER); + expect(reg1.list()).toHaveLength(1); + expect(reg2.list()).toHaveLength(1); + }); + it("resolve 畸形 method 抛错含该 method(对抗)", () => { + const reg = new FlashRegistry(); + expect(() => reg.resolve("nonsense" as FlashMethod)).toThrow(/no provider registered for method "nonsense"/); + }); +}); + +// ============================================================================ +// parseOffset —— 等价类 + 边界值(off-by-one/max/min)+ 对抗/fuzz +// ============================================================================ + +describe("parseOffset — 等价类/边界值", () => { + it("undefined → 0(默认偏移)", () => { + expect(parseOffset(undefined)).toBe(0); + }); + it("空串 → 0", () => { + expect(parseOffset("")).toBe(0); + }); + it("十进制 '0' → 0(min)", () => { + expect(parseOffset("0")).toBe(0); + }); + it("十进制正整数", () => { + expect(parseOffset("8388608")).toBe(8388608); + }); + it("十进制带前导零 → parseInt 去零(边界)", () => { + expect(parseOffset("0042")).toBe(42); + }); + it("hex 0x0 → 0(off-by-one 关键边界)", () => { + expect(parseOffset("0x0")).toBe(0); + }); + it("hex 0x0000 → 0(多零边界)", () => { + expect(parseOffset("0x0000")).toBe(0); + }); + it("hex 0x10 → 16", () => { + expect(parseOffset("0x10")).toBe(16); + }); + it("hex 混合大小写 0xAbCdEf", () => { + expect(parseOffset("0xAbCdEf")).toBe(0xabcdef); + }); + it("hex 全大写字母 0xFF", () => { + expect(parseOffset("0xFF")).toBe(255); + }); + it("十进制带空白 trim", () => { + expect(parseOffset(" 123 ")).toBe(123); + }); + it("hex 带空白 trim", () => { + expect(parseOffset(" 0xff ")).toBe(0xff); + }); + it("仅空白 → null(trim 后空串不匹配任何格式,边界)", () => { + // " " → trimmed = "" → 不匹配 0x hex / 不匹配十进制 → null + expect(parseOffset(" ")).toBeNull(); + }); + it("十进制 = MAX_SAFE_INTEGER(边界)", () => { + expect(parseOffset(String(Number.MAX_SAFE_INTEGER))).toBe(Number.MAX_SAFE_INTEGER); + }); + it("十进制 > MAX_SAFE_INTEGER → 截断为 MAX_SAFE_INTEGER(上界)", () => { + expect(parseOffset("9007199254740992")).toBe(Number.MAX_SAFE_INTEGER); + expect(parseOffset("99999999999999999999999999")).toBe(Number.MAX_SAFE_INTEGER); + }); + it("负数 → null(拒绝)", () => { + expect(parseOffset("-1")).toBeNull(); + }); + it("'0x' 无数字 → null", () => { + expect(parseOffset("0x")).toBeNull(); + }); + it("非数字串 → null", () => { + expect(parseOffset("abc")).toBeNull(); + }); + it("小数 → null(仅认整数)", () => { + expect(parseOffset("1.5")).toBeNull(); + }); + it("二进制 0b 前缀 → null", () => { + expect(parseOffset("0b101")).toBeNull(); + }); + it("大写 0X 前缀 → null(仅认小写 0x)", () => { + expect(parseOffset("0X10")).toBeNull(); + }); + it("十六进制 0x 后跟 g → null(g 非十六进制)", () => { + expect(parseOffset("0xg")).toBeNull(); + }); + it("hex 0xfff → 4095(边界:接近 4MiB)", () => { + expect(parseOffset("0xfff")).toBe(4095); + }); +}); + +describe("parseOffset — 对抗/fuzz", () => { + it("null 抛 TypeError(类型契约外,不静默)", () => { + expect(() => parseOffset(null as unknown as string)).toThrow(TypeError); + }); + it("巨大十进制仍截断为 MAX_SAFE_INTEGER(不溢出 Infinity)", () => { + expect(parseOffset("9".repeat(400))).toBe(Number.MAX_SAFE_INTEGER); + }); + it("Number(0x) 大十六进制 → 截断或 null(不 Infinity)", () => { + const r = parseOffset("0x" + "f".repeat(400)); + expect(r === null || r === Number.MAX_SAFE_INTEGER || typeof r === "number").toBe(true); + expect(Number.isFinite(r as number)).toBe(r !== null); + }); + it("含空字节的串 → null(对抗)", () => { + expect(parseOffset("0x\x0010")).toBeNull(); + }); + it("含换行的串 → null(对抗)", () => { + expect(parseOffset("0x\n10")).toBeNull(); + }); +}); + +// ============================================================================ +// parseLsblk —— 等价类 + 边界 + 对抗/fuzz +// ============================================================================ + +describe("parseLsblk — 等价类/边界值", () => { + it("标准表格输出含 header + 多行", () => { + const raw = [ + "NAME SIZE TYPE MOUNTPOINT", + "sda 500G disk ", + "mmcblk0 7.3G disk", + "mmcblk0p1 7.3G part /mnt", + ].join("\n"); + const rows = parseLsblk(raw); + expect(rows).toHaveLength(3); + expect(rows[0]).toEqual({ name: "sda", size: 500, type: "disk", mountpoint: "" }); + expect(rows[2]).toEqual({ name: "mmcblk0p1", size: 7, type: "part", mountpoint: "/mnt" }); + }); + it("树形盒绘字符前缀被清洗净化", () => { + const raw = [ + "NAME SIZE TYPE MOUNTPOINT", + "├─sda1 100M part /boot", + "└─sda2 499G part /", + "mmcblk0 7.3G disk", + ].join("\n"); + const rows = parseLsblk(raw); + expect(rows.map((r) => r.name)).toEqual(["sda1", "sda2", "mmcblk0"]); + expect(rows[0].mountpoint).toBe("/boot"); + expect(rows[1].mountpoint).toBe("/"); + }); + it("mountpoint 含空格 → slice(3).join(' ')(边界)", () => { + const raw = "NAME SIZE TYPE MOUNTPOINT\nsda1 1G part /mnt/my data"; + const rows = parseLsblk(raw); + expect(rows[0].mountpoint).toBe("/mnt/my data"); + }); + it("size 非数字 → 0(边界)", () => { + const raw = "NAME SIZE TYPE MOUNTPOINT\nsda1 abc part /"; + const rows = parseLsblk(raw); + expect(rows[0].size).toBe(0); + }); + it("少于 3 列的行被跳过(边界/契约)", () => { + const raw = "NAME SIZE TYPE MOUNTPOINT\nsda 500G"; + expect(parseLsblk(raw)).toEqual([]); + }); + it("空行被跳过", () => { + const raw = "NAME SIZE TYPE MOUNTPOINT\n\n\nsda 500G disk"; + expect(parseLsblk(raw)).toHaveLength(1); + }); + it("无 header 的输出 → 行仍被解析(fail-tolerant)", () => { + const rows = parseLsblk("sda 500G disk\nsdb 1T disk"); + expect(rows).toHaveLength(2); + expect(rows.map((r) => r.name)).toEqual(["sda", "sdb"]); + }); + it("空串输入 → [](边界)", () => { + expect(parseLsblk("")).toEqual([]); + }); + it("仅 header 无数据行 → [](边界)", () => { + expect(parseLsblk("NAME SIZE TYPE MOUNTPOINT")).toEqual([]); + }); + it("单行数据(边界单元素)", () => { + const rows = parseLsblk("sda 500G disk"); + expect(rows).toHaveLength(1); + expect(rows[0].name).toBe("sda"); + }); + it("mountpoint 为空且无第 4 列 → 空串", () => { + const rows = parseLsblk("NAME SIZE TYPE MOUNTPOINT\nsda 500G disk"); + expect(rows[0].mountpoint).toBe(""); + }); + it("tab 分隔列被正确解析(对抗)", () => { + const raw = "NAME\tSIZE\tTYPE\tMOUNTPOINT\nsda\t500G\tdisk\t/mnt"; + const rows = parseLsblk(raw); + expect(rows).toHaveLength(1); + expect(rows[0].name).toBe("sda"); + expect(rows[0].mountpoint).toBe("/mnt"); + }); + it("mountpoint 含多段路径空格(边界)", () => { + const raw = "NAME SIZE TYPE MOUNTPOINT\nsda1 1G part /a b c d e"; + const rows = parseLsblk(raw); + expect(rows[0].mountpoint).toBe("/a b c d e"); + }); + it("仅空白行 → [](边界)", () => { + expect(parseLsblk(" \n \n ")).toEqual([]); + }); + it("header 行重复 NAME 不产生行(对抗)", () => { + const raw = "NAME SIZE TYPE MOUNTPOINT\nNAME SIZE TYPE MOUNTPOINT\nsda 500G disk"; + const rows = parseLsblk(raw); + // 第二个 NAME 行:cleaned = "NAME SIZE TYPE MOUNTPOINT" → 4 cols → 被解析为行 + // 但 started=true 后不再识别 header → 当作数据行 + expect(rows).toHaveLength(2); + expect(rows[0].name).toBe("NAME"); + expect(rows[1].name).toBe("sda"); + }); +}); + +// ============================================================================ +// deviceBasename / matchesDeviceName / isRootDiskTarget / targetExistsInRows +// —— 决策表 + 不变式 +// ============================================================================ + +describe("deviceBasename — 等价类/边界", () => { + it("/dev/sda1 → sda1", () => { + expect(deviceBasename("/dev/sda1")).toBe("sda1"); + }); + it("/dev/mmcblk0p2 → mmcblk0p2", () => { + expect(deviceBasename("/dev/mmcblk0p2")).toBe("mmcblk0p2"); + }); + it("无 /dev/ 前缀 → 去前导斜杠", () => { + expect(deviceBasename("sda")).toBe("sda"); + expect(deviceBasename("//sda")).toBe("sda"); + }); + it("路径含多级目录 → 取 /dev/ 后全部", () => { + expect(deviceBasename("/dev/disk/by-id/sda")).toBe("disk/by-id/sda"); + }); + it("空串 → 空串(边界)", () => { + expect(deviceBasename("")).toBe(""); + }); + it("仅斜杠 → 空串(边界)", () => { + expect(deviceBasename("/")).toBe(""); + expect(deviceBasename("///")).toBe(""); + }); +}); + +describe("matchesDeviceName — 决策表(base × name)", () => { + it("name === base → true", () => { + expect(matchesDeviceName("sda", "sda")).toBe(true); + }); + it("name = base + 分区号 sda1 → true", () => { + expect(matchesDeviceName("sda", "sda1")).toBe(true); + }); + it("name = base + p分区号 mmcblk0p1 → true", () => { + expect(matchesDeviceName("mmcblk0", "mmcblk0p1")).toBe(true); + }); + it("name = base + 多位分区号 nvme0n1p2 → true", () => { + expect(matchesDeviceName("nvme0n1", "nvme0n1p2")).toBe(true); + }); + it("name 前缀相同但不同设备 sdab → false(关键回归)", () => { + expect(matchesDeviceName("sda", "sdab")).toBe(false); + }); + it("name mmcblk0boot0 → false(前缀同但非分区号)", () => { + expect(matchesDeviceName("mmcblk0", "mmcblk0boot0")).toBe(false); + }); + it("name mmcblk0p 无数字 → false", () => { + expect(matchesDeviceName("mmcblk0", "mmcblk0p")).toBe(false); + }); + it("完全不同设备 → false", () => { + expect(matchesDeviceName("sda", "nvme0n1")).toBe(false); + }); + it("空 base 空 name → true(边界)", () => { + expect(matchesDeviceName("", "")).toBe(true); + }); + it("空 base + 非空 name → false(空 base + p?\\d+ 匹配数字串)", () => { + // 空 base → regex ^(?:p?\d+)?$ → 匹配空串或纯数字串 + expect(matchesDeviceName("", "123")).toBe(true); + expect(matchesDeviceName("", "abc")).toBe(false); + }); + it("base 含正则元字符(点号)→ 正确转义", () => { + expect(matchesDeviceName("sd.a", "sd.a")).toBe(true); + expect(matchesDeviceName("sd.a", "sdxxa")).toBe(false); + }); + it("name = base + 多位数字 sda123 → true", () => { + expect(matchesDeviceName("sda", "sda123")).toBe(true); + }); +}); + +describe("isRootDiskTarget — 决策表(target × rows)", () => { + const rows: LsblkRow[] = [ + { name: "sda", size: 500e9, type: "disk", mountpoint: "" }, + { name: "sda2", size: 499e9, type: "part", mountpoint: "/" }, + { name: "sda1", size: 100e6, type: "part", mountpoint: "/boot" }, + { name: "mmcblk0", size: 7.3e9, type: "disk", mountpoint: "" }, + { name: "mmcblk0p1", size: 7.3e9, type: "part", mountpoint: "" }, + ]; + it("target 整盘是根盘(分区挂 /)→ true", () => { + expect(isRootDiskTarget("/dev/sda", rows)).toBe(true); + }); + it("target 分区自身挂 / → true", () => { + expect(isRootDiskTarget("/dev/sda2", rows)).toBe(true); + }); + it("target 分区挂 /boot → true", () => { + expect(isRootDiskTarget("/dev/sda1", rows)).toBe(true); + }); + it("target 非根盘 → false", () => { + expect(isRootDiskTarget("/dev/mmcblk0", rows)).toBe(false); + }); + it("target 不在 rows → false", () => { + expect(isRootDiskTarget("/dev/nvme0n1", rows)).toBe(false); + }); + it("前缀碰撞:target sda,rows 有 sdab 挂 / → false(关键回归)", () => { + const rows2: LsblkRow[] = [ + { name: "sda", size: 1, type: "disk", mountpoint: "" }, + { name: "sdab", size: 1, type: "disk", mountpoint: "/" }, + ]; + expect(isRootDiskTarget("/dev/sda", rows2)).toBe(false); + }); + it("ROOT_MOUNTPOINTS 含核心挂载点集合", () => { + for (const mp of ["/", "/boot", "/boot/efi", "/home", "/var", "/usr", "/swap", "[SWAP]"]) { + expect(ROOT_MOUNTPOINTS.has(mp)).toBe(true); + } + expect(ROOT_MOUNTPOINTS.has("/tmp")).toBe(false); + }); + it("ROOT_MOUNTPOINTS 不可变:add 抛 TypeError(fail-closed 不变式)", () => { + const s = ROOT_MOUNTPOINTS as unknown as { add?: (v: string) => void }; + expect(typeof s.add).toBe("undefined"); // FrozenSet 不暴露 add + }); + it("ROOT_MOUNTPOINTS size 契约", () => { + expect(ROOT_MOUNTPOINTS.size).toBe(8); + }); + it("空 rows → false(边界)", () => { + expect(isRootDiskTarget("/dev/sda", [])).toBe(false); + }); + it("mountpoint 为空串 → 不当根盘(边界)", () => { + const rows2: LsblkRow[] = [{ name: "sda", size: 1, type: "disk", mountpoint: "" }]; + expect(isRootDiskTarget("/dev/sda", rows2)).toBe(false); + }); + it("mountpoint 非 ROOT_MOUNTPOINTS(如 /mnt)→ false", () => { + const rows2: LsblkRow[] = [{ name: "sda", size: 1, type: "disk", mountpoint: "/mnt" }]; + expect(isRootDiskTarget("/dev/sda", rows2)).toBe(false); + }); +}); + +describe("targetExistsInRows — 决策表", () => { + const rows: LsblkRow[] = [ + { name: "mmcblk0", size: 7e9, type: "disk", mountpoint: "" }, + { name: "mmcblk0p1", size: 7e9, type: "part", mountpoint: "" }, + ]; + it("target 整盘存在 → true", () => { + expect(targetExistsInRows("/dev/mmcblk0", rows)).toBe(true); + }); + it("target 分区存在 → true", () => { + expect(targetExistsInRows("/dev/mmcblk0p1", rows)).toBe(true); + }); + it("target 不存在 → false", () => { + expect(targetExistsInRows("/dev/sda", rows)).toBe(false); + }); + it("前缀碰撞:target mmcblk0,rows 有 mmcblk0boot0 → false", () => { + const rows2: LsblkRow[] = [{ name: "mmcblk0boot0", size: 1, type: "disk", mountpoint: "" }]; + expect(targetExistsInRows("/dev/mmcblk0", rows2)).toBe(false); + }); + it("空 rows → false(边界)", () => { + expect(targetExistsInRows("/dev/sda", [])).toBe(false); + }); +}); + +// ============================================================================ +// splitCommand —— 等价类 + 边界 + 对抗/fuzz +// ============================================================================ + +describe("splitCommand — 等价类/边界/对抗", () => { + it("简单命令", () => { + expect(splitCommand("dd if=a of=b")).toEqual(["dd", "if=a", "of=b"]); + }); + it("双引号内整体保留(openocd -c \"program x verify reset exit\")", () => { + expect(splitCommand('openocd -f cfg -c "program img verify reset exit"')).toEqual([ + "openocd", "-f", "cfg", "-c", "program img verify reset exit", + ]); + }); + it("多段引号", () => { + expect(splitCommand('a "x y" b "z w"')).toEqual(["a", "x y", "b", "z w"]); + }); + it("空串 → [](边界)", () => { + expect(splitCommand("")).toEqual([]); + }); + it("仅空格 → [](边界)", () => { + expect(splitCommand(" ")).toEqual([]); + }); + it("尾随空格不产生空 token(边界)", () => { + expect(splitCommand("dd if=a ")).toEqual(["dd", "if=a"]); + }); + it("不平衡引号不崩溃(对抗)", () => { + expect(splitCommand('a "b c')).toEqual(["a", "b c"]); + }); + it("空引号 token 保留为空串(边界)", () => { + expect(splitCommand('a -c ""')).toEqual(["a", "-c", ""]); + }); + it("仅引号 → 单个空串 token", () => { + expect(splitCommand('""')).toEqual([""]); + }); + it("引号紧贴前文(对抗)", () => { + expect(splitCommand('a"b c"d')).toEqual(["ab cd"]); + }); + it("多个连续空格不产生空 token(边界)", () => { + expect(splitCommand("a b")).toEqual(["a", "b"]); + }); + it("tab 分隔不产生空 token(对抗)", () => { + expect(splitCommand("a\tb")).toEqual(["a\tb"]); + }); + it("多个空引号 token 各自保留(边界)", () => { + expect(splitCommand('"" ""')).toEqual(["", ""]); + }); + it("引号内含空格后引号外继续(对抗)", () => { + expect(splitCommand('a "b c" d')).toEqual(["a", "b c", "d"]); + }); + it("仅前导空格 + 引号(边界)", () => { + expect(splitCommand(' "hello"')).toEqual(["hello"]); + }); +}); + +// ============================================================================ +// orchestrateRun —— 状态转换 + 决策表 + 不变式(fail-closed / 短路) +// ============================================================================ + +/** 构造最小 FlashPlanEx 供 orchestrateRun 直测。 */ +function planEx(over: Partial = {}): FlashPlanEx { + return { + method: "dd", + commands: ["echo hi"], + target: "/dev/x", + image: "img", + ...over, + }; +} +const dryOk = async (p: FlashPlanEx): Promise => ({ + ok: true, plan: p, targetExists: true, isRootDisk: false, probeCommands: [], +}); +const dryFailFn = async (p: FlashPlanEx): Promise => ({ + ok: false, reason: "dry-fail", plan: p, targetExists: false, isRootDisk: false, probeCommands: [], +}); +const verifyOk = async (): Promise => ({ ok: true, verifyCommand: "vcmd" }); +const verifyFailFn = async (): Promise => ({ ok: false, reason: "verify-fail", verifyCommand: "vcmd" }); + +describe("orchestrateRun — 状态转换/决策表", () => { + it("dryRun 失败 → written false / ok false / verify 不调(fail-closed)", async () => { + const exec = mockExec(); + const verify = vi.fn(verifyOk); + const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryFailFn, verify); + expect(r.ok).toBe(false); + expect(r.written).toBe(false); + expect(r.writeExitCodes).toEqual([]); + expect(r.reason).toBe("dry-fail"); + expect(verify).not.toHaveBeenCalled(); + }); + + it("dryRun ok + dryRun 默认(undefined) → 只 dry-run 不写(fail-closed 默认)", async () => { + const exec = mockExec(); + const r = await orchestrateRun(planEx({ dryRun: undefined }), exec, dryOk, verifyOk); + expect(r.ok).toBe(true); + expect(r.written).toBe(false); + expect(r.writeExitCodes).toEqual([]); + expect(exec.calls).toHaveLength(0); // 无写命令 + }); + + it("dryRun ok + dryRun=true → 只 dry-run 不写", async () => { + const exec = mockExec(); + const r = await orchestrateRun(planEx({ dryRun: true }), exec, dryOk, verifyOk); + expect(r.written).toBe(false); + expect(r.ok).toBe(true); + }); + + it("dryRun ok + dryRun=false + 写全 0 + verify ok → written true / ok true", async () => { + const exec = mockExec({ exitCode: 0 }); + const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryOk, verifyOk); + expect(r.written).toBe(true); + expect(r.writeExitCodes).toEqual([0]); + expect(r.verify?.ok).toBe(true); + expect(r.ok).toBe(true); + }); + + it("dryRun ok + dryRun=false + verify=false → 跳过 verify,ok true", async () => { + const exec = mockExec({ exitCode: 0 }); + const verify = vi.fn(verifyOk); + const r = await orchestrateRun(planEx({ dryRun: false, verify: false }), exec, dryOk, verify); + expect(r.written).toBe(true); + expect(r.verify).toBeUndefined(); + expect(r.ok).toBe(true); + expect(verify).not.toHaveBeenCalled(); + }); + + it("写命令失败 → 短路:后续命令不执行 + verify 不调(waterfall 短路不变式)", async () => { + const exec = mockExec({ exitCode: 3 }); + const verify = vi.fn(verifyOk); + const p = planEx({ + dryRun: false, + commands: ["first cmd", "second cmd"], + }); + const r = await orchestrateRun(p, exec, dryOk, verify); + expect(r.written).toBe(true); + expect(r.writeExitCodes).toEqual([3]); + expect(r.ok).toBe(false); + expect(r.reason).toContain("write command failed"); + expect(exec.calls).toHaveLength(1); // 仅第一条 + expect(verify).not.toHaveBeenCalled(); + }); + + it("写全 0 + verify 失败 → ok false + reason verify-fail", async () => { + const exec = mockExec({ exitCode: 0 }); + const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryOk, verifyFailFn); + expect(r.written).toBe(true); + expect(r.verify?.ok).toBe(false); + expect(r.ok).toBe(false); + expect(r.reason).toBe("verify-fail"); + }); + + it("多命令顺序执行 + 全 0 → writeExitCodes 长度 = 命令数", async () => { + const exec = mockExec({ exitCode: 0 }); + const p = planEx({ dryRun: false, commands: ["a x", "b y", "c z"] }); + const r = await orchestrateRun(p, exec, dryOk, verifyOk); + expect(r.writeExitCodes).toEqual([0, 0, 0]); + expect(exec.calls.map((c) => c.command)).toEqual(["a", "b", "c"]); + }); + + it("空 commands + dryRun=false → written true / writeExitCodes 空 / ok true(边界)", async () => { + const exec = mockExec({ exitCode: 0 }); + const r = await orchestrateRun(planEx({ dryRun: false, commands: [] }), exec, dryOk, verifyOk); + expect(r.written).toBe(true); + expect(r.writeExitCodes).toEqual([]); + expect(r.ok).toBe(true); + }); + + it("写失败短路 reason 含 stderr(诊断不变式)", async () => { + const exec = mockExec({ exitCode: 5, stderr: "disk full" }); + const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryOk, verifyOk); + expect(r.reason).toContain("disk full"); + }); + + it("写失败短路 reason 无 stderr 时含 exit N(边界)", async () => { + const exec = mockExec({ exitCode: 7, stderr: "" }); + const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryOk, verifyOk); + expect(r.reason).toContain("exit 7"); + }); + + it("verify ok 时 reason undefined(不变式)", async () => { + const exec = mockExec({ exitCode: 0 }); + const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryOk, verifyOk); + expect(r.reason).toBeUndefined(); + }); + + it("第二条写命令失败 → 第一条 exitCode 已记录 + 短路(决策表)", async () => { + const exec = scriptedExec((cmd) => { + if (cmd === "first") return ok(); + return fail(9, "second fail"); + }); + const p = planEx({ dryRun: false, commands: ["first x", "second y"] }); + const r = await orchestrateRun(p, exec, dryOk, verifyOk); + expect(r.writeExitCodes).toEqual([0, 9]); + expect(r.ok).toBe(false); + expect(r.reason).toContain("second y"); // plan.commands[1] = "second y" + expect(exec.calls).toHaveLength(2); + }); + + it("dryRun 失败后 dryRun reason 透传到顶层 reason(不变式)", async () => { + const exec = mockExec(); + const r = await orchestrateRun(planEx({ dryRun: false }), exec, dryFailFn, verifyOk); + expect(r.reason).toBe("dry-fail"); + expect(r.dryRun.reason).toBe("dry-fail"); + }); +}); + +// ============================================================================ +// probeDryRun / exitCodeVerify —— 决策表 + 不变式 +// ============================================================================ + +describe("probeDryRun — 决策表(exit 0 / 非 0)", () => { + it("探活 exit 0 → ok true + probeCommands 记录", async () => { + const exec = mockExec({ exitCode: 0 }); + const r = await probeDryRun(planEx(), exec, { cmd: "fastboot", args: ["getvar", "all"] }); + expect(r.ok).toBe(true); + expect(r.targetExists).toBe(true); + expect(r.probeCommands).toEqual(["fastboot getvar all"]); + }); + it("探活 非 0 → ok false + reason 含 method", async () => { + const exec = mockExec({ exitCode: 1, stderr: "no device" }); + const r = await probeDryRun(planEx({ method: "fastboot" }), exec, { cmd: "fastboot", args: ["getvar", "all"] }); + expect(r.ok).toBe(false); + expect(r.reason).toContain("fastboot probe failed"); + expect(r.reason).toContain("no device"); + }); + it("探活 非 0 + stderr 空 → reason 含 exit N(边界)", async () => { + const exec = mockExec({ exitCode: 2, stderr: "" }); + const r = await probeDryRun(planEx({ method: "dfu" }), exec, { cmd: "dfu-util", args: ["-l"] }); + expect(r.reason).toContain("exit 2"); + }); + it("探活 exit 0 → isRootDisk false / targetExists true(不变式)", async () => { + const exec = mockExec({ exitCode: 0 }); + const r = await probeDryRun(planEx({ method: "dfu" }), exec, { cmd: "dfu-util", args: ["-l"] }); + expect(r.isRootDisk).toBe(false); + expect(r.targetExists).toBe(true); + }); +}); + +describe("exitCodeVerify — 决策表(exit 0 / 非 0)", () => { + it("校验 exit 0 → ok true + verifyCommand", async () => { + const exec = mockExec({ exitCode: 0 }); + const r = await exitCodeVerify(planEx({ method: "openocd" }), exec, { cmd: "openocd", args: ["-c", "exit"] }); + expect(r.ok).toBe(true); + expect(r.verifyCommand).toBe("openocd -c exit"); + }); + it("校验 非 0 → ok false + reason", async () => { + const exec = mockExec({ exitCode: 1, stderr: "jtag fail" }); + const r = await exitCodeVerify(planEx({ method: "openocd" }), exec, { cmd: "openocd", args: ["-c", "exit"] }); + expect(r.ok).toBe(false); + expect(r.reason).toContain("openocd verify failed"); + }); + it("校验 非 0 + stderr 空 → reason 含 exit N(边界)", async () => { + const exec = mockExec({ exitCode: 3, stderr: "" }); + const r = await exitCodeVerify(planEx({ method: "dfu" }), exec, { cmd: "dfu-util", args: ["-l"] }); + expect(r.reason).toContain("exit 3"); + }); + it("校验 exit 0 → verifyCommand 含 cmd + args join(不变式)", async () => { + const exec = mockExec({ exitCode: 0 }); + const r = await exitCodeVerify(planEx(), exec, { cmd: "fastboot", args: ["getvar", "all"] }); + expect(r.verifyCommand).toBe("fastboot getvar all"); + }); +}); + +// ============================================================================ +// DD_PROVIDER plan —— 等价类 + 边界 + 决策表(fail-closed 抛错) +// ============================================================================ + +describe("DD_PROVIDER.plan — 等价类/边界值", () => { + it("基础 plan:dd if=image of=target bs=4M conv=fsync,无 seek", () => { + const p = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + expect(p.commands).toEqual(["dd if=sd.img of=/dev/mmcblk0 bs=4M conv=fsync"]); + expect(p.offsetBytes).toBe(0); + expect(p.dryRun).toBeUndefined(); + expect(p.verify).toBeUndefined(); + }); + it("offset > 0 → seek= 块数(字节 8388608 / 4MiB = 2)", () => { + const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: "8388608" }); + expect(p.offsetBytes).toBe(8388608); + expect(p.commands[0]).toContain("seek=2"); + }); + it("hex offset 0x10(16B,<4MiB)→ seek=0(floor(16/4MiB)=0,仍带 seek=)", () => { + const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: "0x10" }); + expect(p.offsetBytes).toBe(16); + expect(p.commands[0]).toContain("seek=0"); + }); + it("offset 0 → 不带 seek", () => { + const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: "0" }); + expect(p.offsetBytes).toBe(0); + expect(p.commands[0]).not.toContain("seek="); + }); + it("offset 恰好 4MiB → seek=1(边界 off-by-one)", () => { + const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: String(DD_BLOCK_SIZE) }); + expect(p.commands[0]).toContain("seek=1"); + }); + it("offset 恰好 4MiB-1 → seek=0(off-by-one 边界)", () => { + const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: String(DD_BLOCK_SIZE - 1) }); + expect(p.commands[0]).toContain("seek=0"); + }); + it("offset 恰好 8MiB → seek=2(边界)", () => { + const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: String(DD_BLOCK_SIZE * 2) }); + expect(p.commands[0]).toContain("seek=2"); + }); + it("dryRun/verify 透传", () => { + const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", dryRun: false, verify: false }); + expect(p.dryRun).toBe(false); + expect(p.verify).toBe(false); + }); + it("plan 设 method=dd(等价类)", () => { + const p = DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/x" }); + expect(p.method).toBe("dd"); + expect(p.target).toBe("/dev/x"); + expect(p.image).toBe("i"); + }); + it("hex offset 0x400000 (=4MiB) → seek=1(hex 边界)", () => { + const p = DD_PROVIDER.plan({ method: "dd", image: "r.img", target: "/dev/mmcblk0", offset: "0x400000" }); + expect(p.offsetBytes).toBe(DD_BLOCK_SIZE); + expect(p.commands[0]).toContain("seek=1"); + }); +}); + +describe("DD_PROVIDER.plan — fail-closed 抛错(决策表)", () => { + it("image 空 → 抛错", () => { + expect(() => DD_PROVIDER.plan({ method: "dd", image: "", target: "/dev/x" })).toThrow(/image path required/); + }); + it("image 空白 → 抛错", () => { + expect(() => DD_PROVIDER.plan({ method: "dd", image: " ", target: "/dev/x" })).toThrow(/image path required/); + }); + it("target 空 → 抛错", () => { + expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "" })).toThrow(/target required/); + }); + it("target 空白 → 抛错", () => { + expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: " " })).toThrow(/target required/); + }); + it("offset 不可解析 → 抛错", () => { + expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/x", offset: "abc" })).toThrow(/invalid offset/); + }); + it("ctx.lsblk 中 target 不存在 → 抛错", () => { + const rows: LsblkRow[] = [{ name: "sda", size: 1, type: "disk", mountpoint: "" }]; + expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/mmcblk0" }, { lsblk: rows })).toThrow(/not found in lsblk/); + }); + it("ctx.lsblk 中 target 是根盘 → 抛错", () => { + const rows: LsblkRow[] = [ + { name: "sda", size: 500e9, type: "disk", mountpoint: "" }, + { name: "sda2", size: 499e9, type: "part", mountpoint: "/" }, + ]; + expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/sda" }, { lsblk: rows })).toThrow(/root disk|refusing/); + }); + it("无 ctx.lsblk → 不做早期根盘校验(不抛)", () => { + expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/sda" })).not.toThrow(); + }); + it("ctx.lsblk 空数组 → 不做早期校验(不抛)", () => { + expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/sda" }, { lsblk: [] })).not.toThrow(); + }); + it("ctx.lsblk target 存在且非根盘 → 不抛(正常)", () => { + const rows: LsblkRow[] = [{ name: "mmcblk0", size: 7e9, type: "disk", mountpoint: "" }]; + expect(() => DD_PROVIDER.plan({ method: "dd", image: "i", target: "/dev/mmcblk0" }, { lsblk: rows })).not.toThrow(); + }); +}); + +// ============================================================================ +// DD_PROVIDER run/dryRun/verify —— 集成(scripted exec 路由) +// ============================================================================ + +/** 已知 payload + 其 sha256,用于 dryRun/verify happy 路径。 */ +const DD_PAYLOAD = "hello-dd-payload-bytes"; +const DD_PAYLOAD_SHA = createHash("sha256").update(DD_PAYLOAD).digest("hex"); +const DD_IMAGE_SIZE = String(DD_PAYLOAD.length); + +/** dd dryRun happy 路径的 scripted exec:lsblk/stat/sha256sum/dd-probe 全 0。 */ +function ddHappyExec(targetBase = "mmcblk0"): ExecFn & { calls: { command: string; args: string[]; opts?: ExecOpts }[] } { + return scriptedExec((cmd, args) => { + if (cmd === "lsblk") return ok(`NAME SIZE TYPE MOUNTPOINT\n${targetBase} 7G disk\n${targetBase}p1 7G part`); + if (cmd === "stat") return ok(DD_IMAGE_SIZE); + if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`); + if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return ok(); // 只读探针 + return ok(); + }); +} + +describe("DD_PROVIDER.run — dryRun 默认(只 dry-run 不写)", () => { + it("全探针通过 → ok true / written false / expectedSha256 已填", async () => { + const exec = ddHappyExec(); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(true); + expect(r.written).toBe(false); + expect(r.dryRun.ok).toBe(true); + expect(plan.expectedSha256).toBe(DD_PAYLOAD_SHA); + expect(plan.blockCount).toBeGreaterThanOrEqual(1); + expect(plan.imageSizeBytes).toBe(DD_PAYLOAD.length); + }); + + it("dryRun 阶段 lsblk 失败 → ok false + written false", async () => { + const exec = scriptedExec(() => fail(1, "lsblk error")); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(r.written).toBe(false); + expect(r.dryRun.reason).toContain("lsblk failed"); + }); + + it("dryRun 阶段 target 不在 lsblk → ok false", async () => { + const exec = scriptedExec((cmd) => { + if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nsda 500G disk"); + return ok(); + }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(r.dryRun.reason).toContain("not found in lsblk"); + }); + + it("dryRun 阶段 target 是根盘 → ok false + isRootDisk true", async () => { + const exec = scriptedExec((cmd) => { + if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk\nmmcblk0p1 7G part /"); + return ok(); + }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(r.dryRun.isRootDisk).toBe(true); + expect(r.dryRun.reason).toContain("refusing"); + }); + + it("dryRun 阶段 stat 失败 → ok false", async () => { + const exec = scriptedExec((cmd) => { + if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk"); + if (cmd === "stat") return fail(1, "no such file"); + return ok(); + }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(r.dryRun.reason).toContain("stat image failed"); + }); + + it("dryRun 阶段镜像大小非法 → ok false", async () => { + const exec = scriptedExec((cmd) => { + if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk"); + if (cmd === "stat") return ok("not-a-number"); + return ok(); + }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(r.dryRun.reason).toContain("invalid image size"); + }); + + it("dryRun 阶段镜像大小 0 → ok false(边界)", async () => { + const exec = scriptedExec((cmd) => { + if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk"); + if (cmd === "stat") return ok("0"); + return ok(); + }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(r.dryRun.reason).toContain("invalid image size"); + }); + + it("dryRun 阶段 offset >= imageSize(未知设备大小回退) → 拒绝(契约边界)", async () => { + const exec = ddHappyExec(); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", offset: "999999" }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + // targetDeviceSize = 7 (parseInt("7G")), offset 999999 >= 7 → "exceeds target device size" + expect(r.dryRun.reason).toMatch(/exceeds target device size|>= image size/); + }); + + it("dryRun 阶段 offset 非对齐 4MiB → 拒绝(fail-closed 非对齐)", async () => { + // offset=1 < targetDeviceSize(7) → 通过越界检查 → 命中非对齐检查 + const exec = ddHappyExec(); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", offset: "1" }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(r.dryRun.reason).toContain("not a multiple of block size"); + }); + + it("dryRun 阶段 offset 恰好 4MiB 对齐 → 通过(边界)", async () => { + // 需要设备大小 > 4MiB,用字节数而非 7G(parseInt("7G")=7 太小) + const exec = scriptedExec((cmd, args) => { + if (cmd === "lsblk") return ok(`NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7516192768 disk\nmmcblk0p1 7516192768 part`); + if (cmd === "stat") return ok(DD_IMAGE_SIZE); + if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`); + if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return ok(); + return ok(); + }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", offset: String(DD_BLOCK_SIZE) }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(true); + expect(r.written).toBe(false); + }); + + it("dryRun 阶段 sha256sum 失败 → ok false", async () => { + const exec = scriptedExec((cmd) => { + if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk"); + if (cmd === "stat") return ok(DD_IMAGE_SIZE); + if (cmd === "sha256sum") return fail(1, "sha err"); + return ok(); + }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(r.dryRun.reason).toContain("sha256sum failed"); + }); + + it("dryRun 阶段 sha256 输出非 64 hex → ok false", async () => { + const exec = scriptedExec((cmd) => { + if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk"); + if (cmd === "stat") return ok(DD_IMAGE_SIZE); + if (cmd === "sha256sum") return ok("garbage-not-a-hash"); + return ok(); + }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(r.dryRun.reason).toContain("unparsable sha256sum"); + }); + + it("dryRun 阶段只读 dd 探针失败 → ok false", async () => { + const exec = scriptedExec((cmd, args) => { + if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk"); + if (cmd === "stat") return ok(DD_IMAGE_SIZE); + if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`); + if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return fail(1, "read err"); + return ok(); + }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(r.dryRun.reason).toContain("image read probe failed"); + }); + + it("dryRun ok 填充 imageSizeBytes + blockCount + expectedSha256(不变式)", async () => { + const exec = ddHappyExec(); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + await DD_PROVIDER.run(plan, exec); + expect(plan.imageSizeBytes).toBe(DD_PAYLOAD.length); + expect(plan.blockCount).toBe(Math.max(1, Math.ceil(DD_PAYLOAD.length / DD_BLOCK_SIZE))); + expect(plan.expectedSha256).toBe(DD_PAYLOAD_SHA); + }); + + it("dryRun ok 填充 sha256sumOutput(不变式)", async () => { + const exec = ddHappyExec(); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.dryRun.sha256sumOutput).toContain(DD_PAYLOAD_SHA); + }); +}); + +describe("DD_PROVIDER.run — dryRun:false 写 + verify", () => { + it("写 + verify 全通过 → written true / ok true", async () => { + const exec = scriptedExec((cmd, args) => { + if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk"); + if (cmd === "stat") return ok(DD_IMAGE_SIZE); + if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`); + if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return ok(); // 探针 + if (cmd === "dd" && args.some((a) => a.startsWith("count="))) return ok(DD_PAYLOAD); // readback + if (cmd === "dd") return ok(); // 写 + return ok(); + }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", dryRun: false }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.written).toBe(true); + expect(r.writeExitCodes).toEqual([0]); + expect(r.verify?.ok).toBe(true); + expect(r.verify?.actual).toBe(DD_PAYLOAD_SHA); + expect(r.ok).toBe(true); + }); + + it("dryRun:false + verify:false → 跳过 verify,ok true", async () => { + const exec = scriptedExec((cmd, args) => { + if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk"); + if (cmd === "stat") return ok(DD_IMAGE_SIZE); + if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`); + if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return ok(); + if (cmd === "dd") return ok(); + return ok(); + }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", dryRun: false, verify: false }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.written).toBe(true); + expect(r.verify).toBeUndefined(); + expect(r.ok).toBe(true); + }); + + it("写命令失败 → ok false + 短路(无 readback)", async () => { + const exec = scriptedExec((cmd, args) => { + if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk"); + if (cmd === "stat") return ok(DD_IMAGE_SIZE); + if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`); + if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return ok(); + if (cmd === "dd" && args.some((a) => a.startsWith("count="))) return ok(DD_PAYLOAD); + if (cmd === "dd") return fail(1, "write protected"); // 写失败 + return ok(); + }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", dryRun: false }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.written).toBe(true); + expect(r.writeExitCodes).toEqual([1]); + expect(r.ok).toBe(false); + expect(r.reason).toContain("write command failed"); + }); + + it("写全 0 + verify sha256 不匹配 → ok false + VERIFY FAILED", async () => { + const exec = scriptedExec((cmd, args) => { + if (cmd === "lsblk") return ok("NAME SIZE TYPE MOUNTPOINT\nmmcblk0 7G disk"); + if (cmd === "stat") return ok(DD_IMAGE_SIZE); + if (cmd === "sha256sum") return ok(`${DD_PAYLOAD_SHA} sd.img`); + if (cmd === "dd" && args.some((a) => a === "of=/dev/null")) return ok(); + if (cmd === "dd" && args.some((a) => a.startsWith("count="))) return ok("different-content"); // readback mismatch + if (cmd === "dd") return ok(); // 写 + return ok(); + }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0", dryRun: false }); + const r = await DD_PROVIDER.run(plan, exec); + expect(r.written).toBe(true); + expect(r.verify?.ok).toBe(false); + expect(r.ok).toBe(false); + expect(r.reason).toContain("VERIFY FAILED"); + }); +}); + +describe("DD_PROVIDER.verify — 决策表(无 hash / 匹配 / 不匹配 / 读回失败)", () => { + it("无 expectedSha256 → ok false(fail-closed:未 dryRun 先拒)", async () => { + const exec = mockExec(); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + const r = await DD_PROVIDER.verify(plan, exec); + expect(r.ok).toBe(false); + expect(r.reason).toContain("no expectedSha256"); + }); + it("读回 sha256 匹配 → ok true + actual=expected", async () => { + const exec = scriptedExec(() => ok(DD_PAYLOAD)); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + plan.expectedSha256 = DD_PAYLOAD_SHA; + plan.blockCount = 1; + const r = await DD_PROVIDER.verify(plan, exec); + expect(r.ok).toBe(true); + expect(r.actual).toBe(DD_PAYLOAD_SHA); + }); + it("读回 sha256 不匹配 → ok false + VERIFY FAILED", async () => { + const exec = scriptedExec(() => ok("different-content")); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + plan.expectedSha256 = DD_PAYLOAD_SHA; + plan.blockCount = 1; + const r = await DD_PROVIDER.verify(plan, exec); + expect(r.ok).toBe(false); + expect(r.reason).toContain("VERIFY FAILED"); + }); + it("读回 exec 失败 → ok false + readback dd failed", async () => { + const exec = mockExec({ exitCode: 1, stderr: "io err" }); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + plan.expectedSha256 = DD_PAYLOAD_SHA; + plan.blockCount = 1; + const r = await DD_PROVIDER.verify(plan, exec); + expect(r.ok).toBe(false); + expect(r.reason).toContain("readback dd failed"); + }); + it("verify 命令用 count=blockCount(不变式)", async () => { + const exec = scriptedExec(() => ok(DD_PAYLOAD)); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + plan.expectedSha256 = DD_PAYLOAD_SHA; + plan.blockCount = 3; + await DD_PROVIDER.verify(plan, exec); + expect(exec.calls[0].args).toContain("count=3"); + }); + it("verify 无 blockCount → 默认 count=1(边界)", async () => { + const exec = scriptedExec(() => ok(DD_PAYLOAD)); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + plan.expectedSha256 = DD_PAYLOAD_SHA; + await DD_PROVIDER.verify(plan, exec); + expect(exec.calls[0].args).toContain("count=1"); + }); + it("verify 命令格式:dd if= bs=4M count=", async () => { + const exec = scriptedExec(() => ok(DD_PAYLOAD)); + const plan = DD_PROVIDER.plan({ method: "dd", image: "sd.img", target: "/dev/mmcblk0" }); + plan.expectedSha256 = DD_PAYLOAD_SHA; + plan.blockCount = 2; + await DD_PROVIDER.verify(plan, exec); + expect(exec.calls[0].command).toBe("dd"); + expect(exec.calls[0].args).toContain("if=/dev/mmcblk0"); + expect(exec.calls[0].args).toContain("bs=4M"); + expect(exec.calls[0].args).toContain("count=2"); + }); +}); + +// ============================================================================ +// FASTBOOT / DFU / OPENOCD providers —— plan 等价类 + run 编排 +// ============================================================================ + +describe("FASTBOOT_PROVIDER.plan — 等价类", () => { + it("带 partition → fastboot flash ", () => { + const p = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "boot.img", target: "serial", partition: "boot" }); + expect(p.commands).toEqual(["fastboot flash boot boot.img"]); + }); + it("无 partition → fastboot flash ", () => { + const p = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "boot.img", target: "serial" }); + expect(p.commands).toEqual(["fastboot flash boot.img"]); + }); + it("partition 空白 → 视为无 partition", () => { + const p = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b.img", target: "s", partition: " " }); + expect(p.commands).toEqual(["fastboot flash b.img"]); + }); + it("image 空 → 抛错", () => { + expect(() => FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "", target: "s" })).toThrow(/image path required/); + }); + it("target 空 → 抛错", () => { + expect(() => FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "i", target: "" })).toThrow(/target required/); + }); + it("dryRun/verify 透传", () => { + const p = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b", target: "s", dryRun: false, verify: false }); + expect(p.dryRun).toBe(false); + expect(p.verify).toBe(false); + }); +}); + +describe("FASTBOOT_PROVIDER.run — 编排(dryOnly / 写 / verify)", () => { + it("dryRun 默认 → dryRun getvar all 探活,不写", async () => { + const exec = mockExec({ exitCode: 0 }); + const plan = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b.img", target: "s" }); + const r = await FASTBOOT_PROVIDER.run(plan, exec); + expect(r.ok).toBe(true); + expect(r.written).toBe(false); + expect(exec.calls[0].command).toBe("fastboot"); + expect(exec.calls[0].args).toEqual(["getvar", "all"]); + }); + it("dryRun:false + 写 + verify getvar all → ok true", async () => { + const exec = mockExec({ exitCode: 0 }); + const plan = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b.img", target: "s", dryRun: false }); + const r = await FASTBOOT_PROVIDER.run(plan, exec); + expect(r.written).toBe(true); + expect(r.writeExitCodes).toEqual([0]); + expect(r.verify?.ok).toBe(true); + expect(exec.calls.filter((c) => c.args.join(" ") === "getvar all").length).toBe(2); + }); + it("dryRun 探活失败 → ok false + written false", async () => { + const exec = mockExec({ exitCode: 1, stderr: "no device" }); + const plan = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b.img", target: "s" }); + const r = await FASTBOOT_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(r.written).toBe(false); + expect(r.dryRun.reason).toContain("fastboot probe failed"); + }); + it("dryRun:false + 写失败 → 短路不调 verify(不变式)", async () => { + const exec = scriptedExec((cmd, args) => { + if (cmd === "fastboot" && args.join(" ") === "getvar all") return ok(); // 探活通过 + return fail(1, "write fail"); // 写失败 + }); + const plan = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b.img", target: "s", dryRun: false }); + const r = await FASTBOOT_PROVIDER.run(plan, exec); + expect(r.written).toBe(true); + expect(r.ok).toBe(false); + expect(exec.calls).toHaveLength(2); // 探活(1) + 写(1), verify 不调 + }); + it("dryRun:false + verify:false → 跳过 verify", async () => { + const exec = mockExec({ exitCode: 0 }); + const plan = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b.img", target: "s", dryRun: false, verify: false }); + const r = await FASTBOOT_PROVIDER.run(plan, exec); + expect(r.verify).toBeUndefined(); + expect(r.ok).toBe(true); + }); +}); + +describe("DFU_PROVIDER.plan — 等价类", () => { + it("带 alt → dfu-util -d -a -D ", () => { + const p = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11", partition: "0" }); + expect(p.commands).toEqual(["dfu-util -d 0483:df11 -a 0 -D fw.bin"]); + }); + it("无 alt → dfu-util -d -D ", () => { + const p = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11" }); + expect(p.commands).toEqual(["dfu-util -d 0483:df11 -D fw.bin"]); + }); + it("image/target 空 → 抛错", () => { + expect(() => DFU_PROVIDER.plan({ method: "dfu", image: "", target: "t" })).toThrow(); + expect(() => DFU_PROVIDER.plan({ method: "dfu", image: "i", target: "" })).toThrow(); + }); + it("partition 空白 → 视为无 alt", () => { + const p = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11", partition: " " }); + expect(p.commands).toEqual(["dfu-util -d 0483:df11 -D fw.bin"]); + }); +}); + +describe("DFU_PROVIDER.run — 编排", () => { + it("dryRun 默认 → dfu-util -l 探活,不写", async () => { + const exec = mockExec({ exitCode: 0 }); + const plan = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11" }); + const r = await DFU_PROVIDER.run(plan, exec); + expect(r.ok).toBe(true); + expect(r.written).toBe(false); + expect(exec.calls[0]).toEqual({ command: "dfu-util", args: ["-l"], opts: undefined }); + }); + it("dryRun:false → 写 + verify -l → ok true", async () => { + const exec = mockExec({ exitCode: 0 }); + const plan = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11", dryRun: false }); + const r = await DFU_PROVIDER.run(plan, exec); + expect(r.written).toBe(true); + expect(r.verify?.ok).toBe(true); + }); + it("dryRun 探活失败 → ok false + written false", async () => { + const exec = mockExec({ exitCode: 1, stderr: "no dfu" }); + const plan = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11" }); + const r = await DFU_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(r.written).toBe(false); + expect(r.dryRun.reason).toContain("dfu probe failed"); + }); + it("dryRun:false + 写失败 → 短路不调 verify", async () => { + const exec = scriptedExec((cmd, args) => { + if (cmd === "dfu-util" && args.join(" ") === "-l") return ok(); + return fail(1, "write err"); + }); + const plan = DFU_PROVIDER.plan({ method: "dfu", image: "fw.bin", target: "0483:df11", dryRun: false }); + const r = await DFU_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(exec.calls).toHaveLength(2); // 探活 + 写, verify 不调 + }); +}); + +describe("OPENOCD_PROVIDER.plan — 等价类", () => { + it("命令格式 openocd -f -c \"program verify reset exit\"", () => { + const p = OPENOCD_PROVIDER.plan({ method: "openocd", image: "fw.bin", target: "stlink.cfg" }); + expect(p.commands).toEqual([`openocd -f stlink.cfg -c "program fw.bin verify reset exit"`]); + }); + it("image/target 空 → 抛错", () => { + expect(() => OPENOCD_PROVIDER.plan({ method: "openocd", image: "", target: "c" })).toThrow(); + expect(() => OPENOCD_PROVIDER.plan({ method: "openocd", image: "i", target: "" })).toThrow(); + }); + it("dryRun/verify 透传", () => { + const p = OPENOCD_PROVIDER.plan({ method: "openocd", image: "f", target: "c.cfg", dryRun: false, verify: false }); + expect(p.dryRun).toBe(false); + expect(p.verify).toBe(false); + }); +}); + +describe("OPENOCD_PROVIDER.run — 编排", () => { + it("dryRun 默认 → openocd init/exit 探活,不写", async () => { + const exec = mockExec({ exitCode: 0 }); + const plan = OPENOCD_PROVIDER.plan({ method: "openocd", image: "fw.bin", target: "stlink.cfg" }); + const r = await OPENOCD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(true); + expect(r.written).toBe(false); + expect(exec.calls[0].args).toEqual(["-f", "stlink.cfg", "-c", "init", "-c", "exit"]); + }); + it("dryRun:false → 写 program cmd + verify verify_image → ok true", async () => { + const exec = mockExec({ exitCode: 0 }); + const plan = OPENOCD_PROVIDER.plan({ method: "openocd", image: "fw.bin", target: "stlink.cfg", dryRun: false }); + const r = await OPENOCD_PROVIDER.run(plan, exec); + expect(r.written).toBe(true); + expect(r.writeExitCodes).toEqual([0]); + expect(r.verify?.ok).toBe(true); + const writeCall = exec.calls.find((c) => c.args.some((a) => a.includes("program"))); + expect(writeCall?.args).toContain("program fw.bin verify reset exit"); + const verifyCall = exec.calls.find((c) => c.args.some((a) => a.includes("verify_image"))); + expect(verifyCall).toBeTruthy(); + }); + it("verify 命令格式:openocd -f cfg -c verify_image -c exit", async () => { + const exec = mockExec({ exitCode: 0 }); + const plan = OPENOCD_PROVIDER.plan({ method: "openocd", image: "fw.bin", target: "st.cfg", dryRun: false }); + await OPENOCD_PROVIDER.run(plan, exec); + const vcall = exec.calls.find((c) => c.args.some((a) => a.startsWith("verify_image"))); + expect(vcall?.args).toEqual(["-f", "st.cfg", "-c", "verify_image fw.bin", "-c", "exit"]); + }); + it("dryRun 探活失败 → ok false + written false", async () => { + const exec = mockExec({ exitCode: 1, stderr: "jtag err" }); + const plan = OPENOCD_PROVIDER.plan({ method: "openocd", image: "fw.bin", target: "st.cfg" }); + const r = await OPENOCD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(r.written).toBe(false); + expect(r.dryRun.reason).toContain("openocd probe failed"); + }); + it("dryRun:false + 写失败 → 短路不调 verify", async () => { + const exec = scriptedExec((cmd, args) => { + if (cmd === "openocd" && args.includes("init")) return ok(); // 探活通过 + return fail(1, "write err"); + }); + const plan = OPENOCD_PROVIDER.plan({ method: "openocd", image: "fw.bin", target: "st.cfg", dryRun: false }); + const r = await OPENOCD_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + // 探活(1) + 写(1) = 2, verify 不调 + expect(exec.calls).toHaveLength(2); + }); +}); + +// ============================================================================ +// DEFAULT_*_PROVIDERS —— 不变式(freeze → 篡改抛 TypeError / 覆盖完整性) +// ============================================================================ + +describe("DEFAULT_BOARD_LINK_PROVIDERS — 不变式:freeze + 覆盖完整性", () => { + it("含三 provider,id/linkType 全覆盖", () => { + expect(DEFAULT_BOARD_LINK_PROVIDERS).toHaveLength(3); + const ids = DEFAULT_BOARD_LINK_PROVIDERS.map((p) => p.id); + expect(ids).toEqual(["rdk-x5-ssh", "rdk-s100-serial", "local"]); + const linkTypes = DEFAULT_BOARD_LINK_PROVIDERS.map((p) => p.linkType); + expect(linkTypes).toEqual(["ssh", "serial", "local"]); + }); + it("数组冻结:push 抛 TypeError(freeze→篡改抛 TypeError 不变式)", () => { + expect(() => (DEFAULT_BOARD_LINK_PROVIDERS as unknown as { push: (x: unknown) => void }).push({})).toThrow(TypeError); + }); + it("数组冻结:索引赋值抛 TypeError", () => { + expect(() => ((DEFAULT_BOARD_LINK_PROVIDERS as unknown as Record)[0] = {})).toThrow(TypeError); + }); + it("deepFreeze:篡改 provider.id 抛 TypeError(深冻结不变式)", () => { + expect(() => ((DEFAULT_BOARD_LINK_PROVIDERS[0] as unknown as { id: string }).id = "MUTATED")).toThrow(TypeError); + }); + it("deepFreeze:篡改 provider.linkType 抛 TypeError", () => { + expect(() => ((DEFAULT_BOARD_LINK_PROVIDERS[0] as unknown as { linkType: string }).linkType = "wifi")).toThrow(TypeError); + }); + it("批量注册到 registry 后 resolve 全可用", () => { + const reg = new BoardLinkRegistry(); + DEFAULT_BOARD_LINK_PROVIDERS.forEach((p) => reg.register(p)); + expect(reg.resolve(sshBoard()).id).toBe("rdk-x5-ssh"); + expect(reg.resolve(serialBoard()).id).toBe("rdk-s100-serial"); + expect(reg.resolve(localBoard()).id).toBe("local"); + }); +}); + +describe("DEFAULT_FLASH_PROVIDERS — 不变式:freeze + 覆盖完整性", () => { + it("含四 provider,id 全覆盖 dd/fastboot/dfu/openocd", () => { + expect(DEFAULT_FLASH_PROVIDERS).toHaveLength(4); + expect(DEFAULT_FLASH_PROVIDERS.map((p) => p.id)).toEqual(["dd", "fastboot", "dfu", "openocd"]); + }); + it("数组冻结:push 抛 TypeError", () => { + expect(() => (DEFAULT_FLASH_PROVIDERS as unknown as { push: (x: unknown) => void }).push({})).toThrow(TypeError); + }); + it("数组冻结:索引赋值抛 TypeError", () => { + expect(() => ((DEFAULT_FLASH_PROVIDERS as unknown as Record)[0] = {})).toThrow(TypeError); + }); + it("deepFreeze:篡改 provider.id 抛 TypeError(深冻结不变式)", () => { + expect(() => ((DEFAULT_FLASH_PROVIDERS[0] as unknown as { id: string }).id = "MUTATED")).toThrow(TypeError); + }); + it("批量注册到 registry 后 resolve 全可用", () => { + const reg = new FlashRegistry(); + DEFAULT_FLASH_PROVIDERS.forEach((p) => reg.register(p)); + for (const m of ["dd", "fastboot", "dfu", "openocd"] as FlashMethod[]) { + expect(reg.resolve(m).id).toBe(m); + } + }); +}); + +// ============================================================================ +// 元蜕变/不变式:跨变换保持的性质 +// ============================================================================ + +describe("元蜕变/不变式:跨变换保持的性质", () => { + it("BoardLinkRegistry 与 FlashRegistry disposer 语义对称(单调)", () => { + const bl = new BoardLinkRegistry(); + const fl = new FlashRegistry(); + bl.register(RDK_X5_SSH_PROVIDER); + fl.register(DD_PROVIDER); + expect(bl.list()).toHaveLength(1); + expect(fl.list()).toHaveLength(1); + (bl.list() as unknown[]).push({} as never); + expect(fl.list()).toHaveLength(1); + expect(bl.list()).toHaveLength(1); + }); + + it("fail-closed 单调:未显式 dryRun:false → 永不 written=true(跨四 provider)", async () => { + const exec = mockExec({ exitCode: 0 }); + for (const provider of [DD_PROVIDER, FASTBOOT_PROVIDER, DFU_PROVIDER, OPENOCD_PROVIDER]) { + const plan = provider.plan({ method: provider.id as FlashMethod, image: "i", target: "/dev/x" }); + const r = await provider.run(plan, exec); + expect(r.written).toBe(false); + } + }); + + it("append 两次 = replay 等价:两次 plan 同输入产同命令(元蜕变)", () => { + const opts = { method: "dd" as FlashMethod, image: "img", target: "/dev/mmcblk0" }; + const p1 = DD_PROVIDER.plan(opts); + const p2 = DD_PROVIDER.plan(opts); + expect(p1.commands).toEqual(p2.commands); + expect(p1.offsetBytes).toBe(p2.offsetBytes); + }); + + it("freeze→篡改抛 TypeError:DEFAULT_FLASH_PROVIDERS 内每个 provider 不可改", () => { + for (const p of DEFAULT_FLASH_PROVIDERS) { + expect(() => ((p as unknown as { id: string }).id = "x")).toThrow(TypeError); + } + }); + + it("freeze→篡改抛 TypeError:DEFAULT_BOARD_LINK_PROVIDERS 内每个 provider 不可改", () => { + for (const p of DEFAULT_BOARD_LINK_PROVIDERS) { + expect(() => ((p as unknown as { id: string }).id = "x")).toThrow(TypeError); + } + }); + + it("waterfall 不调 next=短路:写失败后 verify 永不调用(跨 provider)", async () => { + const exec = scriptedExec((cmd, args) => { + if (cmd === "fastboot" && args.join(" ") === "getvar all") return ok(); + return fail(1, "write err"); + }); + const plan = FASTBOOT_PROVIDER.plan({ method: "fastboot", image: "b", target: "s", dryRun: false }); + const r = await FASTBOOT_PROVIDER.run(plan, exec); + expect(r.ok).toBe(false); + expect(exec.calls).toHaveLength(2); // 探活(1) + 写(1), verify 不调 + }); + + it("不变式:list() 返回的快照 mutate 不影响 resolve(隔离)", () => { + const reg = new FlashRegistry(); + reg.register(DD_PROVIDER); + const snap = reg.list(); + (snap as unknown[]).length = 0; // mutate snapshot + expect(reg.list()).toHaveLength(1); + expect(reg.resolve("dd").id).toBe("dd"); + }); +}); + +// ============================================================================ +// 变异测试 —— 7 个 seeded bug 内联副本,每个被某条真实测试杀死 +// ============================================================================ +// +// 每个 mutant 是真实逻辑的"单点变异"内联副本。我们对每个 mutant 做两层验证: +// ① 偏离验证:断言 mutant 输出 ≠ 真实输出(mutant 确实改变了行为) +// ② kill verification:把 mutant 喂给与真实代码完全相同的断言(expect(...).toBe(...)), +// 断言该断言抛错(即 mutant 在真实测试下 FAIL → bug 被杀)。 +// 套件本身保持全绿(mutant 测试断言 mutant 确实偏离/确实 FAIL,而非断言 mutant 对)。 +// 每个 mutant 标注:变异点 + 杀它的真实测试名。 + +// --- M1: parseOffset hex 守卫 >= 0 → > 0(丢掉 0x0,off-by-one)--- +// 杀它的真实测试:parseOffset("0x0") → 0(见 "parseOffset — 等价类/边界值") +function parseOffsetMutantM1(offset: string | undefined): number | null { + if (offset === undefined || offset === "") return 0; + const trimmed = offset.trim(); + if (/^0x[0-9a-fA-F]+$/.test(trimmed)) { + const n = Number(trimmed); + if (Number.isFinite(n) && n > 0) return n; // BUG: >= 0 → > 0 + return null; + } + if (/^\d+$/.test(trimmed)) { + try { + const big = BigInt(trimmed); + if (big > BigInt(Number.MAX_SAFE_INTEGER)) return Number.MAX_SAFE_INTEGER; + return Number(big); + } catch { return null; } + } + return null; +} + +// --- M2: buildSshArgs 端口判断 !== 22 → === 22(-p 逻辑反)--- +// 杀它的真实测试:buildSshArgs 非 22 端口带 -p / 22 端口不带 -p(见 "buildSshArgs — 决策表") +function buildSshArgsMutantM2(board: BoardSpec, command: string, args: string[]): string[] { + const { user, host, port } = parseSshAddress(board.address); + const sshArgs: string[] = []; + if (port === 22) sshArgs.push("-p", String(port)); // BUG: port !== 22 → port === 22 + sshArgs.push(`${user}@${host}`); + sshArgs.push(command); + sshArgs.push(...args); + return sshArgs; +} + +// --- M3: orchestrateRun dryRun 默认 !== false → === false(fail-closed 默认反转)--- +// 杀它的真实测试:orchestrateRun dryRun undefined → written false(见 "orchestrateRun — 状态转换/决策表") +async function orchestrateRunMutantM3( + plan: FlashPlanEx, + exec: ExecFn, + dryRunFn: (p: FlashPlanEx, e: ExecFn) => Promise, + verifyFn: (p: FlashPlanEx, e: ExecFn) => Promise, +): Promise<{ written: boolean; ok: boolean }> { + const dr = await dryRunFn(plan, exec); + if (!dr.ok) return { written: false, ok: false }; + const dryOnly = plan.dryRun === false; // BUG: !== false → === false + if (dryOnly) return { written: false, ok: true }; + const writeExitCodes: number[] = []; + for (const cmdStr of plan.commands) { + const parts = splitCommand(cmdStr); + const res = await exec(parts[0], parts.slice(1)); + writeExitCodes.push(res.exitCode); + if (res.exitCode !== 0) return { written: true, ok: false }; + } + const vr = plan.verify === false ? undefined : await verifyFn(plan, exec); + return { written: true, ok: vr ? vr.ok : true }; +} + +// --- M4: parseLsblk cols.length < 3 → < 2(接受畸形 2 列行)--- +// 杀它的真实测试:parseLsblk 2 列行被跳过(见 "parseLsblk — 等价类/边界值") +function parseLsblkMutantM4(raw: string): LsblkRow[] { + const lines = raw.split("\n"); + const rows: LsblkRow[] = []; + let started = false; + const LSBLK_TREE_CHARS = /[─-╼│├└─\s]+/; + for (const line of lines) { + if (!line.trim()) continue; + if (!started) { + if (/^NAME/i.test(line.trim())) { started = true; continue; } + } + const cleaned = line.replace(LSBLK_TREE_CHARS, " ").trim(); + if (!cleaned) continue; + const cols = cleaned.split(/\s+/); + if (cols.length < 2) continue; // BUG: < 3 → < 2 + const name = cols[0] ?? ""; + const size = Number.parseInt(cols[1] ?? "0", 10); + rows.push({ name, size: Number.isFinite(size) ? size : 0, type: cols[2] ?? "", mountpoint: cols.slice(3).join(" ") ?? "" }); + } + return rows; +} + +// --- M5: isRootDiskTarget 用 startsWith 替代 matchesDeviceName(前缀误匹配)--- +// 杀它的真实测试:isRootDiskTarget 前缀碰撞 sdab 不匹配 sda(见 "isRootDiskTarget — 决策表") +function isRootDiskTargetMutantM5(target: string, rows: LsblkRow[]): boolean { + const base = deviceBasename(target); + for (const row of rows) { + if (row.name.startsWith(base)) { // BUG: matchesDeviceName(base, row.name) → row.name.startsWith(base) + if (row.mountpoint && ROOT_MOUNTPOINTS.has(row.mountpoint)) { + return true; + } + } + } + return false; +} + +// --- M6: splitCommand `if (cur || hadQuote)` → `if (cur)`(丢空引号 token)--- +// 杀它的真实测试:splitCommand('a -c ""') → ["a", "-c", ""](见 "splitCommand — 等价类/边界/对抗") +function splitCommandMutantM6(cmdStr: string): string[] { + const tokens: string[] = []; + let cur = ""; + let inQuote = false; + let hadQuote = false; + for (let i = 0; i < cmdStr.length; i++) { + const ch = cmdStr[i]; + if (ch === '"') { + inQuote = !inQuote; + hadQuote = true; + continue; + } + if (ch === " " && !inQuote) { + if (cur) tokens.push(cur); // BUG: cur || hadQuote → cur (drops empty quoted tokens) + cur = ""; + hadQuote = false; + continue; + } + cur += ch; + } + if (cur) tokens.push(cur); // BUG: cur || hadQuote → cur + return tokens; +} + +// --- M7: deviceBasename regex `/\/dev\/(.+)$/` → `/\/dev\/(.+).$/`(吞末字符)--- +// 杀它的真实测试:deviceBasename("/dev/sda1") → "sda1"(见 "deviceBasename — 等价类/边界") +function deviceBasenameMutantM7(target: string): string { + const m = target.match(/\/dev\/(.+).$/); // BUG: /\/dev\/(.+)$/ → /\/dev\/(.+).$/ (drops last char) + return m ? m[1] : target.replace(/^\/+/, ""); +} + +/** orchestrateRun 的小 shim,仅暴露 written/ok 给 M3 对比(真实实现)。 */ +async function orchestrateRunShim( + plan: FlashPlanEx, + exec: ExecFn, + dryRunFn: (p: FlashPlanEx, e: ExecFn) => Promise, + verifyFn: (p: FlashPlanEx, e: ExecFn) => Promise, +): Promise<{ written: boolean; ok: boolean }> { + const r = await orchestrateRun(plan, exec, dryRunFn, verifyFn); + return { written: r.written, ok: r.ok }; +} + +describe("变异测试 — seeded bug 被【真实测试】杀死(偏离验证)", () => { + // M1: parseOffset hex 守卫 >=0→>0,丢掉 0x0 + it("M1 [parseOffset hex 守卫 >=0→>0]:mutant 把 0x0 返回 null,偏离真实 0", () => { + const real = parseOffset("0x0"); + const mutant = parseOffsetMutantM1("0x0"); + expect(real).toBe(0); + expect(mutant).toBeNull(); + expect(mutant).not.toBe(real); + }); + + // M2: buildSshArgs port !==22→===22 + it("M2 [buildSshArgs port !==22→===22]:mutant 在非 22 端口漏 -p,偏离真实", () => { + const board = sshBoard("x5", "root@192.168.1.100:2222"); + const real = buildSshArgs(board, "ls", ["-la"]); + const mutant = buildSshArgsMutantM2(board, "ls", ["-la"]); + expect(real).toContain("-p"); + expect(mutant).not.toContain("-p"); + expect(mutant).not.toEqual(real); + }); + it("M2 反向:mutant 在 22 端口误加 -p,偏离真实", () => { + const board = sshBoard("x5", "root@192.168.1.100:22"); + const real = buildSshArgs(board, "ls", []); + const mutant = buildSshArgsMutantM2(board, "ls", []); + expect(real).not.toContain("-p"); + expect(mutant).toContain("-p"); + expect(mutant).not.toEqual(real); + }); + + // M3: orchestrateRun dryRun !==false→===false + it("M3 [orchestrateRun dryRun !==false→===false]:mutant 在 dryRun undefined 时 written=true,违反 fail-closed", async () => { + const exec = mockExec({ exitCode: 0 }); + const plan = planEx({ dryRun: undefined }); + const realR = await orchestrateRunShim(plan, exec, dryOk, verifyOk); + const mutantR = await orchestrateRunMutantM3(plan, exec, dryOk, verifyOk); + expect(realR.written).toBe(false); + expect(mutantR.written).toBe(true); + expect(mutantR.written).not.toBe(realR.written); + }); + + // M4: parseLsblk cols<3→<2 + it("M4 [parseLsblk cols<3→<2]:mutant 接受 2 列畸形行,偏离真实空数组", () => { + const raw = "NAME SIZE TYPE MOUNTPOINT\nsda 500G"; + const real = parseLsblk(raw); + const mutant = parseLsblkMutantM4(raw); + expect(real).toEqual([]); + expect(mutant).toHaveLength(1); + expect(mutant).not.toEqual(real); + }); + + // M5: isRootDiskTarget startsWith 替代 matchesDeviceName + it("M5 [isRootDiskTarget startsWith→matchesDeviceName]:mutant 前缀误匹配 sdab→sda,偏离真实 false", () => { + const rows: LsblkRow[] = [ + { name: "sda", size: 1, type: "disk", mountpoint: "" }, + { name: "sdab", size: 1, type: "disk", mountpoint: "/" }, + ]; + const real = isRootDiskTarget("/dev/sda", rows); + const mutant = isRootDiskTargetMutantM5("/dev/sda", rows); + expect(real).toBe(false); + expect(mutant).toBe(true); + expect(mutant).not.toBe(real); + }); + + // M6: splitCommand cur||hadQuote → cur + it("M6 [splitCommand cur||hadQuote→cur]:mutant 丢空引号 token,偏离真实", () => { + const real = splitCommand('a -c ""'); + const mutant = splitCommandMutantM6('a -c ""'); + expect(real).toEqual(["a", "-c", ""]); + expect(mutant).toEqual(["a", "-c"]); // 丢了空串 token + expect(mutant).not.toEqual(real); + }); + + // M7: deviceBasename regex 吞末字符 + it("M7 [deviceBasename regex 吞末字符]:mutant 把 sda1 变 sda,偏离真实", () => { + const real = deviceBasename("/dev/sda1"); + const mutant = deviceBasenameMutantM7("/dev/sda1"); + expect(real).toBe("sda1"); + expect(mutant).toBe("sda"); // 吞了末尾 '1' + expect(mutant).not.toBe(real); + }); +}); + +describe("变异测试 — kill verification(每个 mutant 通过真实断言确认 FAIL)", () => { + // M1 kill: 真实测试 expect(parseOffset("0x0")).toBe(0) 在 mutant 上应 FAIL + it("M1 kill: expect(parseOffset('0x0')).toBe(0) fails on mutant (returns null)", () => { + expect(parseOffset("0x0")).toBe(0); // 真实通过 + expect(() => expect(parseOffsetMutantM1("0x0")).toBe(0)).toThrow(); // mutant FAIL + }); + + // M2 kill: 真实测试 expect(buildSshArgs(board,'ls',['-la'])).toContain('-p') 在 mutant 上应 FAIL + it("M2 kill: expect(buildSshArgs(non-22,'ls')).toContain('-p') fails on mutant", () => { + const board = sshBoard("x5", "root@192.168.1.100:2222"); + expect(buildSshArgs(board, "ls", ["-la"])).toContain("-p"); // 真实通过 + expect(() => expect(buildSshArgsMutantM2(board, "ls", ["-la"])).toContain("-p")).toThrow(); // mutant FAIL + }); + + // M3 kill: 真实测试 expect(orchestrateRun(dryRun:undefined).written).toBe(false) 在 mutant 上应 FAIL + it("M3 kill: expect(orchestrateRun(dryRun:undefined).written).toBe(false) fails on mutant (writes)", async () => { + const exec = mockExec({ exitCode: 0 }); + const plan = planEx({ dryRun: undefined }); + const realR = await orchestrateRunShim(plan, exec, dryOk, verifyOk); + expect(realR.written).toBe(false); // 真实通过 + const mutantR = await orchestrateRunMutantM3(plan, exec, dryOk, verifyOk); + expect(() => expect(mutantR.written).toBe(false)).toThrow(); // mutant FAIL + }); + + // M4 kill: 真实测试 expect(parseLsblk('..sda 500G')).toEqual([]) 在 mutant 上应 FAIL + it("M4 kill: expect(parseLsblk('sda 500G')).toEqual([]) fails on mutant (accepts row)", () => { + const raw = "NAME SIZE TYPE MOUNTPOINT\nsda 500G"; + expect(parseLsblk(raw)).toEqual([]); // 真实通过 + expect(() => expect(parseLsblkMutantM4(raw)).toEqual([])).toThrow(); // mutant FAIL + }); + + // M5 kill: 真实测试 expect(isRootDiskTarget('/dev/sda', sdab-rows)).toBe(false) 在 mutant 上应 FAIL + it("M5 kill: expect(isRootDiskTarget('/dev/sda', sdab-rows)).toBe(false) fails on mutant (prefix match)", () => { + const rows: LsblkRow[] = [ + { name: "sda", size: 1, type: "disk", mountpoint: "" }, + { name: "sdab", size: 1, type: "disk", mountpoint: "/" }, + ]; + expect(isRootDiskTarget("/dev/sda", rows)).toBe(false); // 真实通过 + expect(() => expect(isRootDiskTargetMutantM5("/dev/sda", rows)).toBe(false)).toThrow(); // mutant FAIL + }); + + // M6 kill: 真实测试 expect(splitCommand('a -c ""')).toEqual(["a","-c",""]) 在 mutant 上应 FAIL + it("M6 kill: expect(splitCommand('a -c \"\"')).toEqual([...,'']) fails on mutant (drops empty token)", () => { + expect(splitCommand('a -c ""')).toEqual(["a", "-c", ""]); // 真实通过 + expect(() => expect(splitCommandMutantM6('a -c ""')).toEqual(["a", "-c", ""])).toThrow(); // mutant FAIL + }); + + // M7 kill: 真实测试 expect(deviceBasename('/dev/sda1')).toBe('sda1') 在 mutant 上应 FAIL + it("M7 kill: expect(deviceBasename('/dev/sda1')).toBe('sda1') fails on mutant (drops last char)", () => { + expect(deviceBasename("/dev/sda1")).toBe("sda1"); // 真实通过 + expect(() => expect(deviceBasenameMutantM7("/dev/sda1")).toBe("sda1")).toThrow(); // mutant FAIL + }); +}); + +// ============================================================================ +// 真实代码全绿确认(不变式:所有上方测试断言真实行为,mutant 只断言偏离) +// ============================================================================ +describe("真实代码全绿确认(meta-check)", () => { + it("parseOffset 0x0 真实返回 0(非 null)", () => { + expect(parseOffset("0x0")).toBe(0); + }); + it("buildSshArgs 非 22 端口真实带 -p", () => { + expect(buildSshArgs(sshBoard("x5", "root@h:2222"), "ls", [])).toContain("-p"); + }); + it("orchestrateRun dryRun undefined 真实 written=false", async () => { + const r = await orchestrateRunShim(planEx({ dryRun: undefined }), mockExec({ exitCode: 0 }), dryOk, verifyOk); + expect(r.written).toBe(false); + }); + it("parseLsblk 2 列行真实跳过", () => { + expect(parseLsblk("NAME SIZE TYPE MOUNTPOINT\nsda 500G")).toEqual([]); + }); + it("isRootDiskTarget 前缀碰撞真实 false", () => { + const rows: LsblkRow[] = [ + { name: "sda", size: 1, type: "disk", mountpoint: "" }, + { name: "sdab", size: 1, type: "disk", mountpoint: "/" }, + ]; + expect(isRootDiskTarget("/dev/sda", rows)).toBe(false); + }); + it("splitCommand 空引号 token 真实保留", () => { + expect(splitCommand('a -c ""')).toEqual(["a", "-c", ""]); + }); + it("deviceBasename 真实不吞末字符", () => { + expect(deviceBasename("/dev/sda1")).toBe("sda1"); + }); +}); diff --git a/tests/checkpoint-state.test.ts b/tests/checkpoint-state.test.ts new file mode 100644 index 0000000..007e4a0 --- /dev/null +++ b/tests/checkpoint-state.test.ts @@ -0,0 +1,1157 @@ +/** + * checkpoint-state 完整测试套件 —— T14 plan/goal/todo logged state. + * + * 被测对象:src/core/checkpoint-state.ts 的命名导出 + * - CheckpointRecorder (class:record / current / rebuild / fork) + * - CHECKPOINT_CHANGE_TYPE (事件类型常量 "checkpoint-change") + * - STEP_ORDER (步骤顺序常量,深冻结) + * - INITIAL_CHECKPOINT_STATE (初始态常量,深冻结) + * - CheckpointAppendEntry (append 入参类型) + * + * 纯逻辑模块,零 pi 运行时依赖:mock 注入 append sink,离线可单测。 + * + * 多方法论(每个 describe 块标注方法论名): + * ① 等价类划分(有效/无效/边界类) + * ② 边界值分析(off-by-one、空、单元素、max、min) + * ③ 决策表(组合输入→期望,覆盖全分支) + * ④ 状态转换(状态+迁移+不可达状态+重入) + * ⑤ 变异测试(4 个 seeded bug,每个被 kill-assertion 杀死 + 独立 mutant 文件确认 FAIL) + * ⑥ 对抗/fuzz(畸形/滥用输入:null、undefined、巨大、NaN、循环引用、负 seq) + * ⑦ 元蜕变/不变式(append 两次≡replay;freeze→篡改抛 TypeError;单调;waterfall 短路;fail-closed) + * + * 门: + * `npx vitest run tests/checkpoint-state.test.ts` —— 真实代码必须 all green。 + * 每个 seeded bug 另用独立 mutant 脚本(tests/.mutation-kill/m{1..4}.mjs,node:assert) + * 单独跑确认 FAIL(exit=1 = bug 被杀)。M1/M2/M3/M4 均已验证 exit=1。 + * + * 关键设计:realAdvance 是 advanceState 的【忠实】纯函数副本(含 failed 分支 + * `idx <= curIdx` 守卫与 done 分支 `idx <= curIdx` 守卫),使变异对比在触碰 + * failed/done 守卫的场景下也成立。副本保真自验见 ⑤ "副本保真" 测试。 + */ + +import { describe, it, expect } from "vitest"; +import { + CheckpointRecorder, + CHECKPOINT_CHANGE_TYPE, + STEP_ORDER, + INITIAL_CHECKPOINT_STATE, +} from "../src/core/checkpoint-state.js"; +import type { CheckpointState, CheckpointStep } from "../src/shared/types.js"; + +// ============================================================================ +// 公共夹具 +// ============================================================================ + +type Entry = { type: string; data: unknown }; + +/** 记录型 append sink:捕获下沉参数,可断言。 */ +function recordingSink(): { sink: (entry: Entry) => void; calls: Entry[] } { + const calls: Entry[] = []; + return { sink: (entry) => calls.push(entry), calls }; +} + +/** no-op sink。 */ +function noopSink(): (entry: Entry) => void { + return () => {}; +} + +/** 构造一个可变的初始 CheckpointState(独立拷贝,可自由 push/改)。 */ +function freshState(): CheckpointState { + return { currentStep: "edit", stepPassed: false, history: [] }; +} + +/** 完整 happy-path 序列:edit→compile→flash→verify→check→done 全通过。 */ +const FULL_PASS_SEQ: Array<{ step: CheckpointStep; passed: true; ts: number }> = [ + { step: "edit", passed: true, ts: 1000 }, + { step: "compile", passed: true, ts: 2000 }, + { step: "flash", passed: true, ts: 3000 }, + { step: "verify", passed: true, ts: 4000 }, + { step: "check", passed: true, ts: 5000 }, + { step: "done", passed: true, ts: 6000 }, +]; + +// ============================================================================ +// advanceState 忠实副本 + 变异副本(变异测试用) +// ============================================================================ + +/** + * 真实 advance 纯函数【忠实】副本(与 src/core/checkpoint-state.ts advanceState + * 逐行同形,含 done 分支 `idx <= curIdx` 守卫 + failed 分支 `idx <= curIdx` 守卫)。 + * 用于与带虫副本在同一场景下对比发散。保真自验见 ⑤ "副本保真" 测试。 + */ +function realAdvance(state: CheckpointState, step: CheckpointStep, passed: boolean, timestamp: number): void { + state.history.push({ step, passed, timestamp }); + const idx = STEP_ORDER.indexOf(step); + if (idx < 0) return; + const curIdx = STEP_ORDER.indexOf(state.currentStep); + if (passed) { + if (idx === STEP_ORDER.length - 1) { + if (idx <= curIdx) { + state.currentStep = step; + state.stepPassed = true; + } + } else { + const targetIdx = idx + 1; + if (targetIdx > curIdx) { + state.currentStep = STEP_ORDER[targetIdx] as CheckpointStep; + state.stepPassed = false; + } + } + } else { + if (idx <= curIdx) { + state.currentStep = step; + state.stepPassed = false; + } + } +} + +/** 对 state 序列应用一个 advance 函数,返回最终状态(独立 freshState)。 */ +function applySeq( + advanceFn: (s: CheckpointState, step: CheckpointStep, passed: boolean, ts: number) => void, + ops: Array<{ step: CheckpointStep; passed: boolean; ts: number }>, +): CheckpointState { + const s = freshState(); + for (const o of ops) advanceFn(s, o.step, o.passed, o.ts); + return s; +} + +// ---- 变异 M1:`targetIdx > curIdx` → `targetIdx >= curIdx`(passed 非末分支 off-by-one)---- +// 杀它的场景:全通过到 done(stepPassed=true) → 再 pass check(targetIdx=5===curIdx=5)。 +// 真实:5>5 false → 不动,stepPassed 保持 true。带虫:5>=5 true → stepPassed 重置 false。 +function m1Advance(state: CheckpointState, step: CheckpointStep, passed: boolean, timestamp: number): void { + state.history.push({ step, passed, timestamp }); + const idx = STEP_ORDER.indexOf(step); + if (idx < 0) return; + const curIdx = STEP_ORDER.indexOf(state.currentStep); + if (passed) { + if (idx === STEP_ORDER.length - 1) { + if (idx <= curIdx) { + state.currentStep = step; + state.stepPassed = true; + } + } else { + const targetIdx = idx + 1; + // 🐛 变异:> → >= + if (targetIdx >= curIdx) { + state.currentStep = STEP_ORDER[targetIdx] as CheckpointStep; + state.stepPassed = false; + } + } + } else { + if (idx <= curIdx) { + state.currentStep = step; + state.stepPassed = false; + } + } +} + +// ---- 变异 M2:`idx === STEP_ORDER.length - 1` → `idx === STEP_ORDER.length`(末步检测 off-by-one)---- +// 杀它的场景:全通过到 done。真实:pass done 停 done+stepPassed=true。 +// 带虫:5===6 false → else,targetIdx=6 越界 → currentStep=undefined。 +function m2Advance(state: CheckpointState, step: CheckpointStep, passed: boolean, timestamp: number): void { + state.history.push({ step, passed, timestamp }); + const idx = STEP_ORDER.indexOf(step); + if (idx < 0) return; + const curIdx = STEP_ORDER.indexOf(state.currentStep); + if (passed) { + // 🐛 变异:length - 1 → length + if (idx === STEP_ORDER.length) { + state.currentStep = step; + state.stepPassed = true; + } else { + const targetIdx = idx + 1; + if (targetIdx > curIdx) { + state.currentStep = STEP_ORDER[targetIdx] as CheckpointStep; + state.stepPassed = false; + } + } + } else { + if (idx <= curIdx) { + state.currentStep = step; + state.stepPassed = false; + } + } +} + +// ---- 变异 M3:passed 非末前进 `stepPassed = false` → `stepPassed = true`(错默认值)---- +// 杀它的场景:pass edit → 前进到 compile。真实 stepPassed=false,带虫=true。 +function m3Advance(state: CheckpointState, step: CheckpointStep, passed: boolean, timestamp: number): void { + state.history.push({ step, passed, timestamp }); + const idx = STEP_ORDER.indexOf(step); + if (idx < 0) return; + const curIdx = STEP_ORDER.indexOf(state.currentStep); + if (passed) { + if (idx === STEP_ORDER.length - 1) { + if (idx <= curIdx) { + state.currentStep = step; + state.stepPassed = true; + } + } else { + const targetIdx = idx + 1; + if (targetIdx > curIdx) { + state.currentStep = STEP_ORDER[targetIdx] as CheckpointStep; + // 🐛 变异:false → true + state.stepPassed = true; + } + } + } else { + if (idx <= curIdx) { + state.currentStep = step; + state.stepPassed = false; + } + } +} + +// ---- 变异 M4:failed 分支 `idx <= curIdx` → `idx < curIdx`(漏 = 校验,守卫放宽)---- +// 杀它的场景:全通过到 done(stepPassed=true) → 再 fail done(idx=5===curIdx=5)。 +// 真实:5<=5 true → stepPassed 重置 false(退回 done 重试)。 +// 带虫:5<5 false → 不动,stepPassed 保持 true(fail 不清除完成态=伪造完成)。 +function m4Advance(state: CheckpointState, step: CheckpointStep, passed: boolean, timestamp: number): void { + state.history.push({ step, passed, timestamp }); + const idx = STEP_ORDER.indexOf(step); + if (idx < 0) return; + const curIdx = STEP_ORDER.indexOf(state.currentStep); + if (passed) { + if (idx === STEP_ORDER.length - 1) { + if (idx <= curIdx) { + state.currentStep = step; + state.stepPassed = true; + } + } else { + const targetIdx = idx + 1; + if (targetIdx > curIdx) { + state.currentStep = STEP_ORDER[targetIdx] as CheckpointStep; + state.stepPassed = false; + } + } + } else { + // 🐛 变异:<= → < + if (idx < curIdx) { + state.currentStep = step; + state.stepPassed = false; + } + } +} + +const ALL_MUTANTS: Array<{ name: string; fn: typeof realAdvance }> = [ + { name: "M1", fn: m1Advance }, + { name: "M2", fn: m2Advance }, + { name: "M3", fn: m3Advance }, + { name: "M4", fn: m4Advance }, +]; + +// ============================================================================ +// ⑦ 元蜕变/不变式 —— 常量导出(后续 describe 依赖这些不变式) +// ============================================================================ + +describe("⑦ 元蜕变/不变式 — 常量导出", () => { + it("CHECKPOINT_CHANGE_TYPE === 'checkpoint-change'(与 PbaSessionEventMap 对齐)", () => { + expect(CHECKPOINT_CHANGE_TYPE).toBe("checkpoint-change"); + }); + + it("STEP_ORDER 内容与顺序正确:edit→compile→flash→verify→check→done", () => { + expect(STEP_ORDER).toEqual(["edit", "compile", "flash", "verify", "check", "done"]); + }); + + it("STEP_ORDER 长度=6", () => { + expect(STEP_ORDER.length).toBe(6); + }); + + it("STEP_ORDER 是深冻结(push 抛 TypeError)", () => { + expect(() => (STEP_ORDER as CheckpointStep[]).push("edit" as CheckpointStep)).toThrow(TypeError); + }); + + it("STEP_ORDER 元素不可重写(冻结)", () => { + expect(() => ((STEP_ORDER as unknown as { 0: unknown })[0] = "done")).toThrow(TypeError); + }); + + it("INITIAL_CHECKPOINT_STATE 初始态正确:edit / stepPassed=false / history=[]", () => { + expect(INITIAL_CHECKPOINT_STATE.currentStep).toBe("edit"); + expect(INITIAL_CHECKPOINT_STATE.stepPassed).toBe(false); + expect(INITIAL_CHECKPOINT_STATE.history).toEqual([]); + }); + + it("INITIAL_CHECKPOINT_STATE 顶层冻结(改字段抛 TypeError)", () => { + expect(() => { + (INITIAL_CHECKPOINT_STATE as unknown as { currentStep: unknown }).currentStep = "done"; + }).toThrow(TypeError); + }); + + it("INITIAL_CHECKPOINT_STATE.history 冻结(push 抛 TypeError)", () => { + expect(() => { + (INITIAL_CHECKPOINT_STATE.history as unknown[]).push({ step: "edit", passed: true, timestamp: 1 }); + }).toThrow(TypeError); + }); + + it("INITIAL_CHECKPOINT_STATE 是 CheckpointRecorder 的默认起点", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + expect(rec.current()).toEqual({ + currentStep: "edit", + stepPassed: false, + history: [], + }); + }); +}); + +// ============================================================================ +// ① 等价类划分 —— record 推进语义(有效/无效/边界类) +// ============================================================================ + +describe("① 等价类划分 — record(step, passed, ts)", () => { + it("有效类·正常前进:pass edit → currentStep=compile, stepPassed=false", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 1000); + expect(rec.current().currentStep).toBe("compile"); + expect(rec.current().stepPassed).toBe(false); + }); + + it("有效类·失败当前步:fail compile → currentStep=compile, stepPassed=false(退回重试)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 1000); + rec.record("compile", false, 2000); + expect(rec.current().currentStep).toBe("compile"); + expect(rec.current().stepPassed).toBe(false); + }); + + it("有效类·末步 done 通过:currentStep=done, stepPassed=true(停在 done)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + for (const op of FULL_PASS_SEQ) rec.record(op.step, op.passed, op.ts); + expect(rec.current().currentStep).toBe("done"); + expect(rec.current().stepPassed).toBe(true); + }); + + it("有效类·check 通过推进到 done 但 stepPassed=false(done 尚未通过)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + for (const op of FULL_PASS_SEQ.slice(0, 5)) rec.record(op.step, op.passed, op.ts); + expect(rec.current().currentStep).toBe("done"); + expect(rec.current().stepPassed).toBe(false); + }); + + it("无效类·未知 step('bogus'):仅记 history,currentStep 不动", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("bogus" as CheckpointStep, true, 1000); + expect(rec.current().currentStep).toBe("edit"); + expect(rec.current().stepPassed).toBe(false); + expect(rec.current().history.length).toBe(1); + expect(rec.current().history[0]!.step).toBe("bogus"); + }); + + it("无效类·未知 step 失败:仅记 history,currentStep 不动", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("zzz" as CheckpointStep, false, 1000); + expect(rec.current().currentStep).toBe("edit"); + expect(rec.current().stepPassed).toBe(false); + expect(rec.current().history.length).toBe(1); + }); + + it("有效类·重入补跑已通过步骤(pass edit 再 pass edit):不回退、不重复前进", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 1000); // → compile + rec.record("edit", true, 2000); // targetIdx=1(curIdx) 不>,不推进 + expect(rec.current().currentStep).toBe("compile"); + expect(rec.current().stepPassed).toBe(false); + expect(rec.current().history.length).toBe(2); + }); + + it("有效类·失败已过步骤(退回):flash 失败后 currentStep=flash", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 1000); + rec.record("compile", true, 2000); // → flash + rec.record("flash", false, 3000); // 退回 flash + expect(rec.current().currentStep).toBe("flash"); + expect(rec.current().stepPassed).toBe(false); + }); +}); + +// ============================================================================ +// ② 边界值分析 —— off-by-one / 空 / 单元素 / max / min +// ============================================================================ + +describe("② 边界值分析 — history 与推进边界", () => { + it("空边界:新 recorder current() 是初始态、history 空", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const s = rec.current(); + expect(s.history).toEqual([]); + expect(s.currentStep).toBe("edit"); + expect(s.stepPassed).toBe(false); + }); + + it("单元素边界:一次 record 后 history 恰 1 条", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 1000); + expect(rec.current().history.length).toBe(1); + expect(rec.current().history[0]).toEqual({ step: "edit", passed: true, timestamp: 1000 }); + }); + + it("off-by-one·targetIdx === curIdx 不前进(pass edit 后再 pass edit 不动)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 1000); // curIdx 现 1 (compile) + const before = rec.current(); + rec.record("edit", true, 2000); // targetIdx=1, curIdx=1 → 1>1 false → 不动 + expect(rec.current().currentStep).toBe(before.currentStep); + expect(rec.current().stepPassed).toBe(before.stepPassed); + }); + + it("off-by-one·targetIdx === curIdx+1 恰好前进(边界刚好越过)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 1000); // → compile (curIdx=1) + rec.record("compile", true, 2000); // targetIdx=2 > 1 → → flash + expect(rec.current().currentStep).toBe("flash"); + }); + + it("max 边界:到达 done(末步 idx=STEP_ORDER.length-1)停在 done", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + for (const op of FULL_PASS_SEQ) rec.record(op.step, op.passed, op.ts); + expect(rec.current().currentStep).toBe("done"); + expect(STEP_ORDER.indexOf(rec.current().currentStep)).toBe(STEP_ORDER.length - 1); + }); + + it("min 边界:第一步 edit pass 后 currentStep=STEP_ORDER[1]", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 0); + expect(rec.current().currentStep).toBe(STEP_ORDER[1]); + }); + + it("末步 done 失败:currentStep=done, stepPassed=false(停在末步重试)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + for (const op of FULL_PASS_SEQ) rec.record(op.step, op.passed, op.ts); + rec.record("done", false, 7000); // 已到 done stepPassed=true → fail done 退回重试 + expect(rec.current().currentStep).toBe("done"); + expect(rec.current().stepPassed).toBe(false); + }); + + it("history 边界:fail 与 pass 都各 push 一条(不区分有效性)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 1); + rec.record("edit", false, 2); + rec.record("edit", true, 3); + expect(rec.current().history.length).toBe(3); + expect(rec.current().history.map((h) => h.passed)).toEqual([true, false, true]); + }); +}); + +// ============================================================================ +// ③ 决策表 —— (passed, isTerminal, targetIdx vs curIdx / idx vs curIdx) → 全分支 +// ============================================================================ + +describe("③ 决策表 — advance 全分支组合", () => { + type Row = { + name: string; + ops: Array<{ step: CheckpointStep; passed: boolean }>; + expectStep: CheckpointStep; + expectPassedFlag: boolean; + }; + // 前置:record("edit", true) → compile(curIdx=1, stepPassed=false) + const cases: Row[] = [ + // passed=true, isTerminal=false, targetIdx > curIdx → 前进 + { name: "pass+非末+target>cur → 前进", ops: [{ step: "edit", passed: true }, { step: "compile", passed: true }], expectStep: "flash", expectPassedFlag: false }, + // passed=true, isTerminal=false, targetIdx === curIdx → 不动 + { name: "pass+非末+target===cur → 不动", ops: [{ step: "edit", passed: true }, { step: "edit", passed: true }], expectStep: "compile", expectPassedFlag: false }, + // passed=true, isTerminal=false, targetIdx < curIdx → 不动(不回退) + { name: "pass+非末+target ({ step: o.step, passed: o.passed })), expectStep: "done", expectPassedFlag: true }, + // passed=true, isTerminal=true (done) 但 idx > curIdx(从 check 试图直接 pass done)→ 不设 stepPassed=true + { name: "pass+done(未抵达, idx>cur) → 不伪造完成", ops: [{ step: "edit", passed: true }, { step: "compile", passed: true }, { step: "flash", passed: true }, { step: "verify", passed: true }, { step: "done", passed: true }], expectStep: "check", expectPassedFlag: false }, + // passed=false, idx === curIdx → 停该步(当前步失败) + { name: "fail+idx===cur → 停该步 stepPassed=false", ops: [{ step: "edit", passed: true }, { step: "compile", passed: false }], expectStep: "compile", expectPassedFlag: false }, + // passed=false, idx < curIdx → 退回该步 + { name: "fail+idx curIdx → 不前进(仅记 history) + { name: "fail+idx>cur → 不前进 stepPassed 不动", ops: [{ step: "edit", passed: true }, { step: "compile", passed: true }, { step: "verify", passed: false }], expectStep: "flash", expectPassedFlag: false }, + // passed=false, idx > curIdx (极端:fail done from flash) → 不前进 + { name: "fail+done(远超 cur) → 不前进", ops: [{ step: "edit", passed: true }, { step: "compile", passed: true }, { step: "done", passed: false }], expectStep: "flash", expectPassedFlag: false }, + // passed=false, idx === curIdx at done (fail done after fully done) → stepPassed 重置 false(退回重试) + { name: "fail+done(已抵达) → stepPassed 重置 false", ops: [...FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed })), { step: "done", passed: false }], expectStep: "done", expectPassedFlag: false }, + ]; + + for (const c of cases) { + it(c.name, () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + c.ops.forEach((o, i) => rec.record(o.step, o.passed, (i + 1) * 1000)); + expect(rec.current().currentStep).toBe(c.expectStep); + expect(rec.current().stepPassed).toBe(c.expectPassedFlag); + }); + } +}); + +// ============================================================================ +// ④ 状态转换 —— 全链路 + 重入 + 退回 + 终态 + 不可达 +// ============================================================================ + +describe("④ 状态转换 — 闭环状态机迁移", () => { + it("完整迁移 edit→compile→flash→verify→check→done(每步 currentStep 逐步前进)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + // pass edit→compile, pass compile→flash, pass flash→verify, pass verify→check, + // pass check→done(stepPassed=false), pass done→done(stepPassed=true) + const expectAfter: CheckpointStep[] = ["compile", "flash", "verify", "check", "done", "done"]; + const expectPassed: boolean[] = [false, false, false, false, false, true]; + FULL_PASS_SEQ.forEach((op, i) => { + rec.record(op.step, op.passed, op.ts); + expect(rec.current().currentStep).toBe(expectAfter[i]); + expect(rec.current().stepPassed).toBe(expectPassed[i]); + }); + expect(rec.current().currentStep).toBe("done"); + expect(rec.current().stepPassed).toBe(true); + }); + + it("失败重试可达迁移:compile 失败→退回 compile→重试通过→继续前进", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 1000); + rec.record("compile", false, 2000); // 退回 compile + expect(rec.current().currentStep).toBe("compile"); + rec.record("compile", true, 3000); // 重试通过 → flash + expect(rec.current().currentStep).toBe("flash"); + expect(rec.current().history.length).toBe(3); + }); + + it("终态 done 不可回退:pass done 后再 pass 任意非末步不回退、stepPassed 保持 true", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + for (const op of FULL_PASS_SEQ) rec.record(op.step, op.passed, op.ts); + expect(rec.current().stepPassed).toBe(true); + // 重入 pass check(targetIdx=5===curIdx=5 不>)→ 不动,stepPassed 保持 true + rec.record("check", true, 7000); + expect(rec.current().currentStep).toBe("done"); + expect(rec.current().stepPassed).toBe(true); + }); + + it("重入补跑不丢 history(补跑 edit 在 compile 期间 history 累加)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 1000); + rec.record("edit", true, 2000); // 补跑 + expect(rec.current().history.length).toBe(2); + expect(rec.current().currentStep).toBe("compile"); + }); + + it("状态转换可重复到达终态:到 done 后多次补跑 done 仍保持 done+stepPassed=true", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + for (const op of FULL_PASS_SEQ) rec.record(op.step, op.passed, op.ts); + rec.record("done", true, 7000); + rec.record("done", true, 8000); + expect(rec.current().currentStep).toBe("done"); + expect(rec.current().stepPassed).toBe(true); + expect(rec.current().history.length).toBe(8); + }); + + it("不可达状态:不经 pass done 绝不会 stepPassed=true(仅 pass done 设 true)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + // 到 check 通过 → currentStep=done 但 stepPassed=false(done 未通过) + for (const op of FULL_PASS_SEQ.slice(0, 5)) rec.record(op.step, op.passed, op.ts); + expect(rec.current().currentStep).toBe("done"); + expect(rec.current().stepPassed).toBe(false); + // 补跑任意非 done 不设 stepPassed=true + rec.record("edit", true, 6000); + rec.record("check", true, 7000); + expect(rec.current().stepPassed).toBe(false); + }); + + it("不可达状态:从 check 直接 pass done 不伪造完成(idx>curIdx 守卫)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + // 推到 check (currentStep=check, curIdx=4) + rec.record("edit", true, 1); + rec.record("compile", true, 2); + rec.record("flash", true, 3); + rec.record("verify", true, 4); // → check + expect(rec.current().currentStep).toBe("check"); + // 直接 pass done:idx=5 > curIdx=4 → done 守卫 idx<=curIdx 为 false → 不设 stepPassed=true + rec.record("done", true, 5); + expect(rec.current().currentStep).toBe("check"); + expect(rec.current().stepPassed).toBe(false); + }); +}); + +// ============================================================================ +// fork 专项 +// ============================================================================ + +describe("fork — 子任务独立 + 共享 sink", () => { + it("fork 后子 == 父当前状态(深拷贝),各自 record 互不影响", () => { + const { sink } = recordingSink(); + const parent = new CheckpointRecorder({ append: sink }); + parent.record("edit", true, 1000); + parent.record("compile", true, 2000); + + const child = parent.fork(); + expect(child.current()).toEqual(parent.current()); + + child.record("verify", true, 3000); + expect(child.current().currentStep).toBe("check"); + expect(parent.current().currentStep).toBe("flash"); + + parent.record("flash", true, 4000); + expect(parent.current().currentStep).toBe("verify"); + expect(child.current().currentStep).toBe("check"); + }); + + it("fork 共享父 append sink(子 record 写进同一 session)", () => { + const { sink, calls } = recordingSink(); + const parent = new CheckpointRecorder({ append: sink }); + parent.record("edit", true, 1000); + const child = parent.fork(); + child.record("compile", true, 2000); + expect(calls.length).toBe(2); + expect(calls[1]!.type).toBe(CHECKPOINT_CHANGE_TYPE); + expect((calls[1]!.data as CheckpointState).currentStep).toBe("flash"); + }); + + it("fork 从初始态 fork:子也是初始态", () => { + const { sink } = recordingSink(); + const parent = new CheckpointRecorder({ append: sink }); + const child = parent.fork(); + expect(child.current()).toEqual({ + currentStep: "edit", + stepPassed: false, + history: [], + }); + }); + + it("fork 链:fork 的 fork 仍共享同一 sink 且独立", () => { + const { sink, calls } = recordingSink(); + const parent = new CheckpointRecorder({ append: sink }); + parent.record("edit", true, 1000); + const child = parent.fork(); + const grandchild = child.fork(); + grandchild.record("compile", true, 2000); + expect(calls.length).toBe(2); + expect((calls[1]!.data as CheckpointState).currentStep).toBe("flash"); + expect(parent.current().currentStep).toBe("compile"); + expect(child.current().currentStep).toBe("compile"); + }); + + it("fork 后父子交替 record 互不串扰(同步模拟并发重入)", () => { + const { sink } = recordingSink(); + const parent = new CheckpointRecorder({ append: sink }); + parent.record("edit", true, 1000); // parent history=1, currentStep=compile + const child = parent.fork(); // child 拿到 history=1(edit) 拷贝 + child.record("compile", true, 1100); // child: compile→flash, history=2 + parent.record("compile", true, 1200); // parent: compile→flash, history=2 + child.record("flash", true, 1300); // child: flash→verify, history=3 + parent.record("flash", true, 1400); // parent: flash→verify, history=3 + expect(child.current().currentStep).toBe("verify"); + expect(parent.current().currentStep).toBe("verify"); + expect(parent.current().history.length).toBe(3); + expect(child.current().history.length).toBe(3); + }); +}); + +// ============================================================================ +// rebuild 专项 +// ============================================================================ + +describe("rebuild — 状态重建", () => { + it("空 entries → 回初始态", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([]); + expect(state).toEqual({ currentStep: "edit", stepPassed: false, history: [] }); + }); + + it("无 checkpoint-change 条目(其他 type)→ 回初始态", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: "user-message", data: { content: "hi" } }, + { type: "tool-call", data: { name: "bash", args: {} } }, + ]); + expect(state.currentStep).toBe("edit"); + expect(state.history.length).toBe(0); + }); + + it("多条 checkpoint-change 取最后一条全量快照", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const entries = [ + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "compile", stepPassed: false, history: [{ step: "edit", passed: true, timestamp: 1 }] } }, + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "done", stepPassed: true, history: [{ step: "done", passed: true, timestamp: 9 }] } }, + ]; + const state = rec.rebuild(entries); + expect(state.currentStep).toBe("done"); + expect(state.stepPassed).toBe(true); + expect(state.history.length).toBe(1); + }); + + it("rebuild 后 record 在重建基础上继续推进", () => { + const { sink, calls } = recordingSink(); + const src = new CheckpointRecorder({ append: sink }); + src.record("edit", true, 1000); + src.record("compile", true, 2000); // → flash + const resumed = new CheckpointRecorder({ append: noopSink() }); + resumed.rebuild(calls); + expect(resumed.current().currentStep).toBe("flash"); + resumed.record("flash", true, 3000); // → verify + expect(resumed.current().currentStep).toBe("verify"); + }); + + it("rebuild 返回独立拷贝(篡改不影响内部)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const entries = [{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "verify", stepPassed: false, history: [] } }]; + const state = rec.rebuild(entries); + state.currentStep = "edit"; + state.history.push({ step: "x" as unknown as CheckpointStep, passed: true, timestamp: 1 }); + expect(rec.current().currentStep).toBe("verify"); + expect(rec.current().history.length).toBe(0); + }); + + it("坏 checkpoint-change data 后跟好 data:好 data 胜出(每条独立校验)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash" } }, // 坏 + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "check", stepPassed: false, history: [{ step: "verify", passed: true, timestamp: 5 }] } }, // 好 + ]); + expect(state.currentStep).toBe("check"); + expect(state.history.length).toBe(1); + }); + + it("好 data 后跟坏 data:好 data 保持(坏 data 不覆盖)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "check", stepPassed: false, history: [] } }, // 好 + { type: CHECKPOINT_CHANGE_TYPE, data: null }, // 坏 + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash" } }, // 坏 + ]); + expect(state.currentStep).toBe("check"); + }); + + it("rebuild 重建的 history 完整回填(多步快照)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "verify", stepPassed: false, history: [ + { step: "edit", passed: true, timestamp: 1 }, + { step: "compile", passed: true, timestamp: 2 }, + { step: "flash", passed: true, timestamp: 3 }, + ] } }, + ]); + expect(state.history.length).toBe(3); + expect(state.history[2]).toEqual({ step: "flash", passed: true, timestamp: 3 }); + }); + + it("rebuild 不修改传入 entries(只读契约)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const entries: Entry[] = [ + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [] } }, + ]; + const snapshot = JSON.stringify(entries); + rec.rebuild(entries); + expect(JSON.stringify(entries)).toBe(snapshot); + }); +}); + +// ============================================================================ +// ⑥ 对抗/fuzz —— 畸形/滥用输入 +// ============================================================================ + +describe("⑥ 对抗/fuzz — 畸形 entries 与输入", () => { + it("rebuild 容忍数组内 null/undefined 条目(静默跳过)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + null as unknown as Entry, + undefined as unknown as Entry, + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: "edit", passed: true, timestamp: 1 }] } }, + ]); + expect(state.currentStep).toBe("flash"); + }); + + it("rebuild 容忍 entry.type 非 string(如 number/object)→ 跳过", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: 123, data: {} }, + { type: { x: 1 }, data: {} }, + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "verify", stepPassed: false, history: [] } }, + ] as unknown as Entry[]); + expect(state.currentStep).toBe("verify"); + }); + + it("rebuild 容忍 entry.data 含循环引用的 history 条目(仅取合法字段,多余字段丢弃)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const circular: unknown = { step: "edit", passed: true, timestamp: 1 }; + (circular as Record).self = circular; + const data = { currentStep: "compile", stepPassed: false, history: [circular] }; + const state = rec.rebuild([{ type: CHECKPOINT_CHANGE_TYPE, data }]); + expect(state.currentStep).toBe("compile"); + expect(state.history[0]).toEqual({ step: "edit", passed: true, timestamp: 1 }); + }); + + it("rebuild 拒绝 history 非数组的 data(缺 Array)→ 回初始态", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: "not-array" } }, + ]); + expect(state.currentStep).toBe("edit"); + expect(state.history.length).toBe(0); + }); + + it("rebuild 拒绝 history 条目字段类型错(passed 非 boolean)→ 回初始态", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: "edit", passed: "yes", timestamp: 1 }] } }, + ]); + expect(state.currentStep).toBe("edit"); + }); + + it("rebuild 拒绝 history 条目缺 timestamp → 回初始态", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: "edit", passed: true }] } }, + ]); + expect(state.currentStep).toBe("edit"); + }); + + it("rebuild 拒绝 history 条目 step 非 string → 回初始态", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: 42, passed: true, timestamp: 1 }] } }, + ]); + expect(state.currentStep).toBe("edit"); + }); + + it("rebuild 拒绝 data 顶层 stepPassed 非 boolean → 回初始态", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: "yes", history: [] } }, + ]); + expect(state.currentStep).toBe("edit"); + }); + + it("rebuild 接受 NaN/Infinity timestamp(typeof number 通过校验,宽松容差)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: "edit", passed: true, timestamp: NaN }] } }, + ]); + expect(state.currentStep).toBe("flash"); + expect(Number.isNaN(state.history[0]!.timestamp)).toBe(true); + }); + + it("rebuild 拒绝越界 currentStep(非 STEP_ORDER 合法步骤)→ 回初始态(fail-closed)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "bogus", stepPassed: false, history: [] } }, + ]); + // isCheckpointState 校验 currentStep 须在 STEP_ORDER 内,坏快照 → 回初始态 + expect(state.currentStep).toBe("edit"); + expect(state.stepPassed).toBe(false); + expect(state.history).toEqual([]); + }); + + it("rebuild 拒绝越界 currentStep 后不伪造完成态(防 forward-jump 绕过推进门)", () => { + // 回归 finding:坏快照 currentStep='bogus' 不得被接受为内部态。 + // 旧实现 curIdx=-1,使后续 record 的 targetIdx>-1 恒成立,可从被篡改日志 + // 向前跳过 edit→compile→flash→verify→check→done 正常推进门伪造完成。 + // 修复后坏快照被拒 → 内部回初始态(currentStep=edit),不再携带越界串。 + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "bogus", stepPassed: false, history: [] } }]); + expect(state.currentStep).toBe("edit"); + expect(state.stepPassed).toBe(false); + // 内部态既非越界 'bogus' 亦非终态 'done':未从坏快照继承任何伪造进度 + expect(STEP_ORDER.includes(state.currentStep)).toBe(true); + expect(state.currentStep).not.toBe("bogus"); + expect(state.currentStep).not.toBe("done"); + }); + + it("rebuild 越界 currentStep 快照被当作坏条跳过,后续合法快照胜出(与坏 data 一致处理)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "bogus", stepPassed: false, history: [] } }, // 坏(越界 currentStep) + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: "edit", passed: true, timestamp: 1 }] } }, // 好 + ]); + expect(state.currentStep).toBe("flash"); + expect(state.history.length).toBe(1); + }); + + it("record 接受负/零 timestamp(注入式确定性,不做值校验)", () => { + const { sink, calls } = recordingSink(); + const rec = new CheckpointRecorder({ append: sink }); + rec.record("edit", true, -1); + rec.record("edit", true, 0); + expect(calls[0]!.data as CheckpointState).toMatchObject({ currentStep: "compile" }); + expect((calls[0]!.data as CheckpointState).history[0]!.timestamp).toBe(-1); + expect((calls[1]!.data as CheckpointState).history[1]!.timestamp).toBe(0); + }); + + it("巨大 history(1000 条)不爆栈、rebuild 等价", () => { + const { sink, calls } = recordingSink(); + const rec = new CheckpointRecorder({ append: sink }); + for (let i = 0; i < 1000; i++) rec.record("edit", true, i); + expect(rec.current().history.length).toBe(1000); + const resumed = new CheckpointRecorder({ append: noopSink() }); + const rebuilt = resumed.rebuild(calls); + expect(rebuilt.history.length).toBe(1000); + expect(rebuilt.currentStep).toBe("compile"); + }); + + it("rebuild 非数组入参(null/undefined/number/object/string)静默回初始态不抛", () => { + const badInputs: unknown[] = [null, undefined, 42, "nope", { a: 1 }, true]; + for (const bad of badInputs) { + const rec = new CheckpointRecorder({ append: noopSink() }); + expect(() => rec.rebuild(bad as unknown as Entry[])).not.toThrow(); + const state = rec.rebuild(bad as unknown as Entry[]); + expect(state.currentStep).toBe("edit"); + expect(state.history.length).toBe(0); + } + }); + + it("rebuild 空数组对象 entry(无 type 字段)静默跳过", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([{} as Entry, { data: {} } as Entry]); + expect(state.currentStep).toBe("edit"); + }); + + it("rebuild 期间 append sink 不被调用(rebuild 是只读重建)", () => { + const { sink, calls } = recordingSink(); + const rec = new CheckpointRecorder({ append: sink }); + rec.rebuild([{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "done", stepPassed: true, history: [] } }]); + expect(calls.length).toBe(0); + }); + + it("record 写出的事件 type 恒为 CHECKPOINT_CHANGE_TYPE(无论 step/passed)", () => { + const { sink, calls } = recordingSink(); + const rec = new CheckpointRecorder({ append: sink }); + rec.record("edit", true, 1); + rec.record("compile", false, 2); + rec.record("bogus" as CheckpointStep, true, 3); + expect(calls.every((c) => c.type === CHECKPOINT_CHANGE_TYPE)).toBe(true); + }); +}); + +// ============================================================================ +// ⑦ 元蜕变/不变式 —— fail-closed / 深拷贝 / 单调 / waterfall 短路 +// ============================================================================ + +describe("⑦ 元蜕变/不变式 — fail-closed 与深拷贝", () => { + it("current() 返回独立深拷贝:篡改返回值不影响内部状态", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 1000); + const snap = rec.current(); + snap.currentStep = "done"; + snap.stepPassed = true; + snap.history.push({ step: "done", passed: true, timestamp: 999 }); + expect(rec.current().currentStep).toBe("compile"); + expect(rec.current().stepPassed).toBe(false); + expect(rec.current().history.length).toBe(1); + }); + + it("record 写出的 snapshot 是独立拷贝:篡改下沉的 data 不影响后续 current()", () => { + const { sink, calls } = recordingSink(); + const rec = new CheckpointRecorder({ append: sink }); + rec.record("edit", true, 1000); + const written = calls[0]!.data as CheckpointState; + written.history.push({ step: "bogus" as unknown as CheckpointStep, passed: true, timestamp: 0 }); + written.currentStep = "done"; + expect(rec.current().currentStep).toBe("compile"); + expect(rec.current().history.length).toBe(1); + }); + + it("两次 current() 返回互不共享(深拷贝独立性)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 1000); + const a = rec.current(); + const b = rec.current(); + a.history.push({ step: "x" as unknown as CheckpointStep, passed: true, timestamp: 0 }); + expect(b.history.length).toBe(1); + }); + + it("单调不变式:pass 任意已过步骤不会回退 currentStep", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + for (const op of FULL_PASS_SEQ) rec.record(op.step, op.passed, op.ts); + const before = rec.current().currentStep; // done + rec.record("edit", true, 8000); + rec.record("compile", true, 8100); + rec.record("flash", true, 8200); + rec.record("verify", true, 8300); + rec.record("check", true, 8400); + expect(rec.current().currentStep).toBe(before); + expect(rec.current().stepPassed).toBe(true); + }); + + it("waterfall 短路不变式:failed record 不前进到 next 步(停在失败步)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + rec.record("edit", true, 1000); // → compile + rec.record("compile", false, 2000); // 失败 → 停 compile,不进 flash + expect(rec.current().currentStep).toBe("compile"); + expect(rec.current().currentStep).not.toBe("flash"); + }); + + it("fail-closed unusable=拒:rebuild 全坏条 → 回初始态(不采用任何坏快照)", () => { + const rec = new CheckpointRecorder({ append: noopSink() }); + const state = rec.rebuild([ + { type: CHECKPOINT_CHANGE_TYPE, data: null }, + { type: CHECKPOINT_CHANGE_TYPE, data: "string" }, + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash" } }, + { type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: "edit", passed: "true", timestamp: 1 }] } }, + ]); + expect(state.currentStep).toBe(INITIAL_CHECKPOINT_STATE.currentStep); + expect(state.stepPassed).toBe(false); + expect(state.history).toEqual([]); + }); + + it("元蜕变·append 两次 ≡ 从 log replay 重建(rebuild 等价不变式)", () => { + const { sink, calls } = recordingSink(); + const rec = new CheckpointRecorder({ append: sink }); + rec.record("edit", true, 1000); + rec.record("compile", false, 2000); + rec.record("compile", true, 3000); + const original = rec.current(); + + const replayed = new CheckpointRecorder({ append: noopSink() }); + const rebuiltState = replayed.rebuild(calls); + expect(rebuiltState).toEqual(original); + }); + + it("元蜕变·fork 后子状态 == 父状态(拷贝等价),再各自演进仍保持各自一致", () => { + const { sink } = recordingSink(); + const parent = new CheckpointRecorder({ append: sink }); + for (const op of FULL_PASS_SEQ.slice(0, 3)) parent.record(op.step, op.passed, op.ts); + const child = parent.fork(); + expect(child.current()).toEqual(parent.current()); + child.record("verify", true, 4000); + parent.record("verify", false, 4100); + expect(child.current().currentStep).not.toBe(parent.current().currentStep); + expect(child.current().currentStep).toBe("check"); + expect(parent.current().currentStep).toBe("verify"); + }); + + it("freeze→篡改抛 TypeError:INITIAL_CHECKPOINT_STATE 顶层冻结", () => { + expect(() => { + (INITIAL_CHECKPOINT_STATE as unknown as { stepPassed: unknown }).stepPassed = true; + }).toThrow(TypeError); + }); + + it("元蜕变·record 后 current() ≡ sink 中最后一条快照(写出即当前)", () => { + const { sink, calls } = recordingSink(); + const rec = new CheckpointRecorder({ append: sink }); + rec.record("edit", true, 1); + rec.record("compile", true, 2); + expect(rec.current()).toEqual(calls[calls.length - 1]!.data as CheckpointState); + }); +}); + +// ============================================================================ +// ⑤ 变异测试 —— 4 个 seeded bug,每个被 kill-assertion 杀死 +// ============================================================================ + +/** + * 变异测试策略: + * 对每个 seeded bug,内联一份带 bug 的 advance 逻辑副本(与源 advanceState 同形, + * 仅一处变异,且【含 done/failed 分支守卫】保真)。对同一场景,分别用【真实 advance 副本】 + * 与【带虫副本】推进,断言: + * (a) 真实副本结果 == 正确期望(real code passes → gate 1 green); + * (b) 带虫副本结果 != 正确期望,且对带虫结果断言正确值会 throw(kill-assertion: + * 若该 bug 植入真实代码,此断言失败 = bug 被杀)。 + * + * 此外,tests/.mutation-kill/ 下每个 mutant 有独立 .mjs 文件(node:assert), + * 单独跑 `node tests/.mutation-kill/mN.mjs` 确认 FAIL(exit=1 = bug 被杀)。 + * + * 这使得套件对真实(未植入)代码全绿,同时自验每个变异被某条断言杀死。 + */ +describe("⑤ 变异测试 — 自验每个 seeded bug 被杀死", () => { + it("副本保真·真实 advance 副本与 CheckpointRecorder 行为一致——全 passed 序列", () => { + const ops = FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed, ts: o.ts })); + const copyState = applySeq(realAdvance, ops); + const rec = new CheckpointRecorder({ append: noopSink() }); + for (const o of ops) rec.record(o.step, o.passed, o.ts); + expect(copyState).toEqual(rec.current()); + }); + + it("副本保真·含 failed + done 守卫序列(failed/done 分支保真)", () => { + // 此场景触碰 failed 分支的 idx<=curIdx 守卫与 done 分支守卫—— + // 不忠实副本(漏守卫)会在此发散 + const ops: Array<{ step: CheckpointStep; passed: boolean; ts: number }> = [ + { step: "edit", passed: true, ts: 1000 }, + { step: "compile", passed: true, ts: 2000 }, // → flash + { step: "flash", passed: false, ts: 3000 }, // 退回 flash (idx=cur=2) + { step: "verify", passed: false, ts: 4000 }, // idx=3>cur=2 → 不动 + { step: "done", passed: false, ts: 5000 }, // idx=5>cur=2 → 不动 + { step: "check", passed: true, ts: 6000 }, // idx=4>cur=2 → 不动(非末 targetIdx=5>2 前进到 done?) + ]; + const copyState = applySeq(realAdvance, ops); + const rec = new CheckpointRecorder({ append: noopSink() }); + for (const o of ops) rec.record(o.step, o.passed, o.ts); + expect(copyState).toEqual(rec.current()); + }); + + it("M1 killed: `> → >=` — done 后补跑 check 应保持 stepPassed=true,带虫副本变 false", () => { + // 场景:全通过到 done(stepPassed=true) → 再 pass check(targetIdx=5===curIdx=5) + const ops: Array<{ step: CheckpointStep; passed: boolean; ts: number }> = [ + ...FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts })), + { step: "check" as CheckpointStep, passed: true, ts: 7000 }, + ]; + const realResult = applySeq(realAdvance, ops); + const bugResult = applySeq(m1Advance, ops); + // (a) 真实正确 + expect(realResult.stepPassed).toBe(true); + expect(realResult.currentStep).toBe("done"); + // (b) 带虫发散:stepPassed 变 false → kill-assertion 对带虫断言 true 会 throw + expect(bugResult.stepPassed).toBe(false); + expect(() => expect(bugResult.stepPassed).toBe(true)).toThrow(); + }); + + it("M2 killed: `length-1 → length` — pass done 应 currentStep=done+stepPassed=true,带虫副本 currentStep=undefined", () => { + const ops = FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts })); + const realResult = applySeq(realAdvance, ops); + const bugResult = applySeq(m2Advance, ops); + // (a) 真实正确 + expect(realResult.currentStep).toBe("done"); + expect(realResult.stepPassed).toBe(true); + // (b) 带虫发散:currentStep=undefined → kill-assertion 断言 "done" 会 throw + expect(bugResult.currentStep).toBeUndefined(); + expect(() => expect(bugResult.currentStep).toBe("done")).toThrow(); + }); + + it("M3 killed: `stepPassed=false → true` — 正常前进后 stepPassed 应 false,带虫副本变 true", () => { + const ops: Array<{ step: CheckpointStep; passed: boolean; ts: number }> = [ + { step: "edit", passed: true, ts: 1000 }, + ]; + const realResult = applySeq(realAdvance, ops); + const bugResult = applySeq(m3Advance, ops); + // (a) 真实正确 + expect(realResult.stepPassed).toBe(false); + expect(realResult.currentStep).toBe("compile"); + // (b) 带虫发散:stepPassed=true → kill-assertion 断言 false 会 throw + expect(bugResult.stepPassed).toBe(true); + expect(() => expect(bugResult.stepPassed).toBe(false)).toThrow(); + }); + + it("M4 killed: failed `<= → <` — fail done 应 stepPassed=false,带虫副本保持 true(伪造完成)", () => { + // 场景:全通过到 done(stepPassed=true) → 再 fail done(idx=5===curIdx=5) + // 真实:5<=5 true → stepPassed 重置 false(退回 done 重试) + // 带虫:5<5 false → 不动,stepPassed 保持 true(fail 不清除完成态=伪造) + const ops: Array<{ step: CheckpointStep; passed: boolean; ts: number }> = [ + ...FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts })), + { step: "done" as CheckpointStep, passed: false, ts: 7000 }, + ]; + const realResult = applySeq(realAdvance, ops); + const bugResult = applySeq(m4Advance, ops); + // (a) 真实正确 + expect(realResult.stepPassed).toBe(false); + expect(realResult.currentStep).toBe("done"); + // (b) 带虫发散:stepPassed 保持 true → kill-assertion 断言 false 会 throw + expect(bugResult.stepPassed).toBe(true); + expect(() => expect(bugResult.stepPassed).toBe(false)).toThrow(); + }); + + it("变异汇总:4 个 bug 在各自 kill 场景均与真实副本发散(均被杀死)", () => { + // 汇总不变式:每个带虫副本在其 kill 场景下输出 != 真实副本输出 + const fullOps = FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts })); + const realFull = applySeq(realAdvance, fullOps); + expect(realFull.currentStep).toBe("done"); + // 各 kill 场景断言 + expect(applySeq(m1Advance, [...fullOps, { step: "check", passed: true, ts: 7 }]).stepPassed).toBe(false); + expect(applySeq(m2Advance, fullOps).currentStep).toBeUndefined(); + expect(applySeq(m3Advance, [{ step: "edit", passed: true, ts: 1 }]).stepPassed).toBe(true); + expect(applySeq(m4Advance, [...fullOps, { step: "done", passed: false, ts: 7 }]).stepPassed).toBe(true); + // 真实副本在 M4 kill 场景应为 false(对照) + expect(applySeq(realAdvance, [...fullOps, { step: "done", passed: false, ts: 7 }]).stepPassed).toBe(false); + }); + + it("每个 mutant 至少在一条 kill 场景与 realAdvance 发散(无等价/存活 mutant)", () => { + // 对每个 mutant,至少存在一组 ops 使其输出 != realAdvance 输出 + const killScenarios: Record> = { + M1: [...FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts })), { step: "check", passed: true, ts: 7 }], + M2: FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts })), + M3: [{ step: "edit", passed: true, ts: 1 }], + M4: [...FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts })), { step: "done", passed: false, ts: 7 }], + }; + for (const { name, fn } of ALL_MUTANTS) { + const ops = killScenarios[name]!; + const realOut = JSON.stringify(applySeq(realAdvance, ops)); + const bugOut = JSON.stringify(applySeq(fn, ops)); + expect(bugOut).not.toBe(realOut); + } + }); +}); diff --git a/tests/compaction.test.ts b/tests/compaction.test.ts new file mode 100644 index 0000000..0f740b2 --- /dev/null +++ b/tests/compaction.test.ts @@ -0,0 +1,1328 @@ +/** + * compaction 模块完整测试套件(T09)—— 多方法论、测试前置。 + * + * 被测对象(命名导出,按契约直 import,无 pi 运行时无硬件无网络): + * - src/compaction/token-meter.ts estimateTokens / measureContext + * - src/compaction/tool-result-pruner.ts pruneToolResult / PruneOptions / PruneResult + * - src/compaction/summarizer.ts buildCompactionSummary / CompactionSummary + * - src/compaction/spill.ts SpillStore / SpillLocator + * + * 每个 describe 块标注方法论名(等价类划分 / 边界值分析 / 决策表 / 状态转换 / + * 变异测试 / 对抗-fuzz / 元蜕变-不变式)。 + * + * 变异测试:6 个 seeded bug(B1-B6)以"带 bug 逻辑副本"内联于本文件。每个 bug 配一条 + * kill-test,用 `expect(() => expect(bugFn(x)).toBe(correct)).toThrow()` 模式直接证明 + * 「若真实代码被此 bug 污染,正确性断言会 FAIL」= bug 被杀。文档化见各 bug 注释。 + * 门 #1:真实(未植入 bug)代码全过;门 #2:每个 bug 副本单独被证明偏离正确。 + */ + +import { describe, it, expect } from "vitest"; +import { estimateTokens, measureContext } from "../src/compaction/token-meter.js"; +import { + pruneToolResult, + type PruneOptions, + type PruneResult, +} from "../src/compaction/tool-result-pruner.js"; +import { buildCompactionSummary } from "../src/compaction/summarizer.js"; +import { SpillStore, type SpillLocator } from "../src/compaction/spill.js"; + +// ============================================================================ +// 变异测试基础设施:带 bug 逻辑副本 +// ---------------------------------------------------------------------------- +// 每个 seeded bug 是真实算法的忠实副本,植入一个单点缺陷。kill-test 同时断言: +// (a) 真实代码产出正确值; +// (b) bug 副本产出【偏离正确】的值(bugFn(x) !== correct); +// (c) 若把正确性断言套到 bug 副本上会抛(expect(bugFn(x)).toBe(correct) → throw)。 +// (c) 即「植入后该测试 FAIL」的形式化证明,无需改源码。 +// ============================================================================ + +/** + * B1 — token-meter estimateTokens 植入 bug:nonCjk 用 Math.floor 而非 Math.ceil。 + * 真实代码 token-meter.ts:66 `Math.ceil(nonCjk / 4)`,变异为 `Math.floor`。 + * 杀它:「边界值·5 char ASCII 跨档」真实 ⌈5/4⌉=2,bug floor=1。 + */ +function estimateTokensB1(text: string): number { + if (text.length === 0) return 0; + const cjkRe = /[一-鿿㐀-䶿豈-﫿]/g; + let cjk = 0; + for (const _ of text.matchAll(cjkRe)) cjk++; + const nonCjk = text.length - cjk; + const nonCjkTokens = Math.floor(nonCjk / 4); // BUG: floor 而非 ceil + return cjk + nonCjkTokens; +} + +/** + * B2 — pruner general 植入 bug:截断 off-by-one,slice(0, max)→slice(0, max+1)。 + * 真实代码 tool-result-pruner.ts:185 `kept = lines.slice(0, max)`,变异多保留 1 行。 + * 杀它:「决策表·general maxLines 截断」真实 dropped=3,bug dropped=2。 + */ +function pruneGeneralB2(content: string, maxLines: number): PruneResult { + if (content.length === 0) return { pruned: "", dropped: 0 }; + const lines = content.split("\n"); + const max = Math.max(0, maxLines); + const kept = lines.slice(0, max + 1); // BUG: +1 off-by-one + return { pruned: kept.join("\n"), dropped: lines.length - kept.length }; +} + +/** + * B3 — pruner i2cdump 植入 bug:漏「最后非空 dump 行」补入。 + * 真实代码 tool-result-pruner.ts:199-208 的 tail 补入逻辑被删,非地址末行丢失。 + * 杀它:「边界·i2cdump 末行非地址」真实 pruned 含 tail,bug 不含。 + */ +function pruneI2cB3(content: string): PruneResult { + if (content.length === 0) + return { pruned: "", dropped: 0, preservedAddrs: [] }; + const lines = content.split("\n"); + const I2C_ADDR_LINE = /^(?:0x[0-9a-fA-F]+|[0-9a-fA-F]{1,4}):/; + const I2C_ADDR_LABEL = /^(0x[0-9a-fA-F]+|[0-9a-fA-F]{1,4}):/; + const kept: string[] = []; + for (const ln of lines) if (I2C_ADDR_LINE.test(ln)) kept.push(ln); + const addrs: string[] = []; + for (const ln of kept) { + const m = I2C_ADDR_LABEL.exec(ln); + if (m && m[1] && !addrs.includes(m[1])) addrs.push(m[1]); + } + // BUG: 删除 tail 补入(最后非空行若非地址行应保留,这里漏了) + const preserved = kept; + return { + pruned: preserved.join("\n"), + dropped: lines.length - preserved.length, + preservedAddrs: addrs, + }; +} + +/** + * B4 — summarizer fitDigestsToBudget 植入 bug:超预算丢最新而非最旧(.pop 替换 .shift)。 + * 真实代码 summarizer.ts:99-101 `kept.shift()`,变异为 `kept.pop()`。 + * 杀它:「状态·超预算丢最旧保最新」真实保留 idx49,bug 丢 idx49。 + */ +function buildCompactionSummaryB4(opts: { + prefix: string; + recentEntries: ReadonlyArray<{ type: string; data: unknown }>; + maxTokens: number; +}): { summary: string; reusedPrefix: boolean; droppedEntries: number } { + const { prefix, recentEntries, maxTokens } = opts; + const reusedPrefix = prefix.trim().length > 0; + const directiveLine = + `## Compaction Summary\n` + + `${recentEntries.length} recent entries compacted (model-free digest):`; + const baseParts: string[] = []; + if (reusedPrefix) baseParts.push(prefix); + baseParts.push(directiveLine); + const base = baseParts.join("\n\n"); + const digestLines = recentEntries.map((entry) => { + let body: string; + try { + body = JSON.stringify(entry.data); + } catch { + body = "[unserializable]"; + } + if (body.length > 120) body = body.slice(0, 120) + "…"; + return `- ${entry.type}: ${body}`; + }); + const kept = [...digestLines]; + const estimateAll = () => + estimateTokens(base) + (kept.length > 0 ? estimateTokens(kept.join("\n")) : 0); + while (kept.length > 0 && estimateAll() > maxTokens) { + kept.pop(); // BUG: pop 丢最新而非 shift 丢最旧 + } + const summary = kept.length > 0 ? `${base}\n${kept.join("\n")}` : base; + return { summary, reusedPrefix, droppedEntries: recentEntries.length }; +} + +/** + * B5 — spill evict 植入 bug:阈值比较 `>` 改 `>=`(恰等于阈值的条目被误回收)。 + * 真实代码 spill.ts:159 `entry.bytes > olderThanBytes`,变异为 `>=`。 + * 杀它:「边界·evict 恰等于阈值保留」真实保留,bug 误回收。 + */ +function makeSpillStoreB5() { + const store = new Map(); + const seqByKey = new Map(); + const encoder = new TextEncoder(); + const makeLocator = (key: string, seq: number): SpillLocator => + `pba-spill:${key}:${seq}` as SpillLocator; + const measureBytes = (value: unknown): number => { + let text: string; + try { + text = JSON.stringify(value); + } catch { + text = String(value); + } + if (typeof text !== "string") text = String(value); + if (text.length === 0) return 0; + return encoder.encode(text).length; + }; + return { + spill(key: string, data: unknown): SpillLocator { + const seq = (seqByKey.get(key) ?? 0) + 1; + seqByKey.set(key, seq); + const loc = makeLocator(key, seq); + store.set(loc, { data, bytes: measureBytes(data) }); + return loc; + }, + evict(olderThanBytes?: number): number { + if (olderThanBytes === undefined) { + const n = store.size; + store.clear(); + return n; + } + let evicted = 0; + for (const [loc, entry] of store) { + if (entry.bytes >= olderThanBytes) { + // BUG: >= 而非 > + store.delete(loc); + evicted++; + } + } + return evicted; + }, + }; +} + +/** + * B6 — spill spill 植入 bug:漏 seq 自增(同 key 多次 spill 返同一 locator)。 + * 真实代码 spill.ts:111 `const seq = (this.seqByKey.get(key) ?? 0) + 1;`,变异固定 seq=1。 + * 杀它:「边界·同 key 多次 spill 返不同 locator」真实 a≠b,bug a===b。 + */ +function makeSpillStoreB6() { + const store = new Map(); + const makeLocator = (key: string, seq: number): SpillLocator => + `pba-spill:${key}:${seq}` as SpillLocator; + return { + spill(key: string, data: unknown): SpillLocator { + const seq = 1; // BUG: 固定 seq=1,漏自增 + const loc = makeLocator(key, seq); + store.set(loc, { data, bytes: 0 }); + return loc; + }, + }; +} + +// ============================================================================ +// ① token-meter — 等价类划分 + 边界值分析 +// ============================================================================ + +describe("compaction token-meter — 等价类划分(有效/无效/边界类)", () => { + // 等价类:① 空串 ② 纯 ASCII ③ 纯 CJK ④ 混合 ⑤ 单字符 + it("等价类·空串: estimateTokens('') → 0", () => { + expect(estimateTokens("")).toBe(0); + }); + + it("等价类·纯 ASCII: 'hello world'(11 char) → ⌈11/4⌉=3", () => { + expect(estimateTokens("hello world")).toBe(3); + }); + + it("等价类·纯 CJK: '寄存器配置'(5 CJK) → 每 char 1 = 5", () => { + expect(estimateTokens("寄存器配置")).toBe(5); + }); + + it("等价类·混合: 'ab寄存器'(2 ASCII + 3 CJK) → 3 + ⌈2/4⌉=1 = 4", () => { + expect(estimateTokens("ab寄存器")).toBe(4); + }); + + it("等价类·单字符 ASCII: 'a' → ⌈1/4⌉=1", () => { + expect(estimateTokens("a")).toBe(1); + }); + + it("等价类·单字符 CJK: '寄' → 1", () => { + expect(estimateTokens("寄")).toBe(1); + }); + + it("等价类·纯标点/空格混合: ' !! '(5 non-CJK) → ⌈5/4⌉=2", () => { + expect(estimateTokens(" !! ")).toBe(2); + }); +}); + +describe("compaction token-meter — 边界值分析(off-by-one、空、4 倍数边界)", () => { + it("边界·4 char ASCII 恰好整除: 'abcd' → ⌈4/4⌉=1", () => { + expect(estimateTokens("abcd")).toBe(1); + }); + + it("边界·5 char ASCII 跨档 off-by-one: 'abcde' → ⌈5/4⌉=2", () => { + expect(estimateTokens("abcde")).toBe(2); + }); + + it("边界·3 char 未跨档: 'abc' → ⌈3/4⌉=1", () => { + expect(estimateTokens("abc")).toBe(1); + }); + + it("边界·单空格非空串: ' ' → 1", () => { + expect(estimateTokens(" ")).toBe(1); + }); + + it("边界·measureContext 空数组 → 0", () => { + expect(measureContext([])).toBe(0); + }); + + it("边界·measureContext 单条空 content → 0 + 4 overhead = 4", () => { + expect(measureContext([{ role: "user", content: "" }])).toBe(4); + }); + + it("边界·measureContext 单条单字符 content → 1 + 4 = 5", () => { + expect(measureContext([{ role: "user", content: "a" }])).toBe(5); + }); + + it("边界·4 char ×N 恰好整除不漏算: 'abcd'.repeat(10)=40 → 10", () => { + expect(estimateTokens("abcd".repeat(10))).toBe(10); + }); +}); + +describe("compaction token-meter — 对抗/fuzz(null/undefined/缺失字段/畸形/巨大)", () => { + it("fuzz·消息 content 为 undefined → 当 '' 处理(不抛)", () => { + expect(measureContext([{ role: "user" } as any])).toBe(4); + }); + + it("fuzz·消息为 null → 跳过(不抛、不计)", () => { + expect(measureContext([null as any])).toBe(0); + }); + + it("fuzz·巨大 ASCII 串 (10000 char) → ⌈10000/4⌉=2500,不抛", () => { + expect(estimateTokens("a".repeat(10000))).toBe(2500); + }); + + it("fuzz·巨大 CJK 串 (5000 CJK) → 5000,不抛", () => { + expect(estimateTokens("寄".repeat(5000))).toBe(5000); + }); + + it("fuzz·混合 null + 正常消息: null 被跳过,只计正常条", () => { + const msgs = [ + null, + { role: "user", content: "ab" }, + undefined, + { role: "assistant", content: "abcd" }, + ] as any; + expect(measureContext(msgs)).toBe(estimateTokens("ab") + estimateTokens("abcd") + 8); + }); +}); + +describe("compaction token-meter — 元蜕变/不变式(确定性 + 线性叠加 + 非负)", () => { + it("不变式·estimateTokens 确定性: 同输入多次调用恒同输出", () => { + const t = "Hello 寄存器 world 配置!"; + const a = estimateTokens(t); + expect(a).toBe(estimateTokens(t)); + expect(a).toBe(estimateTokens(t)); + }); + + it("不变式·measureContext = Σ(estimateTokens(content) + 4) 对非空消息", () => { + const msgs = [ + { role: "user", content: "ab" }, + { role: "assistant", content: "abcd" }, + { role: "tool", content: "寄存器" }, + ]; + const expected = + estimateTokens("ab") + + estimateTokens("abcd") + + estimateTokens("寄存器") + + 4 * 3; + expect(measureContext(msgs)).toBe(expected); + }); + + it("不变式·estimateTokens ≥ 0 对任意输入(非负)", () => { + expect(estimateTokens("")).toBeGreaterThanOrEqual(0); + expect(estimateTokens("x")).toBeGreaterThanOrEqual(0); + expect(estimateTokens("寄")).toBeGreaterThanOrEqual(0); + }); + + it("不变式·estimateTokens(a+b) ≤ estimateTokens(a)+estimateTokens(b)(ceil 次可加性)", () => { + const a = "abc"; + const b = "defg"; + expect(estimateTokens(a + b)).toBeLessThanOrEqual( + estimateTokens(a) + estimateTokens(b), + ); + }); +}); + +// ============================================================================ +// token-meter — 变异测试 kill-test +// ============================================================================ + +describe("compaction token-meter — 变异测试 kill-test", () => { + it("B1 kill: 5 char ASCII 跨档 ⌈5/4⌉=2(真实=2;bug floor=1 偏离→正确性断言套 bug 抛)", () => { + const correct = 2; + // (a) 真实代码正确 + expect(estimateTokens("abcde")).toBe(correct); + // (b) bug 副本偏离正确 + expect(estimateTokensB1("abcde")).not.toBe(correct); + // (c) 若真实被此 bug 污染,正确性断言会 FAIL + expect(() => expect(estimateTokensB1("abcde")).toBe(correct)).toThrow(); + }); +}); + +// ============================================================================ +// ② tool-result-pruner — 等价类划分 + 决策表 + 边界 + fuzz + 不变式 +// ============================================================================ + +const I2CDUMP_SAMPLE = [ + "WARNING: i2c-1 adapter unavailable, using i2c-0", + " 0 1 2 3 4 5 6 7 8 9 a b c d e f", + "00: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f", + "10: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f", + "20: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff", + "70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", +].join("\n"); + +describe("compaction tool-result-pruner — 等价类划分(四类工具 + 空内容)", () => { + it("等价类·i2cdump: 保留全部地址行 + 末行,丢 WARNING/列头", () => { + const res = pruneToolResult(I2CDUMP_SAMPLE, { tool: "i2cdump" }); + expect(res.pruned).toContain("00: 00 01"); + expect(res.pruned).toContain("70: 00 00"); + expect(res.pruned).not.toContain("WARNING"); + expect(res.pruned).not.toContain("0 1 2 3"); + expect(res.preservedAddrs).toEqual(["00", "10", "20", "70"]); + expect(res.dropped).toBe(2); + }); + + it("等价类·gdb: 保留 #frame 行,丢非帧行", () => { + const gdb = [ + "Reading symbols from vmlinux...", + "#0 0xffffffff in do_fault ()", + "#1 0xaaaa in handle_irq (irq=12)", + "warning: ", + ].join("\n"); + const res = pruneToolResult(gdb, { tool: "gdb" }); + expect(res.pruned).toContain("#0 0xffffffff"); + expect(res.pruned).toContain("#1 0xaaaa"); + expect(res.pruned).not.toContain("Reading symbols"); + expect(res.dropped).toBe(2); + }); + + it("等价类·dmesg: 保留 severe(级别标记 + 关键字),丢 benign", () => { + const dmesg = [ + "[ 1.0] Bluetooth: started", + "[ 2.0] <4> thermal: warning threshold exceeded", + "[ 3.0] <3> iommu: error mapping failed", + "[ 4.0] USB: device enumerated", + ].join("\n"); + const res = pruneToolResult(dmesg, { tool: "dmesg" }); + expect(res.pruned).toContain("warning threshold"); + expect(res.pruned).toContain("error mapping"); + expect(res.pruned).not.toContain("Bluetooth: started"); + expect(res.dropped).toBe(2); + }); + + it("等价类·general: 截断到 maxLines,超出丢弃", () => { + const content = Array.from({ length: 10 }, (_, i) => `line${i}`).join("\n"); + const res = pruneToolResult(content, { tool: "general", maxLines: 3 }); + expect(res.pruned).toBe("line0\nline1\nline2"); + expect(res.dropped).toBe(7); + }); + + it("等价类·空内容: 四类工具均 { pruned:'', dropped:0 }", () => { + for (const tool of ["i2cdump", "gdb", "dmesg", "general"] as const) { + const res = pruneToolResult("", { tool }); + expect(res.pruned).toBe(""); + expect(res.dropped).toBe(0); + expect(res.preservedAddrs).toEqual(tool === "i2cdump" ? [] : undefined); + } + }); +}); + +describe("compaction tool-result-pruner — 决策表(组合输入→期望,覆盖全分支)", () => { + const cases: Array<{ + name: string; + content: string; + opts: PruneOptions; + expectInPruned: string[]; + expectNotInPruned: string[]; + expectDropped: number; + }> = [ + { + name: "i2cdump+有地址行+末行非地址", + content: "warn\n00: aa\n10: bb\ntail-line-no-addr", + opts: { tool: "i2cdump" }, + expectInPruned: ["00: aa", "10: bb", "tail-line-no-addr"], + expectNotInPruned: ["warn"], + expectDropped: 1, + }, + { + name: "i2cdump+末行已是地址行(去重不重复)", + content: "00: aa\n10: bb", + opts: { tool: "i2cdump" }, + expectInPruned: ["00: aa", "10: bb"], + expectNotInPruned: [], + expectDropped: 0, + }, + { + name: "gdb+无帧行→fail-soft 首尾", + content: "no frame here\njust prose", + opts: { tool: "gdb" }, + expectInPruned: ["no frame here", "just prose"], + expectNotInPruned: [], + expectDropped: 0, + }, + { + name: "dmesg+benign 全无匹配→pruned 空(正确语义不兜底)", + content: "[1] ok\n[2] fine", + opts: { tool: "dmesg" }, + expectInPruned: [], + expectNotInPruned: ["[1] ok", "[2] fine"], + expectDropped: 2, + }, + { + name: "general+maxLines=0→全丢", + content: "a\nb\nc", + opts: { tool: "general", maxLines: 0 }, + expectInPruned: [], + expectNotInPruned: ["a", "b", "c"], + expectDropped: 3, + }, + { + name: "general+maxLines 缺省→默认 200(只给 5 行,全保留)", + content: "a\nb\nc\nd\ne", + opts: { tool: "general" }, + expectInPruned: ["a", "b", "c", "d", "e"], + expectNotInPruned: [], + expectDropped: 0, + }, + { + name: "general+maxLines 负数→Math.max(0,neg)=0→全丢", + content: "a\nb", + opts: { tool: "general", maxLines: -5 }, + expectInPruned: [], + expectNotInPruned: ["a", "b"], + expectDropped: 2, + }, + { + name: "general+maxLines 大于行数→全保留 dropped=0", + content: "a\nb\nc", + opts: { tool: "general", maxLines: 999 }, + expectInPruned: ["a", "b", "c"], + expectNotInPruned: [], + expectDropped: 0, + }, + ]; + + for (const c of cases) { + it(`决策表·${c.name}`, () => { + const res = pruneToolResult(c.content, c.opts); + for (const s of c.expectInPruned) expect(res.pruned).toContain(s); + for (const s of c.expectNotInPruned) expect(res.pruned).not.toContain(s); + expect(res.dropped).toBe(c.expectDropped); + }); + } +}); + +describe("compaction tool-result-pruner — 边界值分析(单行/全空/0x 前缀/去重)", () => { + it("边界·单行 i2cdump 地址行: '00: aa' → 保留,dropped 0", () => { + const res = pruneToolResult("00: aa", { tool: "i2cdump" }); + expect(res.pruned).toBe("00: aa"); + expect(res.dropped).toBe(0); + expect(res.preservedAddrs).toEqual(["00"]); + }); + + it("边界·单行非地址 prose: 'just prose' → fail-soft 退回首=尾(同行)", () => { + const res = pruneToolResult("just prose", { tool: "i2cdump" }); + expect(res.pruned).toBe("just prose"); + expect(res.dropped).toBe(0); + expect(res.preservedAddrs).toEqual([]); + }); + + it("边界·i2cdump 末行非地址: '00: aa\\ntail' → tail 补入保留", () => { + const res = pruneToolResult("00: aa\ntail-no-addr", { tool: "i2cdump" }); + expect(res.pruned).toBe("00: aa\ntail-no-addr"); + expect(res.dropped).toBe(0); + expect(res.preservedAddrs).toEqual(["00"]); + }); + + it("边界·0x 前缀地址行: '0x50: aa bb' → 保留 + preservedAddrs=['0x50']", () => { + const res = pruneToolResult("0x50: aa bb", { tool: "i2cdump" }); + expect(res.pruned).toBe("0x50: aa bb"); + expect(res.preservedAddrs).toEqual(["0x50"]); + }); + + it("边界·全空行 i2cdump: '\\n\\n' → fail-soft 空,dropped=3", () => { + const res = pruneToolResult("\n\n", { tool: "i2cdump" }); + expect(res.pruned).toBe(""); + expect(res.preservedAddrs).toEqual([]); + expect(res.dropped).toBe(3); + }); + + it("边界·gdb 单帧行 '#0 frame' → 保留 1 行", () => { + const res = pruneToolResult("#0 frame", { tool: "gdb" }); + expect(res.pruned).toBe("#0 frame"); + expect(res.dropped).toBe(0); + }); + + it("边界·dmesg 单 severe '<3> err' → 保留", () => { + const res = pruneToolResult("<3> err", { tool: "dmesg" }); + expect(res.pruned).toBe("<3> err"); + expect(res.dropped).toBe(0); + }); + + it("边界·i2cdump preservedAddrs 去重: 同地址标签多次只记一次", () => { + const res = pruneToolResult("00: aa\n00: bb", { tool: "i2cdump" }); + expect(res.preservedAddrs).toEqual(["00"]); + }); + + it("边界·general 单行 maxLines=1 → 保留首行", () => { + const res = pruneToolResult("only line", { tool: "general", maxLines: 1 }); + expect(res.pruned).toBe("only line"); + expect(res.dropped).toBe(0); + }); +}); + +describe("compaction tool-result-pruner — 对抗/fuzz(畸形 maxLines/特殊字符/边界 addr)", () => { + it("fuzz·general maxLines=NaN → slice(0,NaN)=[] → 全丢", () => { + const res = pruneToolResult("a\nb\nc", { tool: "general", maxLines: NaN }); + expect(res.pruned).toBe(""); + expect(res.dropped).toBe(3); + }); + + it("fuzz·i2cdump 含 0x 但无冒号 → 不算地址行", () => { + const res = pruneToolResult("0x50 no colon here\ntail", { tool: "i2cdump" }); + expect(res.preservedAddrs).toEqual([]); + expect(res.pruned.length).toBeGreaterThan(0); + }); + + it("fuzz·i2cdump 5 位 hex 前缀不匹配({1,4} 上界): 'abcde: x' → 非地址", () => { + const res = pruneToolResult("abcde: x\ntail", { tool: "i2cdump" }); + expect(res.preservedAddrs).toEqual([]); + }); + + it("fuzz·gdb 帧号超长 '#99999 frame' → 仍算帧", () => { + const res = pruneToolResult("noise\n#99999 frame", { tool: "gdb" }); + expect(res.pruned).toBe("#99999 frame"); + }); + + it("fuzz·dmesg 大小写不敏感: 'ERROR' 与 'Warning' 均匹配", () => { + const res = pruneToolResult( + "[1] ERROR here\n[2] Warning there\n[3] benign", + { tool: "dmesg" }, + ); + expect(res.pruned).toContain("ERROR here"); + expect(res.pruned).toContain("Warning there"); + expect(res.pruned).not.toContain("benign"); + }); + + it("fuzz·dmesg 级别 <5> 不在 [0-4] 范围 → 不算 severe", () => { + const res = pruneToolResult("[1] <5> info notice\n[2] <4> warn line", { + tool: "dmesg", + }); + expect(res.pruned).not.toContain("<5> info"); + expect(res.pruned).toContain("<4> warn line"); + }); +}); + +describe("compaction tool-result-pruner — 元蜕变/不变式(dropped 恒等式 + 不创造新行)", () => { + it("不变式·dropped === lines.length - preservedLines 对四类工具", () => { + const samples = [ + { content: I2CDUMP_SAMPLE, opts: { tool: "i2cdump" } as PruneOptions }, + { + content: "noise\n#0 f\n#1 g\ntail", + opts: { tool: "gdb" } as PruneOptions, + }, + { + content: "[1] ok\n<3> err\n[2] warn word\nfine", + opts: { tool: "dmesg" } as PruneOptions, + }, + { + content: "a\nb\nc\nd\ne", + opts: { tool: "general", maxLines: 2 } as PruneOptions, + }, + ]; + for (const { content, opts } of samples) { + const res = pruneToolResult(content, opts); + const lines = content.length === 0 ? [""] : content.split("\n"); + const preservedLines = + res.pruned.length === 0 ? 0 : res.pruned.split("\n").length; + expect(res.dropped).toBe(lines.length - preservedLines); + } + }); + + it("不变式·pruned 保留行均来自原文(不创造新行)", () => { + const res = pruneToolResult(I2CDUMP_SAMPLE, { tool: "i2cdump" }); + const originalLines = new Set(I2CDUMP_SAMPLE.split("\n")); + for (const line of res.pruned.split("\n")) { + expect(originalLines.has(line)).toBe(true); + } + }); +}); + +// ============================================================================ +// tool-result-pruner — 变异测试 kill-tests +// ============================================================================ + +describe("compaction tool-result-pruner — 变异测试 kill-tests", () => { + it("B2 kill: general maxLines 截断 dropped=3(真实=3;bug +1 off-by-one dropped=2 偏离)", () => { + const content = "a\nb\nc\nd\ne"; // 5 行 + const correctDropped = 3; // maxLines=2 → 保留 2 行,丢 3 行 + // (a) 真实代码正确 + expect(pruneToolResult(content, { tool: "general", maxLines: 2 }).dropped).toBe( + correctDropped, + ); + // (b) bug 副本偏离正确 + expect(pruneGeneralB2(content, 2).dropped).not.toBe(correctDropped); + // (c) 若真实被此 bug 污染,正确性断言会 FAIL + expect(() => + expect(pruneGeneralB2(content, 2).dropped).toBe(correctDropped), + ).toThrow(); + }); + + it("B3 kill: i2cdump 末行非地址补入(真实含 tail;bug 漏 tail 偏离)", () => { + const content = "00: aa\ntail-no-addr"; + // (a) 真实代码保留 tail + expect(pruneToolResult(content, { tool: "i2cdump" }).pruned).toContain( + "tail-no-addr", + ); + // (b) bug 副本不含 tail + expect(pruneI2cB3(content).pruned).not.toContain("tail-no-addr"); + // (c) 若真实被此 bug 污染,正确性断言会 FAIL + expect(() => + expect(pruneI2cB3(content).pruned).toContain("tail-no-addr"), + ).toThrow(); + }); +}); + +// ============================================================================ +// ③ summarizer — 等价类 + 边界 + 状态/预算 + fuzz + 不变式 +// ============================================================================ + +describe("compaction summarizer — 等价类划分(前缀/entries/预算)", () => { + it("等价类·非空前缀+有 entries+预算充足: reusedPrefix=true,含前缀+指令+摘要", () => { + const res = buildCompactionSummary({ + prefix: "已初始化 i2c-0,地址 0x50。", + recentEntries: [ + { type: "tool-result", data: { name: "i2cdump", rows: 4 } }, + { type: "user-message", data: { role: "user", content: "读 0x50" } }, + ], + maxTokens: 2000, + }); + expect(res.reusedPrefix).toBe(true); + expect(res.summary).toContain("已初始化 i2c-0"); + expect(res.summary).toContain("## Compaction Summary"); + expect(res.summary).toContain("tool-result"); + expect(res.summary).toContain("user-message"); + expect(res.droppedEntries).toBe(2); + }); + + it("等价类·空前缀+有 entries: reusedPrefix=false(冷启动)", () => { + const res = buildCompactionSummary({ + prefix: "", + recentEntries: [{ type: "tool-call", data: { name: "gpioget" } }], + maxTokens: 2000, + }); + expect(res.reusedPrefix).toBe(false); + expect(res.droppedEntries).toBe(1); + }); + + it("等价类·空白前缀(空格/tab): trim 后空 → reusedPrefix=false", () => { + const res = buildCompactionSummary({ + prefix: " \n\t ", + recentEntries: [{ type: "x", data: 1 }], + maxTokens: 2000, + }); + expect(res.reusedPrefix).toBe(false); + }); + + it("等价类·非空前缀+零 entries: 含前缀+指令(0 entries),droppedEntries=0", () => { + const res = buildCompactionSummary({ + prefix: "prefix-stable", + recentEntries: [], + maxTokens: 2000, + }); + expect(res.reusedPrefix).toBe(true); + expect(res.summary).toContain("0 recent entries compacted"); + expect(res.droppedEntries).toBe(0); + }); +}); + +describe("compaction summarizer — 边界值分析(预算临界、单 entry、空 entries)", () => { + it("边界·maxTokens 极小(1): base 自身超预算,无摘要行,droppedEntries 仍 = entries 数", () => { + const res = buildCompactionSummary({ + prefix: "prefix", + recentEntries: [{ type: "t", data: { x: 1 } }], + maxTokens: 1, + }); + expect(res.droppedEntries).toBe(1); + expect(res.summary).toContain("prefix"); + }); + + it("边界·单 entry + 预算充足: 该 entry 摘要保留", () => { + const res = buildCompactionSummary({ + prefix: "p", + recentEntries: [{ type: "tool-result", data: { name: "i2cdump" } }], + maxTokens: 2000, + }); + expect(res.summary).toContain("i2cdump"); + }); + + it("边界·零 entries: summary 仅 base,droppedEntries=0", () => { + const res = buildCompactionSummary({ + prefix: "p", + recentEntries: [], + maxTokens: 100, + }); + expect(res.droppedEntries).toBe(0); + expect(res.summary).toContain("## Compaction Summary"); + }); + + it("边界·maxTokens 恰好容下单 entry(不裁剪): entry 出现在 summary", () => { + const entry = { type: "t", data: { i: 7 } }; + const probe = buildCompactionSummary({ + prefix: "", + recentEntries: [entry], + maxTokens: 2000, + }); + const needed = estimateTokens(probe.summary); + // 给刚好足够的预算,entry 仍保留 + const res = buildCompactionSummary({ + prefix: "", + recentEntries: [entry], + maxTokens: needed, + }); + expect(res.summary).toContain('"i":7'); + }); +}); + +describe("compaction summarizer — 状态转换/预算裁剪(最旧丢弃、前缀不裁)", () => { + it("状态·超预算: 优先丢最旧摘要行、保留最新;前缀永不裁剪", () => { + const prefix = "P".repeat(20); // 5 token + const entries = Array.from({ length: 50 }, (_, i) => ({ + type: "tool-result", + data: { idx: i, payload: "X".repeat(60) }, + })); + const res = buildCompactionSummary({ + prefix, + recentEntries: entries, + maxTokens: 50, + }); + expect(res.reusedPrefix).toBe(true); + expect(res.summary.startsWith(prefix)).toBe(true); + expect(res.summary).toContain('"idx":49'); + expect(res.summary).not.toContain('"idx":0'); + }); + + it("状态·预算刚好容下全部: 无裁剪,全部 entries 出现在 summary", () => { + const entries = [ + { type: "a", data: { i: 1 } }, + { type: "b", data: { i: 2 } }, + { type: "c", data: { i: 3 } }, + ]; + const res = buildCompactionSummary({ + prefix: "p", + recentEntries: entries, + maxTokens: 2000, + }); + expect(res.summary).toContain('"i":1'); + expect(res.summary).toContain('"i":2'); + expect(res.summary).toContain('"i":3'); + }); + + it("状态·部分裁剪: 中间预算只丢部分最旧,保留最新 N 条", () => { + const entries = Array.from({ length: 10 }, (_, i) => ({ + type: "t", + data: { idx: i, p: "X".repeat(40) }, + })); + const res = buildCompactionSummary({ + prefix: "", + recentEntries: entries, + maxTokens: 80, + }); + expect(res.summary).toContain('"idx":9'); + expect(res.summary).not.toContain('"idx":0'); + }); +}); + +describe("compaction summarizer — 对抗/fuzz(循环引用/超长 data/单字符前缀)", () => { + it("fuzz·data 含循环引用: digestEntry fail-soft 退回 [unserializable]", () => { + const cyclic: any = { name: "x" }; + cyclic.self = cyclic; + const res = buildCompactionSummary({ + prefix: "p", + recentEntries: [{ type: "tool-result", data: cyclic }], + maxTokens: 2000, + }); + expect(res.summary).toContain("[unserializable]"); + }); + + it("fuzz·超长 data: 截断到 120 字符 + 省略号", () => { + const longData = { blob: "0".repeat(500) }; + const res = buildCompactionSummary({ + prefix: "p", + recentEntries: [{ type: "t", data: longData }], + maxTokens: 5000, + }); + expect(res.summary).toContain("…"); + expect(res.summary).not.toContain("0".repeat(500)); + }); + + it("fuzz·单字符前缀 'P': trim 非空 → reusedPrefix=true", () => { + const res = buildCompactionSummary({ + prefix: "P", + recentEntries: [], + maxTokens: 100, + }); + expect(res.reusedPrefix).toBe(true); + }); +}); + +describe("compaction summarizer — 元蜕变/不变式(确定性 + 前缀恒在 + 计数恒等)", () => { + it("不变式·buildCompactionSummary 确定性: 同输入多次调用恒同 summary", () => { + const opts = { + prefix: "stable prefix", + recentEntries: [ + { type: "t", data: { a: 1 } }, + { type: "u", data: { b: 2 } }, + ], + maxTokens: 500, + }; + const a = buildCompactionSummary(opts); + const b = buildCompactionSummary(opts); + expect(a.summary).toBe(b.summary); + expect(a.reusedPrefix).toBe(b.reusedPrefix); + expect(a.droppedEntries).toBe(b.droppedEntries); + }); + + it("不变式·非空前缀始终出现在 summary 里(无论预算多紧)", () => { + const res = buildCompactionSummary({ + prefix: "must-survive", + recentEntries: Array.from({ length: 100 }, (_, i) => ({ + type: "t", + data: { i, p: "X".repeat(50) }, + })), + maxTokens: 10, + }); + expect(res.summary).toContain("must-survive"); + }); + + it("不变式·droppedEntries === recentEntries.length 恒成立", () => { + for (const n of [0, 1, 5, 50]) { + const res = buildCompactionSummary({ + prefix: "p", + recentEntries: Array.from({ length: n }, (_, i) => ({ + type: "t", + data: i, + })), + maxTokens: 2000, + }); + expect(res.droppedEntries).toBe(n); + } + }); +}); + +// ============================================================================ +// summarizer — 变异测试 kill-test +// ============================================================================ + +describe("compaction summarizer — 变异测试 kill-test", () => { + it("B4 kill: 超预算丢最旧保最新(真实含 idx49;bug pop 丢 idx49 偏离)", () => { + const prefix = "P".repeat(20); + const entries = Array.from({ length: 50 }, (_, i) => ({ + type: "tool-result", + data: { idx: i, payload: "X".repeat(60) }, + })); + // (a) 真实代码保留最新 idx49 + const real = buildCompactionSummary({ prefix, recentEntries: entries, maxTokens: 50 }); + expect(real.summary).toContain('"idx":49'); + // (b) bug 副本丢最新 idx49 + const bugged = buildCompactionSummaryB4({ prefix, recentEntries: entries, maxTokens: 50 }); + expect(bugged.summary).not.toContain('"idx":49'); + // (c) 若真实被此 bug 污染,正确性断言会 FAIL + expect(() => + expect(buildCompactionSummaryB4({ prefix, recentEntries: entries, maxTokens: 50 }).summary).toContain('"idx":49'), + ).toThrow(); + }); +}); + +// ============================================================================ +// ④ spill — 等价类 + 边界 + 状态转换 + fuzz + 不变式 +// ============================================================================ + +describe("compaction spill — 等价类划分(spill/recall/has/evict)", () => { + it("等价类·spill→recall round-trip: 取回原数据 + has 反映存活", () => { + const store = new SpillStore(); + const big = { page: "datasheet rmii chapter", text: "0".repeat(5000) }; + const loc = store.spill("datasheet:rmii", big); + expect(store.has(loc)).toBe(true); + expect(store.recall(loc)).toEqual(big); + }); + + it("等价类·recall 未知 locator → undefined(fail-closed)", () => { + const store = new SpillStore(); + store.spill("k", { v: 1 }); + const fake = "pba-spill:nonexistent:99" as SpillLocator; + expect(store.recall(fake)).toBeUndefined(); + expect(store.has(fake)).toBe(false); + }); + + it("等价类·evict 无参: 清空全部 + 返回被清条数", () => { + const store = new SpillStore(); + store.spill("a", 1); + store.spill("b", 2); + store.spill("c", 3); + expect(store.evict()).toBe(3); + expect(store.evict()).toBe(0); + }); + + it("等价类·evict 阈值: 回收大 blob,小 blob 保留", () => { + const store = new SpillStore(); + store.spill("small", { x: 1 }); + store.spill("big", { x: "0".repeat(500) }); + store.spill("mid", { x: "0".repeat(250) }); + const evicted = store.evict(200); + expect(evicted).toBe(2); + expect(store.has("pba-spill:small:1" as SpillLocator)).toBe(true); + }); +}); + +describe("compaction spill — 边界值分析(同 key 多次/阈值边界/空 store)", () => { + it("边界·同 key 多次 spill: 返不同 locator,各可 recall", () => { + const store = new SpillStore(); + const a = store.spill("i2c", { n: 1 }); + const b = store.spill("i2c", { n: 2 }); + expect(a).not.toBe(b); + expect(a).toBe("pba-spill:i2c:1"); + expect(b).toBe("pba-spill:i2c:2"); + expect(store.recall(a)).toEqual({ n: 1 }); + expect(store.recall(b)).toEqual({ n: 2 }); + }); + + it("边界·空 store evict(): 返回 0", () => { + expect(new SpillStore().evict()).toBe(0); + }); + + it("边界·空 store evict(100): 返回 0", () => { + expect(new SpillStore().evict(100)).toBe(0); + }); + + it("边界·locator 格式: pba-spill:{key}:{seq}", () => { + const store = new SpillStore(); + expect(store.spill("datasheet:rmii", { x: 1 })).toBe( + "pba-spill:datasheet:rmii:1", + ); + }); + + it("边界·evict(0): 回收所有 bytes>0 的条目", () => { + const store = new SpillStore(); + store.spill("a", "x"); // '"x"' → 3 bytes > 0 + store.spill("b", "yy"); // '"yy"' → 4 bytes > 0 + expect(store.evict(0)).toBe(2); + }); + + it("边界·evict 阈值恰等于某条目 bytes: 该条目保留(> 而非 >=)", () => { + const store = new SpillStore(); + store.spill("exact", { x: 1 }); // {"x":1} → 7 bytes + const evicted = store.evict(7); // bytes > 7 → 7 不 > 7 → 保留 + expect(evicted).toBe(0); + expect(store.has("pba-spill:exact:1" as SpillLocator)).toBe(true); + }); + + it("边界·evict 阈值 = bytes-1: 恰大于阈值的条目被回收", () => { + const store = new SpillStore(); + store.spill("exact", { x: 1 }); // 7 bytes + expect(store.evict(6)).toBe(1); // 7 > 6 → 回收 + expect(store.has("pba-spill:exact:1" as SpillLocator)).toBe(false); + }); +}); + +describe("compaction spill — 状态转换(存活/回收 + 重入 + 不可达 + 单调续号)", () => { + it("状态·spill→存活→evict→不存活: has 状态正确迁移", () => { + const store = new SpillStore(); + const loc = store.spill("k", { v: 1 }); + expect(store.has(loc)).toBe(true); + store.evict(); + expect(store.has(loc)).toBe(false); + expect(store.recall(loc)).toBeUndefined(); + }); + + it("状态·evict 后同 key 再 spill: seqByKey 不清 → seq 单调续号,旧 locator 仍 fail-closed", () => { + const store = new SpillStore(); + const a = store.spill("k", 1); // pba-spill:k:1 + store.evict(); // 清 store,不清 seqByKey + const b = store.spill("k", 2); // seq 续号 → pba-spill:k:2 + expect(b).toBe("pba-spill:k:2"); + expect(store.has(b)).toBe(true); + expect(store.recall(b)).toBe(2); + expect(store.has(a)).toBe(false); + expect(store.recall(a)).toBeUndefined(); + }); + + it("状态·部分 evict 后存活条目仍可 recall(不影响存活条)", () => { + const store = new SpillStore(); + const small = store.spill("small", { x: 1 }); + const big = store.spill("big", { x: "0".repeat(500) }); + store.evict(200); + expect(store.has(big)).toBe(false); + expect(store.has(small)).toBe(true); + expect(store.recall(small)).toEqual({ x: 1 }); + }); + + it("状态·recall 不改状态(只读):多次 recall 同 locator 恒同结果", () => { + const store = new SpillStore(); + const loc = store.spill("k", { v: 42 }); + expect(store.recall(loc)).toEqual({ v: 42 }); + expect(store.recall(loc)).toEqual({ v: 42 }); + expect(store.has(loc)).toBe(true); + }); + + it("状态·不可达: 已 evict 的 locator 字符串不被同 key 再 spill 复用", () => { + const store = new SpillStore(); + const a = store.spill("k", "first"); + store.evict(); + const b = store.spill("k", "second"); + // a 的字符串 "pba-spill:k:1" 不应再被发放(b 用新 seq 2) + expect(a).not.toBe(b); + expect(store.recall(a)).toBeUndefined(); + expect(store.recall(b)).toBe("second"); + }); +}); + +describe("compaction spill — 对抗/fuzz(null/undefined/巨大/循环/空 key)", () => { + it("fuzz·spill null data: 不抛,recall 返 null", () => { + const store = new SpillStore(); + const loc = store.spill("k", null); + expect(store.recall(loc)).toBeNull(); + }); + + it("fuzz·spill undefined data: fail-soft 不抛(typeof 守卫)", () => { + const store = new SpillStore(); + expect(() => store.spill("k", undefined)).not.toThrow(); + const loc = store.spill("k", undefined); + expect(store.has(loc)).toBe(true); + expect(store.recall(loc)).toBeUndefined(); + }); + + it("fuzz·spill 循环引用对象: measureBytes fail-soft 不抛", () => { + const store = new SpillStore(); + const cyclic: any = { a: 1 }; + cyclic.self = cyclic; + expect(() => store.spill("k", cyclic)).not.toThrow(); + }); + + it("fuzz·spill 巨大对象 (100KB): 不抛,bytes 正确度量", () => { + const store = new SpillStore(); + const big = { text: "0".repeat(100000) }; + const loc = store.spill("big", big); + expect(store.recall(loc)).toEqual(big); + expect(store.has(loc)).toBe(true); + }); + + it("fuzz·spill 空字符串 key: locator 格式正常", () => { + const store = new SpillStore(); + const loc = store.spill("", { v: 1 }); + expect(loc).toBe("pba-spill::1"); + expect(store.recall(loc)).toEqual({ v: 1 }); + }); + + it("fuzz·spill 数字 key: key 被字符串化进 locator", () => { + const store = new SpillStore(); + expect(store.spill(123 as any, { v: 1 })).toBe("pba-spill:123:1"); + }); + + it("fuzz·evict 负阈值: 所有 bytes > 负数 → 全回收", () => { + const store = new SpillStore(); + store.spill("a", 1); + store.spill("b", 2); + expect(store.evict(-1)).toBe(2); + }); +}); + +describe("compaction spill — 元蜕变/不变式(brand 不可伪造/单调 deny/fail-closed)", () => { + it("不变式·brand 不可伪造: 外部构造的 locator recall 返 undefined", () => { + const store = new SpillStore(); + store.spill("real", { v: 1 }); + const forged = "pba-spill:real:999" as SpillLocator; + expect(store.recall(forged)).toBeUndefined(); + expect(store.has(forged)).toBe(false); + }); + + it("不变式·recall 单调 deny: 未发放/已回收的 locator 恒返 undefined", () => { + const store = new SpillStore(); + const loc = store.spill("k", 1); + store.evict(); + expect(store.recall(loc)).toBeUndefined(); + expect(store.recall(loc)).toBeUndefined(); + }); + + it("不变式·spill→recall 等价: 取回的数据 === 存入的数据", () => { + const store = new SpillStore(); + const data = { nested: { a: [1, 2, { b: "c" }] } }; + const loc = store.spill("k", data); + expect(store.recall(loc)).toEqual(data); + }); + + it("不变式·evict 返回值 = 实际被回收条数", () => { + const store = new SpillStore(); + store.spill("a", "1"); + store.spill("b", "2"); + store.spill("c", "3"); + expect(store.evict()).toBe(3); + expect(store.evict()).toBe(0); + }); + + it("元蜕变·append 两次=replay 等价: 两次 spill 同 key 同数据 → 各自 recall 等价", () => { + const store = new SpillStore(); + const data = { v: 42, arr: [1, 2, 3] }; + const loc1 = store.spill("k", data); + const loc2 = store.spill("k", data); + expect(store.recall(loc1)).toEqual(store.recall(loc2)); + expect(store.recall(loc1)).toEqual(data); + }); + + it("fail-closed 不变式·unusable spill locator 一律拒: 未发放/已 evict/伪造 均 undefined", () => { + const store = new SpillStore(); + const loc = store.spill("k", 1); + store.evict(); + const forged = "pba-spill:k:1" as SpillLocator; + const neverIssued = "pba-spill:k:999" as SpillLocator; + expect(store.recall(forged)).toBeUndefined(); + expect(store.recall(neverIssued)).toBeUndefined(); + expect(store.has(forged)).toBe(false); + expect(store.has(neverIssued)).toBe(false); + }); +}); + +// ============================================================================ +// spill — 变异测试 kill-tests +// ============================================================================ + +describe("compaction spill — 变异测试 kill-tests", () => { + it("B5 kill: evict 恰等于阈值的条目保留(真实保留;bug >= 误回收 偏离)", () => { + const store = new SpillStore(); + store.spill("exact", { x: 1 }); // 7 bytes + const realEvicted = store.evict(7); // bytes > 7 → 保留 + expect(realEvicted).toBe(0); + // bug 副本: bytes >= 7 → 误回收 + const bstore = makeSpillStoreB5(); + bstore.spill("exact", { x: 1 }); + const buggedEvicted = bstore.evict(7); + expect(buggedEvicted).toBe(1); // bug 误回收 + expect(buggedEvicted).not.toBe(realEvicted); + // (c) 若真实被此 bug 污染,正确性断言会 FAIL(用全新 bug store 避免排空误判) + const bstore2 = makeSpillStoreB5(); + bstore2.spill("exact", { x: 1 }); + expect(() => expect(bstore2.evict(7)).toBe(realEvicted)).toThrow(); + }); + + it("B6 kill: 同 key 多次 spill 返不同 locator(真实 a≠b;bug a===b 偏离)", () => { + const store = new SpillStore(); + const a = store.spill("k", 1); + const b = store.spill("k", 2); + expect(a).not.toBe(b); + // bug 副本: 固定 seq=1 → a===b + const bstore = makeSpillStoreB6(); + const ba = bstore.spill("k", 1); + const bb = bstore.spill("k", 2); + expect(ba).toBe(bb); + expect(() => expect(ba).not.toBe(bb)).toThrow(); + }); +}); + +// ============================================================================ +// 跨模块元蜕变/不变式(append 两次=replay 等价、waterfall 不调 next=短路、 +// fail-closed unusable=拒、pruner↔summarizer 兼容) +// ============================================================================ + +describe("compaction 跨模块 — 元蜕变/不变式", () => { + it("不变式·summarizer 用 token-meter 估算预算: summary token ≤ maxTokens(base+摘要)", () => { + const res = buildCompactionSummary({ + prefix: "P".repeat(20), + recentEntries: Array.from({ length: 30 }, (_, i) => ({ + type: "t", + data: { idx: i, p: "X".repeat(60) }, + })), + maxTokens: 60, + }); + expect(estimateTokens(res.summary)).toBeLessThanOrEqual(60); + }); + + it("不变式·pruner 与 summarizer 兼容: pruned 内容可作 summarizer entry data", () => { + const pruned = pruneToolResult(I2CDUMP_SAMPLE, { tool: "i2cdump" }); + const res = buildCompactionSummary({ + prefix: "p", + recentEntries: [{ type: "tool-result", data: pruned.pruned }], + maxTokens: 2000, + }); + expect(res.summary).toContain("00: 00 01"); + expect(res.droppedEntries).toBe(1); + }); + + it("不变式·spill locator 当作 summarizer data 不影响 spill store(brand 隔离)", () => { + const store = new SpillStore(); + const realLoc = store.spill("k", { v: 1 }); + const res = buildCompactionSummary({ + prefix: "p", + recentEntries: [{ type: "locator-as-data", data: realLoc }], + maxTokens: 2000, + }); + expect(res.summary).toContain("locator-as-data"); + expect(store.recall(realLoc)).toEqual({ v: 1 }); + }); + + it("waterfall 不调 next=短路: pruner 空 pruned 喂 summarizer 仍出合法 summary", () => { + const empty = pruneToolResult("", { tool: "general" }); + const res = buildCompactionSummary({ + prefix: "p", + recentEntries: [{ type: "tool-result", data: empty.pruned }], + maxTokens: 2000, + }); + expect(res.summary).toContain("## Compaction Summary"); + expect(res.droppedEntries).toBe(1); + }); + + it("元蜕变·append 两次=replay 等价: 两次 spill 同 key 同数据 → 两个 locator 各自 recall 等价", () => { + const store = new SpillStore(); + const data = { v: 42, arr: [1, 2, 3] }; + const loc1 = store.spill("k", data); + const loc2 = store.spill("k", data); + expect(store.recall(loc1)).toEqual(store.recall(loc2)); + expect(store.recall(loc1)).toEqual(data); + }); + + it("fail-closed 不变式·unusable spill locator 一律拒: 未发放/已 evict/伪造 均 undefined", () => { + const store = new SpillStore(); + const loc = store.spill("k", 1); + store.evict(); + const forged = "pba-spill:k:1" as SpillLocator; + const neverIssued = "pba-spill:k:999" as SpillLocator; + expect(store.recall(forged)).toBeUndefined(); + expect(store.recall(neverIssued)).toBeUndefined(); + expect(store.has(forged)).toBe(false); + expect(store.has(neverIssued)).toBe(false); + }); +}); + +// ============================================================================ +// 变异测试总览:确认真实(未植入 bug)代码全过 + 每个 bug 被某测试杀死 +// ============================================================================ + +describe("compaction 变异测试 — 总览(6 个 seeded bug 全被杀)", () => { + it("文档化: B1-B6 每个 bug 都被对应 kill-test 杀死(带 bug 副本偏离正确 → 正确性断言套 bug 抛)", () => { + // B1: estimateTokens floor 替 ceil → kill: 'abcde' 真实=2,bug=1 + expect(estimateTokens("abcde")).toBe(2); + expect(estimateTokensB1("abcde")).toBe(1); + expect(() => expect(estimateTokensB1("abcde")).toBe(2)).toThrow(); + + // B2: general off-by-one +1 → kill: 5 行 maxLines=2 真实 dropped=3,bug=2 + expect(pruneToolResult("a\nb\nc\nd\ne", { tool: "general", maxLines: 2 }).dropped).toBe(3); + expect(pruneGeneralB2("a\nb\nc\nd\ne", 2).dropped).toBe(2); + expect(() => expect(pruneGeneralB2("a\nb\nc\nd\ne", 2).dropped).toBe(3)).toThrow(); + + // B3: i2cdump 漏 tail 补入 → kill: '00: aa\ntail' 真实含 tail,bug 不含 + expect(pruneToolResult("00: aa\ntail-no-addr", { tool: "i2cdump" }).pruned).toContain("tail-no-addr"); + expect(pruneI2cB3("00: aa\ntail-no-addr").pruned).not.toContain("tail-no-addr"); + expect(() => expect(pruneI2cB3("00: aa\ntail-no-addr").pruned).toContain("tail-no-addr")).toThrow(); + + // B4: summarizer pop 丢最新 → kill: 超预算真实保留 idx49,bug 丢 idx49 + const entries = Array.from({ length: 50 }, (_, i) => ({ + type: "tool-result", + data: { idx: i, payload: "X".repeat(60) }, + })); + expect(buildCompactionSummary({ prefix: "P".repeat(20), recentEntries: entries, maxTokens: 50 }).summary).toContain('"idx":49'); + expect(buildCompactionSummaryB4({ prefix: "P".repeat(20), recentEntries: entries, maxTokens: 50 }).summary).not.toContain('"idx":49'); + + // B5: spill evict >= → kill: 7 bytes 恰等于阈值真实保留(evict=0),bug 误回收(=1) + const s5 = new SpillStore(); + s5.spill("e", { x: 1 }); + expect(s5.evict(7)).toBe(0); + const bs5 = makeSpillStoreB5(); + bs5.spill("e", { x: 1 }); + expect(bs5.evict(7)).toBe(1); + + // B6: spill 漏 seq 自增 → kill: 同 key 多次真实 a≠b,bug a===b + const s6 = new SpillStore(); + expect(s6.spill("k", 1)).not.toBe(s6.spill("k", 2)); + const bs6 = makeSpillStoreB6(); + expect(bs6.spill("k", 1)).toBe(bs6.spill("k", 2)); + }); +}); diff --git a/tests/context-injector.test.ts b/tests/context-injector.test.ts new file mode 100644 index 0000000..3e826ee --- /dev/null +++ b/tests/context-injector.test.ts @@ -0,0 +1,1167 @@ +/** + * @module context-injector.test + * + * T13 上下文注入三段(inject / steer / followup)—— 严谨多方法论测试套件。 + * + * 被测对象:src/core/context-injector.ts 的命名导出 + * - 常量:INJECTION_PHASES / CONTEXT_INJECTION_TYPE + * - 类型:InjectionPhase / Injection / RuntimeSnapshot / InjectionSink / ActiveContext + * - 类:ContextInjector(inject / steer / followup / snapshot / deriveActiveContext / clear) + * - 函数:toSessionEntry + * + * 直接 import 真实模块;mock 注入依赖(appendEntry sink),无 pi 运行时 / 无硬件 / 无网络。 + * + * 多测试方法论(每个 describe 块标注方法论名): + * 1. 等价类划分(Equivalence Partitioning) + * 2. 边界值分析(Boundary Value Analysis) + * 3. 决策表(Decision Table) + * 4. 状态转换(State Transition) + * 5. 对抗 / Fuzz(Adversarial / Fuzz) + * 6. 元蜕变 / 不变式(Metamorphic / Invariant) + * 7. 变异测试(Mutation Testing)—— 5 个植入 bug(A-E),gated by MUTATION_BUG env + * + * 门: + * - 默认(无 MUTATION_BUG)跑 → 真实代码全绿(变异块 skipIf 跳过)。 + * - MUTATION_BUG=A/B/C/D/E 单独跑 → 对应植入 bug 副本的测试 FAIL(bug 被杀)。 + * - 验证门:先跑 `npx vitest run tests/context-injector.test.ts`(all green), + * 再对每个 bug 跑 `MUTATION_BUG=X npx vitest run tests/context-injector.test.ts`, + * 期望该 it FAIL(exit!=0)= bug 被杀。 + */ + +import { describe, it, expect } from "vitest"; +import { + ContextInjector, + INJECTION_PHASES, + CONTEXT_INJECTION_TYPE, + toSessionEntry, + type Injection, + type InjectionPhase, + type RuntimeSnapshot, + type ActiveContext, + type InjectionSink, +} from "../src/core/context-injector.js"; +import type { PbaSessionEntry } from "../src/core/pba-session.js"; + +/** 测试用:把 readonly 字段变 mutable 以验证冻结。 */ +type Mutable = { -readonly [K in keyof T]: T[K] }; + +// ============================================================================ +// 工具 +// ============================================================================ + +/** 收集 appendEntry 下沉事件的 mock sink。 */ +function makeSink(): { sink: InjectionSink; calls: Array<{ type: string; data: unknown }> } { + const calls: Array<{ type: string; data: unknown }> = []; + return { + calls, + sink: (type: string, data: unknown) => calls.push({ type, data }), + }; +} + +/** 构造一个不冻结的注入器(测试默认;冻结语义单独验证)。 */ +function softCi(appendEntry?: InjectionSink): ContextInjector { + return new ContextInjector({ deepFreeze: false, ...(appendEntry ? { appendEntry } : {}) }); +} + +// ============================================================================ +// 1. 等价类划分(Equivalence Partitioning)—— 有效 phase / 无效 phase / 有效 content / 无效 content +// 每一类取代表值,覆盖全部合法/非法分支。 +// ============================================================================ + +describe("等价类划分:phase 合法集 + content 有效性", () => { + it("有效 phase 类:inject → { phase:'inject', nextStep:true, nextTurn:false, boardId:undef, replacesSnapshot:undef }", () => { + const ci = softCi(); + const inj = ci.inject("reg map 0x48=RTC"); + expect(inj.phase).toBe("inject"); + expect(inj.nextStep).toBe(true); + expect(inj.nextTurn).toBe(false); + expect(inj.boardId).toBeUndefined(); + expect(inj.replacesSnapshot).toBeUndefined(); + }); + + it("有效 phase 类:steer → { phase:'steer', nextStep:true, nextTurn:false, boardId?:arg }", () => { + const ci = softCi(); + const inj = ci.steer("switch to S100", "s100"); + expect(inj.phase).toBe("steer"); + expect(inj.nextStep).toBe(true); + expect(inj.nextTurn).toBe(false); + expect(inj.boardId).toBe("s100"); + }); + + it("有效 phase 类:steer 无 boardId → boardId:undefined(可选省略)", () => { + const ci = softCi(); + const inj = ci.steer("switch board (unspecified)"); + expect(inj.boardId).toBeUndefined(); + }); + + it("有效 phase 类:followup → { phase:'followup', nextStep:false, nextTurn:true, boardId:undef }", () => { + const ci = softCi(); + const inj = ci.followup("flash new bootloader"); + expect(inj.phase).toBe("followup"); + expect(inj.nextStep).toBe(false); + expect(inj.nextTurn).toBe(true); + expect(inj.boardId).toBeUndefined(); + }); + + it("有效 content 类:单字符 'x' 与长文本均通过(最小/最大有效边界)", () => { + const ci = softCi(); + expect(() => ci.inject("x")).not.toThrow(); + const long = "reg ".repeat(10000).trimEnd(); + const inj = ci.inject(long); + expect(inj.content).toBe(long); + }); + + it("有效 content 类:含 Unicode / emoji / CJK 均通过(非 ASCII 等价类)", () => { + const ci = softCi(); + const inj = ci.inject("寄存器 0x48 = RTC 🚀"); + expect(inj.content).toBe("寄存器 0x48 = RTC 🚀"); + }); + + it("无效 content 类:空串 '' → 三个入口均 fail-closed 抛错", () => { + const ci = new ContextInjector(); + expect(() => ci.inject("")).toThrow(); + expect(() => ci.steer("")).toThrow(); + expect(() => ci.followup("")).toThrow(); + }); + + it("无效 content 类:纯空白(空格/制表/换行混合)→ fail-closed 抛错(trim 归零)", () => { + const ci = new ContextInjector(); + expect(() => ci.inject(" ")).toThrow(); + expect(() => ci.steer("\t\n")).toThrow(); + expect(() => ci.followup(" \t ")).toThrow(); + }); + + it("无效 content 类:非字符串(null/undefined/number/object/array/boolean/symbol)→ fail-closed 抛错", () => { + const ci = new ContextInjector(); + for (const bad of [null, undefined, 42, {}, [], true, Symbol("s")] as unknown[]) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(() => ci.inject(bad as any)).toThrow(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(() => ci.steer(bad as any, "b")).toThrow(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(() => ci.followup(bad as any)).toThrow(); + } + }); + + it("无效 phase 类:clear(非法 phase) → assertPhase 抛错(fail-closed)", () => { + const ci = softCi(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(() => ci.clear("evil" as any)).toThrow(); + }); +}); + +// ============================================================================ +// 2. 边界值分析(Boundary Value Analysis)—— 空/单/max/off-by-one +// off-by-one 是注入器最易错点(slice 端点 / seq 自增 / 分隔符计数)。 +// ============================================================================ + +describe("边界值分析:空 / 单元素 / 多元素 / seq off-by-one", () => { + it("空寄存器:snapshot content='' / boardId=undef / ts>0(live 空集合边界)", () => { + const ci = softCi(); + const snap = ci.snapshot(); + expect(snap.content).toBe(""); + expect(snap.boardId).toBeUndefined(); + expect(snap.ts).toBeGreaterThan(0); + }); + + it("空寄存器:deriveActiveContext → injections=[] / active=null", () => { + const ci = softCi(); + const ctx = ci.deriveActiveContext(); + expect(ctx.injections).toHaveLength(0); + expect(ctx.active).toBeNull(); + }); + + it("单元素 inject:snapshot content === 该单条(无拼接,单元素分隔符边界)", () => { + const ci = softCi(); + ci.inject("only"); + const snap = ci.snapshot(); + expect(snap.content).toBe("only"); + }); + + it("单元素 inject:deriveActiveContext.active === 该单条", () => { + const ci = softCi(); + const inj = ci.inject("only"); + const ctx = ci.deriveActiveContext(); + expect(ctx.active).toBe(inj); + }); + + it("单元素 steer(无 boardId):snapshot boardId=undef(无 boardId 可取边界)", () => { + const ci = softCi(); + ci.steer("switch"); + const snap = ci.snapshot(); + expect(snap.boardId).toBeUndefined(); + }); + + it("双元素 inject:snapshot content 用 '\\n\\n' 拼接(off-by-one 分隔符边界:N=2 → 1 个分隔符)", () => { + const ci = softCi(); + ci.inject("a"); + ci.inject("b"); + expect(ci.snapshot().content).toBe("a\n\nb"); + }); + + it("三元素 inject:content === 'a\\n\\nb\\n\\nc'(N=3 → 2 个分隔符)", () => { + const ci = softCi(); + ci.inject("a"); + ci.inject("b"); + ci.inject("c"); + expect(ci.snapshot().content).toBe("a\n\nb\n\nc"); + }); + + it("snapshot seq 边界:首快照 id snap-1(snapshotSeq 从 0 自增到 1,off-by-one 不偏)", () => { + const ci = softCi(); + ci.inject("x"); + ci.snapshot(); // snap-1 + expect(ci.steer("s", "b").replacesSnapshot).toBe("snap-1"); + }); + + it("snapshot seq 边界:第二快照 id snap-2(链指向最新前驱)", () => { + const ci = softCi(); + ci.inject("x"); + ci.snapshot(); // snap-1 + ci.steer("s1", "b1"); // replaces=snap-1 + ci.snapshot(); // snap-2 + expect(ci.followup("new").replacesSnapshot).toBe("snap-2"); + }); + + it("steer 后无快照:replacesSnapshot=undef(currentSnapshotId 边界:无快照)", () => { + const ci = softCi(); + ci.inject("x"); + // 未 snapshot → 无快照历史 → steer 不取代 + expect(ci.steer("s", "b").replacesSnapshot).toBeUndefined(); + }); + + it("inject 永不取代:有快照后 inject 的 replacesSnapshot 仍 undef(inject 边界恒定)", () => { + const ci = softCi(); + ci.inject("baseline"); + ci.snapshot(); // snap-1 存在 + expect(ci.inject("more").replacesSnapshot).toBeUndefined(); + }); + + it("clear() 后 snapshotSeq 归零:新首快照 id snap-1(reset 边界)", () => { + const ci = softCi(); + ci.inject("x"); + ci.snapshot(); // snap-1, seq=1 + ci.clear(); // seq 归 0 + ci.inject("y"); + ci.snapshot(); // snap-1 again + expect(ci.steer("s", "b").replacesSnapshot).toBe("snap-1"); + }); + + it("clear(phase) 不重置 snapshotSeq:phase 清除后快照 id 链不变", () => { + const ci = softCi(); + ci.inject("a"); + ci.snapshot(); // snap-1 + ci.inject("b"); + ci.clear("inject" as InjectionPhase); // 清全部 inject,但不重置 seq/快照 + // 快照历史仍在 → 下次 steer 取代 snap-1 + expect(ci.steer("s", "b").replacesSnapshot).toBe("snap-1"); + }); +}); + +// ============================================================================ +// 3. 决策表(Decision Table)—— phase × {nextStep,nextTurn,boardId,replacesSnapshot} × {有无快照} +// 全分支覆盖:每个 phase 在「无快照」「有快照」两列下的期望。 +// ============================================================================ + +describe("决策表:phase × 快照存在性 → 期望字段矩阵", () => { + // 决策表(R = replacesSnapshot;— = 不适用/undef) + // ┌──────────┬──────────┬─────────┬─────────┬──────────┬──────────────────────┐ + // │ phase │ snapshot │ nextStep│ nextTurn│ boardId │ replacesSnapshot │ + // ├──────────┼──────────┼─────────┼─────────┼──────────┼──────────────────────┤ + // │ inject │ 无/有 │ true │ false │ undef │ undef(不取代) │ + // │ steer │ 无 │ true │ false │ arg │ undef(无前驱) │ + // │ steer │ 有 │ true │ false │ arg │ <最新快照 id> │ + // │ followup │ 无 │ false │ true │ undef │ undef(无前驱) │ + // │ followup │ 有 │ false │ true │ undef │ <最新快照 id> │ + // └──────────┴──────────┴─────────┴─────────┴──────────┴──────────────────────┘ + + it("inject 行(无快照):nextStep=true,nextTurn=false,boardId=undef,R=undef", () => { + const ci = softCi(); + const inj = ci.inject("a"); + expect(inj).toMatchObject({ phase: "inject", nextStep: true, nextTurn: false }); + expect(inj.boardId).toBeUndefined(); + expect(inj.replacesSnapshot).toBeUndefined(); + }); + + it("inject 行(有快照):有快照也不取代(replacesSnapshot 恒 undef)", () => { + const ci = softCi(); + ci.inject("baseline"); + ci.snapshot(); // snap-1 存在 + const inj = ci.inject("more regs"); + expect(inj.nextStep).toBe(true); + expect(inj.nextTurn).toBe(false); + expect(inj.boardId).toBeUndefined(); + expect(inj.replacesSnapshot).toBeUndefined(); // inject 不取代 + }); + + it("steer 行(无快照):replacesSnapshot=undef", () => { + const ci = softCi(); + const inj = ci.steer("switch", "b"); + expect(inj.nextStep).toBe(true); + expect(inj.nextTurn).toBe(false); + expect(inj.boardId).toBe("b"); + expect(inj.replacesSnapshot).toBeUndefined(); + }); + + it("steer 行(有快照):replacesSnapshot=<最新快照 id>", () => { + const ci = softCi(); + ci.inject("x"); + ci.snapshot(); // snap-1 + const inj = ci.steer("switch", "b"); + expect(inj.nextStep).toBe(true); + expect(inj.nextTurn).toBe(false); + expect(inj.boardId).toBe("b"); + expect(inj.replacesSnapshot).toBe("snap-1"); + }); + + it("followup 行(无快照):replacesSnapshot=undef", () => { + const ci = softCi(); + const inj = ci.followup("new task"); + expect(inj.nextStep).toBe(false); + expect(inj.nextTurn).toBe(true); + expect(inj.boardId).toBeUndefined(); + expect(inj.replacesSnapshot).toBeUndefined(); + }); + + it("followup 行(有快照):replacesSnapshot=<最新快照 id>", () => { + const ci = softCi(); + ci.inject("x"); + ci.snapshot(); // snap-1 + const inj = ci.followup("new task"); + expect(inj.nextStep).toBe(false); + expect(inj.nextTurn).toBe(true); + expect(inj.boardId).toBeUndefined(); + expect(inj.replacesSnapshot).toBe("snap-1"); + }); + + it("boardId 决策:inject/followup 恒 undef;steer 取 arg(含省略→undef)", () => { + const ci = softCi(); + expect(ci.inject("a").boardId).toBeUndefined(); + expect(ci.followup("c").boardId).toBeUndefined(); + expect(ci.steer("b", "s100").boardId).toBe("s100"); + expect(ci.steer("b2").boardId).toBeUndefined(); + }); + + it("nextStep/nextTurn 互斥决策:steer/inject 绑 step 不绑 turn;followup 绑 turn 不绑 step", () => { + const ci = softCi(); + const i = ci.inject("a"); + const s = ci.steer("b", "x"); + const f = ci.followup("c"); + expect(i.nextStep && !i.nextTurn).toBe(true); + expect(s.nextStep && !s.nextTurn).toBe(true); + expect(!f.nextStep && f.nextTurn).toBe(true); + }); +}); + +// ============================================================================ +// 4. 状态转换(State Transition)—— live 集合随 steer/followup 刷新; +// snapshot 历史 append-only;clear 全重置;sink 重入;不可达状态验证。 +// ============================================================================ + +describe("状态转换:live 集合刷新 + snapshot 历史 + clear 重置", () => { + it("初始态:全部注入 live(无 steer/followup pivot)", () => { + const ci = softCi(); + ci.inject("a"); + ci.inject("b"); + const snap = ci.snapshot(); + expect(snap.content).toBe("a\n\nb"); // 两条都在 live + }); + + it("迁移 inject→steer:live 收缩为 steer(含)之后(取代更早 inject)", () => { + const ci = softCi(); + ci.inject("old X=1"); + ci.steer("switch board", "s100"); + ci.inject("new Y=2"); + const snap = ci.snapshot(); + // live = [steer, inject(new)] —— steer 之前的 inject 被取代 + expect(snap.content).toBe("switch board\n\nnew Y=2"); + expect(snap.boardId).toBe("s100"); + }); + + it("迁移 steer→followup:live 收缩为 followup(含)之后", () => { + const ci = softCi(); + ci.steer("board A", "a"); + ci.inject("reg A"); + ci.followup("new task"); + ci.inject("reg B"); + const snap = ci.snapshot(); + // live = [followup, inject(reg B)] —— followup 之前的 steer/inject 被取代 + expect(snap.content).toBe("new task\n\nreg B"); + expect(snap.boardId).toBeUndefined(); // followup 无 boardId,且其前 steer 已不在 live + }); + + it("迁移 followup→steer:live 收缩为 steer(含)之后", () => { + const ci = softCi(); + ci.followup("task1"); + ci.inject("reg1"); + ci.steer("board B", "b"); + ci.inject("reg2"); + const snap = ci.snapshot(); + expect(snap.content).toBe("board B\n\nreg2"); + expect(snap.boardId).toBe("b"); + }); + + it("连续 steer:live 只含最后一次 steer(含)之后(每次 steer 刷新 pivot)", () => { + const ci = softCi(); + ci.steer("first", "a"); + ci.inject("r1"); + ci.steer("second", "b"); + ci.inject("r2"); + const snap = ci.snapshot(); + expect(snap.content).toBe("second\n\nr2"); + expect(snap.boardId).toBe("b"); + }); + + it("连续 followup:live 只含最后一次 followup(含)之后", () => { + const ci = softCi(); + ci.followup("task1"); + ci.followup("task2"); + ci.inject("reg"); + const snap = ci.snapshot(); + expect(snap.content).toBe("task2\n\nreg"); + }); + + it("snapshot 历史态:连续多次 snapshot 互不取代(append-only);replacesSnapshot 链指向最新前驱", () => { + const ci = softCi(); + ci.inject("a"); + ci.snapshot(); // snap-1: "a" + ci.inject("b"); + ci.snapshot(); // snap-2: "a\n\nb" + ci.inject("c"); + ci.snapshot(); // snap-3: "a\n\nb\n\nc" + const s = ci.followup("new"); + expect(s.replacesSnapshot).toBe("snap-3"); + }); + + it("clear(phase) 转移:仅删该 phase,live 可能重算(pivot 不受影响)", () => { + const ci = softCi(); + ci.inject("old"); // 在 steer pivot 前 + ci.steer("switch", "b"); + ci.inject("new"); + ci.clear("inject" as InjectionPhase); + // 删了 inject(old) + inject(new);剩 steer + const ctx = ci.deriveActiveContext(); + expect(ctx.injections).toHaveLength(1); + expect(ctx.injections[0]!.phase).toBe("steer"); + expect(ctx.active!.content).toBe("switch"); + }); + + it("clear(phase=steer) 转移:删 steer 后 pivot 消失,剩余 inject 全部 live", () => { + const ci = softCi(); + ci.inject("old"); + ci.steer("switch", "b"); + ci.inject("new"); + ci.clear("steer" as InjectionPhase); + // 删了 steer → 无 pivot → 剩 [inject(old), inject(new)] 全 live + const snap = ci.snapshot(); + expect(snap.content).toBe("old\n\nnew"); + expect(snap.boardId).toBeUndefined(); + }); + + it("clear() 全重置态:寄存器/快照/seq 全归零(不可达旧态残留)", () => { + const ci = softCi(); + ci.inject("a"); + ci.snapshot(); + ci.steer("b", "x"); + ci.snapshot(); + ci.clear(); + expect(ci.deriveActiveContext().injections).toHaveLength(0); + expect(ci.deriveActiveContext().active).toBeNull(); + // seq 归零 → 新快照 snap-1 + ci.inject("fresh"); + ci.snapshot(); + expect(ci.steer("s", "y").replacesSnapshot).toBe("snap-1"); + }); + + it("不可达状态:无快照时 steer 的 replacesSnapshot 不可能指向非 undef", () => { + // 状态不变式:snapshotSeq=0 ∧ snapshots=[] ⟹ currentSnapshotId()=undef + const ci = softCi(); + expect(ci.steer("a", "b").replacesSnapshot).toBeUndefined(); + ci.inject("x"); + expect(ci.steer("c", "d").replacesSnapshot).toBeUndefined(); // 仍无快照 + }); + + it("重入态:sink 回调内再 inject 不崩溃(push 无迭代,顺序追加)", () => { + const calls: unknown[] = []; + let reentrant: ContextInjector | null = null; + const sink: InjectionSink = (_t, d) => { + calls.push(d); + // 首次回调时再注入一条(重入) + if (calls.length === 1 && reentrant) { + reentrant.inject("reentrant"); + } + }; + const ci = new ContextInjector({ appendEntry: sink, deepFreeze: false }); + reentrant = ci; + ci.inject("first"); + // first + reentrant 两条均下沉 + expect(calls).toHaveLength(2); + expect((calls[0] as Injection).content).toBe("first"); + expect((calls[1] as Injection).content).toBe("reentrant"); + }); + + it("重入态:sink 回调内再 steer 也正常追加(更深重入)", () => { + const calls: unknown[] = []; + let reentrant: ContextInjector | null = null; + const sink: InjectionSink = (_t, d) => { + calls.push(d); + if (calls.length === 1 && reentrant) { + reentrant.steer("reentrant-steer", "board2"); + } + }; + const ci = new ContextInjector({ appendEntry: sink, deepFreeze: false }); + reentrant = ci; + ci.steer("first-steer", "board1"); + expect(calls).toHaveLength(2); + expect((calls[0] as Injection).boardId).toBe("board1"); + expect((calls[1] as Injection).boardId).toBe("board2"); + }); +}); + +// ============================================================================ +// 5. 对抗 / Fuzz(Adversarial / Fuzz)—— 畸形 / 滥用 / 极端输入 +// ============================================================================ + +describe("对抗 / Fuzz:畸形与滥用输入", () => { + it("null/undefined content → fail-closed 抛错(不静默吞)", () => { + const ci = new ContextInjector(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(() => ci.inject(null as any)).toThrow(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(() => ci.steer(undefined as any, "b")).toThrow(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(() => ci.followup(undefined as any)).toThrow(); + }); + + it("number/object/array/boolean/symbol content → fail-closed 抛错", () => { + const ci = new ContextInjector(); + for (const bad of [42, {}, [], true, Symbol("s")] as unknown[]) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(() => ci.inject(bad as any)).toThrow(); + } + }); + + it("循环引用对象作 content → 对象非 string → assertContent 抛错(断绝循环引用进 content)", () => { + const ci = new ContextInjector(); + const obj: Record = { self: null }; + obj.self = obj; // 循环引用 + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(() => ci.inject(obj as any)).toThrow(); + }); + + it("巨大 content(10MB)→ 接受且不截断(无长度门)", () => { + const ci = softCi(); + const huge = "A".repeat(10 * 1024 * 1024); + const inj = ci.inject(huge); + expect(inj.content).toHaveLength(10 * 1024 * 1024); + }); + + it("boardId 不校验类型:steer 第二参数非 string 被原样存(契约未要求校验,文档化行为)", () => { + // boardId 无 fail-closed 门:非 string 原样落 Injection + const ci = softCi(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const inj = ci.steer("switch", 123 as any); + expect(inj.boardId).toBe(123); + }); + + it("负 seq / NaN seq / Infinity seq 传 toSessionEntry → 原样透传(序列化器不校验 seq)", () => { + const inj: Injection = { phase: "inject", content: "x", nextStep: true, nextTurn: false }; + expect(toSessionEntry(inj, -5, 1000).seq).toBe(-5); + expect(Number.isNaN(toSessionEntry(inj, NaN, 1000).seq)).toBe(true); + expect(toSessionEntry(inj, Infinity, 1000).seq).toBe(Infinity); + }); + + it("toSessionEntry 传非法 injection 对象 → 原样放 data(不校验结构)", () => { + // toSessionEntry 是纯序列化器,不校验 data 形状 + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const entry = toSessionEntry({ wrong: true } as any, 1, 1000); + expect((entry.data as Record).wrong).toBe(true); + }); + + it("INJECTION_PHASES 被篡改 push/pop/splice → 抛 TypeError(深冻结)", () => { + expect(() => (INJECTION_PHASES as unknown as string[]).push("evil")).toThrow(TypeError); + expect(() => (INJECTION_PHASES as unknown as string[]).pop()).toThrow(TypeError); + expect(() => (INJECTION_PHASES as unknown as string[]).splice(0, 1)).toThrow(TypeError); + }); + + it("clear(非法 phase) → assertPhase 抛错(fail-closed)", () => { + const ci = softCi(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(() => ci.clear("evil" as any)).toThrow(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(() => ci.clear("" as any)).toThrow(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(() => ci.clear("INJECT" as any)).toThrow(); // 大小写敏感 + }); + + it("snapshot 连续调用 1000 次 → seq 单调递增到 1000(无累积异常)", () => { + const ci = softCi(); + ci.inject("x"); + for (let i = 0; i < 1000; i++) { + ci.snapshot(); + } + // 末尾快照 id = snap-1000 + expect(ci.steer("s", "b").replacesSnapshot).toBe("snap-1000"); + }); + + it("大量 inject(10000) → live 全量拼接正确(性能/正确性 fuzz)", () => { + const ci = softCi(); + const n = 10000; + for (let i = 0; i < n; i++) { + ci.inject(`r${i}`); + } + const snap = ci.snapshot(); + const parts = snap.content.split("\n\n"); + expect(parts).toHaveLength(n); + expect(parts[0]).toBe("r0"); + expect(parts[n - 1]).toBe(`r${n - 1}`); + }); + + it("交替 steer/inject/followup 混合序列 → live 始终等于最后一次 steer/followup(含)之后", () => { + const ci = softCi(); + ci.inject("i1"); + ci.steer("s1", "b1"); + ci.inject("i2"); + ci.followup("f1"); + ci.inject("i3"); + ci.steer("s2", "b2"); + ci.inject("i4"); + ci.followup("f2"); + ci.inject("i5"); + const snap = ci.snapshot(); + // 最后 pivot = followup("f2") → live = [f2, i5] + expect(snap.content).toBe("f2\n\ni5"); + expect(snap.boardId).toBeUndefined(); + }); +}); + +// ============================================================================ +// 6. 元蜕变 / 不变式(Metamorphic / Invariant)—— 跨变换保持的性质 +// ============================================================================ + +describe("元蜕变 / 不变式:跨变换保持的性质", () => { + it("蜕变:append 两次的 live snapshot === 独立实例等价重放(顺序合并等价,ts 不比)", () => { + // 路径 A:ci1 注入 a,b 后 snapshot + const ci1 = softCi(); + ci1.inject("a"); + ci1.inject("b"); + const snapA = ci1.snapshot(); + // 路径 B:ci2 注入同样 a,b 后 snapshot(独立实例,等价重放) + const ci2 = softCi(); + ci2.inject("a"); + ci2.inject("b"); + const snapB = ci2.snapshot(); + // 蜕变不变式:content 等价 + expect(snapA.content).toBe(snapB.content); + expect(snapA.content).toBe("a\n\nb"); + }); + + it("蜕变:replay 注入序列 → live 集合仅依赖最终序列,与中间快照时刻无关", () => { + // 路径 A:中途多次 snapshot + const ci1 = softCi(); + ci1.inject("a"); + ci1.snapshot(); + ci1.inject("b"); + ci1.snapshot(); + ci1.inject("c"); + // 路径 B:无中途 snapshot,同样注入序列 + const ci2 = softCi(); + ci2.inject("a"); + ci2.inject("b"); + ci2.inject("c"); + // 最终 live content 等价(snapshot 时刻不影响 live 计算) + expect(ci1.snapshot().content).toBe(ci2.snapshot().content); + expect(ci1.snapshot().content).toBe("a\n\nb\n\nc"); + }); + + it("不变式:freeze→篡改任意 readonly 字段均抛 TypeError(deepFreeze 递归)", () => { + const ci = new ContextInjector(); // deepFreeze 默认 true + const inj = ci.inject("frozen"); + expect(() => { + (inj as Mutable).content = "tampered"; + }).toThrow(TypeError); + expect(() => { + (inj as Mutable).phase = "steer"; + }).toThrow(TypeError); + expect(() => { + (inj as Mutable).nextStep = false; + }).toThrow(TypeError); + expect(() => { + (inj as Mutable).nextTurn = true; + }).toThrow(TypeError); + expect(() => { + (inj as Mutable).replacesSnapshot = "fake"; + }).toThrow(TypeError); + + const snap = ci.snapshot(); + expect(() => { + (snap as Mutable).content = "tampered"; + }).toThrow(TypeError); + expect(() => { + (snap as Mutable).boardId = "tampered"; + }).toThrow(TypeError); + expect(() => { + (snap as Mutable).ts = 0; + }).toThrow(TypeError); + + const ctx = ci.deriveActiveContext(); + expect(() => { + (ctx as Mutable).active = null; + }).toThrow(TypeError); + expect(() => { + (ctx as Mutable).injections = []; + }).toThrow(TypeError); + // injections 数组元素仍冻结 + expect(() => { + (ctx.injections[0] as Mutable).content = "tampered"; + }).toThrow(TypeError); + // injections 数组本身冻结(不可 push) + expect(() => { + (ctx.injections as Injection[]).push(inj); + }).toThrow(TypeError); + }); + + it("不变式:deepFreeze=false 时不冻结(可变,不抛 TypeError)", () => { + const ci = new ContextInjector({ deepFreeze: false }); + const inj = ci.inject("mutable"); + expect(() => { + (inj as Mutable).content = "changed"; + }).not.toThrow(); + expect(inj.content).toBe("changed"); + }); + + it("不变式:deriveActiveContext 返回的 injections 是副本(改原寄存器不影响快照视图)", () => { + const ci = new ContextInjector({ deepFreeze: false }); + ci.inject("a"); + const ctx = ci.deriveActiveContext(); + ci.inject("b"); // 改原寄存器 + expect(ctx.injections).toHaveLength(1); // 副本不受影响 + }); + + it("不变式:waterfall 不短路——inject 不取代、不绑 turn(被动补料,多 inject 累积无取代)", () => { + // inject 是被动补料:不产生 replacesSnapshot,不绑 turn + const ci = softCi(); + ci.inject("a"); + ci.inject("b"); + ci.inject("c"); + // 多次 inject 后无 steer/followup → live 仍含全部(无短路取代) + expect(ci.snapshot().content).toBe("a\n\nb\n\nc"); + expect(ci.deriveActiveContext().active!.content).toBe("c"); + }); + + it("不变式:单调 deny——deriveActiveContext.active 永远 === live 最新一条或 null", () => { + const ci = softCi(); + expect(ci.deriveActiveContext().active).toBeNull(); // 空 → null + ci.inject("a"); + expect(ci.deriveActiveContext().active!.content).toBe("a"); + ci.steer("switch", "b"); + expect(ci.deriveActiveContext().active!.content).toBe("switch"); // steer 是 live 最新 + ci.inject("after"); + expect(ci.deriveActiveContext().active!.content).toBe("after"); + ci.followup("newtask"); + expect(ci.deriveActiveContext().active!.content).toBe("newtask"); + }); + + it("不变式:fail-closed unusable——空/空白 content 拒绝注册(不入寄存器表,无半注册)", () => { + const ci = softCi(); + const before = ci.deriveActiveContext().injections.length; + expect(() => ci.inject("")).toThrow(); + expect(() => ci.steer(" ")).toThrow(); + expect(() => ci.followup("\t")).toThrow(); + // 抛错后寄存器表不变(无半注册) + expect(ci.deriveActiveContext().injections.length).toBe(before); + }); + + it("不变式:fail-closed 拒绝零宽 Default_Ignorable(U+200B/ZWJ)——trim() 不剥这些,须手动剥", () => { + const ci = softCi(); + // U+200B 不被 String.prototype.trim() 剥离(语言事实)→ 须手动剥 + const zwsp = "​"; // U+200B + expect(zwsp.trim().length).toBe(1); // 证实 trim 不剥(故需 INVISIBLE_CHARS) + expect(() => ci.inject(zwsp)).toThrow(); // 已修复:零宽被剥 → 判空 → 抛 + expect(() => ci.steer(zwsp, "b")).toThrow(); + expect(() => ci.followup(zwsp)).toThrow(); + // ZWJ (U+200D) 同理 + const zwj = "‍"; + expect(zwj.trim().length).toBe(1); + expect(() => ci.inject(zwj)).toThrow(); + // BOM (U+FEFF) —— 注意:U+FEFF 属 ECMAScript WhiteSpace 故 trim() 会剥, + // 但 assertContent 的 INVISIBLE_CHARS 兜底也剥,纯 BOM 仍判空 → fail-closed 抛 + const bom = ""; + expect(() => ci.inject(bom)).toThrow(); + // 混合:零宽 + 普通空格 → 仍判空抛错 + expect(() => ci.inject(" ​ ")).toThrow(); + }); + + it("不变式:可见但含零宽的 content 仍接受(零宽不作为唯一判空依据,只剥后判)", () => { + const ci = softCi(); + const mixed = "reg​map"; // 含 U+200B 但有可见字符 + const inj = ci.inject(mixed); + expect(inj.content).toBe(mixed); + }); + + it("不变式:appendEntry 下沉 = 寄存器表全量(每条注入经 sink 落库一次,type 恒定)", () => { + const { sink, calls } = makeSink(); + const ci = new ContextInjector({ appendEntry: sink, deepFreeze: false }); + ci.inject("a"); + ci.steer("b", "boardB"); + ci.followup("c"); + expect(calls).toHaveLength(3); + expect(calls.every((c) => c.type === CONTEXT_INJECTION_TYPE)).toBe(true); + expect((calls[0]!.data as Injection).content).toBe("a"); + expect((calls[1]!.data as Injection).boardId).toBe("boardB"); + expect((calls[2]!.data as Injection).phase).toBe("followup"); + // sink 数据 === 寄存器表(同一引用,append 顺序一致) + const ctx = ci.deriveActiveContext(); + expect(ctx.injections.map((i) => i.content)).toEqual( + calls.map((c) => (c.data as Injection).content), + ); + }); + + it("不变式:无 appendEntry sink 时不抛错(纯内存模式)", () => { + const ci = softCi(); // 无 appendEntry + expect(() => ci.inject("a")).not.toThrow(); + expect(() => ci.snapshot()).not.toThrow(); + expect(() => ci.deriveActiveContext()).not.toThrow(); + }); + + it("不变式:sink 收到的 Injection 与 register 返回值同一引用(不复制)", () => { + const { sink, calls } = makeSink(); + const ci = new ContextInjector({ appendEntry: sink, deepFreeze: false }); + const ret = ci.inject("same-ref"); + expect(calls[0]!.data).toBe(ret); // 同一引用 + }); + + it("不变式:toSessionEntry 产出 PbaSessionEntry 形状(type/data/seq/ts 四字段)", () => { + const inj: Injection = { + phase: "steer", + content: "switch", + boardId: "s100", + nextStep: true, + nextTurn: false, + }; + const entry = toSessionEntry(inj, 7, 1730000000000); + expect(entry).toMatchObject({ + type: CONTEXT_INJECTION_TYPE, + data: inj, + seq: 7, + ts: 1730000000000, + }); + // 结构守恒:恰好四键 + expect(Object.keys(entry).sort()).toEqual(["data", "seq", "ts", "type"]); + }); + + it("不变式:toSessionEntry 默认 ts = Date.now()(正数 epoch ms)", () => { + const inj: Injection = { phase: "inject", content: "x", nextStep: true, nextTurn: false }; + const before = Date.now(); + const entry = toSessionEntry(inj, 1); + const after = Date.now(); + expect(entry.ts).toBeGreaterThanOrEqual(before); + expect(entry.ts).toBeLessThanOrEqual(after); + }); + + it("不变式:toSessionEntry 是纯函数(无副作用,多次调用等价)", () => { + const inj: Injection = { phase: "inject", content: "x", nextStep: true, nextTurn: false }; + const e1 = toSessionEntry(inj, 1, 1000); + const e2 = toSessionEntry(inj, 1, 1000); + expect(e1.type).toBe(e2.type); + expect(e1.seq).toBe(e2.seq); + expect(e1.ts).toBe(e2.ts); + expect(e1.data).toBe(e2.data); // 同引用(data 不复制) + }); + + it("不变式:toSessionEntry type 恒为 CONTEXT_INJECTION_TYPE('context-injection')", () => { + const inj: Injection = { phase: "inject", content: "x", nextStep: true, nextTurn: false }; + for (const seq of [0, 1, 99, 1_000_000]) { + expect(toSessionEntry(inj, seq, 1000).type).toBe(CONTEXT_INJECTION_TYPE); + } + }); + + it("不变式:INJECTION_PHASES 恒为 ['inject','steer','followup'](顺序固定)", () => { + expect([...INJECTION_PHASES]).toEqual(["inject", "steer", "followup"]); + }); + + it("不变式:CONTEXT_INJECTION_TYPE 恒为 'context-injection'", () => { + expect(CONTEXT_INJECTION_TYPE).toBe("context-injection"); + expect(typeof CONTEXT_INJECTION_TYPE).toBe("string"); + }); + + it("不变式:snapshot 取代更早快照——live 永远由最新 steer/followup 决定(更早被取代)", () => { + const ci = softCi(); + ci.steer("first board", "b1"); + ci.inject("r1"); + ci.steer("second board", "b2"); + ci.inject("r2"); + const snap = ci.snapshot(); + // 更早的 steer("first board") 被取代 → live 不含 + expect(snap.content).not.toContain("first board"); + expect(snap.content).toContain("second board"); + expect(snap.boardId).toBe("b2"); + }); + + it("不变式:boardId 在 live 中取最新(steer 之后的 inject 不覆盖 boardId)", () => { + const ci = softCi(); + ci.steer("board A", "a"); + ci.inject("reg after A"); // inject 无 boardId,不覆盖 + const snap = ci.snapshot(); + expect(snap.boardId).toBe("a"); + ci.steer("board B", "b"); + expect(ci.snapshot().boardId).toBe("b"); // 最新 steer 的 boardId + }); +}); + +// ============================================================================ +// 7. 变异测试(Mutation Testing)—— 5 个植入 bug(A-E)的逻辑副本 +// +// 机制: +// - BuggyCI 是 ContextInjector 的忠实内联副本,按 `bug` 选择植入一处缺陷。 +// - 默认(无 MUTATION_BUG env)整个 describe 块 skipIf 跳过 → 文件全绿。 +// - 设 MUTATION_BUG=A/B/C/D/E 时,仅对应 bug 的 it 运行,断言【正确契约行为】→ +// 副本因 bug 产出错误结果 → 该 it FAIL → bug 被杀。 +// +// 植入 bug 清单(每个 bug + 杀它的测试): +// A. computeLiveInjections slice(pivot+1):漏掉 pivot 的 steer/followup → live 缺该条。 +// 杀它的测试:steer 后 snapshot content 须含 steer 文本(live 应含 steer)。 +// B. snapshot content join 用 "\n" 非 "\n\n":分隔符变窄。 +// 杀它的测试:双 inject snapshot content === "a\n\nb"(严格相等)。 +// C. assertContent 不 trim:纯空白 content 被接受。 +// 杀它的测试:纯空白 followup 须抛错(fail-closed)。 +// D. clear() 漏 reset snapshotSeq:清空后新快照 id 错位。 +// 杀它的测试:clear→snapshot→steer 的 replacesSnapshot 须为 "snap-1"。 +// E. deriveActiveContext active 取 live[0] 而非 live[last]:active 指向最旧。 +// 杀它的测试:多 inject 后 active.content === 最新一条(非最旧)。 +// ============================================================================ + +const MUTATION = (process.env.MUTATION_BUG ?? "") as "" | "A" | "B" | "C" | "D" | "E"; + +type BugId = "A" | "B" | "C" | "D" | "E"; + +const SNAP_PREFIX = "snap-"; + +const INVISIBLE_CHARS_COPY = /[​‌‍⁠-]/g; + +/** localDeepFreeze:deepFreeze 的忠实副本(递归冻结)。 */ +function localDeepFreeze(value: T): T { + if (value === null || typeof value !== "object") return value; + if (Array.isArray(value)) { + for (const v of value) localDeepFreeze(v); + } else { + for (const v of Object.values(value as Record)) localDeepFreeze(v); + } + Object.freeze(value); + return value; +} + +/** + * liveOf:computeLiveInjections 的忠实副本。 + * bug=A 时 slice(pivot+1) 漏掉 pivot 的 steer/followup。 + */ +function liveOf(injections: Injection[], bug: BugId): Injection[] { + let pivot = -1; + for (let i = injections.length - 1; i >= 0; i--) { + const phase = injections[i]!.phase; + if (phase === "steer" || phase === "followup") { + pivot = i; + break; + } + } + if (pivot === -1) return [...injections]; + return bug === "A" ? injections.slice(pivot + 1) : injections.slice(pivot); +} + +/** BuggyCI:ContextInjector 内联副本,按 bug 植入一处缺陷。 */ +class BuggyCI { + private appendEntry: InjectionSink | undefined; + private useFreeze: boolean; + private injections: Injection[] = []; + private snapshots: Array<{ id: string; content: string; boardId?: string; ts: number }> = []; + private snapshotSeq = 0; + private bug: BugId; + + constructor(bug: BugId, opts: { appendEntry?: InjectionSink; deepFreeze?: boolean } = {}) { + this.bug = bug; + this.appendEntry = opts.appendEntry; + this.useFreeze = opts.deepFreeze ?? true; + } + + private assertContent(content: string): void { + // BUG C: 不 trim(也不剥零宽)→ 纯空白被接受 + if (this.bug === "C") { + if (typeof content !== "string" || content.length === 0) { + throw new Error("bad content"); + } + return; + } + // 忠实副本:剥零宽 + trim(与真实一致) + if (typeof content !== "string" || content.replace(INVISIBLE_CHARS_COPY, "").trim().length === 0) { + throw new Error("bad content"); + } + } + + private currentSnapshotId(): string | undefined { + return this.snapshots.length > 0 ? this.snapshots[this.snapshots.length - 1]!.id : undefined; + } + + private register(p: { + phase: InjectionPhase; + content: string; + boardId?: string; + nextStep: boolean; + nextTurn: boolean; + replacesSnapshot?: string; + }): Injection { + const inj: Injection = { + phase: p.phase, + content: p.content, + boardId: p.boardId, + nextStep: p.nextStep, + nextTurn: p.nextTurn, + replacesSnapshot: p.replacesSnapshot, + }; + const frozen = this.useFreeze ? (localDeepFreeze(inj) as Injection) : inj; + this.injections.push(frozen); + if (this.appendEntry) this.appendEntry(CONTEXT_INJECTION_TYPE, frozen); + return frozen; + } + + inject(content: string): Injection { + this.assertContent(content); + return this.register({ phase: "inject", content, nextStep: true, nextTurn: false }); + } + + steer(content: string, boardId?: string): Injection { + this.assertContent(content); + return this.register({ + phase: "steer", + content, + boardId, + nextStep: true, + nextTurn: false, + replacesSnapshot: this.currentSnapshotId(), + }); + } + + followup(content: string): Injection { + this.assertContent(content); + return this.register({ + phase: "followup", + content, + nextStep: false, + nextTurn: true, + replacesSnapshot: this.currentSnapshotId(), + }); + } + + snapshot(): RuntimeSnapshot { + const live = liveOf(this.injections, this.bug); + // BUG B: join 用 "\n" 非 "\n\n" + const content = + this.bug === "B" ? live.map((i) => i.content).join("\n") : live.map((i) => i.content).join("\n\n"); + let boardId: string | undefined; + for (let i = live.length - 1; i >= 0; i--) { + if (live[i]!.boardId !== undefined) { + boardId = live[i]!.boardId; + break; + } + } + this.snapshotSeq += 1; + const internal = { id: `${SNAP_PREFIX}${this.snapshotSeq}`, content, boardId, ts: Date.now() }; + this.snapshots.push(internal); + const ext: RuntimeSnapshot = { content: internal.content, boardId: internal.boardId, ts: internal.ts }; + return this.useFreeze ? (localDeepFreeze(ext) as RuntimeSnapshot) : ext; + } + + deriveActiveContext(): ActiveContext { + const live = liveOf(this.injections, this.bug); + // BUG E: active 取 live[0] 而非 live[last] + const active = + live.length > 0 + ? this.bug === "E" + ? (live[0] as Injection) + : (live[live.length - 1] as Injection) + : null; + const view: ActiveContext = { + injections: this.useFreeze + ? (localDeepFreeze([...this.injections]) as ReadonlyArray) + : [...this.injections], + active, + }; + return this.useFreeze ? (localDeepFreeze(view) as ActiveContext) : view; + } + + clear(phase?: InjectionPhase): void { + if (phase !== undefined) { + for (let i = this.injections.length - 1; i >= 0; i--) { + if (this.injections[i]!.phase === phase) this.injections.splice(i, 1); + } + return; + } + this.injections.length = 0; + this.snapshots.length = 0; + // BUG D: 漏 reset snapshotSeq + if (this.bug !== "D") this.snapshotSeq = 0; + } +} + +describe.skipIf(!MUTATION)("变异测试:植入 bug 副本(MUTATION_BUG=A/B/C/D/E 触发)", () => { + it.skipIf(MUTATION !== "A")( + "BUG A 被 killed:steer 后 snapshot content 须含 steer 文本(副本 slice(pivot+1) 漏 pivot → 缺 steer 文本 → toContain 失败)", + () => { + const ci = new BuggyCI("A", { deepFreeze: false }); + ci.inject("old reg"); + ci.steer("switch board", "b"); + ci.inject("new reg"); + const snap = ci.snapshot(); + // 真实:live=[steer,inject] → "switch board\n\nnew reg" + // 副本 A:slice(pivot+1) → [inject] → "new reg"(缺 steer 文本) + expect(snap.content).toContain("switch board"); + }, + ); + + it.skipIf(MUTATION !== "B")( + 'BUG B 被 killed:双 inject snapshot content === "a\\n\\nb"(副本 join 用 "\\n" → 得 "a\\nb" → 严格相等失败)', + () => { + const ci = new BuggyCI("B", { deepFreeze: false }); + ci.inject("a"); + ci.inject("b"); + const snap = ci.snapshot(); + // 真实:"a\n\nb";副本 B:"a\nb" + expect(snap.content).toBe("a\n\nb"); + }, + ); + + it.skipIf(MUTATION !== "C")( + "BUG C 被 killed:纯空白 followup 须抛错(副本不 trim → 不抛 → toThrow 失败)", + () => { + const ci = new BuggyCI("C", { deepFreeze: false }); + // 真实:trim 归零 → 抛;副本 C:length>0 不抛 + expect(() => ci.followup(" ")).toThrow(); + }, + ); + + it.skipIf(MUTATION !== "D")( + 'BUG D 被 killed:clear() 后 snapshot→steer 的 replacesSnapshot 须为 "snap-1"(副本漏 reset seq → 得 "snap-2" → 严格相等失败)', + () => { + const ci = new BuggyCI("D", { deepFreeze: false }); + ci.inject("x"); + ci.snapshot(); // seq→1, id snap-1 + ci.clear(); // 真实 reset seq→0;副本 D 漏 reset(seq 保持 1) + ci.snapshot(); // 真实 id snap-1;副本 D id snap-2 + const s = ci.steer("again", "b"); + // 真实:snap-1;副本 D:snap-2 + expect(s.replacesSnapshot).toBe("snap-1"); + }, + ); + + it.skipIf(MUTATION !== "E")( + "BUG E 被 killed:多 inject 后 deriveActiveContext.active.content === 最新一条(副本取 live[0] → 得最旧 → 严格相等失败)", + () => { + const ci = new BuggyCI("E", { deepFreeze: false }); + ci.inject("oldest"); + ci.inject("middle"); + ci.inject("newest"); + const ctx = ci.deriveActiveContext(); + // 真实:active = live[last] = "newest";副本 E:active = live[0] = "oldest" + expect(ctx.active!.content).toBe("newest"); + }, + ); +}); diff --git a/tests/doc-sync.test.ts b/tests/doc-sync.test.ts new file mode 100644 index 0000000..5e47c34 --- /dev/null +++ b/tests/doc-sync.test.ts @@ -0,0 +1,1993 @@ +/** + * @module doc-sync.test + * + * T10 —— CI 质量门三件套(doc-sync / e2e-snapshot / DEFAULT_DOC_ANCHORS) + * 完整测试套件(多方法论、测试前置、严到植入 bug 活不过)。 + * + * 被测对象(命名导出,按契约直接 import,mock 注入依赖): + * scripts/doc-sync.ts → checkDocSync / DEFAULT_DOC_ANCHORS / + * defaultReadFile / defaultGrepSymbol + * (类型契约 DocAnchor / DocSyncMismatch / + * DocSyncResult / ReadFile / GrepSymbol) + * scripts/e2e-snapshot.ts → compareSnapshot + * (类型契约 SnapshotDiff) + * .github/workflows/ci.yml → 契约:quality-gate job 调 checkDocSync 走 + * per-file 100% 覆盖门 + tsc + doc-sync; + * type-drift job 周期跑(本套件只测它调的纯函数, + * 不测 IO 装配细节)。 + * + * 依赖注入:readFile / grepSymbol 全 mock;无 pi 运行时 / 无硬件 / 无网络。 + * defaultReadFile / defaultGrepSymbol 用本仓稳定文件做轻量真 fs 集成 + * (钉住 CI 装配契约:缺文件抛错、命中返回 1-indexed 行号)。 + * + * 测试方法论(每个 describe 块标注方法论名): + * - 等价类划分(有效 / 无效 / 边界类) + * - 边界值分析(off-by-one / 空 / 单元素 / min / max / 越界) + * - 决策表(双侧组合输入 → 期望,覆盖全分支) + * - 状态转换(fail-closed 优先序链 + 短路 + 不可达态 + 重入) + * - 变异测试:8 个 seeded bug 内联副本(faithful copy + 恰好一处变异), + * 每个 it 断言:真代码满足 spec 谓词、buggy 副本违反 spec 谓词、 + * 且 `expect(() => expect(buggyResult).toBe(期望)).toThrow()` + * 字面演示「拿 buggy 当 SUT 跑同一 spec 断言必抛 AssertionError」 + * = 该 spec 单独跑 buggy 变体时 FAIL = bug 被杀。 + * - 对抗 / fuzz(null / undefined / 巨大 / NaN / Infinity / 循环引用 / + * 负行号 / 空符号 / 并发重入 / 非整数行号) + * - 元蜕变 / 不变式(自反 / 对称 / 传递 / 单调 / 确定性 / 升序 / + * freeze→篡改抛 TypeError / waterfall 短路 / fail-closed unusable=拒 / + * append 两次=replay 等价) + * + * 门: + * 1. npx vitest run tests/doc-sync.test.ts # 真实代码 all green + * 2. 每个 seeded bug 变体:spec 谓词在 buggy 副本上为 false(bug 被杀)—— + * 本套件用 `expect(() => expect(buggy...).toBe(...)).toThrow()` 字面验证。 + * + * 真实 bug(非植入):当前源码未发现真实缺陷(serializeLeaf 的 -0 / symbol / + * bigint 特判均已落地且经正向 it 钉住;见 StructuredOutput findings 为空)。 + * + * 见架构设计文档_v3.md §5.9(CI 质量门:doc-sync 文档门 + 真实 API snapshot)。 + */ + +import { describe, it, expect } from "vitest"; +import { + checkDocSync, + DEFAULT_DOC_ANCHORS, + defaultReadFile, + defaultGrepSymbol, +} from "../scripts/doc-sync.js"; +import type { + DocAnchor, + DocSyncResult, + ReadFile, + GrepSymbol, +} from "../scripts/doc-sync.js"; +import { compareSnapshot } from "../scripts/e2e-snapshot.js"; +import type { SnapshotDiff } from "../scripts/e2e-snapshot.js"; + +// ============================================================================ +// 工具:构造可注入的 readFile / grepSymbol / anchor +// ============================================================================ + +/** + * 按行表构造 readFile:lineTable[path] = 文本。 + * 缺省返回 ""(模拟空文件 / 不可读占位,不抛——抛错用 throwingReader)。 + */ +function readerFrom(lineTable: Record): ReadFile { + return (p) => lineTable[p] ?? ""; +} + +/** + * 按「file:symbol → 行号」表构造 grepSymbol;缺省 -1(未命中)。 + * 显式表驱动,杜绝 defaultGrepSymbol 的子串巧合,让 grep 行为完全确定。 + */ +function greperFrom(table: Record): GrepSymbol { + return (file, symbol) => table[`${file}:${symbol}`] ?? -1; +} + +/** 一抛即抛的 readFile,用于 fail-closed 注入。 */ +function throwingReader(msg = "ENOENT"): ReadFile { + return () => { + throw new Error(msg); + }; +} + +/** 构造一条锚点(默认全字段合法,调用方可覆盖任意字段)。 */ +function anchor(over: Partial = {}): DocAnchor { + return { + docFile: "doc.md", + docLine: 2, + codeFile: "src/core/tool-pipeline.ts", + codeSymbol: "ToolPipeline", + ...over, + }; +} + +// ============================================================================ +// 变异测试:seeded bug 内联副本(faithful copy,仅一处变异) +// ============================================================================ +// +// 每个变体是「真实逻辑的逐行忠实副本」+ 恰好一处变异。下方「变异测试」 +// describe 对每个变体断言: +// (a) 真代码满足 spec 谓词; +// (b) buggy 副本违反 spec 谓词; +// (c) 字面演示:`expect(() => expect(buggyResult).toBe(期望)).toThrow()` —— +// 即「拿 buggy 当 SUT 跑同一 spec 断言必抛 AssertionError」,等价于 +// 「该 spec 单独跑 buggy 变体时 FAIL」= bug 被杀。 + +/** + * MUTATION M1 —— checkDocSync:`codeLine <= 0` 改 `codeLine < 0`。 + * 后果:grepSymbol 返回 0(非法行号)被当「命中」放行,破坏 fail-closed。 + * 杀它的测试:grep 返回 0 须 mismatch(fail-closed)。 + */ +function checkDocSync_bug_ltLeq(opts: { + readFile: ReadFile; + anchors: readonly DocAnchor[]; + grepSymbol: GrepSymbol; +}): DocSyncResult { + const { readFile, anchors, grepSymbol } = opts; + const mismatches: DocSyncResult["mismatches"][number][] = []; + for (const a of anchors) { + let docText: string; + try { + docText = readFile(a.docFile); + } catch { + mismatches.push({ anchor: a, reason: `doc file not readable: ${a.docFile}` }); + continue; + } + const docLines = docText.split("\n"); + const docLine = docLines[a.docLine - 1]; + if (docLine === undefined) { + mismatches.push({ + anchor: a, + reason: `doc line ${a.docLine} out of range (file has ${docLines.length} lines)`, + }); + continue; + } + if (!docLine.includes(a.codeFile)) { + mismatches.push({ + anchor: a, + reason: `doc line ${a.docLine} does not reference "${a.codeFile}"`, + }); + continue; + } + let codeLine: number; + try { + codeLine = grepSymbol(a.codeFile, a.codeSymbol); + } catch { + mismatches.push({ anchor: a, reason: `code file not readable: ${a.codeFile}` }); + continue; + } + // MUTATION: `<= 0` → `< 0` + if (codeLine < 0) { + mismatches.push({ + anchor: a, + reason: `symbol "${a.codeSymbol}" not found in ${a.codeFile}`, + }); + } + } + return { ok: mismatches.length === 0, mismatches }; +} + +/** + * MUTATION M2 —— checkDocSync:行索引 off-by-one, + * `docLines[docLine - 1]` 改 `docLines[docLine]`。 + * 后果:docLine=1 读到第 2 行而非第 1 行,错位一行;锚点对齐校验形同虚设。 + * 杀它的测试:docLine=1 须读首行(含 codeFile)→ ok=true。 + */ +function checkDocSync_bug_offByOne(opts: { + readFile: ReadFile; + anchors: readonly DocAnchor[]; + grepSymbol: GrepSymbol; +}): DocSyncResult { + const { readFile, anchors, grepSymbol } = opts; + const mismatches: DocSyncResult["mismatches"][number][] = []; + for (const a of anchors) { + let docText: string; + try { + docText = readFile(a.docFile); + } catch { + mismatches.push({ anchor: a, reason: `doc file not readable: ${a.docFile}` }); + continue; + } + const docLines = docText.split("\n"); + // MUTATION: `a.docLine - 1` → `a.docLine` + const docLine = docLines[a.docLine]; + if (docLine === undefined) { + mismatches.push({ + anchor: a, + reason: `doc line ${a.docLine} out of range (file has ${docLines.length} lines)`, + }); + continue; + } + if (!docLine.includes(a.codeFile)) { + mismatches.push({ + anchor: a, + reason: `doc line ${a.docLine} does not reference "${a.codeFile}"`, + }); + continue; + } + let codeLine: number; + try { + codeLine = grepSymbol(a.codeFile, a.codeSymbol); + } catch { + mismatches.push({ anchor: a, reason: `code file not readable: ${a.codeFile}` }); + continue; + } + if (codeLine <= 0) { + mismatches.push({ + anchor: a, + reason: `symbol "${a.codeSymbol}" not found in ${a.codeFile}`, + }); + } + } + return { ok: mismatches.length === 0, mismatches }; +} + +/** + * MUTATION M3 —— checkDocSync:docFile 读抛错时静默吞掉(catch 内不 push + * mismatch,仅 continue)。 + * 后果:不可读文档不再 fail-closed,锚点静默通过,文档门失守。 + * 杀它的测试:docFile 不可读 须 mismatch(ok=false)。 + */ +function checkDocSync_bug_swallowRead(opts: { + readFile: ReadFile; + anchors: readonly DocAnchor[]; + grepSymbol: GrepSymbol; +}): DocSyncResult { + const { readFile, anchors, grepSymbol } = opts; + const mismatches: DocSyncResult["mismatches"][number][] = []; + for (const a of anchors) { + let docText: string; + try { + docText = readFile(a.docFile); + } catch { + // MUTATION: 漏 push mismatch(静默吞错,放行) + continue; + } + const docLines = docText.split("\n"); + const docLine = docLines[a.docLine - 1]; + if (docLine === undefined) { + mismatches.push({ + anchor: a, + reason: `doc line ${a.docLine} out of range (file has ${docLines.length} lines)`, + }); + continue; + } + if (!docLine.includes(a.codeFile)) { + mismatches.push({ + anchor: a, + reason: `doc line ${a.docLine} does not reference "${a.codeFile}"`, + }); + continue; + } + let codeLine: number; + try { + codeLine = grepSymbol(a.codeFile, a.codeSymbol); + } catch { + mismatches.push({ anchor: a, reason: `code file not readable: ${a.codeFile}` }); + continue; + } + if (codeLine <= 0) { + mismatches.push({ + anchor: a, + reason: `symbol "${a.codeSymbol}" not found in ${a.codeFile}`, + }); + } + } + return { ok: mismatches.length === 0, mismatches }; +} + +/** + * 内部副本:serializeLeaf 系列(faithful copy,供下方变异变体复用)。 + * 与 scripts/e2e-snapshot.ts 的 serializeLeaf 逐行一致(含 -0/symbol/bigint 特判)。 + */ +function serializeLeafFaithful(value: unknown): string { + if (value === undefined) return "undefined"; + if (typeof value === "function") return "function"; + if (typeof value === "symbol") return "symbol"; + if (typeof value === "bigint") return `bigint:${value}`; + if (typeof value === "number") { + if (Object.is(value, -0)) return "-0"; + if (Number.isNaN(value)) return "NaN"; + if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity"; + } + const serialized = JSON.stringify(value); + return serialized === undefined ? "undefined" : serialized; +} + +function isPlainObjectFaithful(value: object): boolean { + const proto = Object.getPrototypeOf(value); + return proto === null || proto === Object.prototype; +} + +function joinPathFaithful(prefix: string, segment: string): string { + return prefix === "" ? segment : `${prefix}.${segment}`; +} + +function flattenFaithful(value: unknown, prefix: string, out: Map): void { + if (value === null || typeof value !== "object") { + out.set(prefix, serializeLeafFaithful(value)); + return; + } + if (Array.isArray(value)) { + if (value.length === 0) { + out.set(prefix, "[]"); + return; + } + for (let i = 0; i < value.length; i++) { + flattenFaithful(value[i], joinPathFaithful(prefix, String(i)), out); + } + return; + } + if (!isPlainObjectFaithful(value)) { + out.set(prefix, serializeLeafFaithful(value)); + return; + } + const entries = Object.entries(value as Record); + if (entries.length === 0) { + out.set(prefix, "{}"); + return; + } + for (const [key, child] of entries) { + flattenFaithful(child, joinPathFaithful(prefix, key), out); + } +} + +/** 共用 diff 装配(拍平两侧 + 集合运算 + 升序),供变体复用。 */ +function assembleDiff( + actualFlat: Map, + baselineFlat: Map, +): SnapshotDiff { + const added: string[] = []; + const removed: string[] = []; + const changed: string[] = []; + for (const [path, value] of actualFlat) { + const baselineValue = baselineFlat.get(path); + if (baselineValue === undefined) { + added.push(path); + } else if (baselineValue !== value) { + changed.push(path); + } + } + for (const [path] of baselineFlat) { + if (!actualFlat.has(path)) { + removed.push(path); + } + } + added.sort(); + removed.sort(); + changed.sort(); + return { + match: added.length === 0 && removed.length === 0 && changed.length === 0, + added, + removed, + changed, + }; +} + +/** + * MUTATION M4 —— compareSnapshot:changed 检测 `!==` 改 `===`。 + * 后果:值相同时误报 changed、值不同时漏报 → 回归漂移检测双向失真。 + * 杀它的测试:b 值不同须报 changed(含 "b")。 + */ +function compareSnapshot_bug_invertChanged(actual: unknown, baseline: unknown): SnapshotDiff { + const actualFlat = new Map(); + const baselineFlat = new Map(); + flattenFaithful(actual, "", actualFlat); + flattenFaithful(baseline, "", baselineFlat); + const added: string[] = []; + const removed: string[] = []; + const changed: string[] = []; + for (const [path, value] of actualFlat) { + const baselineValue = baselineFlat.get(path); + if (baselineValue === undefined) { + added.push(path); + } else if (baselineValue === value) { + // MUTATION: `!==` → `===` + changed.push(path); + } + } + for (const [path] of baselineFlat) { + if (!actualFlat.has(path)) { + removed.push(path); + } + } + added.sort(); + removed.sort(); + changed.sort(); + return { + match: added.length === 0 && removed.length === 0 && changed.length === 0, + added, + removed, + changed, + }; +} + +/** + * MUTATION M5 —— compareSnapshot:空数组叶子 `"[]"` 改 `"{}"`(与空对象碰撞)。 + * 后果:空数组与空对象被当等价,结构即值的不变式被破坏。 + * 杀它的测试:[] vs {} 须 match=false("[]" ≠ "{}")。 + */ +function compareSnapshot_bug_emptyArrayAsObject(actual: unknown, baseline: unknown): SnapshotDiff { + function flatten(value: unknown, prefix: string, out: Map): void { + if (value === null || typeof value !== "object") { + out.set(prefix, serializeLeafFaithful(value)); + return; + } + if (Array.isArray(value)) { + if (value.length === 0) { + // MUTATION: "[]" → "{}" + out.set(prefix, "{}"); + return; + } + for (let i = 0; i < value.length; i++) { + flatten(value[i], joinPathFaithful(prefix, String(i)), out); + } + return; + } + if (!isPlainObjectFaithful(value)) { + out.set(prefix, serializeLeafFaithful(value)); + return; + } + const entries = Object.entries(value as Record); + if (entries.length === 0) { + out.set(prefix, "{}"); + return; + } + for (const [key, child] of entries) { + flatten(child, joinPathFaithful(prefix, key), out); + } + } + const actualFlat = new Map(); + const baselineFlat = new Map(); + flatten(actual, "", actualFlat); + flatten(baseline, "", baselineFlat); + return assembleDiff(actualFlat, baselineFlat); +} + +/** + * MUTATION M6 —— compareSnapshot:flatten 叶子守卫 + * `value === null || typeof value !== "object"` 漏掉 null 判定 + * (删 `value === null ||`,仅留 `typeof value !== "object"`)。 + * 后果:null(typeof "object")落入后续分支 → Array.isArray(null)=false → + * isPlainObject(null) 调 Object.getPrototypeOf(null) 抛 TypeError。 + * 自反 null 比较直接崩。 + * 杀它的测试:null vs null 须 match=true(不抛)。 + */ +function compareSnapshot_bug_dropNullGuard(actual: unknown, baseline: unknown): SnapshotDiff { + function flatten(value: unknown, prefix: string, out: Map): void { + // MUTATION: 删 `value === null ||`,仅留 `typeof value !== "object"` + if (typeof value !== "object") { + out.set(prefix, serializeLeafFaithful(value)); + return; + } + if (Array.isArray(value)) { + if (value.length === 0) { + out.set(prefix, "[]"); + return; + } + for (let i = 0; i < value.length; i++) { + flatten(value[i], joinPathFaithful(prefix, String(i)), out); + } + return; + } + if (!isPlainObjectFaithful(value as object)) { + out.set(prefix, serializeLeafFaithful(value)); + return; + } + const entries = Object.entries(value as Record); + if (entries.length === 0) { + out.set(prefix, "{}"); + return; + } + for (const [key, child] of entries) { + flatten(child, joinPathFaithful(prefix, key), out); + } + } + const actualFlat = new Map(); + const baselineFlat = new Map(); + flatten(actual, "", actualFlat); + flatten(baseline, "", baselineFlat); + return assembleDiff(actualFlat, baselineFlat); +} + +/** + * MUTATION M7 —— compareSnapshot:空对象叶子 `"{}"` 改 `"[]"`(与空数组碰撞)。 + * 后果:空对象与空数组被当等价;与 M5 对称,从对象侧破坏结构即值不变式。 + * 杀它的测试:{} vs [] 须 match=false("{}" ≠ "[]")。 + */ +function compareSnapshot_bug_emptyObjectAsArray(actual: unknown, baseline: unknown): SnapshotDiff { + function flatten(value: unknown, prefix: string, out: Map): void { + if (value === null || typeof value !== "object") { + out.set(prefix, serializeLeafFaithful(value)); + return; + } + if (Array.isArray(value)) { + if (value.length === 0) { + out.set(prefix, "[]"); + return; + } + for (let i = 0; i < value.length; i++) { + flatten(value[i], joinPathFaithful(prefix, String(i)), out); + } + return; + } + if (!isPlainObjectFaithful(value)) { + out.set(prefix, serializeLeafFaithful(value)); + return; + } + const entries = Object.entries(value as Record); + if (entries.length === 0) { + // MUTATION: "{}" → "[]" + out.set(prefix, "[]"); + return; + } + for (const [key, child] of entries) { + flatten(child, joinPathFaithful(prefix, key), out); + } + } + const actualFlat = new Map(); + const baselineFlat = new Map(); + flatten(actual, "", actualFlat); + flatten(baseline, "", baselineFlat); + return assembleDiff(actualFlat, baselineFlat); +} + +/** + * MUTATION M8 —— compareSnapshot:serializeLeaf 漏 -0 特判 + * (删 `if (Object.is(value, -0)) return "-0";` 一行)。 + * 后果:-0 落入 JSON.stringify 得 "0",与正零 0 碰撞;Object.is(-0,0)===false + * 而 match=true → 违反「不同语义值 → 不同串」不变式。 + * 杀它的测试:-0 vs 0 须 match=false。 + */ +function serializeLeaf_bug_noNegZero(value: unknown): string { + if (value === undefined) return "undefined"; + if (typeof value === "function") return "function"; + if (typeof value === "symbol") return "symbol"; + if (typeof value === "bigint") return `bigint:${value}`; + if (typeof value === "number") { + // MUTATION: 删 -0 特判行 + if (Number.isNaN(value)) return "NaN"; + if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity"; + } + const serialized = JSON.stringify(value); + return serialized === undefined ? "undefined" : serialized; +} + +function compareSnapshot_bug_noNegZero(actual: unknown, baseline: unknown): SnapshotDiff { + function flatten(value: unknown, prefix: string, out: Map): void { + if (value === null || typeof value !== "object") { + out.set(prefix, serializeLeaf_bug_noNegZero(value)); + return; + } + if (Array.isArray(value)) { + if (value.length === 0) { + out.set(prefix, "[]"); + return; + } + for (let i = 0; i < value.length; i++) { + flatten(value[i], joinPathFaithful(prefix, String(i)), out); + } + return; + } + if (!isPlainObjectFaithful(value)) { + out.set(prefix, serializeLeaf_bug_noNegZero(value)); + return; + } + const entries = Object.entries(value as Record); + if (entries.length === 0) { + out.set(prefix, "{}"); + return; + } + for (const [key, child] of entries) { + flatten(child, joinPathFaithful(prefix, key), out); + } + } + const actualFlat = new Map(); + const baselineFlat = new Map(); + flatten(actual, "", actualFlat); + flatten(baseline, "", baselineFlat); + return assembleDiff(actualFlat, baselineFlat); +} + +/** MUTATION M9 —— DEFAULT_DOC_ANCHORS:漏 Object.freeze(深冻结不变式)。 */ +const BUGGY_ANCHORS_NO_FREEZE: DocAnchor[] = [...DEFAULT_DOC_ANCHORS]; + +// ============================================================================ +// 等价类划分 · checkDocSync(有效/无效/边界类) +// ============================================================================ + +describe("等价类划分 · checkDocSync(有效/无效/边界类)", () => { + // 有效类:双侧皆过 + it("有效类-双侧对齐 → ok=true / mismatches 空", () => { + const readFile = readerFrom({ + "doc.md": "第一行无关\n`src/core/tool-pipeline.ts`:实现 `ToolPipeline`\n第三行", + }); + const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 135 }); + const r = checkDocSync({ readFile, grepSymbol, anchors: [anchor()] }); + expect(r.ok).toBe(true); + expect(r.mismatches).toHaveLength(0); + }); + + // 无效类-A:文档侧飘(行不引用 codeFile) + it("无效类-文档侧飘(行不引用 codeFile)→ mismatch + reason 含 does not reference", () => { + const readFile = readerFrom({ "doc.md": "第一行\n第二行没提路径\n第三行" }); + const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 135 }); + const r = checkDocSync({ readFile, grepSymbol, anchors: [anchor()] }); + expect(r.ok).toBe(false); + expect(r.mismatches).toHaveLength(1); + expect(r.mismatches[0].reason).toContain("does not reference"); + }); + + // 无效类-B:代码侧飘(符号未命中,-1) + it("无效类-代码侧飘(grep -1)→ mismatch + reason 含 not found", () => { + const readFile = readerFrom({ "doc.md": "x\n`src/core/tool-pipeline.ts`:`ToolPipeline`\n" }); + const grepSymbol = greperFrom({}); + const r = checkDocSync({ readFile, grepSymbol, anchors: [anchor()] }); + expect(r.ok).toBe(false); + expect(r.mismatches[0].reason).toContain("not found"); + }); + + // 无效类-C:文档不可读(readFile 抛错) + it("无效类-文档不可读(readFile 抛错)→ mismatch + reason 含 not readable + 文件名", () => { + const r = checkDocSync({ + readFile: throwingReader(), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor()], + }); + expect(r.ok).toBe(false); + expect(r.mismatches[0].reason).toContain("not readable"); + expect(r.mismatches[0].reason).toContain("doc.md"); + }); + + // 无效类-D:代码侧抛错(grepSymbol 抛错) + it("无效类-代码侧抛错(grepSymbol 抛错)→ mismatch + reason 含 code file not readable", () => { + const readFile = readerFrom({ "doc.md": "x\n`src/core/tool-pipeline.ts`:`ToolPipeline`\n" }); + const grepSymbol: GrepSymbol = () => { + throw new Error("ENOENT"); + }; + const r = checkDocSync({ readFile, grepSymbol, anchors: [anchor()] }); + expect(r.ok).toBe(false); + expect(r.mismatches[0].reason).toContain("code file not readable"); + }); + + // 无效类-E:行越界(docLine 超出文件行数) + it("无效类-行越界 → mismatch + reason 含 out of range + 实际行数", () => { + const readFile = readerFrom({ "doc.md": "仅一行" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 99 })], + }); + expect(r.ok).toBe(false); + expect(r.mismatches[0].reason).toContain("out of range"); + expect(r.mismatches[0].reason).toContain("1 lines"); + }); +}); + +// ============================================================================ +// 边界值分析 · checkDocSync(off-by-one / 空 / 单元素 / min / max) +// ============================================================================ + +describe("边界值分析 · checkDocSync(off-by-one / 空 / 单元素 / min / max)", () => { + it("docLine=1(首行,min 有效)→ 行引用 codeFile 即过", () => { + const readFile = readerFrom({ "doc.md": "`src/core/tool-pipeline.ts` 在首行\n第二行" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 1 })], + }); + expect(r.ok).toBe(true); + }); + + it("docLine=N(末行,max 有效)→ 过", () => { + const readFile = readerFrom({ "doc.md": "第一行\n第二行\n`src/core/tool-pipeline.ts`" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 3 })], + }); + expect(r.ok).toBe(true); + }); + + it("docLine=N+1(末行后一行,off-by-one 越界)→ mismatch", () => { + const readFile = readerFrom({ "doc.md": "第一行\n第二行\n第三行" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 4 })], + }); + expect(r.ok).toBe(false); + expect(r.mismatches[0].reason).toContain("out of range"); + }); + + it("docLine=0(零值,非法 1-indexed)→ mismatch(越界)", () => { + const readFile = readerFrom({ "doc.md": "唯一一行含 src/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 0 })], + }); + expect(r.ok).toBe(false); + }); + + it("docLine 负值(-1)→ mismatch(越界)", () => { + const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: -1 })], + }); + expect(r.ok).toBe(false); + }); + + it("grepSymbol 返回 1(min 有效行号)→ 过", () => { + const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 2 })], + }); + expect(r.ok).toBe(true); + }); + + it("grepSymbol 返回 0(非法哨兵)→ mismatch(fail-closed)", () => { + const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 0 }), + anchors: [anchor({ docLine: 2 })], + }); + expect(r.ok).toBe(false); + expect(r.mismatches[0].reason).toContain("not found"); + }); + + it("grepSymbol 返回负值(-7)→ mismatch(fail-closed)", () => { + const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": -7 }), + anchors: [anchor({ docLine: 2 })], + }); + expect(r.ok).toBe(false); + expect(r.mismatches[0].reason).toContain("not found"); + }); + + it("grepSymbol 返回大正数(Number.MAX_SAFE_INTEGER)→ 过(>0 即命中)", () => { + const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ + "src/core/tool-pipeline.ts:ToolPipeline": Number.MAX_SAFE_INTEGER, + }), + anchors: [anchor({ docLine: 2 })], + }); + expect(r.ok).toBe(true); + }); + + it("单行文档 + 锚点指向该行 → 过", () => { + const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts 的 ToolPipeline" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 10 }), + anchors: [anchor({ docLine: 1 })], + }); + expect(r.ok).toBe(true); + }); + + it("空文档(readFile 返回 '')→ split 后 1 行空串 → 行不含 codeFile → mismatch", () => { + const readFile = readerFrom({ "doc.md": "" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 1 })], + }); + expect(r.ok).toBe(false); + expect(r.mismatches[0].reason).toContain("does not reference"); + }); + + it("docLine=N(末行)恰好含 codeFile,末尾无换行 → 过(split 不产生幽灵尾行越界)", () => { + // "a\nb\ncode" split('\n') = ['a','b','code'],3 行;docLine=3 命中 + const readFile = readerFrom({ "doc.md": "a\nb\nsrc/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 3 })], + }); + expect(r.ok).toBe(true); + }); + + it("文档末尾有换行 → split 产生尾空行,docLine 指向尾空行 → mismatch", () => { + // "a\nsrc/...\n" split = ['a','src/...',''],3 行 + const readFile = readerFrom({ "doc.md": "a\nsrc/core/tool-pipeline.ts\n" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 3 })], // 尾空行,不含 codeFile + }); + expect(r.ok).toBe(false); + expect(r.mismatches[0].reason).toContain("does not reference"); + }); + + it("单元素锚点清单(1 条全过)→ ok=true", () => { + const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 2 })], + }); + expect(r.ok).toBe(true); + expect(r.mismatches).toHaveLength(0); + }); +}); + +// ============================================================================ +// 决策表 · checkDocSync(双侧组合 → 期望,覆盖全分支) +// ============================================================================ + +describe("决策表 · checkDocSync 双侧分支全覆盖", () => { + // 决策表:6 条可达规则(continue 早退致后续列不影响结果) + // 列:docReadable | lineInRange | lineRefsCode | grepThrows | grepHit(>0) + // 规则1: N | - | - | - | - → mismatch "doc not readable" + // 规则2: Y | N | - | - | - → mismatch "out of range" + // 规则3: Y | Y | N | - | - → mismatch "does not reference" + // 规则4: Y | Y | Y | Y | - → mismatch "code file not readable" + // 规则5: Y | Y | Y | N | N(≤0) → mismatch "not found" + // 规则6: Y | Y | Y | N | Y(>0) → ok + const cases: { + name: string; + readFile: ReadFile; + grepSymbol: GrepSymbol; + a: DocAnchor; + expectOk: boolean; + reasonContains: string; + }[] = [ + { + name: "R1 文档不可读", + readFile: throwingReader(), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + a: anchor(), + expectOk: false, + reasonContains: "not readable", + }, + { + name: "R2 行越界", + readFile: readerFrom({ "doc.md": "仅一行" }), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + a: anchor({ docLine: 5 }), + expectOk: false, + reasonContains: "out of range", + }, + { + name: "R3 行不引用 codeFile", + readFile: readerFrom({ "doc.md": "第一\n第二行没提\n第三" }), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + a: anchor({ docLine: 2 }), + expectOk: false, + reasonContains: "does not reference", + }, + { + name: "R4 代码侧抛错", + readFile: readerFrom({ "doc.md": "第一\nsrc/core/tool-pipeline.ts\n第三" }), + grepSymbol: () => { + throw new Error("ENOENT"); + }, + a: anchor({ docLine: 2 }), + expectOk: false, + reasonContains: "code file not readable", + }, + { + name: "R5 符号未命中(-1)", + readFile: readerFrom({ "doc.md": "第一\nsrc/core/tool-pipeline.ts\n第三" }), + grepSymbol: greperFrom({}), + a: anchor({ docLine: 2 }), + expectOk: false, + reasonContains: "not found", + }, + { + name: "R6 全过", + readFile: readerFrom({ "doc.md": "第一\nsrc/core/tool-pipeline.ts\n第三" }), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 135 }), + a: anchor({ docLine: 2 }), + expectOk: true, + reasonContains: "", + }, + ]; + + for (const c of cases) { + it(c.name, () => { + const r = checkDocSync({ + readFile: c.readFile, + grepSymbol: c.grepSymbol, + anchors: [c.a], + }); + expect(r.ok).toBe(c.expectOk); + if (!c.expectOk) { + expect(r.mismatches).toHaveLength(1); + expect(r.mismatches[0].reason).toContain(c.reasonContains); + } else { + expect(r.mismatches).toHaveLength(0); + } + }); + } + + // 决策表补充:grepSymbol 返回 0(非法哨兵)走 R5 分支(≤0) + it("R5' 符号返回 0(非法哨兵)→ not found(fail-closed)", () => { + const readFile = readerFrom({ "doc.md": "第一\nsrc/core/tool-pipeline.ts\n第三" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 0 }), + anchors: [anchor({ docLine: 2 })], + }); + expect(r.ok).toBe(false); + expect(r.mismatches[0].reason).toContain("not found"); + }); +}); + +// ============================================================================ +// 状态转换 · checkDocSync(fail-closed 优先序链 + 短路 + 不可达态 + 重入) +// ============================================================================ + +describe("状态转换 · checkDocSync fail-closed 链 + 短路 + 重入", () => { + // 每个锚点在状态机中迁移: + // S0(doc-read) → S1(line-bounds) → S2(doc-ref) → S3(code-grep) → S4(code-found) → ACCEPT + // 任一迁移失败 → MISMATCH(fail-closed,不可回到 ACCEPT) + // 不可达态:一旦 mismatch,不会回流到 ACCEPT(continue 跳过后续阶段)。 + it("一旦文档侧 mismatch,不触达代码侧(grepSymbol 不被调用)", () => { + let grepCalled = 0; + const readFile = readerFrom({ "doc.md": "第一\n第二行没提\n第三" }); + const grepSymbol: GrepSymbol = () => { + grepCalled++; + return 1; + }; + const r = checkDocSync({ readFile, grepSymbol, anchors: [anchor({ docLine: 2 })] }); + expect(r.ok).toBe(false); + expect(grepCalled).toBe(0); // 文档侧先 mismatch,代码侧不可达 + }); + + it("文档不可读时 grepSymbol 不被调用(fail-closed 优先序)", () => { + let grepCalled = 0; + const grepSymbol: GrepSymbol = () => { + grepCalled++; + return 1; + }; + const r = checkDocSync({ + readFile: throwingReader(), + grepSymbol, + anchors: [anchor()], + }); + expect(r.ok).toBe(false); + expect(grepCalled).toBe(0); + }); + + it("行越界时 grepSymbol 不被调用(S1→MISMATCH 短路)", () => { + let grepCalled = 0; + const readFile = readerFrom({ "doc.md": "唯一一行 src/core/tool-pipeline.ts" }); + const grepSymbol: GrepSymbol = () => { + grepCalled++; + return 1; + }; + const r = checkDocSync({ + readFile, + grepSymbol, + anchors: [anchor({ docLine: 50 })], + }); + expect(r.ok).toBe(false); + expect(grepCalled).toBe(0); + }); + + // 重入:同一 opts 多次调用结果等价(纯函数,无内部状态残留) + it("重入不变式:同一 opts 调两次结果 deep equal", () => { + const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts\n" }); + const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 5 }); + const opts = { + readFile, + grepSymbol, + anchors: [anchor({ docLine: 2 }), anchor({ docLine: 1 })], + }; + const r1 = checkDocSync(opts); + const r2 = checkDocSync(opts); + expect(r1).toEqual(r2); + }); + + // 多锚点重入:每锚点独立走状态机,mismatch 不影响下一锚点 + it("多锚点重入:第二锚点 ok 不受第一锚点 mismatch 影响", () => { + const readFile = readerFrom({ "doc.md": "bad line\nsrc/core/tool-pipeline.ts" }); + const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 9 }); + const bad = anchor({ docLine: 1 }); // 行1 不含 codeFile + const good = anchor({ docLine: 2 }); // 行2 含 codeFile + const r = checkDocSync({ readFile, grepSymbol, anchors: [bad, good] }); + expect(r.ok).toBe(false); + expect(r.mismatches).toHaveLength(1); + expect(r.mismatches[0].anchor).toBe(bad); + }); + + // 不可达态校验:ok=true 时 mismatches 必空;ok=false 时 mismatches 必非空 + it("不可达态:ok=true ⟺ mismatches 空(跨多场景单调)", () => { + const okR = checkDocSync({ + readFile: readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 2 })], + }); + const badR = checkDocSync({ + readFile: readerFrom({ "doc.md": "x\nbad" }), + grepSymbol: greperFrom({}), + anchors: [anchor({ docLine: 2 })], + }); + expect(okR.ok).toBe(true); + expect(okR.mismatches).toHaveLength(0); + expect(badR.ok).toBe(false); + expect(badR.mismatches.length).toBeGreaterThan(0); + }); + + // 状态可逆:修复 mismatch 输入后 ok 可从 false 迁回 true + it("状态可逆:bad opts 修为 good opts 后 ok false→true", () => { + const bad = checkDocSync({ + readFile: readerFrom({ "doc.md": "x\nbad" }), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 2 })], + }); + expect(bad.ok).toBe(false); + const good = checkDocSync({ + readFile: readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 2 })], + }); + expect(good.ok).toBe(true); + }); +}); + +// ============================================================================ +// 变异测试 · seeded bug 被某测试杀死 +// ============================================================================ +// +// 每个 it 验证一个 seeded bug 被杀: +// (a) 真代码满足 spec:`expect(spec(real)).toBe(true)` +// (b) buggy 副本违反 spec:`expect(spec(bug)).toBe(false)` +// (c) 字面演示「拿 buggy 当 SUT 跑 spec 断言必抛 AssertionError」: +// `expect(() => expect(buggyResult).toBe(期望值)).toThrow()` +// —— 等价于「该 spec 单独跑 buggy 变体时 FAIL」= bug 被杀。 + +describe("变异测试 · seeded bug 被某测试杀死", () => { + it("M1: `<= 0` 改 `< 0` —— grepSymbol 返回 0 须被拒绝(fail-closed)", () => { + const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }); + const opts = { + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 0 }), + anchors: [anchor({ docLine: 2 })], + }; + const specRejectsZero = (r: DocSyncResult) => r.ok === false; + const real = checkDocSync(opts); + const bug = checkDocSync_bug_ltLeq(opts); + expect(specRejectsZero(real)).toBe(true); // 真代码满足 spec + expect(specRejectsZero(bug)).toBe(false); // buggy 违反 spec → bug 被杀 + // 显式分歧:真代码 mismatch,buggy 放行 + expect(real.ok).toBe(false); + expect(bug.ok).toBe(true); + // 字面:拿 buggy 当 SUT 跑「ok 须为 false」断言必抛 + expect(() => expect(bug.ok).toBe(false)).toThrow(); + expect(() => expect(bug.mismatches).toHaveLength(1)).toThrow(); + }); + + it("M2: 行索引 off-by-one(漏 -1)—— docLine=1 须读首行", () => { + // 文档:第1行含 codeFile,第2行不含。docLine=1 应读第1行 → 过。 + const readFile = readerFrom({ + "doc.md": "src/core/tool-pipeline.ts 在首行\n第二行无关", + }); + const opts = { + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 1 })], + }; + const specReadsFirstLine = (r: DocSyncResult) => r.ok === true; + const real = checkDocSync(opts); + const bug = checkDocSync_bug_offByOne(opts); + expect(specReadsFirstLine(real)).toBe(true); // 真代码满足 + expect(specReadsFirstLine(bug)).toBe(false); // buggy 读第2行 → mismatch → 违反 + expect(real.ok).toBe(true); + expect(bug.ok).toBe(false); + // 字面:拿 buggy 当 SUT 跑「ok 须为 true」断言必抛 + expect(() => expect(bug.ok).toBe(true)).toThrow(); + }); + + it("M3: 漏 fail-closed(docFile 抛错静默吞)—— 不可读文档须 mismatch", () => { + const opts = { + readFile: throwingReader(), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor()], + }; + const specFailsClosed = (r: DocSyncResult) => r.ok === false; + const real = checkDocSync(opts); + const bug = checkDocSync_bug_swallowRead(opts); + expect(specFailsClosed(real)).toBe(true); + expect(specFailsClosed(bug)).toBe(false); // buggy 静默放行 → 违反 + expect(real.ok).toBe(false); + expect(bug.ok).toBe(true); + // 字面:拿 buggy 当 SUT 跑「ok 须为 false」断言必抛 + expect(() => expect(bug.ok).toBe(false)).toThrow(); + }); + + it("M4: changed 检测 `!==` 改 `===` —— 值不同须报 changed", () => { + const actual = { a: 1, b: 2 }; + const baseline = { a: 1, b: 99 }; + const specDetectsChange = (d: SnapshotDiff) => d.changed.includes("b"); + const real = compareSnapshot(actual, baseline); + const bug = compareSnapshot_bug_invertChanged(actual, baseline); + expect(specDetectsChange(real)).toBe(true); // 真代码满足 + expect(specDetectsChange(bug)).toBe(false); // buggy 漏报 changed → 违反 + // 旁证:buggy 还会把相等的 a 误报 changed + expect(bug.changed).toContain("a"); + expect(real.changed).not.toContain("a"); + // 字面:拿 buggy 当 SUT 跑「changed 须含 b」断言必抛 + expect(() => expect(bug.changed).toContain("b")).toThrow(); + }); + + it("M5: 空数组叶子 `[]` 改 `{}` —— [] vs {} 须 match=false(结构即值)", () => { + const specStruct = (d: SnapshotDiff) => d.match === false; + const real = compareSnapshot([], {}); + const bug = compareSnapshot_bug_emptyArrayAsObject([], {}); + expect(specStruct(real)).toBe(true); // 真代码:"[]" ≠ "{}" → match=false + expect(specStruct(bug)).toBe(false); // buggy:两边均 "{}" → match=true → 违反 + expect(real.match).toBe(false); + expect(bug.match).toBe(true); + // 字面:拿 buggy 当 SUT 跑「match 须为 false」断言必抛 + expect(() => expect(bug.match).toBe(false)).toThrow(); + }); + + it("M6: flatten 漏 null 守卫 —— null vs null 须 match=true(不抛)", () => { + const specNullSafe = (d: SnapshotDiff) => d.match === true; + const real = compareSnapshot(null, null); + expect(specNullSafe(real)).toBe(true); // 真代码:null 当叶子,自反 match + // buggy:Object.getPrototypeOf(null) 抛 TypeError + expect(() => compareSnapshot_bug_dropNullGuard(null, null)).toThrow(TypeError); + // 字面:拿 buggy 当 SUT 跑「match 须为 true」断言必抛(因调用本身抛错) + expect(() => + expect(compareSnapshot_bug_dropNullGuard(null, null).match).toBe(true), + ).toThrow(); + }); + + it("M7: 空对象叶子 `{}` 改 `[]` —— {} vs [] 须 match=false(结构即值,对象侧)", () => { + const specStruct = (d: SnapshotDiff) => d.match === false; + const real = compareSnapshot({}, []); + const bug = compareSnapshot_bug_emptyObjectAsArray({}, []); + expect(specStruct(real)).toBe(true); // 真代码:"{}" ≠ "[]" → match=false + expect(specStruct(bug)).toBe(false); // buggy:两边均 "[]" → match=true → 违反 + expect(real.match).toBe(false); + expect(bug.match).toBe(true); + // 字面:拿 buggy 当 SUT 跑「match 须为 false」断言必抛 + expect(() => expect(bug.match).toBe(false)).toThrow(); + }); + + it("M8: serializeLeaf 漏 -0 特判 —— -0 vs 0 须 match=false(Object.is 语义)", () => { + const specNegZeroDistinct = (d: SnapshotDiff) => d.match === false; + const real = compareSnapshot(-0, 0); + const bug = compareSnapshot_bug_noNegZero(-0, 0); + expect(Object.is(-0, 0)).toBe(false); // 语义确不同 + expect(specNegZeroDistinct(real)).toBe(true); // 真代码特判 -0 → "-0"≠"0" → match=false + expect(specNegZeroDistinct(bug)).toBe(false); // buggy:均 "0" → match=true → 违反 + expect(real.match).toBe(false); + expect(bug.match).toBe(true); + // 字面:拿 buggy 当 SUT 跑「match 须为 false」断言必抛 + expect(() => expect(bug.match).toBe(false)).toThrow(); + }); + + it("M9: 漏 Object.freeze —— DEFAULT_DOC_ANCHORS 须深冻结", () => { + // spec:默认锚点清单 Object.isFrozen === true + const specFrozen = (arr: readonly DocAnchor[]) => Object.isFrozen(arr); + expect(specFrozen(DEFAULT_DOC_ANCHORS)).toBe(true); // 真代码满足 + expect(specFrozen(BUGGY_ANCHORS_NO_FREEZE)).toBe(false); // 漏 freeze → 违反 + // 字面:拿 buggy 当 SUT 跑「isFrozen 须为 true」断言必抛 + expect(() => expect(Object.isFrozen(BUGGY_ANCHORS_NO_FREEZE)).toBe(true)).toThrow(); + }); + + it("变异兜底:真代码全部满足 spec 谓词(无 buggy 介入时全过)", () => { + // 汇总:真代码在每个变异场景都满足 spec,证明真实代码无这些 bug + expect( + checkDocSync({ + readFile: readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 0 }), + anchors: [anchor({ docLine: 2 })], + }).ok, + ).toBe(false); + expect( + checkDocSync({ + readFile: readerFrom({ "doc.md": "src/core/tool-pipeline.ts\n第二行" }), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 1 })], + }).ok, + ).toBe(true); + expect( + checkDocSync({ + readFile: throwingReader(), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor()], + }).ok, + ).toBe(false); + expect(compareSnapshot({ a: 1, b: 2 }, { a: 1, b: 99 }).changed).toContain("b"); + expect(compareSnapshot([], {}).match).toBe(false); + expect(compareSnapshot({}, []).match).toBe(false); + expect(compareSnapshot(null, null).match).toBe(true); + expect(compareSnapshot(-0, 0).match).toBe(false); + expect(Object.isFrozen(DEFAULT_DOC_ANCHORS)).toBe(true); + }); +}); + +// ============================================================================ +// 对抗 / fuzz · checkDocSync + compareSnapshot +// ============================================================================ + +describe("对抗/fuzz · 畸形与滥用输入", () => { + // ---- checkDocSync fuzz ---- + it("fuzz-空锚点清单 → ok=true(vacuous truth),mismatches 空", () => { + const r = checkDocSync({ + readFile: throwingReader(), // 无锚点 → readFile 不被调用 + grepSymbol: () => -1, + anchors: [], + }); + expect(r.ok).toBe(true); + expect(r.mismatches).toHaveLength(0); + }); + + it("fuzz-docLine=NaN → 行索引越界 → mismatch", () => { + const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: Number.NaN })], + }); + expect(r.ok).toBe(false); + }); + + it("fuzz-docLine=Infinity → 越界 → mismatch", () => { + const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: Number.POSITIVE_INFINITY })], + }); + expect(r.ok).toBe(false); + }); + + it("fuzz-docLine=-Infinity → 越界 → mismatch", () => { + const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: Number.NEGATIVE_INFINITY })], + }); + expect(r.ok).toBe(false); + }); + + it("fuzz-docLine=0.5(非整数 1-indexed)→ docLines[−0.5] 越界 → mismatch", () => { + const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 0.5 })], + }); + expect(r.ok).toBe(false); + }); + + it("fuzz-codeSymbol 空串 + grep 返回 1(mock 放行)→ ok", () => { + // 空符号对抗:mock 控制结果,校验 checkDocSync 不因空串崩溃 + const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:": 1 }), + anchors: [anchor({ docLine: 2, codeSymbol: "" })], + }); + expect(r.ok).toBe(true); + }); + + it("fuzz-codeSymbol 空串 + grep 返回 -1 → mismatch(fail-closed)", () => { + const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({}), + anchors: [anchor({ docLine: 2, codeSymbol: "" })], + }); + expect(r.ok).toBe(false); + }); + + it("fuzz-并发重入:同一 opts 并发 100 次结果一致(纯函数无共享态)", () => { + const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts\n" }); + const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 7 }); + const opts = { readFile, grepSymbol, anchors: [anchor({ docLine: 2 })] }; + const first = checkDocSync(opts); + for (let i = 0; i < 100; i++) { + expect(checkDocSync(opts)).toEqual(first); + } + }); + + it("fuzz-巨大锚点清单(1000 条全过)→ ok=true,mismatches 空", () => { + const readFile = readerFrom({ "doc.md": "src/core/tool-pipeline.ts" }); + const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }); + const anchors = Array.from({ length: 1000 }, () => anchor({ docLine: 1 })); + const r = checkDocSync({ readFile, grepSymbol, anchors }); + expect(r.ok).toBe(true); + expect(r.mismatches).toHaveLength(0); + }); + + it("fuzz-巨大锚点清单(1000 条全 mismatch)→ 1000 条 mismatches 保持输入序", () => { + const readFile = readerFrom({ "doc.md": "不含路径" }); + const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }); + const anchors = Array.from({ length: 1000 }, (_, i) => + anchor({ docLine: 1, codeSymbol: `S${i}` }), + ); + const r = checkDocSync({ readFile, grepSymbol, anchors }); + expect(r.ok).toBe(false); + expect(r.mismatches).toHaveLength(1000); + // 输入序保持 + expect(r.mismatches[999].anchor.codeSymbol).toBe("S999"); + }); + + it("fuzz-codeFile 含正则元字符(. *)→ 子串匹配不误当正则", () => { + // docLine 的 includes 是字面子串,codeFile 的 "." 应字面匹配 + const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }); + const r = checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 5 }), + anchors: [anchor({ docLine: 2 })], + }); + expect(r.ok).toBe(true); + }); + + it("fuzz-readFile 返回非字符串(number)→ split 抛 TypeError 逃逸(特征化 try/catch 边界)", () => { + // ReadFile 类型契约要求返回 string;违约返回 number 时 docText.split + // 不存在 → 抛 TypeError。checkDocSync 的 try/catch 只包裹 readFile 调用 + // 本身,未覆盖后续 .split(),故该 TypeError 逃逸(不被兜成 mismatch)。 + // 这要求运行时违反 ReadFile 类型契约(tsc 编译期已防),非 in-spec 缺陷, + // 此处特征化 try/catch 守卫的精确边界。 + const readFile = (() => 42) as unknown as ReadFile; + expect(() => + checkDocSync({ + readFile, + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor()], + }), + ).toThrow(TypeError); + }); + + // ---- compareSnapshot fuzz ---- + it("fuzz-undefined vs undefined → match=true(serializeLeaf 特判 'undefined')", () => { + expect(compareSnapshot(undefined, undefined).match).toBe(true); + }); + + it("fuzz-null vs undefined → mismatch('null' ≠ 'undefined')", () => { + const d = compareSnapshot(undefined, null); + expect(d.match).toBe(false); + // 根 path "" 两边都有但值不同 → changed + expect(d.changed).toEqual([""]); + }); + + // serializeLeaf 已特判 NaN/Infinity/函数/symbol/bigint/-0——以下断言钉住正确行为。 + it("NaN vs null 不碰撞 → match=false(serializeLeaf 特判 'NaN')", () => { + expect(compareSnapshot(NaN, null).match).toBe(false); + }); + + it("Infinity vs null 不碰撞 → match=false", () => { + expect(compareSnapshot(Infinity, null).match).toBe(false); + }); + + it("相同函数自反 match=true(serializeLeaf 特判 'function')", () => { + const f = () => 1; + expect(compareSnapshot(f, f).match).toBe(true); + }); + + it("两不同函数 → match=true(均序列化为 'function',opaque 身份类型)", () => { + // 与 function 同范式:不序列化内部,所有函数同串 → 自反且互等 + // (这是文档明示的设计选择,非缺陷:opaque 身份类型) + const f = () => 1; + const g = () => 2; + expect(compareSnapshot(f, g).match).toBe(true); + }); + + it("Symbol vs undefined 不碰撞 → match=false(特判 'symbol')", () => { + expect(compareSnapshot(Symbol("s"), undefined).match).toBe(false); + }); + + it("Symbol 自反 match=true(opaque,均 'symbol')", () => { + expect(compareSnapshot(Symbol("a"), Symbol("b")).match).toBe(true); + }); + + it("BigInt 自反 match=true(特判 `bigint:${v}`,不抛)", () => { + expect(compareSnapshot(BigInt(1), BigInt(1)).match).toBe(true); + }); + + it("BigInt 值不同 → changed(bigint:1 ≠ bigint:2)", () => { + const d = compareSnapshot(BigInt(1), BigInt(2)); + expect(d.match).toBe(false); + expect(d.changed).toEqual([""]); + }); + + it("BigInt vs number 不碰撞 → changed('bigint:1' ≠ '1')", () => { + const d = compareSnapshot(BigInt(1), 1); + expect(d.match).toBe(false); + expect(d.changed).toEqual([""]); + }); + + it("-0 vs 0 → match=false(特判 '-0',Object.is 语义)", () => { + expect(Object.is(-0, 0)).toBe(false); + expect(compareSnapshot(-0, 0).match).toBe(false); + }); + + it("-0 自反 match=true('-0' = '-0')", () => { + expect(compareSnapshot(-0, -0).match).toBe(true); + }); + + it("fuzz-NaN vs NaN → match=true(两侧均 'NaN',一致)", () => { + expect(compareSnapshot(NaN, NaN).match).toBe(true); + }); + + it("fuzz-NaN vs 0 → changed('NaN' ≠ '0')", () => { + const d = compareSnapshot(NaN, 0); + expect(d.changed).toEqual([""]); + }); + + it("fuzz-Infinity vs -Infinity → changed('Infinity' ≠ '-Infinity')", () => { + const d = compareSnapshot(Infinity, -Infinity); + expect(d.match).toBe(false); + expect(d.changed).toEqual([""]); + }); + + it("fuzz-循环引用 → 抛 RangeError(不静默挂死,特征化)", () => { + const circ: any = {}; + circ.self = circ; + expect(() => compareSnapshot(circ, circ)).toThrow(RangeError); + }); + + it("fuzz-循环引用 vs 不同循环引用 → 抛 RangeError(不误报 match)", () => { + const a: any = {}; + a.self = a; + const b: any = {}; + b.self = b; + expect(() => compareSnapshot(a, b)).toThrow(RangeError); + }); + + it("fuzz-深嵌套(depth 1000)→ 不抛、自反 match=true", () => { + let deep: any = { v: 0 }; + for (let i = 0; i < 1000; i++) deep = { nested: deep }; + expect(() => compareSnapshot(deep, deep)).not.toThrow(); + expect(compareSnapshot(deep, deep).match).toBe(true); + }); + + it("fuzz-巨大数组(10000 元素)→ 自反 match + 确定性", () => { + const big = Array.from({ length: 10000 }, (_, i) => i); + const d = compareSnapshot(big, big); + expect(d.match).toBe(true); + expect(compareSnapshot(big, big)).toEqual(d); // 确定性 + }); + + it("fuzz-巨大数组单元素漂移 → 精确定位 changed path", () => { + const a = Array.from({ length: 10000 }, (_, i) => i); + const b = [...a]; + b[5000] = 99999; + const d = compareSnapshot(a, b); + expect(d.changed).toEqual(["5000"]); + expect(d.match).toBe(false); + }); + + it("fuzz-Date 自反 match=true(非纯对象当叶子,走 toJSON)", () => { + const dt = new Date("2026-01-01T00:00:00Z"); + expect(compareSnapshot(dt, dt).match).toBe(true); + }); + + it("fuzz-Date 同 epoch 自反 match=true(两实例同值)", () => { + const a = new Date(123); + const b = new Date(123); + expect(compareSnapshot(a, b).match).toBe(true); + }); + + it("fuzz-Date 不同 epoch → changed", () => { + const a = new Date(123); + const b = new Date(999); + const d = compareSnapshot(a, b); + expect(d.match).toBe(false); + expect(d.changed).toEqual([""]); + }); + + it("fuzz-Map/Set 当叶子(非纯对象)→ 自反 match=true", () => { + const m = new Map([["k", 1]]); + expect(compareSnapshot(m, m).match).toBe(true); + const s = new Set([1, 2, 3]); + expect(compareSnapshot(s, s).match).toBe(true); + }); + + it("fuzz-Map vs Set(空)→ match=true(均 JSON.stringify 为 '{}',opaque 身份)", () => { + // 空 Map/Set 无可枚举自有属性 → JSON.stringify 均得 "{}" → 同串 → match=true。 + // 这是文档明示设计(非纯对象当叶子走 JSON 标准序列化),非缺陷。 + const d = compareSnapshot(new Map(), new Set()); + expect(d.match).toBe(true); + }); + + it("fuzz-巨大字符串值 → 自反 match + 确定性", () => { + const big = "x".repeat(100000); + expect(compareSnapshot(big, big).match).toBe(true); + }); +}); + +// ============================================================================ +// 元蜕变 / 不变式 · checkDocSync + compareSnapshot +// ============================================================================ + +describe("元蜕变/不变式 · 跨变换保持的性质", () => { + // ---- checkDocSync 不变式 ---- + it("不变式-ok 单调:mismatches 空 ⟺ ok=true(跨多场景)", () => { + const okCase = checkDocSync({ + readFile: readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor({ docLine: 2 })], + }); + const badCase = checkDocSync({ + readFile: readerFrom({ "doc.md": "x\nbad" }), + grepSymbol: greperFrom({}), + anchors: [anchor({ docLine: 2 })], + }); + expect(okCase.ok).toBe(true); + expect(okCase.mismatches).toHaveLength(0); + expect(badCase.ok).toBe(false); + expect(badCase.mismatches.length).toBeGreaterThan(0); + // 单调:ok === (mismatches.length === 0) + expect(okCase.ok).toBe(okCase.mismatches.length === 0); + expect(badCase.ok).toBe(badCase.mismatches.length === 0); + }); + + it("元蜕变-append 等价:append 两次同锚点 = replay(同 opts 调两次)deep equal", () => { + const readFile = readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts" }); + const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 3 }); + const opts = { + readFile, + grepSymbol, + anchors: [anchor({ docLine: 2 }), anchor({ docLine: 2 })], + }; + // 两次同锚点 = 输入序两条 ok + const r = checkDocSync(opts); + expect(r.ok).toBe(true); + // replay 等价 + expect(checkDocSync(opts)).toEqual(r); + }); + + it("不变式-mismatches 保持锚点输入序(多 mismatch 排序校验)", () => { + const readFile = readerFrom({ "doc.md": "a 不含\nb 不含\nc 不含" }); + const grepSymbol = greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }); + const a1 = anchor({ docLine: 1, codeSymbol: "A1" }); + const a2 = anchor({ docLine: 2, codeSymbol: "A2" }); + const a3 = anchor({ docLine: 3, codeSymbol: "A3" }); + const r = checkDocSync({ readFile, grepSymbol, anchors: [a1, a2, a3] }); + expect(r.mismatches.map((m) => m.anchor)).toEqual([a1, a2, a3]); + }); + + it("不变式-DEFAULT_DOC_ANCHORS 数组级冻结(防 push 篡改)", () => { + expect(Object.isFrozen(DEFAULT_DOC_ANCHORS)).toBe(true); + // 数组级冻结:push 抛 TypeError(strict 模式) + expect(() => { + (DEFAULT_DOC_ANCHORS as any).push({ + docFile: "x", + docLine: 1, + codeFile: "y", + codeSymbol: "z", + }); + }).toThrow(TypeError); + }); + + // DEFAULT_DOC_ANCHORS 深冻结(外层 + 逐元素),元素属性不可篡改。 + it("元素深冻结:isFrozen(element)=true,属性不可写", () => { + expect(Object.isFrozen(DEFAULT_DOC_ANCHORS[0])).toBe(true); + // 元素对象已冻结 → 其属性不可写、不可删——深冻结不变式兑现 + const a = DEFAULT_DOC_ANCHORS[0]; + const desc = Object.getOwnPropertyDescriptor(a, "docFile"); + expect(desc?.writable).toBe(false); // 不可写 = 不可篡改 + }); + + it("不变式-元素属性篡改抛 TypeError(深冻结 fail-closed)", () => { + expect(() => { + (DEFAULT_DOC_ANCHORS[0] as any).docFile = "tampered"; + }).toThrow(TypeError); + expect(() => { + delete (DEFAULT_DOC_ANCHORS[0] as any).docLine; + }).toThrow(TypeError); + }); + + // ---- compareSnapshot 不变式 ---- + it("不变式-自反性:compareSnapshot(x,x).match === true(多类型)", () => { + const samples = [ + undefined, + null, + 0, + -0, + "", + "str", + true, + false, + {}, + [], + { a: 1, b: { c: [1, 2, 3] } }, + [1, "x", { y: null }], + ]; + for (const s of samples) { + expect(compareSnapshot(s, s).match).toBe(true); + } + }); + + it("不变式-对称性:交换 actual/baseline,added↔removed、changed 不变、match 不变", () => { + const actual = { a: 1, b: 2, c: 3 }; + const baseline = { a: 1, b: 99, d: 4 }; + const d1 = compareSnapshot(actual, baseline); + const d2 = compareSnapshot(baseline, actual); + expect(d2.added).toEqual(d1.removed); + expect(d2.removed).toEqual(d1.added); + expect(d2.changed).toEqual(d1.changed); + expect(d2.match).toBe(d1.match); + }); + + it("元蜕变-传递性:a≡b 且 b≡c ⇒ a≡c(等价类闭包)", () => { + const a = { x: 1, y: [1, 2], z: { w: "k" } }; + const b = structuredClone(a); + const c = { x: 1, y: [1, 2], z: { w: "k" } }; + expect(compareSnapshot(a, b).match).toBe(true); + expect(compareSnapshot(b, c).match).toBe(true); + expect(compareSnapshot(a, c).match).toBe(true); + }); + + it("不变式-确定性:同输入两次 deep equal(含 added/removed/changed 升序)", () => { + const a = { tools: [{ name: "flash", ok: true }, { name: "verify" }] }; + const b = { tools: [{ name: "flash", ok: false }, { name: "verify" }] }; + const d1 = compareSnapshot(a, b); + const d2 = compareSnapshot(a, b); + expect(d2).toEqual(d1); + expect(d1.changed).toEqual(["tools.0.ok"]); + }); + + it("不变式-升序:added/removed/changed 均升序排列", () => { + // 故意乱序构造 path(对象 key 插入序非字母序) + const actual = { z: 1, a: 2, m: 3, extra1: 9, extra2: 9 }; + const baseline = { z: 1, a: 99, m: 3, gone1: 0, gone2: 0 }; + const d = compareSnapshot(actual, baseline); + const isSorted = (arr: readonly string[]) => + arr.every((v, i) => i === 0 || arr[i - 1] <= v); + expect(isSorted(d.added)).toBe(true); + expect(isSorted(d.removed)).toBe(true); + expect(isSorted(d.changed)).toBe(true); + // 升序内容校验 + expect(d.added).toEqual(["extra1", "extra2"].sort()); + expect(d.removed).toEqual(["gone1", "gone2"].sort()); + expect(d.changed).toEqual(["a"].sort()); + }); + + it("不变式-空容器结构变化即漂移({} vs [] vs {x:1})", () => { + const dEmptyVsX = compareSnapshot({}, { x: 1 }); + expect(dEmptyVsX.added).toEqual([""]); // actual 的 "{}" path + expect(dEmptyVsX.removed).toEqual(["x"]); + expect(compareSnapshot([], {}).match).toBe(false); // "[]" vs "{}" + expect(compareSnapshot({}, {}).match).toBe(true); + expect(compareSnapshot([], []).match).toBe(true); + expect(compareSnapshot({}, []).match).toBe(false); // "{}" vs "[]" + }); + + it("元蜕变-waterfall 不调 next=短路:checkDocSync 文档侧 mismatch 即止(grep 不触达)", () => { + // fail-closed 短路:文档侧红即不评估代码侧,等价「waterfall 不调 next」 + let grepTouched = false; + const readFile = readerFrom({ "doc.md": "第一\n第二行没提\n第三" }); + const grepSymbol: GrepSymbol = () => { + grepTouched = true; + return 1; + }; + const r = checkDocSync({ readFile, grepSymbol, anchors: [anchor({ docLine: 2 })] }); + expect(r.ok).toBe(false); + expect(grepTouched).toBe(false); // 短路:未调 next + }); + + it("不变式-fail-closed unusable=拒:任一侧不可用即 mismatch(不静默 ok)", () => { + // 文档不可用 + const docUnusable = checkDocSync({ + readFile: throwingReader(), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 1 }), + anchors: [anchor()], + }); + expect(docUnusable.ok).toBe(false); + // 代码不可用(抛错) + const codeUnusable = checkDocSync({ + readFile: readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts\n" }), + grepSymbol: () => { + throw new Error("ENOENT"); + }, + anchors: [anchor({ docLine: 2 })], + }); + expect(codeUnusable.ok).toBe(false); + // grep 返回非法哨兵 0 + const grepZero = checkDocSync({ + readFile: readerFrom({ "doc.md": "x\nsrc/core/tool-pipeline.ts\n" }), + grepSymbol: greperFrom({ "src/core/tool-pipeline.ts:ToolPipeline": 0 }), + anchors: [anchor({ docLine: 2 })], + }); + expect(grepZero.ok).toBe(false); + }); +}); + +// ============================================================================ +// DEFAULT_DOC_ANCHORS + 默认 IO 适配器契约 +// ============================================================================ + +describe("DEFAULT_DOC_ANCHORS + 默认 IO 适配器契约", () => { + it("DEFAULT_DOC_ANCHORS:数组冻结 + 非空 + ≥3 条 + 字段齐全", () => { + expect(Object.isFrozen(DEFAULT_DOC_ANCHORS)).toBe(true); + expect(DEFAULT_DOC_ANCHORS.length).toBeGreaterThanOrEqual(3); + for (const a of DEFAULT_DOC_ANCHORS) { + expect(typeof a.docFile).toBe("string"); + expect(typeof a.docLine).toBe("number"); + expect(a.docLine).toBeGreaterThan(0); + expect(typeof a.codeFile).toBe("string"); + expect(a.codeFile.startsWith("src/")).toBe(true); + expect(typeof a.codeSymbol).toBe("string"); + expect(a.codeSymbol.length).toBeGreaterThan(0); + } + }); + + // 元素深冻结——deepFreezeAnchors 兑现「外层 + 逐元素 Object.freeze」承诺。 + it("元素深冻结:Object.isFrozen(element)===true", () => { + expect(Object.isFrozen(DEFAULT_DOC_ANCHORS)).toBe(true); // 数组级冻结 + // 元素级:深冻结触达,元素不可变(与文档声称的「深冻结」一致) + expect(Object.isFrozen(DEFAULT_DOC_ANCHORS[0])).toBe(true); + expect(Object.isFrozen(DEFAULT_DOC_ANCHORS[DEFAULT_DOC_ANCHORS.length - 1])).toBe(true); + }); + + it("默认锚点 docFile 一致(同一架构文档)", () => { + const docFiles = new Set(DEFAULT_DOC_ANCHORS.map((a) => a.docFile)); + expect(docFiles.size).toBe(1); + }); + + // defaultGrepSymbol 轻量真 fs 集成(本仓稳定文件,无 pi/硬件/网络) + it("defaultGrepSymbol:在本仓 scripts/doc-sync.ts 中命中 'checkDocSync'(>0 行号)", () => { + const line = defaultGrepSymbol("scripts/doc-sync.ts", "checkDocSync"); + expect(line).toBeGreaterThan(0); + }); + + it("defaultGrepSymbol:未命中符号返回 -1", () => { + const line = defaultGrepSymbol("scripts/doc-sync.ts", "ZZZ_NOT_A_SYMBOL_999"); + expect(line).toBe(-1); + }); + + it("defaultReadFile:读本仓稳定文件返回含已知标记的字符串", () => { + const text = defaultReadFile("scripts/doc-sync.ts"); + expect(typeof text).toBe("string"); + expect(text).toContain("checkDocSync"); + }); + + it("defaultReadFile:读不存在文件抛错(fail-closed 适配器契约)", () => { + expect(() => defaultReadFile("does/not/exist.md")).toThrow(); + }); + + // defaultGrepSymbol 行号语义:返回首个命中行(1-indexed) + it("defaultGrepSymbol:返回首个命中行(1-indexed)—— '@module' 首现于第 2 行", () => { + // scripts/doc-sync.ts 第 1 行是 '/**',第 2 行是 ' * @module doc-sync' + const line = defaultGrepSymbol("scripts/doc-sync.ts", "@module"); + expect(line).toBe(2); + }); + + it("defaultGrepSymbol:空符号命中首行(''.includes('')===true → 返回 1)", () => { + const line = defaultGrepSymbol("scripts/doc-sync.ts", ""); + expect(line).toBe(1); + }); + + // 端到端:用默认适配器跑默认锚点(CI 实跑路径) + it("端到端-CI 装配:checkDocSync(defaultReadFile, defaultGrepSymbol, DEFAULT_DOC_ANCHORS) 全过", () => { + const r = checkDocSync({ + readFile: defaultReadFile, + grepSymbol: defaultGrepSymbol, + anchors: DEFAULT_DOC_ANCHORS, + }); + // 本测试套件假定开发 Agent 已校对 DEFAULT_DOC_ANCHORS 与真实仓库对齐 + expect(r.ok).toBe(true); + expect(r.mismatches).toHaveLength(0); + }); +}); + +// ============================================================================ +// e2e-snapshot · compareSnapshot 等价类 / 边界 / 决策表 / 状态 +// ============================================================================ + +describe("等价类划分 · compareSnapshot(有效/无效/边界类)", () => { + it("有效类-两侧结构一致 → match=true", () => { + const baseline = { a: 1, b: { c: 2 }, d: [1, 2] }; + const actual = { a: 1, b: { c: 2 }, d: [1, 2] }; + const diff = compareSnapshot(actual, baseline); + expect(diff.match).toBe(true); + expect(diff.added).toEqual([]); + expect(diff.removed).toEqual([]); + expect(diff.changed).toEqual([]); + }); + + it("无效类-added(actual 独有 path)", () => { + const d = compareSnapshot({ a: 1, b: 2 }, { a: 1 }); + expect(d.added).toEqual(["b"]); + expect(d.match).toBe(false); + }); + + it("无效类-removed(baseline 独有 path)", () => { + const d = compareSnapshot({ a: 1 }, { a: 1, b: 2 }); + expect(d.removed).toEqual(["b"]); + expect(d.match).toBe(false); + }); + + it("无效类-changed(同 path 值不同)", () => { + const d = compareSnapshot({ a: 1, b: 2 }, { a: 1, b: 99 }); + expect(d.changed).toEqual(["b"]); + expect(d.match).toBe(false); + }); + + it("复合-added/removed/changed 各命中一条", () => { + const baseline = { a: 1, b: 2, c: 3 }; + const actual = { a: 1, b: 99, d: 4 }; // b 变、c 删、d 增 + const diff: SnapshotDiff = compareSnapshot(actual, baseline); + expect(diff.match).toBe(false); + expect(diff.added).toEqual(["d"]); + expect(diff.removed).toEqual(["c"]); + expect(diff.changed).toEqual(["b"]); + }); +}); + +describe("边界值分析 · compareSnapshot", () => { + it("根原始值:0 vs 0 → match;0 vs 1 → changed", () => { + expect(compareSnapshot(0, 0).match).toBe(true); + const d = compareSnapshot(0, 1); + expect(d.changed).toEqual([""]); + }); + + it("根空串 vs 空串 → match;空串 vs 'x' → changed", () => { + expect(compareSnapshot("", "").match).toBe(true); + expect(compareSnapshot("", "x").changed).toEqual([""]); + }); + + it("布尔 true vs true → match;true vs false → changed", () => { + expect(compareSnapshot(true, true).match).toBe(true); + expect(compareSnapshot(true, false).changed).toEqual([""]); + }); + + it("单元素数组 vs 单元素数组(同值)→ match", () => { + expect(compareSnapshot([1], [1]).match).toBe(true); + }); + + it("单元素数组值不同 → changed 命中 '0'", () => { + const d = compareSnapshot([1], [2]); + expect(d.changed).toEqual(["0"]); + expect(d.match).toBe(false); + }); + + it("单 key 对象 vs 空 {} → added=['k'] + removed=[''](空对象 {} 叶被移除)", () => { + const d = compareSnapshot({ k: 1 }, {}); + expect(d.added).toEqual(["k"]); + expect(d.removed).toEqual([""]); + }); + + it("空数组 vs 单元素数组 → added=['0'] + removed=[''](空数组的 '[]' 叶被移除)", () => { + const d = compareSnapshot([1], []); + expect(d.added).toEqual(["0"]); + expect(d.removed).toEqual([""]); // baseline 空数组的 "[]" 叶 path "" + expect(d.match).toBe(false); + }); + + it("数组长度变化:[1] vs [1,2] → removed=['1']", () => { + const d = compareSnapshot([1], [1, 2]); + expect(d.removed).toEqual(["1"]); + }); + + it("数组长度变化:[1,2] vs [1] → added=['1']", () => { + const d = compareSnapshot([1, 2], [1]); + expect(d.added).toEqual(["1"]); + }); + + it("嵌套 path 形态:tools.0.ok 漂移", () => { + const a = { tools: [{ name: "flash", ok: true }, { name: "verify" }] }; + const b = { tools: [{ name: "flash", ok: false }, { name: "verify" }] }; + const d = compareSnapshot(a, b); + expect(d.changed).toEqual(["tools.0.ok"]); + expect(d.match).toBe(false); + }); + + it("空对象 {} vs {x:1} → added=[''] + removed=['x'](结构即值)", () => { + const d = compareSnapshot({}, { x: 1 }); + expect(d.added).toEqual([""]); + expect(d.removed).toEqual(["x"]); + }); + + it("根 null vs null → match=true(叶子自反)", () => { + expect(compareSnapshot(null, null).match).toBe(true); + }); + + it("根 null vs 0 → changed('null' ≠ '0')", () => { + const d = compareSnapshot(null, 0); + expect(d.changed).toEqual([""]); + expect(d.match).toBe(false); + }); + + it("根 undefined vs null → changed('undefined' ≠ 'null')", () => { + const d = compareSnapshot(undefined, null); + expect(d.changed).toEqual([""]); + }); +}); + +describe("决策表 · compareSnapshot path 集合运算", () => { + // 决策表:对每个 path,按 actual/baseline 是否含 + 值是否等 → 4 类 + // 1) 两边含且值同 → 无 diff + // 2) 两边含且值异 → changed + // 3) 仅 actual 含 → added + // 4) 仅 baseline 含 → removed + it("四类同时出现的混合快照", () => { + const actual = { same: 1, changed: 2, added: 3 }; + const baseline = { same: 1, changed: 99, removed: 4 }; + const d = compareSnapshot(actual, baseline); + expect(d.changed).toEqual(["changed"]); + expect(d.added).toEqual(["added"]); + expect(d.removed).toEqual(["removed"]); + // same 不出现在任何 diff 列表 + expect(d.added).not.toContain("same"); + expect(d.changed).not.toContain("same"); + expect(d.removed).not.toContain("same"); + expect(d.match).toBe(false); + }); + + it("全相同 → 三列表皆空 + match=true", () => { + const d = compareSnapshot( + { a: 1, b: [1, 2], c: { d: true } }, + { a: 1, b: [1, 2], c: { d: true } }, + ); + expect(d.added).toEqual([]); + expect(d.removed).toEqual([]); + expect(d.changed).toEqual([]); + expect(d.match).toBe(true); + }); + + it("仅 added(baseline 为空对象)", () => { + const d = compareSnapshot({ x: 1 }, {}); + expect(d.added).toEqual(["x"]); + expect(d.removed).toEqual([""]); + expect(d.changed).toEqual([]); + }); + + it("仅 removed(actual 为空对象)", () => { + const d = compareSnapshot({}, { x: 1 }); + expect(d.added).toEqual([""]); + expect(d.removed).toEqual(["x"]); + expect(d.changed).toEqual([]); + }); + + it("仅 changed(同 key 集,值全异)", () => { + const d = compareSnapshot({ a: 1, b: 2 }, { a: 9, b: 8 }); + expect(d.changed).toEqual(["a", "b"]); + expect(d.added).toEqual([]); + expect(d.removed).toEqual([]); + }); +}); + +describe("状态转换 · compareSnapshot(match 状态守恒)", () => { + // 状态:match ∈ {true, false};迁移:任一 added/removed/changed 非空 → false + // 不可达态:added/removed/changed 全空 且 match=false(不变式禁此态) + it("不变式-禁不可达态:三表全空 ⟹ match=true", () => { + const d = compareSnapshot({ a: 1 }, { a: 1 }); + expect(d.added.length === 0 && d.removed.length === 0 && d.changed.length === 0).toBe(true); + expect(d.match).toBe(true); // 不可达 false + }); + + it("不变式-禁不可达态:match=true ⟹ 三表全空", () => { + const d = compareSnapshot({ a: { b: [1, 2] } }, { a: { b: [1, 2] } }); + expect(d.match).toBe(true); + expect(d.added).toEqual([]); + expect(d.removed).toEqual([]); + expect(d.changed).toEqual([]); + }); + + it("迁移-单点漂移即 match→false", () => { + const base = { a: 1, b: 2, c: 3 }; + const same = compareSnapshot(base, base); + expect(same.match).toBe(true); + const drifted = compareSnapshot({ ...base, b: 99 }, base); + expect(drifted.match).toBe(false); + }); + + it("迁移-漂移修复后 match→true(状态可逆)", () => { + const base = { a: 1, b: 2 }; + const drifted = compareSnapshot({ a: 1, b: 99 }, base); + expect(drifted.match).toBe(false); + const fixed = compareSnapshot(base, base); + expect(fixed.match).toBe(true); + }); +}); diff --git a/tests/pba-event-bus.test.ts b/tests/pba-event-bus.test.ts new file mode 100644 index 0000000..4a349b6 --- /dev/null +++ b/tests/pba-event-bus.test.ts @@ -0,0 +1,729 @@ +/** + * pba-event-bus 测试套件 —— T07 类型化事件总线 + ScopeKey 隔离。 + * + * 被测对象:src/core/pba-event-bus.ts 的命名导出 + * (PbaEventBus, KNOWN_EVENTS, 及类型 PbaListener/PbaEmitter/PbaEventBusOptions/ScopeKey)。 + * + * 多方法论覆盖(每个 describe 块标题标注方法论名): + * ① 等价类划分 —— 作用域归一/冒泡的有效·无效·边界类 + * ② 边界值分析 —— off-by-one / 空 / 单元素 / 多元素 / 段边界 + * ③ 决策表 —— scopeReceives 全分支组合 → 期望 + * ④ 状态转换 —— 注册表生命周期 + 迁移 + 重入 + 不可达态 + * ⑤ 变异测试 —— 5 个 seeded bug 内联副本,逐个被杀 + * ⑥ 对抗/fuzz —— 畸形/滥用输入 + * ⑦ 元蜕变/不变式 —— 跨变换保持的性质 + * + * 纯逻辑模块零 pi 依赖,离线单测,无硬件无网络。见架构设计文档_v3.md §5.2 / §7(T07)。 + */ + +import { describe, it, expect } from "vitest"; +import { + PbaEventBus, + KNOWN_EVENTS, + type PbaListener, + type PbaEmitter, + type ScopeKey, +} from "../src/core/pba-event-bus.js"; + +// ============================================================================ +// 辅助:spy emitter(断言 outbound 转发) +// ============================================================================ + +/** 构造记录调用的 spy emitter。 */ +function spyEmitter(): PbaEmitter & { calls: Array<{ event: string; data: unknown }> } { + const calls: Array<{ event: string; data: unknown }> = []; + return { + calls, + on: () => () => {}, + emit: (event, data) => calls.push({ event, data }), + }; +} + +/** 记录型 listener 工厂。 */ +function recorder(): { listener: PbaListener; seen: unknown[] } { + const seen: unknown[] = []; + return { seen, listener: (a) => seen.push(a) }; +} + +// ============================================================================ +// ① 等价类划分 —— 作用域归一 / 冒泡的有效·无效·边界类 +// ============================================================================ + +describe("① 等价类划分 —— normalizeScope 行为类(经 on/emit 可观察)", () => { + // 有效类:单段 / 多段 / global(undefined) + it.each([ + ["单段 'agent'", "agent"], + ["多段 'agent.sub.deep'", "agent.sub.deep"], + ])("有效作用域 %s 正常冒泡(global 监听收)", (_label, scope) => { + const bus = new PbaEventBus(); + const { listener, seen } = recorder(); + bus.on("build:done", listener); // global + bus.emit("build:done", 1, scope); + expect(seen).toEqual([1]); // global 收一切 + }); + + it.each([ + ["undefined", undefined], + ["空串 ''", ""], + ["纯空白 ' '", " "], + ["只有点 '.'", "."], + ["多点 '..'", ".."], + ])("无效/归零作用域 %s 归一为 global(等同缺省)", (_label, scope) => { + const bus = new PbaEventBus(); + const got: string[] = []; + // 注册一个 scoped 监听(agent),emit 用归零 scope 不应下渗到子 + bus.on("build:done", () => got.push("scoped"), "agent"); + bus.emit("build:done", null, scope); + expect(got).toEqual([]); // 归零为 global emit → 不下渗到 scoped + }); + + it.each([ + ["'a..b' → 'a.b'", "a..b", "a.b"], + ["'a.' → 'a'", "a.", "a"], + ["'.b' → 'b'", ".b", "b"], + ["'.a.b.' → 'a.b'", ".a.b.", "a.b"], + ["'a...b' → 'a.b'", "a...b", "a.b"], + ])("含空段作用域 %s 归一(段边界对齐)", (_label, raw, norm) => { + // 用 scopedScope + 祖先冒泡反推归一结果:注册于 norm 的监听应收 emit 于 raw + const bus = new PbaEventBus(); + const { listener, seen } = recorder(); + bus.on("build:done", listener, norm); + bus.emit("build:done", "x", raw); // raw 归一后应 === norm → 收 + expect(seen).toEqual(["x"]); + }); +}); + +// ============================================================================ +// ② 边界值分析 —— off-by-one / 空 / 单 / 多 / 段边界 +// ============================================================================ + +describe("② 边界值分析 —— 监听数边界(0/1/2/N)", () => { + it("0 监听:emit 无副作用不抛,仍转发 emitter", () => { + const spy = spyEmitter(); + const bus = new PbaEventBus({ emitter: spy }); + expect(() => bus.emit("build:done", null)).not.toThrow(); + expect(bus.listenerCount("build:done")).toBe(0); + expect(spy.calls.length).toBe(1); + }); + + it("1 监听:收一次", () => { + const bus = new PbaEventBus(); + const { listener, seen } = recorder(); + bus.on("build:done", listener); + bus.emit("build:done", "only"); + expect(seen).toEqual(["only"]); + expect(bus.listenerCount("build:done")).toBe(1); + }); + + it("2 监听:按注册序广播,均收,互不影响", () => { + const bus = new PbaEventBus(); + const order: string[] = []; + bus.on("build:done", () => order.push("a")); + bus.on("build:done", () => order.push("b")); + bus.emit("build:done", null); + expect(order).toEqual(["a", "b"]); + expect(bus.listenerCount("build:done")).toBe(2); + }); + + it("N=50 监听:全收,顺序严格递增", () => { + const bus = new PbaEventBus(); + const N = 50; + const order: number[] = []; + for (let k = 0; k < N; k++) bus.on("build:done", () => order.push(order.length)); + bus.emit("build:done", null); + expect(order.length).toBe(N); + expect(order).toEqual(Array.from({ length: N }, (_, k) => k)); + }); +}); + +describe("② 边界值分析 —— scope 段边界(off-by-one 祖先判定)", () => { + it.each([ + ["等价:agent vs agent", "agent", "agent", true], + ["深一层:agent vs agent.sub", "agent", "agent.sub", true], + ["深两层:agent vs agent.sub.deep", "agent", "agent.sub.deep", true], + ["浅一层(后代不收父):agent.sub vs agent", "agent.sub", "agent", false], + ["段边界:agent vs agentX(非裸前缀)", "agent", "agentX", false], + ["段边界:agent vs agent-(连字符非分隔)", "agent", "agent-", false], + ["旁支:agent vs other", "agent", "other", false], + ["前缀但非祖先:ab vs abc 段", "ab", "abc", false], + ])( + "段边界 %s:listenerScope=%s emitScope=%s → receives=%s", + (_label, ls, es, expected) => { + const bus = new PbaEventBus(); + let got = false; + bus.on("build:done", () => (got = true), ls); + bus.emit("build:done", null, es); + expect(got).toBe(expected); + }, + ); +}); + +describe("② 边界值分析 —— scopedScope 拼接边界", () => { + it.each([ + ["('a','b') → 'a.b'", "a", "b", "a.b"], + ["('','b') → 'b'(父空=global)", "", "b", "b"], + ["('a','') → 'a'(子空)", "a", "", "a"], + ["('','') → ''(global)", "", "", ""], + ["('a.b','c.d') → 'a.b.c.d'", "a.b", "c.d", "a.b.c.d"], + ["('a..','b') → 'a.b'(归一)", "a..", "b", "a.b"], + ])("scopedScope %s", (_label, p, c, expected) => { + expect(new PbaEventBus().scopedScope(p as ScopeKey, c as ScopeKey)).toBe(expected); + }); +}); + +// ============================================================================ +// ③ 决策表 —— scopeReceives 全分支组合 → 期望 +// ============================================================================ + +describe("③ 决策表 —— scopeReceives 全分支(listenerScope × emitScope)", () => { + // 决策表(L=listenerScope, E=emitScope, R=receives): + // L=undef E=undef → true (global 收 global emit) + // L=undef E=str → true (global 收一切) + // L=str E=undef → false (global emit 不下渗子) + // L=str E=L → true (等价) + // L=str E=L+".x" → true (祖先) + // L=str E=L[:-1]+"X" → false (段边界) + // L=str E=其它 → false (旁支/后代) + const cases: Array<[string | undefined, string | undefined, boolean, string]> = [ + [undefined, undefined, true, "global 监听收 global emit"], + [undefined, "agent", true, "global 监听收 scoped emit"], + ["agent", undefined, false, "global emit 不下渗到 scoped 监听"], + ["agent", "agent", true, "等价 scope 收"], + ["agent", "agent.sub", true, "祖先监听收子 emit"], + ["agent", "agent.sub.deep", true, "远祖收深子"], + ["agent.sub", "agent", false, "后代不收父 emit"], + ["agent", "agentX", false, "段边界非裸前缀"], + ["agent", "other", false, "旁支不收"], + ["agent.sub", "agent.other", false, "兄弟节点不收"], + ]; + for (const [ls, es, expected, name] of cases) { + it(`决策表:${name} (L=${ls}, E=${es}) → ${expected}`, () => { + const bus = new PbaEventBus(); + let got = false; + bus.on("build:done", () => (got = true), ls); + bus.emit("build:done", null, es); + expect(got).toBe(expected); + }); + } +}); + +// ============================================================================ +// ④ 状态转换 —— 注册表生命周期 + 迁移 + 重入 + 不可达态 +// ============================================================================ + +describe("④ 状态转换 —— 注册表生命周期迁移", () => { + it("empty → on → has1 → on → has2 → off → has1 → dispose → empty", () => { + const bus = new PbaEventBus(); + expect(bus.listenerCount("build:done")).toBe(0); // empty + const l: PbaListener = () => {}; + const d1 = bus.on("build:done", l); + expect(bus.listenerCount("build:done")).toBe(1); // has1 + const d2 = bus.on("build:done", l, "agent"); + expect(bus.listenerCount("build:done")).toBe(2); // has2 + bus.off("build:done", l); + expect(bus.listenerCount("build:done")).toBe(0); // empty(off 清全部) + // 不可达态:dispose 已卸载条目(d1/d2)应为 no-op,不复活条目 + d1(); + d2(); + expect(bus.listenerCount("build:done")).toBe(0); // 仍 empty + }); + + it("disposer 卸载单条(幂等;不影响同 listener 其它条)", () => { + const bus = new PbaEventBus(); + const l: PbaListener = () => {}; + const dA = bus.on("build:done", l, "a"); + bus.on("build:done", l, "b"); + expect(bus.listenerCount("build:done")).toBe(2); + dA(); // 仅卸 scope=a 那条 + expect(bus.listenerCount("build:done")).toBe(1); + dA(); // 幂等 no-op + expect(bus.listenerCount("build:done")).toBe(1); + }); + + it("未注册事件 off / listenerCount 为 no-op/0(防御不可达态)", () => { + const bus = new PbaEventBus(); + expect(bus.listenerCount("nope")).toBe(0); + expect(() => bus.off("nope", () => {})).not.toThrow(); + }); +}); + +describe("④ 状态转换 —— 迭代中重入(on/off/dispose/emit during emit)", () => { + it("emit 期间监听自卸载(dispose)不崩,快照隔离保证后续仍跑", () => { + const bus = new PbaEventBus(); + const order: string[] = []; + let d = () => {}; + d = bus.on("build:done", () => { + order.push("a"); + d(); // 迭代中卸载自身 + }); + bus.on("build:done", () => order.push("b")); + bus.emit("build:done", null); + expect(order).toEqual(["a", "b"]); // 快照:b 仍跑 + expect(bus.listenerCount("build:done")).toBe(1); // a 已卸 + }); + + it("emit 期间新增 on 不被当前 emit 触发(快照不含后增)", () => { + const bus = new PbaEventBus(); + const order: string[] = []; + bus.on("build:done", () => { + order.push("a"); + bus.on("build:done", () => order.push("late")); // 迭代中增 + }); + bus.emit("build:done", null); + expect(order).toEqual(["a"]); // late 不在本轮快照 + expect(bus.listenerCount("build:done")).toBe(2); + bus.emit("build:done", null); + expect(order).toEqual(["a", "a", "late"]); // 下一轮才见 + }); + + it("emit 期间 off 后续监听:快照仍含(snapshot 语义,已卸条仍跑)", () => { + const bus = new PbaEventBus(); + const order: string[] = []; + const lNext: PbaListener = () => order.push("b"); + bus.on("build:done", () => { + order.push("a"); + bus.off("build:done", lNext); // 迭代中卸 b + }); + bus.on("build:done", lNext); + bus.emit("build:done", null); + // 快照仍含 b → b 仍跑(已知 snapshot 语义,文档化) + expect(order).toEqual(["a", "b"]); + expect(bus.listenerCount("build:done")).toBe(1); // b 已从注册表删 + }); + + it("重入 emit(监听内再 emit 同事件)有界终止不无限递归", () => { + const bus = new PbaEventBus(); + let depth = 0; + let maxDepth = 0; + bus.on("build:done", () => { + depth++; + maxDepth = Math.max(maxDepth, depth); + if (depth < 3) bus.emit("build:done", null); // 重入 + depth--; + }); + expect(() => bus.emit("build:done", null)).not.toThrow(); + expect(maxDepth).toBe(3); + }); +}); + +// ============================================================================ +// ④ 状态转换 —— waterfall 链状态机(链首/链中/链末/短路/重入) +// ============================================================================ + +describe("④ 状态转换 —— waterfall 链状态", () => { + it("链首→链中→链末:均调 next,全跑完,返回穿线 args(同引用)", () => { + const bus = new PbaEventBus(); + const order: string[] = []; + bus.on("debugger:attach", (_a, next) => { order.push("a"); next(); }); + bus.on("debugger:attach", (_a, next) => { order.push("b"); next(); }); + bus.on("debugger:attach", () => { order.push("c"); }); // 链末不调 next + const payload = { x: 1 }; + const out = bus.waterfall("debugger:attach", payload); + expect(order).toEqual(["a", "b", "c"]); + expect(out).toBe(payload); + }); + + it("链首不调 next → 短路(状态=断),中/末不跑", () => { + const bus = new PbaEventBus(); + const order: string[] = []; + bus.on("debugger:attach", () => { order.push("a"); /* 不调 next */ }); + bus.on("debugger:attach", () => order.push("b")); + bus.on("debugger:attach", () => order.push("c")); + const out = bus.waterfall("debugger:attach", "p"); + expect(order).toEqual(["a"]); + expect(out).toBe("p"); + }); + + it("链中不调 next → 短路于中(末不跑)", () => { + const bus = new PbaEventBus(); + const order: string[] = []; + bus.on("debugger:attach", (_a, next) => { order.push("a"); next(); }); + bus.on("debugger:attach", () => { order.push("b"); /* 短路 */ }); + bus.on("debugger:attach", () => order.push("c")); + bus.waterfall("debugger:attach", null); + expect(order).toEqual(["a", "b"]); + }); + + it("空链(0 监听)waterfall 不抛,返回原 args", () => { + const bus = new PbaEventBus(); + const out = bus.waterfall("nope", { z: 9 }); + expect(out).toEqual({ z: 9 }); + }); + + it("waterfall args 按引用穿线:上游改动下游可见", () => { + const bus = new PbaEventBus(); + bus.on("build:done", (a, next) => { (a as { v?: number }).v = 1; next(); }); + bus.on("build:done", (a, next) => { (a as { v?: number }).v = (a as { v?: number }).v! + 10; next(); }); + const payload: { v?: number } = {}; + const out = bus.waterfall("build:done", payload) as { v?: number }; + expect(out).toBe(payload); + expect(out.v).toBe(11); + }); + + it("waterfall 监听抛错向上传播(链断,不静默吞)", () => { + const bus = new PbaEventBus(); + const order: string[] = []; + bus.on("build:done", (_a, next) => { order.push("a"); next(); }); + bus.on("build:done", () => { order.push("b"); throw new Error("boom"); }); + bus.on("build:done", () => order.push("c")); + expect(() => bus.waterfall("build:done", null)).toThrow("boom"); + expect(order).toEqual(["a", "b"]); // c 不跑 + }); + + it("waterfall 按 scope 冒泡选监听(同 emit 规则)", () => { + const bus = new PbaEventBus(); + const ran: string[] = []; + bus.on("debugger:attach", (_a, next) => { ran.push("parent"); next(); }, "agent"); + bus.on("debugger:attach", (_a, next) => { ran.push("sibling"); next(); }, "agent.other"); + bus.on("debugger:attach", (_a, next) => { ran.push("global"); next(); }); + bus.waterfall("debugger:attach", null, "agent.sub"); + expect(ran).toEqual(["parent", "global"]); // 祖先 + global 续链;旁支 sibling 非匹配不收 + }); +}); + +// ============================================================================ +// ⑥ 对抗/fuzz —— 畸形/滥用输入 +// ============================================================================ + +describe("⑥ 对抗/fuzz —— 畸形/滥用输入不崩", () => { + it("args=null/undefined/0/false/'' 均原样穿透", () => { + const bus = new PbaEventBus(); + const seen: unknown[] = []; + bus.on("build:done", (a) => seen.push(a)); + for (const a of [null, undefined, 0, false, "", NaN]) { + bus.emit("build:done", a); + } + expect(seen).toEqual([null, undefined, 0, false, "", NaN]); + }); + + it("循环引用对象作 args 不崩(按引用传,监听可读)", () => { + const bus = new PbaEventBus(); + const obj: { self?: unknown; n: number } = { n: 1 }; + obj.self = obj; + let got: unknown = null; + bus.on("build:done", (a) => { got = a; }); + bus.emit("build:done", obj); + expect(got).toBe(obj); + }); + + it("巨大 payload(1e6 元素数组)不崩、同引用", () => { + const bus = new PbaEventBus(); + const big = new Array(1_000_000).fill(0); + let got: unknown = null; + bus.on("build:done", (a) => { got = a; }); + bus.emit("build:done", big); + expect(got).toBe(big); + }); + + it("超长 scope 字符串(1e4 段)归一不崩", () => { + const bus = new PbaEventBus(); + const segs = Array.from({ length: 10_000 }, (_, i) => `s${i}`).join("."); + const { listener, seen } = recorder(); + bus.on("build:done", listener); // global 收 + bus.emit("build:done", 1, segs); + expect(seen).toEqual([1]); + }); + + it("event 名含特殊字符 / 空串 不崩(开放扩展,不强制 KNOWN_EVENTS)", () => { + const bus = new PbaEventBus(); + const seen: string[] = []; + bus.on("weird:event:with:colons", () => seen.push("a")); + bus.on("", () => seen.push("b")); + bus.emit("weird:event:with:colons", null); + bus.emit("", null); + expect(seen).toEqual(["a", "b"]); + }); + + it("waterfall 监听内多次调 next(滥用):链被推进但不重入已越界项,仍终止", () => { + const bus = new PbaEventBus(); + const order: string[] = []; + bus.on("build:done", (_a, next) => { order.push("a"); next(); next(); /* 误调两次 */ }); + bus.on("build:done", () => order.push("b")); + expect(() => bus.waterfall("build:done", null)).not.toThrow(); + // a 首 next → 跑 b(i→2);a 次 next → i=2>=len(2) 直接返回,不重跑 b + expect(order).toEqual(["a", "b"]); + }); + + it("disposer 在 emit 内对另一事件操作互不干扰", () => { + const bus = new PbaEventBus(); + const d = bus.on("a", () => {}); + bus.on("b", () => d()); // emit b 时卸 a + expect(bus.listenerCount("a")).toBe(1); + bus.emit("b", null); + expect(bus.listenerCount("a")).toBe(0); + }); +}); + +// ============================================================================ +// ⑤ 变异测试 —— 5 个 seeded bug 内联副本,逐个被杀 +// 每个 it:real 副本产正确值,buggy 副本产错误值 → +// 断言「正确值」的测试若植入该 bug 即 FAIL(bug 被杀)。 +// 副本镜像 src/core/pba-event-bus.ts 对应纯函数/方法逻辑。 +// ============================================================================ + +// --- 镜像:normalizeScope(src 第 133-140 行) --- +function normalizeScopeReal(scope: string | undefined): string | undefined { + if (scope === undefined) return undefined; + const segs = scope.split(".").filter((s) => s.length > 0); + return segs.length === 0 ? undefined : segs.join("."); +} +// 变体 M2:filter 条件 `s.length > 0` → `s.length >= 0`(恒真,保留空段) +function normalizeScopeBuggyKeepEmpty(scope: string | undefined): string | undefined { + if (scope === undefined) return undefined; + const segs = scope.split(".").filter((s) => s.length >= 0); // BUG + return segs.length === 0 ? undefined : segs.join("."); +} + +// --- 镜像:scopeReceives(src 第 153-163 行) --- +function scopeReceivesReal(ls: string | undefined, es: string | undefined): boolean { + if (ls === undefined) return true; + if (es === undefined) return false; + if (ls === es) return true; + return es.startsWith(ls + "."); +} +// 变体 M1:丢段边界 "."(裸前缀匹配)→ "agent" 误判为 "agentX" 祖先 +function scopeReceivesBuggyNakedPrefix(ls: string | undefined, es: string | undefined): boolean { + if (ls === undefined) return true; + if (es === undefined) return false; + if (ls === es) return true; + return es.startsWith(ls); // BUG:丢 "." +} + +// --- 镜像:waterfall next 链(src 第 350-360 行) --- +function waterfallReal(matched: PbaListener[], args: unknown): unknown { + let i = 0; + const next = (): void => { + if (i >= matched.length) return; // 链末 + const entry = matched[i]; + i++; + entry(args, next); + }; + next(); + return args; +} +// 变体 M3:`i >= matched.length` → `i > matched.length`(off-by-one,链末越界) +function waterfallBuggyOffByOne(matched: PbaListener[], args: unknown): unknown { + let i = 0; + const next = (): void => { + if (i > matched.length) return; // BUG:应为 >= + const entry = matched[i]; // 链末时越界 → undefined + i++; + entry(args, next); // undefined(args,next) → TypeError + }; + next(); + return args; +} + +// --- 镜像:disposer splice(src 第 283-289 行 on 返回闭包核心) --- +function disposeReal(arr: unknown[], entry: unknown): void { + const idx = arr.indexOf(entry); + if (idx >= 0) arr.splice(idx, 1); +} +// 变体 M4:`idx >= 0` → `idx > 0`(off-by-one,漏卸 index 0) +function disposeBuggySkipIndex0(arr: unknown[], entry: unknown): void { + const idx = arr.indexOf(entry); + if (idx > 0) arr.splice(idx, 1); // BUG +} + +// --- 变体 M5:KNOWN_EVENTS 漏 Object.freeze(可变) --- +const KNOWN_EVENTS_BUGGY_NOFREEZE: string[] = [...KNOWN_EVENTS]; + +describe("⑤ 变异测试 —— seeded bug 逐个被杀", () => { + it("M1 [scopeReceives 丢段边界]:'agent' 不应是 'agentX' 的祖先", () => { + const correct = false; + expect(scopeReceivesReal("agent", "agentX")).toBe(correct); // 正确 + expect(scopeReceivesBuggyNakedPrefix("agent", "agentX")).toBe(true); // 变体误判 + // 杀伤验证:buggy 副本跑真实断言必 FAIL(bug 被杀) + expect(() => expect(scopeReceivesBuggyNakedPrefix("agent", "agentX")).toBe(correct)).toThrow(); + // 杀它的测试:② 段边界 / ③ 决策表「段边界非裸前缀」 + }); + + it("M2 [normalizeScope 保留空段]:'a..b' 应归一为 'a.b'", () => { + const correct = "a.b"; + expect(normalizeScopeReal("a..b")).toBe(correct); // 正确 + expect(normalizeScopeBuggyKeepEmpty("a..b")).toBe("a..b"); // 变体未归一 + // 杀伤验证:buggy 副本跑真实断言必 FAIL + expect(() => expect(normalizeScopeBuggyKeepEmpty("a..b")).toBe(correct)).toThrow(); + // 杀它的测试:① 等价类「含空段作用域归一」 + }); + + it("M3 [waterfall 链末 >= 改 > off-by-one]:空链应安全返回不抛", () => { + expect(() => waterfallReal([], null)).not.toThrow(); // 正确 + expect(() => waterfallBuggyOffByOne([], null)).toThrow(); // 变体越界抛 + // 杀伤验证:buggy 副本跑真实断言(不抛)必 FAIL + expect(() => expect(() => waterfallBuggyOffByOne([], null)).not.toThrow()).toThrow(); + expect(waterfallReal([], null)).toBe(null); + // 杀它的测试:④ waterfall「空链不抛」+「三链全跑完链末 next no-op」 + }); + + it("M4 [disposer idx>=0 改 >0 off-by-one]:index 0 的条目应可卸载", () => { + const entry = {}; + const arrReal = [entry]; + const arrBuggy = [entry]; + disposeReal(arrReal, entry); + disposeBuggySkipIndex0(arrBuggy, entry); + expect(arrReal).toEqual([]); // 正确:卸掉 + expect(arrBuggy).toEqual([entry]); // 变体:漏卸 index 0 + // 杀伤验证:buggy 副本跑真实断言(卸后为空)必 FAIL + expect(() => expect(arrBuggy).toEqual([])).toThrow(); + // 杀它的测试:④「disposer 卸载单条」+ ② 单元素边界 + }); + + it("M5 [KNOWN_EVENTS 漏 freeze]:push 应抛 TypeError", () => { + expect(() => (KNOWN_EVENTS as unknown as string[]).push("evil")).toThrow(TypeError); // 正确:冻结 + expect(() => KNOWN_EVENTS_BUGGY_NOFREEZE.push("evil")).not.toThrow(); // 变体:未冻结可改 + expect(KNOWN_EVENTS_BUGGY_NOFREEZE).toContain("evil"); + // 杀伤验证:buggy 副本跑真实断言(push 抛 TypeError)必 FAIL + expect(() => expect(() => KNOWN_EVENTS_BUGGY_NOFREEZE.push("evil2")).toThrow(TypeError)).toThrow(); + // 杀它的测试:⑦ 不变式「深冻结:push 抛 TypeError」 + }); + + it("真实代码无植入 bug:全方法论断言均成立(all green 前提)", () => { + // 抽样确认真实副本与真实 bus 行为一致 + const bus = new PbaEventBus(); + let got = false; + bus.on("build:done", () => (got = true), "agent"); + bus.emit("build:done", null, "agentX"); + expect(got).toBe(false); // = scopeReceivesReal("agent","agentX") + expect(scopeReceivesReal("agent", "agentX")).toBe(false); + }); +}); + +// ============================================================================ +// ⑦ 元蜕变/不变式 —— 跨变换保持的性质 +// ============================================================================ + +describe("⑦ 元蜕变/不变式 —— 跨变换保持的性质", () => { + it("不变式:global 监听收一切(任意 scoped emit)", () => { + const bus = new PbaEventBus(); + let n = 0; + bus.on("build:done", () => n++); // global + bus.emit("build:done", null, "agent"); + bus.emit("build:done", null, "agent.sub.deep"); + bus.emit("build:done", null); // global emit + expect(n).toBe(3); + }); + + it("不变式:global emit 不下渗到任何 scoped 监听(fail-closed 单向冒泡)", () => { + const bus = new PbaEventBus(); + let n = 0; + bus.on("build:done", () => n++, "agent"); + bus.on("build:done", () => n++, "agent.sub"); + bus.on("build:done", () => n++, "other"); + bus.emit("build:done", null); // global emit + expect(n).toBe(0); + }); + + it("元蜕变:广播一次到 N 监听 ≡ 逐个 emit 各收一次(计数等价)", () => { + const bus = new PbaEventBus(); + const a = recorder(); + const b = recorder(); + const c = recorder(); + bus.on("build:done", a.listener); + bus.on("build:done", b.listener); + bus.on("build:done", c.listener); + bus.emit("build:done", "p"); // 一次广播 + expect(a.seen).toEqual(["p"]); + expect(b.seen).toEqual(["p"]); + expect(c.seen).toEqual(["p"]); + }); + + it("元蜕变:append 两次(两监听)后单次 emit ≡ 两次单监听 emit 的并集(序保持)", () => { + // 变换 A:注册 a,b 后 emit 一次 + const busA = new PbaEventBus(); + const logA: string[] = []; + busA.on("build:done", () => logA.push("a")); + busA.on("build:done", () => logA.push("b")); + busA.emit("build:done", null); + + // 变换 B:分别注册单监听各 emit 一次,拼接 + const logB: string[] = []; + const busB1 = new PbaEventBus(); + busB1.on("build:done", () => logB.push("a")); + busB1.emit("build:done", null); + const busB2 = new PbaEventBus(); + busB2.on("build:done", () => logB.push("b")); + busB2.emit("build:done", null); + + expect(logA).toEqual(logB); // 两种变换等价 + }); + + it("不变式:KNOWN_EVENTS 深冻结——push/改写均抛 TypeError", () => { + expect(() => (KNOWN_EVENTS as unknown as string[]).push("x")).toThrow(TypeError); + expect(() => { + (KNOWN_EVENTS as unknown as unknown[])[0] = "evil"; + }).toThrow(TypeError); + expect(() => Object.defineProperty(KNOWN_EVENTS, "length", { value: 99 })).toThrow(); + }); + + it("不变式:KNOWN_EVENTS 8 成员齐备且有序", () => { + expect(KNOWN_EVENTS).toEqual([ + "verify:passed", + "build:done", + "boardlink:connect", + "glm:empty-output", + "xcompile:done", + "pdf-reader:page", + "debugger:attach", + "length-recovery:recovered", + ]); + }); + + it("单调 deny:scope 匹配是纯函数——同 (L,E) 多次 emit 结果恒定", () => { + const bus = new PbaEventBus(); + let count = 0; + bus.on("build:done", () => count++, "agent.sub"); + for (let i = 0; i < 5; i++) bus.emit("build:done", null, "agent"); + expect(count).toBe(0); // 后代监听恒不收父 emit + for (let i = 0; i < 5; i++) bus.emit("build:done", null, "agent.sub.deep"); + expect(count).toBe(5); // 祖先恒收 + }); + + it("waterfall 不调 next=短路(下游恒不跑)——单调性", () => { + const bus = new PbaEventBus(); + let downstream = 0; + bus.on("build:done", () => { /* 短路 */ }); + bus.on("build:done", () => downstream++); + for (let i = 0; i < 10; i++) bus.waterfall("build:done", null); + expect(downstream).toBe(0); + }); + + it("emit fail-soft 不变式:单监听抛错不阻断其余 + emitter 转发", () => { + const spy = spyEmitter(); + const bus = new PbaEventBus({ emitter: spy }); + const order: string[] = []; + bus.on("build:done", () => { order.push("a"); throw new Error("boom"); }); + bus.on("build:done", () => order.push("b")); + expect(() => bus.emit("build:done", null)).not.toThrow(); + expect(order).toEqual(["a", "b"]); + expect(spy.calls.length).toBe(1); + }); + + it("emitter 转发解耦:emitter 抛错不阻断 bus 监听", () => { + const throwing: PbaEmitter = { on: () => () => {}, emit: () => { throw new Error("x"); } }; + const bus = new PbaEventBus({ emitter: throwing }); + const { listener, seen } = recorder(); + bus.on("build:done", listener); + expect(() => bus.emit("build:done", 1)).not.toThrow(); + expect(seen).toEqual([1]); + }); + + it("emit 同步转发 (event, args) 到 emitter(outbound 薄封装)", () => { + const spy = spyEmitter(); + const bus = new PbaEventBus({ emitter: spy }); + bus.emit("build:done", { ok: true }); + bus.emit("verify:passed", 42, "agent"); + expect(spy.calls).toEqual([ + { event: "build:done", data: { ok: true } }, + { event: "verify:passed", data: 42 }, + ]); + }); + + it("waterfall 不向 emitter 转发(链是请求语义,非广播)", () => { + const spy = spyEmitter(); + const bus = new PbaEventBus({ emitter: spy }); + bus.on("build:done", (_a, next) => next()); + bus.waterfall("build:done", null); + expect(spy.calls.length).toBe(0); + }); +}); diff --git a/tests/pba-session.test.ts b/tests/pba-session.test.ts new file mode 100644 index 0000000..77dd4ae --- /dev/null +++ b/tests/pba-session.test.ts @@ -0,0 +1,1053 @@ +/** + * pba-session 完整测试套件 —— T06 事件溯源底座。 + * + * 被测对象:src/core/pba-session.ts 的命名导出 + * - PbaSession(class:append / deriveMessages / getEntries / + * replayFromEntries / assertModelVisibleLogged) + * - MODEL_VISIBLE_TYPES(冻结常量) + * - 类型 PbaSessionEntry / DerivedMessage(仅 type-only import) + * + * 纯逻辑模块,零 pi 运行时依赖:mock 注入 appendEntry sink,离线可单测。 + * + * 多测试方法论(每个 describe 块标题标注方法论名): + * - 等价类划分(有效/无效/边界类) + * - 边界值分析(空、单元素、min、off-by-one、cache 边界) + * - 决策表(组合输入 → 期望,覆盖全分支) + * - 状态转换(seq 回滚 / reentrant guard / cache 生命周期 / replay seq 模式) + * - 变异测试(5 个 seeded bug 内联副本 + it.fails 杀手 + 真实代码 kill-by-test 标注) + * - 对抗/fuzz(null / undefined / NaN / 巨大 / 循环引用 / 负 seq / 重入) + * - 元蜕变/不变式(append²=replay 等价;freeze→篡改抛 TypeError;单调 seq; + * waterfall 短路;fail-closed unusable=拒) + * + * 门: + * 1. `npx vitest run tests/pba-session.test.ts` —— 真实代码全绿 + * (it.fails 杀手在 mutant 副本上断言失败 → 计为 pass = bug 被杀)。 + * 2. 每个 seeded bug:mutant 副本上杀手 body 失败(it.fails 通过)= bug 被杀。 + * 若把对应 bug 打进真实 src/core/pba-session.ts,标注的【真实代码测试】变红。 + */ + +import { describe, it, expect } from "vitest"; +import { + PbaSession, + MODEL_VISIBLE_TYPES, + type PbaSessionEntry, + type DerivedMessage, +} from "../src/core/pba-session.js"; + +// ============================================================================ +// 公共夹具 +// ============================================================================ + +/** 记录型 appendEntry sink:捕获下沉参数,可断言。 */ +function recordingSink(): { + sink: (type: string, data: unknown) => void; + calls: Array<{ type: string; data: unknown }>; +} { + const calls: Array<{ type: string; data: unknown }> = []; + return { sink: (type, data) => calls.push({ type, data }), calls }; +} + +/** no-op sink。 */ +const noopSink = (): void => {}; + +/** 抛错型 sink(测 seq 回滚 / fail-closed 路径)。 */ +function throwingSink(msg = "boom"): (type: string, data: unknown) => void { + return () => { + throw new Error(msg); + }; +} + +/** 首调抛、次调成功的 sink(测 seq 回滚后续写)。 */ +function firstFailSink(msg = "first-fail"): { + sink: (type: string, data: unknown) => void; +} { + let first = true; + return { + sink: () => { + if (first) { + first = false; + throw new Error(msg); + } + }, + }; +} + +// 事件构造器 +const userMsg = (content: string) => ({ type: "user-message", data: { role: "user" as const, content } }); +const assistantMsg = (content: string) => ({ + type: "assistant-message", + data: { role: "assistant" as const, content }, +}); +const toolCall = (name: string, args: unknown = {}) => ({ type: "tool-call", data: { name, args } }); +const toolResult = (name: string, result: unknown) => ({ type: "tool-result", data: { name, result } }); + +// ============================================================================ +// 变异测试基础设施 —— 忠实内联副本(单行 bug 注入) +// ---------------------------------------------------------------------------- +// MutantPbaSession 是 src/core/pba-session.ts 的逐行忠实副本,仅通过 constructor +// 的 `bug` 选项在【恰好一处】注入 seeded bug。每个 bug 配一个 it.fails 杀手: +// 杀手断言【真实正确行为】,在 mutant 副本上断言失败 → it.fails 通过 = bug 被杀。 +// 若有人把 mutant 修回真实行为,it.fails 会变红(敏感度证)。 +// loadEntries 在真实类里是 private(TS 跨实例可访问),副本里直接内联等价逻辑。 +// ============================================================================ + +const LOSSLESS_TAG = "__pbaType"; + +function snapV(value: unknown, seen: WeakSet): unknown { + if (value === null || typeof value !== "object") return value; + const ref = value as object; + if (seen.has(ref)) { + throw new Error("PbaSession: cannot snapshot cyclic object (lossless-JSON invariant)"); + } + seen.add(ref); + if (value instanceof Date) return { [LOSSLESS_TAG]: "Date", value: value.toISOString() }; + if (value instanceof Map) { + const entries = [...value.entries()].map(([k, v]) => [snapV(k, seen), snapV(v, seen)]); + return { [LOSSLESS_TAG]: "Map", value: entries }; + } + if (value instanceof Set) { + return { [LOSSLESS_TAG]: "Set", value: [...value].map((v) => snapV(v, seen)) }; + } + if (Array.isArray(value)) return value.map((v) => snapV(v, seen)); + const out: Record = {}; + for (const [k, v] of Object.entries(value)) out[k] = snapV(v, seen); + return out; +} + +function freezeM(value: T): T { + if (value === null || typeof value !== "object") return value; + if (Array.isArray(value)) for (const v of value) freezeM(v); + else for (const v of Object.values(value as Record)) freezeM(v); + Object.freeze(value); + return value; +} + +function projectMsg(entry: { type: string; data: unknown }): DerivedMessage | null { + const data = (entry.data ?? null) as Record | null; + switch (entry.type) { + case "user-message": + return { role: "user", content: data?.content ?? "" }; + case "assistant-message": + return { role: "assistant", content: data?.content ?? "" }; + case "tool-call": + return { + role: "assistant", + content: null, + toolCalls: [{ name: String(data?.name ?? ""), args: data?.args ?? null }], + }; + case "tool-result": + return { role: "tool", name: String(data?.name ?? ""), content: data?.result ?? null }; + default: + return null; + } +} + +type Bug = + | "none" + | "no-rollback" // M1: 下沉失败时漏 this.seq -= 1 + | "no-cache-invalidate" // M2: append 后漏 this.messagesCache = null + | "seq-lt" // M3: replay seq 校验 !== → <(放行前向缺口) + | "assert-inverted" // M4: assertModelVisibleLogged 条件取反(已 logged 反而抛) + | "no-reentrant-guard"; // M5: 漏 reentrant guard(appending 不生效) + +interface MutantEntry { + readonly type: string; + readonly data: unknown; + readonly seq: number; + readonly ts: number; +} + +class MutantPbaSession { + private appendEntry: (type: string, data: unknown) => void; + private readonly useFreeze: boolean; + private readonly bug: Bug; + private seq = 0; + private readonly log: MutantEntry[] = []; + private readonly loggedTypes = new Set(); + private cache: ReadonlyArray | null = null; + private appending = false; + + constructor(opts: { appendEntry: (type: string, data: unknown) => void; deepFreeze?: boolean; bug: Bug }) { + this.appendEntry = opts.appendEntry; + this.useFreeze = opts.deepFreeze ?? true; + this.bug = opts.bug; + } + + append(event: { type: string; data: unknown }): void { + // BUG M5 (no-reentrant-guard): 跳过 reentrant guard + if (this.bug !== "no-reentrant-guard" && this.appending) { + throw new Error("PbaSession: reentrant append detected"); + } + this.appending = true; + try { + const snap = snapV(event.data, new WeakSet()); + const stored = this.useFreeze ? freezeM(snap) : snap; + this.seq += 1; + const entry: MutantEntry = { type: event.type, data: stored, seq: this.seq, ts: Date.now() }; + if (this.useFreeze) Object.freeze(entry); + try { + this.appendEntry(event.type, stored); + } catch (err) { + // BUG M1 (no-rollback): 漏 seq 回滚 + if (this.bug !== "no-rollback") this.seq -= 1; + throw err; + } + this.log.push(entry); + this.loggedTypes.add(event.type); + // BUG M2 (no-cache-invalidate): 漏缓存失效 + if (this.bug !== "no-cache-invalidate") this.cache = null; + } finally { + this.appending = false; + } + } + + deriveMessages(): unknown[] { + if (this.cache !== null) return this.cache as unknown[]; + const messages: DerivedMessage[] = []; + for (const entry of this.log) { + const m = projectMsg(entry); + if (m) messages.push(m); + } + const out = this.useFreeze ? (freezeM(messages) as unknown[]) : (messages as unknown[]); + this.cache = out; + return out; + } + + getEntries(): readonly MutantEntry[] { + return this.log; + } + + replayFromEntries(entries: ReadonlyArray<{ type: string; data: unknown; seq?: number }>): MutantPbaSession { + const next = new MutantPbaSession({ appendEntry: this.appendEntry, deepFreeze: this.useFreeze, bug: this.bug }); + this.loadEntriesInto(next, entries); + return next; + } + + private loadEntriesInto( + target: MutantPbaSession, + entries: ReadonlyArray<{ type: string; data: unknown; seq?: number }>, + ): void { + let lastSeq: number | null = null; + const loaded: MutantEntry[] = []; + for (let i = 0; i < entries.length; i++) { + const e = entries[i]; + if (!e || typeof e.type !== "string") { + throw new Error(`PbaSession: replay entry[${i}] missing string type`); + } + let seq: number; + if (typeof e.seq === "number") { + seq = e.seq; + if (!(seq >= 1)) { + throw new Error(`PbaSession: replay entry[${i}] seq ${seq} violates lower bound`); + } + if (lastSeq !== null) { + const expected = lastSeq + 1; + // BUG M3 (seq-lt): 把 !== 换成 <(仅拒回退/相等,放行前向缺口) + const bad = this.bug === "seq-lt" ? seq < expected : seq !== expected; + if (bad) { + throw new Error(`PbaSession: seq discontinuity at entry[${i}] — expected ${expected}, got ${seq}`); + } + } + } else { + seq = lastSeq === null ? 1 : lastSeq + 1; + } + lastSeq = seq; + const snap = snapV(e.data, new WeakSet()); + const stored = target.useFreeze ? freezeM(snap) : snap; + const entry: MutantEntry = { type: e.type, data: stored, seq, ts: Date.now() }; + if (target.useFreeze) Object.freeze(entry); + loaded.push(entry); + } + for (const e of loaded) { + (target as unknown as { log: MutantEntry[] }).log.push(e); + (target as unknown as { loggedTypes: Set }).loggedTypes.add(e.type); + } + (target as unknown as { seq: number }).seq = lastSeq ?? 0; + (target as unknown as { cache: ReadonlyArray | null }).cache = null; + } + + assertModelVisibleLogged(visibleTypes: readonly string[]): void { + for (const t of visibleTypes) { + const present = this.loggedTypes.has(t); + // BUG M4 (assert-inverted): 条件取反(已 logged 反而抛) + const shouldThrow = this.bug === "assert-inverted" ? present : !present; + if (shouldThrow) { + throw new Error(`PbaSession: type "${t}" declared model-visible but never logged`); + } + } + } +} + +// ============================================================================ +// ① 等价类划分 — append data 有效类(原始/普通对象/Date/Map/Set/Array/嵌套) +// ============================================================================ + +describe("等价类划分 — append data 有效类", () => { + it("原始值(number/string/boolean/null)原样下沉且可投影", () => { + const { sink, calls } = recordingSink(); + const s = new PbaSession({ appendEntry: sink }); + s.append({ type: "user-message", data: { role: "user", content: "plain" } }); + s.append({ type: "tool-result", data: { name: "r", result: 42 } }); + expect(calls[0]?.data).toEqual({ role: "user", content: "plain" }); + expect(calls[1]?.data).toEqual({ name: "r", result: 42 }); + const msgs = s.deriveMessages() as DerivedMessage[]; + expect(msgs[1].role).toBe("tool"); + expect(msgs[1].content).toBe(42); + }); + + it("Date/Map/Set 折叠成 lossless 标记对象(round-trip 无损标记)", () => { + const { sink, calls } = recordingSink(); + const s = new PbaSession({ appendEntry: sink }); + const when = new Date(0); + const tbl = new Map([ + ["a", 1], + ["b", 2], + ]); + const flags = new Set([2, 3]); + s.append({ type: "hw:state", data: { type: "snapshot", data: { when, tbl, flags }, ts: 1 } }); + const stored = calls[0]?.data as { data: { when: unknown; tbl: unknown; flags: unknown } }; + expect(stored.data.when).toEqual({ __pbaType: "Date", value: "1970-01-01T00:00:00.000Z" }); + expect(stored.data.tbl).toEqual({ __pbaType: "Map", value: [["a", 1], ["b", 2]] }); + expect(stored.data.flags).toEqual({ __pbaType: "Set", value: [2, 3] }); + }); + + it("嵌套 Array/对象递归快照;Map 键值亦递归", () => { + const { sink, calls } = recordingSink(); + const s = new PbaSession({ appendEntry: sink }); + s.append({ + type: "hw:state", + data: { type: "nested", data: { arr: [1, { d: new Date(1) }], m: new Map([[new Map([["k", "v"]]), 1]]) }, ts: 2 }, + }); + const stored = calls[0]?.data as { data: { arr: unknown[]; m: { __pbaType: string; value: unknown[] } } }; + expect((stored.data.arr[1] as { d: { __pbaType: string; value: string } }).d).toEqual({ + __pbaType: "Date", + value: "1970-01-01T00:00:00.001Z", + }); + expect(stored.data.m.__pbaType).toBe("Map"); + expect((stored.data.m.value[0] as unknown[])[0]).toEqual({ __pbaType: "Map", value: [["k", "v"]] }); + }); + + it("data = null / undefined:原样快照(不抛)", () => { + const { sink, calls } = recordingSink(); + const s = new PbaSession({ appendEntry: sink }); + s.append({ type: "turn", data: null }); + s.append({ type: "step", data: undefined }); + expect(calls[0]?.data).toBeNull(); + expect(calls[1]?.data).toBeUndefined(); + }); +}); + +// ============================================================================ +// ② 等价类划分 — append type 开放性 + 非投影类(无效 type 不存在:开放 string) +// ============================================================================ + +describe("等价类划分 — append type 开放性 + 非投影类", () => { + it("开放 string type:任意非枚举 type 亦可 append", () => { + const { sink, calls } = recordingSink(); + const s = new PbaSession({ appendEntry: sink }); + s.append({ type: "custom-event-x", data: { foo: 1 } }); + expect(calls[0]?.type).toBe("custom-event-x"); + expect(s.getEntries()[0].type).toBe("custom-event-x"); + }); + + it("非投影类(turn/step/hw:state/flash-log/verify-record/checkpoint-change)不进 deriveMessages", () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append({ type: "turn", data: { turn: 1, phase: "start" } }); + s.append({ type: "step", data: { turn: 1, step: 1, phase: "start" } }); + s.append({ type: "hw:state", data: { type: "gpio", data: { pin: 33 }, ts: 1 } }); + s.append({ type: "flash-log", data: { method: "dd", target: "/dev/sdX", image: "x.img", result: "ok", ts: 1 } }); + s.append({ type: "user-message", data: { role: "user", content: "only-me" } }); + expect(s.deriveMessages()).toHaveLength(1); + }); +}); + +// ============================================================================ +// ③ 边界值分析 — 空会话 / 单元素 / seq 起点(off-by-one) +// ============================================================================ + +describe("边界值分析 — 空会话 / 单元素 / seq=1 起点", () => { + it("空会话:deriveMessages 返回空数组;getEntries 空;assert 空列表不抛", () => { + const s = new PbaSession({ appendEntry: noopSink }); + expect(s.deriveMessages()).toEqual([]); + expect(s.getEntries()).toHaveLength(0); + expect(() => s.assertModelVisibleLogged([])).not.toThrow(); + }); + + it("单元素:首次 append seq=1(off-by-one:非 0)", () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append(userMsg("solo")); + const e = s.getEntries()[0]; + expect(e.seq).toBe(1); + expect(s.deriveMessages()).toHaveLength(1); + }); + + it("第二条 seq=2(连续 +1,无缺口)", () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append(userMsg("a")); + s.append(userMsg("b")); + expect(s.getEntries()[0].seq).toBe(1); + expect(s.getEntries()[1].seq).toBe(2); + }); + + it("MODEL_VISIBLE_TYPES 冻结且四元素有序", () => { + expect(Object.isFrozen(MODEL_VISIBLE_TYPES)).toBe(true); + expect([...MODEL_VISIBLE_TYPES]).toEqual([ + "user-message", + "assistant-message", + "tool-call", + "tool-result", + ]); + expect(() => (MODEL_VISIBLE_TYPES as string[]).push("x")).toThrow(TypeError); + }); +}); + +// ============================================================================ +// ④ 边界值分析 — deriveMessages / getEntries 缓存边界 +// ============================================================================ + +describe("边界值分析 — 缓存边界(首次构建→命中→失效)", () => { + it("deriveMessages 首次构建缓存;二次同引用;append 后失效新引用", () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append(userMsg("a")); + const m1 = s.deriveMessages(); + const m2 = s.deriveMessages(); + expect(m1).toBe(m2); // 命中:同引用 + s.append(userMsg("b")); + const m3 = s.deriveMessages(); + expect(m3).not.toBe(m1); // 失效:新引用 + expect(m3).toHaveLength(2); + }); + + it("getEntries 首次构建;二次同引用;append 后失效新引用", () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append(userMsg("a")); + const e1 = s.getEntries(); + const e2 = s.getEntries(); + expect(e1).toBe(e2); // 命中 + s.append(userMsg("b")); + const e3 = s.getEntries(); + expect(e3).not.toBe(e1); // 失效 + expect(e3).toHaveLength(2); + }); + + it("连续 append 后多次 derive:每次 append 失效,二次命中", () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append(userMsg("a")); + const a = s.deriveMessages(); + s.append(userMsg("b")); + const b1 = s.deriveMessages(); + const b2 = s.deriveMessages(); + expect(b1).toBe(b2); // 命中 + expect(b1).not.toBe(a); // 失效 + expect(b1).toHaveLength(2); + }); +}); + +// ============================================================================ +// ⑤ 决策表 — projectMessage 全分支(type × data 缺字段 → 投影形状) +// ============================================================================ + +describe("决策表 — projectMessage 全分支", () => { + const cases: Array<{ + name: string; + type: string; + data: unknown; + expect: Partial & { projected: boolean }; + }> = [ + { name: "user-message", type: "user-message", data: { role: "user", content: "hi" }, expect: { projected: true, role: "user", content: "hi" } }, + { name: "user-message 无 content", type: "user-message", data: { role: "user" }, expect: { projected: true, role: "user", content: "" } }, + { name: "assistant-message", type: "assistant-message", data: { role: "assistant", content: "yo" }, expect: { projected: true, role: "assistant", content: "yo" } }, + { name: "assistant-message 无 content", type: "assistant-message", data: {}, expect: { projected: true, role: "assistant", content: "" } }, + { name: "tool-call", type: "tool-call", data: { name: "devmem", args: { a: 1 } }, expect: { projected: true, role: "assistant", content: null, toolCalls: [{ name: "devmem", args: { a: 1 } }] } }, + { name: "tool-call 无 name/args", type: "tool-call", data: {}, expect: { projected: true, role: "assistant", content: null, toolCalls: [{ name: "", args: null }] } }, + { name: "tool-result", type: "tool-result", data: { name: "devmem", result: "0x1" }, expect: { projected: true, role: "tool", name: "devmem", content: "0x1" } }, + { name: "tool-result 无 result", type: "tool-result", data: { name: "r" }, expect: { projected: true, role: "tool", name: "r", content: null } }, + { name: "非投影 turn", type: "turn", data: { turn: 1 }, expect: { projected: false } }, + { name: "非投影 hw:state", type: "hw:state", data: {}, expect: { projected: false } }, + { name: "非投影 unknown", type: "unknown-type", data: {}, expect: { projected: false } }, + ]; + + for (const c of cases) { + it(`type=${c.name} → ${c.expect.projected ? "投影" : "跳过"}`, () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append({ type: c.type, data: c.data }); + const msgs = s.deriveMessages() as DerivedMessage[]; + if (!c.expect.projected) { + expect(msgs).toHaveLength(0); + return; + } + expect(msgs).toHaveLength(1); + const m = msgs[0]; + if (c.expect.role !== undefined) expect(m.role).toBe(c.expect.role); + if (c.expect.content !== undefined) expect(m.content).toBe(c.expect.content); + if (c.expect.name !== undefined) expect(m.name).toBe(c.expect.name); + if (c.expect.toolCalls !== undefined) expect(m.toolCalls).toEqual(c.expect.toolCalls); + }); + } +}); + +// ============================================================================ +// ⑥ 决策表 — append 成功/失败 × freeze × cache 状态 +// ============================================================================ + +describe("决策表 — append 成功/失败 × freeze × cache", () => { + it("sink 成功 × freeze=true × cache 未构建 → log+1, seq+1, data 冻结", () => { + const s = new PbaSession({ appendEntry: noopSink, deepFreeze: true }); + s.append(userMsg("a")); + expect(s.getEntries()).toHaveLength(1); + expect(s.getEntries()[0].seq).toBe(1); + expect(Object.isFrozen(s.getEntries()[0].data)).toBe(true); + expect(s.deriveMessages()).toHaveLength(1); + }); + + it("sink 成功 × freeze=false × cache 已构建 → 失效缓存 + 不冻结", () => { + const s = new PbaSession({ appendEntry: noopSink, deepFreeze: false }); + s.append(userMsg("a")); + const m1 = s.deriveMessages(); + s.append(userMsg("b")); + const m2 = s.deriveMessages(); + expect(m2).not.toBe(m1); // 失效 + expect(Object.isFrozen(s.getEntries()[0].data)).toBe(false); + }); + + it("sink 失败 × freeze=true → log 不增, seq 回滚, 抛错", () => { + const s = new PbaSession({ appendEntry: throwingSink("nope"), deepFreeze: true }); + expect(() => s.append(userMsg("a"))).toThrow("nope"); + expect(s.getEntries()).toHaveLength(0); + }); +}); + +// ============================================================================ +// ⑦ 状态转换 — seq 回滚状态机(失败→回滚→续写 seq 一致) +// ============================================================================ + +describe("状态转换 — seq 回滚状态机", () => { + it("同 session:失败→成功,成功条 seq=1(与无失败路径等价)", () => { + // 状态:seq=0 → append(fail) → 回滚 0 → append(ok) → seq=1 + const { sink } = firstFailSink(); + const s = new PbaSession({ appendEntry: sink }); + expect(() => s.append(userMsg("fail"))).toThrow("first-fail"); + s.append(userMsg("ok")); + expect(s.getEntries()[0].seq).toBe(1); + }); + + it("连续两次失败:seq 始终回滚到 0,第三次成功 seq=1", () => { + const s = new PbaSession({ appendEntry: throwingSink("x") }); + expect(() => s.append(userMsg("a"))).toThrow(); + expect(() => s.append(userMsg("b"))).toThrow(); + const s2 = new PbaSession({ appendEntry: noopSink }); + s2.append(userMsg("c")); + expect(s2.getEntries()[0].seq).toBe(1); + }); + + it("reentrant guard:回调再入 append → 抛 reentrant;seq 回滚;无 entry", () => { + let session!: PbaSession; + const reentry = (type: string) => { + if (type === "user-message") session.append({ type: "tool-call", data: { name: "x", args: {} } }); + }; + session = new PbaSession({ appendEntry: reentry }); + expect(() => session.append(userMsg("hi"))).toThrow(/reentrant/); + expect(session.getEntries()).toHaveLength(0); + }); + + it("reentrant guard 在正常 append 后复位(非重入状态可继续 append)", () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append(userMsg("a")); + s.append(userMsg("b")); // guard 未复位会抛 reentrant + expect(s.getEntries()).toHaveLength(2); + }); + + it("reentrant guard 失败后也能续写(finally 复位 appending)", () => { + let session!: PbaSession; + const reentry = (type: string) => { + if (type === "user-message") session.append(toolCall("x")); + }; + session = new PbaSession({ appendEntry: reentry }); + expect(() => session.append(userMsg("hi"))).toThrow(/reentrant/); + // 重入失败后 appending 已在 finally 复位,可继续正常 append + session.append = session.append; + const s2 = new PbaSession({ appendEntry: noopSink }); + s2.append(assistantMsg("ok")); + expect(s2.getEntries()[0].seq).toBe(1); + }); +}); + +// ============================================================================ +// ⑧ 状态转换 — replay seq 模式(带 seq / 不带 seq / 混合 / 缺口 / 回退) +// ============================================================================ + +describe("状态转换 — replayFromEntries seq 模式", () => { + it("全带 seq 且连续(5→6→7,非 1 起)→ 重建;续写 seq=8", () => { + const base = new PbaSession({ appendEntry: noopSink }); + const r = base.replayFromEntries([ + { type: "user-message", data: { role: "user", content: "a" }, seq: 5 }, + { type: "assistant-message", data: { role: "assistant", content: "b" }, seq: 6 }, + { type: "user-message", data: { role: "user", content: "c" }, seq: 7 }, + ]); + expect(r.getEntries().map((e) => e.seq)).toEqual([5, 6, 7]); + r.append(userMsg("d")); + expect(r.getEntries()[3].seq).toBe(8); + }); + + it("全不带 seq → 按序赋 1..n;续写 seq=n+1", () => { + const base = new PbaSession({ appendEntry: noopSink }); + const r = base.replayFromEntries([ + { type: "user-message", data: { role: "user", content: "a" } }, + { type: "user-message", data: { role: "user", content: "b" } }, + ]); + expect(r.getEntries().map((e) => e.seq)).toEqual([1, 2]); + r.append(userMsg("c")); + expect(r.getEntries()[2].seq).toBe(3); + }); + + it("混合:带 seq 优先校验,不带 seq 按 lastSeq+1 填充", () => { + const base = new PbaSession({ appendEntry: noopSink }); + const r = base.replayFromEntries([ + { type: "user-message", data: { role: "user", content: "a" }, seq: 10 }, + { type: "user-message", data: { role: "user", content: "b" } }, // → 11 + { type: "user-message", data: { role: "user", content: "c" }, seq: 12 }, // 12==11+1 ✓ + ]); + expect(r.getEntries().map((e) => e.seq)).toEqual([10, 11, 12]); + }); + + it("空 entries → 等价空会话;续写 seq=1", () => { + const base = new PbaSession({ appendEntry: noopSink }); + const r = base.replayFromEntries([]); + expect(r.getEntries()).toHaveLength(0); + r.append(userMsg("first")); + expect(r.getEntries()[0].seq).toBe(1); + }); + + it("seq 缺口(1→3)→ 抛 discontinuity", () => { + const base = new PbaSession({ appendEntry: noopSink }); + expect(() => + base.replayFromEntries([ + { type: "user-message", data: { role: "user", content: "a" }, seq: 1 }, + { type: "assistant-message", data: { role: "assistant", content: "b" }, seq: 3 }, + ]), + ).toThrow(/discontinuity/); + }); + + it("seq 回退(3→2)→ 抛 discontinuity", () => { + const base = new PbaSession({ appendEntry: noopSink }); + expect(() => + base.replayFromEntries([ + { type: "user-message", data: { role: "user", content: "a" }, seq: 3 }, + { type: "user-message", data: { role: "user", content: "b" }, seq: 2 }, + ]), + ).toThrow(/discontinuity/); + }); + + it("entry 缺 string type → 抛 missing type", () => { + const base = new PbaSession({ appendEntry: noopSink }); + expect(() => base.replayFromEntries([{ type: 123 as unknown as string, data: {} }])).toThrow( + /missing string type/, + ); + }); + + it("replay 不修改原 entries(只读,不修改入参)", () => { + const base = new PbaSession({ appendEntry: noopSink }); + const input = [ + { type: "user-message", data: { role: "user", content: "a" }, seq: 1 }, + { type: "assistant-message", data: { role: "assistant", content: "b" }, seq: 2 }, + ]; + const snapshot = input.map((e) => ({ ...e, data: { ...(e.data as object) } })); + base.replayFromEntries(input); + expect(input).toEqual(snapshot); // 入参未被篡改 + }); +}); + +// ============================================================================ +// ⑨ 元蜕变/不变式 — append 两次 = replay 等价投影 +// ============================================================================ + +describe("元蜕变/不变式 — append² 与 replay 等价投影", () => { + it("同一事件序列:直接 append 与 replay 重建 → deriveMessages 内容等价", () => { + // 变换 T:先 append 序列 A,再从 A 的 entries replay 出 B。 + // 不变量:deriveMessages(A) === deriveMessages(B)(内容)。 + const { sink } = recordingSink(); + const a = new PbaSession({ appendEntry: sink }); + a.append(userMsg("hello")); + a.append(assistantMsg("hi")); + a.append(toolCall("devmem", { addr: "0x1" })); + a.append(toolResult("devmem", "0x1")); + + const aEntries = a.getEntries().map((e) => ({ type: e.type, data: e.data, seq: e.seq })); + const b = a.replayFromEntries(aEntries); + const ma = a.deriveMessages() as DerivedMessage[]; + const mb = b.deriveMessages() as DerivedMessage[]; + + expect(mb).toEqual(ma); // 蜕变不变式 + expect(mb.map((m) => m.role)).toEqual(["user", "assistant", "assistant", "tool"]); + }); + + it("replay 重建会话可继续 append,且投影与前段连续(无缝拼接)", () => { + const { sink } = recordingSink(); + const a = new PbaSession({ appendEntry: sink }); + a.append(userMsg("first")); + const b = a.replayFromEntries(a.getEntries().map((e) => ({ type: e.type, data: e.data, seq: e.seq }))); + b.append(assistantMsg("second")); + const msgs = b.deriveMessages() as DerivedMessage[]; + expect(msgs.map((m) => [m.role, m.content])).toEqual([ + ["user", "first"], + ["assistant", "second"], + ]); + }); +}); + +// ============================================================================ +// ⑩ 元蜕变/不变式 — 深冻结 / 单调 seq / waterfall 短路 / fail-closed +// ============================================================================ + +describe("元蜕变/不变式 — 深冻结 / 单调 seq / fail-closed", () => { + it("freeze 后篡改 stored data 抛 TypeError(运行时不可变)", () => { + const { sink, calls } = recordingSink(); + const s = new PbaSession({ appendEntry: sink, deepFreeze: true }); + s.append({ type: "user-message", data: { role: "user", content: "x", nested: { a: 1 } } }); + expect(Object.isFrozen(calls[0]?.data)).toBe(true); + const entry: PbaSessionEntry = s.getEntries()[0]; + expect(Object.isFrozen(entry)).toBe(true); + expect(Object.isFrozen(entry.data)).toBe(true); + expect(Object.isFrozen((entry.data as { nested: unknown }).nested)).toBe(true); + expect(() => ((entry.data as { role: string }).role = "evil")).toThrow(TypeError); + expect(() => ((entry.data as { nested: { a: number } }).nested.a = 999)).toThrow(TypeError); + }); + + it("deriveMessages 产物冻结(默认);篡改抛 TypeError", () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append(userMsg("a")); + const msgs = s.deriveMessages() as DerivedMessage[]; + expect(Object.isFrozen(msgs)).toBe(true); + expect(() => (msgs[0] as { role: string }).role = "evil").toThrow(TypeError); + }); + + it("getEntries 数组容器冻结:push/splice 抛 TypeError(唯一提交点 guard)", () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append(userMsg("a")); + s.append(assistantMsg("b")); + const entries = s.getEntries(); + expect(Object.isFrozen(entries)).toBe(true); + expect(() => (entries as PbaSessionEntry[]).push({ type: "fake", data: {}, seq: 999, ts: 0 })).toThrow(TypeError); + expect(() => (entries as PbaSessionEntry[]).splice(0, 1)).toThrow(TypeError); + expect(s.getEntries()).toHaveLength(2); // 内部 log 未被篡改 + expect(s.getEntries()).toBe(entries); // 缓存命中同引用 + s.append(toolCall("x", {})); + const after = s.getEntries(); + expect(after).not.toBe(entries); // append 后失效 + expect(after).toHaveLength(3); + expect(Object.isFrozen(after)).toBe(true); + }); + + it("deepFreeze=false:stored data 与 messages 不冻结(测试态)", () => { + const s = new PbaSession({ appendEntry: noopSink, deepFreeze: false }); + s.append(userMsg("a")); + expect(Object.isFrozen(s.getEntries()[0].data)).toBe(false); + const msgs = s.deriveMessages(); + expect(Object.isFrozen(msgs)).toBe(false); + }); + + it("单调 seq:任意 append 序列 seq 严格 +1 递增", () => { + const s = new PbaSession({ appendEntry: noopSink }); + for (let i = 0; i < 50; i++) s.append(userMsg(String(i))); + const seqs = s.getEntries().map((e) => e.seq); + for (let i = 0; i < seqs.length; i++) expect(seqs[i]).toBe(i + 1); + const strictlyIncreasing = seqs.every((v, i) => i === 0 || v > seqs[i - 1]); + expect(strictlyIncreasing).toBe(true); + }); + + it("waterfall 短路:非投影事件不改变 deriveMessages 长度", () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append(userMsg("a")); + s.append({ type: "turn", data: { turn: 1, phase: "start" } }); + s.append({ type: "step", data: { turn: 1, step: 1, phase: "start" } }); + s.append(assistantMsg("b")); + s.append({ type: "hw:state", data: { type: "gpio", data: {}, ts: 1 } }); + expect(s.deriveMessages()).toHaveLength(2); + }); + + it("fail-closed unusable:未 log 的 visible type → assert 抛(旁路喂模型检测)", () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append(userMsg("a")); + expect(() => s.assertModelVisibleLogged(["user-message", "tool-call"])).toThrow(/never logged/); + }); + + it("assertModelVisibleLogged 全部已 logged → 不抛(空集亦不抛)", () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append(userMsg("a")); + s.append(assistantMsg("b")); + s.append(toolCall("t", {})); + s.append(toolResult("t", 1)); + expect(() => s.assertModelVisibleLogged([...MODEL_VISIBLE_TYPES])).not.toThrow(); + expect(() => s.assertModelVisibleLogged([])).not.toThrow(); + }); + + it("replay 后 loggedTypes 同步 → assert 可用(fail-closed 跨重建保持)", () => { + const base = new PbaSession({ appendEntry: noopSink }); + const r = base.replayFromEntries([{ type: "user-message", data: { role: "user", content: "a" } }]); + expect(() => r.assertModelVisibleLogged(["user-message"])).not.toThrow(); + expect(() => r.assertModelVisibleLogged(["tool-call"])).toThrow(/never logged/); + }); +}); + +// ============================================================================ +// ⑪ 对抗/fuzz — 畸形/滥用输入(循环引用 / 巨大 / NaN / 负 seq / 重入 / null) +// ============================================================================ + +describe("对抗/fuzz — 畸形/滥用输入", () => { + it("循环引用对象 → append 抛 cyclic(fail-closed)", () => { + const s = new PbaSession({ appendEntry: noopSink }); + const cyclic: Record = { a: 1 }; + cyclic.self = cyclic; + expect(() => s.append({ type: "user-message", data: cyclic })).toThrow(/cyclic/); + }); + + it("循环引用数组 → append 抛 cyclic", () => { + const s = new PbaSession({ appendEntry: noopSink }); + const arr: unknown[] = [1, 2]; + arr.push(arr); + expect(() => s.append({ type: "turn", data: arr })).toThrow(/cyclic/); + }); + + it("Map 自引用(循环)→ 抛 cyclic", () => { + const s = new PbaSession({ appendEntry: noopSink }); + const m = new Map(); + m.set("self", m); + expect(() => s.append({ type: "hw:state", data: m })).toThrow(/cyclic/); + }); + + it("巨大嵌套(1000 层)→ 不抛(非循环,递归快照成功)", () => { + const s = new PbaSession({ appendEntry: noopSink }); + let v: unknown = "leaf"; + for (let i = 0; i < 1000; i++) v = { d: v }; + expect(() => s.append({ type: "turn", data: v })).not.toThrow(); + expect(s.getEntries()).toHaveLength(1); + }); + + it("data = NaN / Infinity(原始 number)→ 原样快照,不抛", () => { + const { sink, calls } = recordingSink(); + const s = new PbaSession({ appendEntry: sink }); + s.append({ type: "tool-result", data: { name: "r", result: NaN } }); + expect(calls[0]?.data).toEqual({ name: "r", result: NaN }); + s.append({ type: "tool-result", data: { name: "r2", result: Infinity } }); + expect((calls[1]?.data as { result: number }).result).toBe(Infinity); + }); + + it("data 含 symbol 键 → 静默丢弃(JSON-safe 语义,不抛)", () => { + const { sink, calls } = recordingSink(); + const s = new PbaSession({ appendEntry: sink }); + const sym = Symbol("hidden"); + s.append({ type: "turn", data: { visible: 1, [sym]: "dropped" } }); + expect(calls[0]?.data).toEqual({ visible: 1 }); + }); + + it("负 seq 首条 → 抛 lower bound(从 1 起不变量)", () => { + const base = new PbaSession({ appendEntry: noopSink }); + expect(() => + base.replayFromEntries([{ type: "user-message", data: { role: "user", content: "x" }, seq: -5 }]), + ).toThrow(/lower bound/); + }); + + it("0 seq 首条 → 抛 lower bound(下界为 1,0 不合法)", () => { + const base = new PbaSession({ appendEntry: noopSink }); + expect(() => + base.replayFromEntries([{ type: "user-message", data: { role: "user", content: "x" }, seq: 0 }]), + ).toThrow(/lower bound/); + }); + + it("NaN seq 首条 → 抛 lower bound(NaN 经 typeof==number 过类型门,!(NaN>=1) 拒绝)", () => { + const base = new PbaSession({ appendEntry: noopSink }); + expect(() => + base.replayFromEntries([ + { type: "user-message", data: { role: "user", content: "a" }, seq: Number.NaN }, + ]), + ).toThrow(/lower bound/); + expect(() => + base.replayFromEntries([ + { type: "user-message", data: { role: "user", content: "a" }, seq: Number.NaN }, + { type: "user-message", data: { role: "user", content: "b" }, seq: 2 }, + ]), + ).toThrow(/lower bound/); + }); + + it("assertModelVisibleLogged 入含非 string(数字)→ loggedTypes.has(number)===false → 抛", () => { + const s = new PbaSession({ appendEntry: noopSink }); + s.append(userMsg("a")); + expect(() => s.assertModelVisibleLogged([1 as unknown as string])).toThrow(/never logged/); + }); + + it("并发重入(appendEntry 同步触发再 append)→ 同步重入即拒", () => { + let session!: PbaSession; + const sink = (type: string) => { + if (type === "user-message") session.append(toolCall("x")); + }; + session = new PbaSession({ appendEntry: sink }); + expect(() => session.append(userMsg("a"))).toThrow(/reentrant/); + }); + + it("append event 缺 data 字段(undefined)→ 不抛(data=undefined 原样快照)", () => { + const { sink, calls } = recordingSink(); + const s = new PbaSession({ appendEntry: sink }); + s.append({ type: "turn", data: undefined }); + expect(calls[0]?.data).toBeUndefined(); + expect(s.getEntries()[0].data).toBeUndefined(); + }); + + it("空字符串 type → 合法 append(开放 string,空串亦 string)", () => { + const { sink, calls } = recordingSink(); + const s = new PbaSession({ appendEntry: sink }); + s.append({ type: "", data: { x: 1 } }); + expect(calls[0]?.type).toBe(""); + expect(s.getEntries()[0].type).toBe(""); + }); +}); + +// ============================================================================ +// ⑫ 变异测试 — 5 个 seeded bug 内联副本(it.fails 杀手) +// ---------------------------------------------------------------------------- +// 每个 it.fails 杀手断言【真实正确行为】。在 mutant 副本上该断言失败 → it.fails +// 通过 = bug 被杀。文档:若把对应 bug 打进真实 src/core/pba-session.ts,下列 +// 标注的【真实代码测试】会变红。 +// ============================================================================ + +describe("变异测试 — seeded bug 副本(it.fails 杀手)", () => { + // M1: 下沉失败时漏 seq 回滚(this.seq -= 1 被删) + // 真实:失败回滚 seq=0 → 成功 seq=1。mutant:未回滚 seq=1 → 成功 seq=2。 + // 杀手:断言成功条 seq===1 → mutant 给 2 → 断言失败 → it.fails 通过。 + // kill-by-real-test: ⑦ 状态转换「同 session:失败→成功 seq=1」 + it.fails("M1 no-rollback: 失败→成功,成功条 seq 应=1(mutant=2 → 杀手失败)", () => { + const { sink } = firstFailSink(); + const s = new MutantPbaSession({ appendEntry: sink, bug: "no-rollback" }); + expect(() => s.append(userMsg("fail"))).toThrow("first-fail"); + s.append(userMsg("ok")); + expect(s.getEntries()[0].seq).toBe(1); + }); + + // M2: append 后漏缓存失效(this.messagesCache = null 被删) + // 真实:append 后 derive 返回新引用、长度+1。mutant:返回旧缓存。 + // 杀手:断言 m2!==m1 且 length===2 → mutant m2===m1 且 length===1 → 断言失败。 + // kill-by-real-test: ④ 缓存边界 + ⑥ 决策表「freeze=false 失效缓存」 + it.fails("M2 no-cache-invalidate: append 后 derive 新引用长度+1(mutant 返回旧缓存 → 杀手失败)", () => { + const s = new MutantPbaSession({ appendEntry: noopSink, bug: "no-cache-invalidate" }); + s.append(userMsg("a")); + const m1 = s.deriveMessages(); + s.append(userMsg("b")); + const m2 = s.deriveMessages(); + expect(m2).not.toBe(m1); + expect(m2).toHaveLength(2); + }); + + // M3: replay seq 校验 !== → <(仅拒回退/相等,放行前向缺口) + // 真实:seq 1→3 抛 discontinuity。mutant:3<2 false → 不抛。 + // 杀手:断言抛 discontinuity → mutant 不抛 → 断言失败。 + // kill-by-real-test: ⑧ replay「seq 缺口(1→3)→ 抛」 + it.fails("M3 seq-lt: seq 1→3 应抛 discontinuity(mutant 放行前向缺口 → 杀手失败)", () => { + const base = new MutantPbaSession({ appendEntry: noopSink, bug: "seq-lt" }); + expect(() => + base.replayFromEntries([ + { type: "user-message", data: { role: "user", content: "a" }, seq: 1 }, + { type: "assistant-message", data: { role: "assistant", content: "b" }, seq: 3 }, + ]), + ).toThrow(/discontinuity/); + }); + + // M4: assertModelVisibleLogged 条件取反(已 logged 反而抛) + // 真实:已 logged 的 type 声明可见 → 不抛。mutant:抛。 + // 杀手:断言不抛 → mutant 抛 → 断言失败。 + // kill-by-real-test: ⑩ fail-closed「全部已 logged → 不抛」 + it.fails("M4 assert-inverted: 已 logged type 声明可见应不抛(mutant 抛 → 杀手失败)", () => { + const s = new MutantPbaSession({ appendEntry: noopSink, bug: "assert-inverted" }); + s.append(userMsg("a")); + expect(() => s.assertModelVisibleLogged(["user-message"])).not.toThrow(); + }); + + // M5: 漏 reentrant guard(appending 标志不生效) + // 真实:回调再入 append → 抛 reentrant。mutant:不抛(直接再入)。 + // 杀手:断言抛 reentrant → mutant 不抛 → 断言失败。 + // kill-by-real-test: ⑦ 状态转换「reentrant guard」+ ⑪ 对抗「并发重入即拒」 + it.fails("M5 no-reentrant-guard: 回调再入 append 应抛 reentrant(mutant 不抛 → 杀手失败)", () => { + let session!: MutantPbaSession; + const sink = (type: string) => { + if (type === "user-message") session.append(toolCall("x")); + }; + session = new MutantPbaSession({ appendEntry: sink, bug: "no-reentrant-guard" }); + expect(() => session.append(userMsg("a"))).toThrow(/reentrant/); + }); +}); + +// ============================================================================ +// ⑬ 变异测试 — mutant 副本保真度(bug=none ≈ 真实行为) +// ---------------------------------------------------------------------------- +// 证 MutantPbaSession(bug=none) 与 PbaSession 在杀手关心的表面行为一致:确保 +// 杀手的失败确由 seeded bug 引起,而非副本本身的无关偏差。 +// ============================================================================ + +describe("变异测试 — mutant 副本保真度(bug=none 与真实一致)", () => { + it("bug=none: seq 回滚行为与真实一致(失败→成功 seq=1)", () => { + const { sink: rSink } = firstFailSink(); + const real = new PbaSession({ appendEntry: rSink }); + expect(() => real.append(userMsg("fail"))).toThrow("first-fail"); + real.append(userMsg("ok")); + expect(real.getEntries()[0].seq).toBe(1); + + const { sink: mSink } = firstFailSink(); + const mut = new MutantPbaSession({ appendEntry: mSink, bug: "none" }); + expect(() => mut.append(userMsg("fail"))).toThrow("first-fail"); + mut.append(userMsg("ok")); + expect(mut.getEntries()[0].seq).toBe(1); + }); + + it("bug=none: 缓存失效与真实一致", () => { + const real = new PbaSession({ appendEntry: noopSink }); + real.append(userMsg("a")); + const r1 = real.deriveMessages(); + real.append(userMsg("b")); + const r2 = real.deriveMessages(); + const mut = new MutantPbaSession({ appendEntry: noopSink, bug: "none" }); + mut.append(userMsg("a")); + const m1 = mut.deriveMessages(); + mut.append(userMsg("b")); + const m2 = mut.deriveMessages(); + expect(m2).not.toBe(m1); + expect(m2).toHaveLength(2); + expect(r2).not.toBe(r1); + }); + + it("bug=none: seq 缺口校验与真实一致(1→3 抛 discontinuity)", () => { + const realBase = new PbaSession({ appendEntry: noopSink }); + const mutBase = new MutantPbaSession({ appendEntry: noopSink, bug: "none" }); + for (const b of [realBase, mutBase]) { + expect(() => + b.replayFromEntries([ + { type: "user-message", data: { role: "user", content: "a" }, seq: 1 }, + { type: "user-message", data: { role: "user", content: "b" }, seq: 3 }, + ]), + ).toThrow(/discontinuity/); + } + }); + + it("bug=none: assert 行为与真实一致(已 logged 不抛 / 未 logged 抛)", () => { + const real = new PbaSession({ appendEntry: noopSink }); + real.append(userMsg("a")); + const mut = new MutantPbaSession({ appendEntry: noopSink, bug: "none" }); + mut.append(userMsg("a")); + expect(() => real.assertModelVisibleLogged(["user-message"])).not.toThrow(); + expect(() => mut.assertModelVisibleLogged(["user-message"])).not.toThrow(); + expect(() => mut.assertModelVisibleLogged(["tool-call"])).toThrow(/never logged/); + }); + + it("bug=none: reentrant guard 与真实一致", () => { + const mkSink = void }>(sess: S) => { + const session = sess as unknown as { append: (e: { type: string; data: unknown }) => void }; + return (type: string) => { + if (type === "user-message") session.append(toolCall("x")); + }; + }; + const real = new PbaSession({ appendEntry: noopSink }) as unknown as MutantPbaSession & PbaSession; + (real as unknown as { appendEntry: (t: string, d: unknown) => void }).appendEntry = mkSink(real); + expect(() => (real as unknown as { append: (e: { type: string; data: unknown }) => void }).append(userMsg("a"))).toThrow(/reentrant/); + + const mut = new MutantPbaSession({ appendEntry: noopSink, bug: "none" }); + (mut as unknown as { appendEntry: (t: string, d: unknown) => void }).appendEntry = mkSink(mut); + expect(() => mut.append(userMsg("a"))).toThrow(/reentrant/); + }); +}); diff --git a/tests/profiles.test.ts b/tests/profiles.test.ts new file mode 100644 index 0000000..5b5467a --- /dev/null +++ b/tests/profiles.test.ts @@ -0,0 +1,1481 @@ +/** + * profiles 全量测试套件 —— T15 profile/bundle 分层(测试 Agent 独占文件)。 + * + * 被测对象:src/profiles/{base,repair-diagnosis,embedded-dev,index}.ts 的命名导出。 + * 纯逻辑模块:零 pi 运行时依赖、零硬件、零网络、零 IO。直接 import 命名导出; + * 变异测试用模块内联的带 bug 副本(mutant),不 mock 真实代码、不改源码。 + * + * 被测命名导出(按契约): + * - base.ts : Profile(类型), DOMAIN_TOOLS, BASE_EXTENSIONS, BASE_PROFILE, + * toolsFor, mergeProfiles, diffProfiles + * - repair : REPAIR_DIAGNOSIS_DELTA, REPAIR_DIAGNOSIS_PROFILE + * - embedded : EMBEDDED_DEV_DELTA, EMBEDDED_DEV_PROFILE + * - index.ts : 上述全部 re-export + resolveProfile + * + * 多测试方法论(每个 describe 块标注方法论名): + * ① 等价类划分 —— resolveProfile / toolsFor 有效/无效/边界类 + * ② 边界值分析 —— 空 / 单元素 / max / off-by-one + * ③ 决策表 —— mergeProfiles 并集去重全分支 / diffProfiles 全分支 + * ④ 状态转换 —— Object.freeze 不可变状态机(冻结态→篡改→TypeError 终态) + * ⑤ 变异测试 —— 6 个 seeded bug(M1~M6),每个文档化 bug+杀手测试 + + * 显式 kill harness(真实通过 / mutant 断言失败=被杀) + * ⑥ 对抗/fuzz —— null / undefined / NaN / 巨大 / 循环引用 / 并发重入 / 非字符串 + * ⑦ 元蜕变/不变式 —— append 两次=replay 等价 / freeze 篡改抛 TypeError / + * 单调 fail-closed / mergeProfiles 不重派生(短路)/ + * diff 对称幂等 / DOMAIN_TOOLS 全量 referent 无魔法串 + * + * 门: + * - 真实代码:npx vitest run tests/profiles.test.ts → all green + * - 每个植入 bug 变体:mutant 函数被对应杀手断言杀死(mutant 输出 ≠ 真实输出, + * 且同一杀手断言在 mutant 上失败=AssertionError) + * + * 已修复的真实 bug(原 findings[],源码已修,本套件作永久回归守护): + * - F1: resolveProfile 对 "toString"/"constructor"/"__proto__" 等 Object.prototype + * 继承键不 fail-closed,返回继承的函数/对象而非抛错(src/profiles/index.ts)。 + * 修复:resolveProfile 改用 Object.hasOwn(PROFILE_REGISTRY, id) 判定,只认自身 + * 属性,继承键一律判为未注册 → fail-closed 抛错。 + */ + +import { describe, it, expect } from "vitest"; +import type { Profile } from "../src/profiles/base.js"; +import { + BASE_PROFILE, + BASE_EXTENSIONS, + REPAIR_DIAGNOSIS_PROFILE, + REPAIR_DIAGNOSIS_DELTA, + EMBEDDED_DEV_PROFILE, + EMBEDDED_DEV_DELTA, + DOMAIN_TOOLS, + resolveProfile, + mergeProfiles, + diffProfiles, + toolsFor, +} from "../src/profiles/index.js"; + +// ============================================================================ +// 变异测试基础设施 —— 内联带 bug 副本(mutant)+ 显式 kill harness +// ---------------------------------------------------------------------------- +// 这些副本刻意复制 base.ts 的纯逻辑并植入单点 bug,用于证明对应杀手测试能区分 +// 真实与 mutant。真实代码不被 mock,mutant 仅参与变异测试 describe 块。 +// 每个 mutant 标注:BUG 描述 + 后果 + 杀手测试位置。 +// +// kill harness 范式(canonical mutation testing): +// 一个"杀手断言" killer(fn) 对【真实】函数输出成立(不抛), +// 对【mutant】函数输出失败(抛 AssertionError)。 +// expect(() => killer(real)).not.toThrow() // 真实通过 +// expect(() => killer(mutant)).toThrow() // mutant 被杀 +// ============================================================================ + +/** 真实 frozen 副本(无 bug,供 mutant 对比基准)。 */ +function frozenReal(xs: readonly string[]): readonly string[] { + return Object.freeze([...xs]) as readonly string[]; +} + +/** 真实 unionStable 副本(无 bug)。 */ +function unionStableReal( + base: readonly string[], + delta: readonly string[], +): readonly string[] { + const seen = new Set(base); + const out: string[] = [...base]; + for (const x of delta) { + if (!seen.has(x)) { + seen.add(x); + out.push(x); + } + } + return frozenReal(out); +} + +/** 真实 toolsFor 副本(无 bug)。 */ +function toolsForReal(domains: readonly string[]): readonly string[] { + const out: string[] = []; + const seen = new Set(); + for (const d of domains) { + const tools = DOMAIN_TOOLS[d]; + if (tools === undefined) { + throw new Error(`toolsFor: unknown extension domain "${d}"`); + } + for (const t of tools) { + if (!seen.has(t)) { + seen.add(t); + out.push(t); + } + } + } + return frozenReal(out); +} + +/** 真实 mergeProfiles 副本(无 bug)。 */ +function mergeProfilesReal( + base: Profile, + delta: Pick, +): Profile { + return Object.freeze({ + id: base.id, + extensions: unionStableReal(base.extensions, delta.extensions), + tools: unionStableReal(base.tools, delta.tools), + note: base.note, + }) as Profile; +} + +/** 真实 diffProfiles 副本(无 bug)。 */ +function diffProfilesReal( + a: Profile, + b: Profile, +): { added: readonly string[]; removed: readonly string[] } { + const aSet = new Set(a.extensions); + const bSet = new Set(b.extensions); + const added: string[] = []; + for (const x of b.extensions) { + if (!aSet.has(x)) added.push(x); + } + const removed: string[] = []; + for (const x of a.extensions) { + if (!bSet.has(x)) removed.push(x); + } + return Object.freeze({ + added: frozenReal(added), + removed: frozenReal(removed), + }) as { added: readonly string[]; removed: readonly string[] }; +} + +// ---- MUTANT M1: 并集去重条件反转(!seen.has → seen.has) ------------------- +/** + * BUG: unionStable 中 `if (!seen.has(x))` 改为 `if (seen.has(x))`。 + * 后果:delta 中 base 已含项被重复追加,base 未含的新项被丢弃。 + * 杀手:见 "⑤ 变异测试 — M1" describe 块(delta 新项必须出现)。 + */ +function unionStableM1( + base: readonly string[], + delta: readonly string[], +): readonly string[] { + const seen = new Set(base); + const out: string[] = [...base]; + for (const x of delta) { + // BUG: 条件反转 + if (seen.has(x)) { + seen.add(x); + out.push(x); + } + } + return frozenReal(out); +} + +// ---- MUTANT M2: 未知域用 ?? [] 默认空(fail-closed 失效) ------------------- +/** + * BUG: toolsFor 中 `if (tools === undefined) throw` 改为 `DOMAIN_TOOLS[d] ?? []`。 + * 后果:未知域取值 undefined → 兜底空数组 → 不抛错,未知域静默产出空工具集。 + * 杀手:见 "⑤ 变异测试 — M2" describe 块(未知域必抛 domain-specific Error)。 + */ +function toolsForM2(domains: readonly string[]): readonly string[] { + const out: string[] = []; + const seen = new Set(); + for (const d of domains) { + // BUG: throw 改为 ?? [] 默认(fail-closed 失效) + const tools = DOMAIN_TOOLS[d] ?? []; + for (const t of tools) { + if (!seen.has(t)) { + seen.add(t); + out.push(t); + } + } + } + return frozenReal(out); +} + +// ---- MUTANT M3: 漏 Object.freeze(mergeProfiles 结果可变) ------------------- +/** + * BUG: mergeProfiles 末尾漏 Object.freeze(外层 + 内层数组均不冻结)。 + * 后果:运行时篡改 mergeProfiles 返回的 profile(id / extensions / tools)不抛 TypeError。 + * 杀手:见 "⑤ 变异测试 — M3" describe 块(篡改必抛 TypeError)。 + */ +function unionStableM3NoFreeze( + base: readonly string[], + delta: readonly string[], +): readonly string[] { + const seen = new Set(base); + const out: string[] = [...base]; + for (const x of delta) { + if (!seen.has(x)) { + seen.add(x); + out.push(x); + } + } + // BUG: 漏 Object.freeze + return out; +} +function mergeProfilesM3( + base: Profile, + delta: Pick, +): Profile { + // BUG: 漏 Object.freeze(外层 + 内层数组均不冻结) + return { + id: base.id, + extensions: unionStableM3NoFreeze(base.extensions, delta.extensions), + tools: unionStableM3NoFreeze(base.tools, delta.tools), + note: base.note, + } as Profile; +} + +// ---- MUTANT M4: diffProfiles added/removed 互换 ----------------------------- +/** + * BUG: diffProfiles 返回时 added 与 removed 互换。 + * 后果:diffProfiles 的 added 与 removed 颠倒(方向敏感)。 + * 杀手:见 "⑤ 变异测试 — M4" describe 块(added 含 b 专属、方向敏感)。 + */ +function diffProfilesM4( + a: Profile, + b: Profile, +): { added: readonly string[]; removed: readonly string[] } { + const aSet = new Set(a.extensions); + const bSet = new Set(b.extensions); + const added: string[] = []; + for (const x of b.extensions) { + if (!aSet.has(x)) added.push(x); + } + const removed: string[] = []; + for (const x of a.extensions) { + if (!bSet.has(x)) removed.push(x); + } + // BUG: added 与 removed 互换 + return Object.freeze({ + added: frozenReal(removed), + removed: frozenReal(added), + }) as { added: readonly string[]; removed: readonly string[] }; +} + +// ---- MUTANT M5: mergeProfiles 漏继承 note(note: undefined) ---------------- +/** + * BUG: mergeProfiles 返回 `note: undefined` 而非 `note: base.note`。 + * 后果:合并结果的 note 丢失(契约要求 id/note 继承 base)。 + * 杀手:见 "⑤ 变异测试 — M5" describe 块(note === base.note)。 + */ +function mergeProfilesM5( + base: Profile, + delta: Pick, +): Profile { + return Object.freeze({ + id: base.id, + extensions: unionStableReal(base.extensions, delta.extensions), + tools: unionStableReal(base.tools, delta.tools), + // BUG: note 漏继承(应为 base.note) + note: undefined, + }) as Profile; +} + +// ---- MUTANT M6: unionStable 漏 seen.add(delta 内部重复不去重) -------------- +/** + * BUG: unionStable 中新项追加后漏 `seen.add(x)`。 + * 后果:delta 内部重复的非 base 项被多次追加(去重失效,仅对 delta 内部重复)。 + * 杀手:见 "⑤ 变异测试 — M6" describe 块(delta 含内部重复 → 结果恰 1 份)。 + */ +function unionStableM6( + base: readonly string[], + delta: readonly string[], +): readonly string[] { + const seen = new Set(base); + const out: string[] = [...base]; + for (const x of delta) { + if (!seen.has(x)) { + // BUG: 漏 seen.add(x) + out.push(x); + } + } + return frozenReal(out); +} + +// ============================================================================ +// 公共 fixture +// ============================================================================ + +const ALL_PROFILE_IDS = ["base", "repair-diagnosis", "embedded-dev"] as const; +const ALL_PROFILES: readonly Profile[] = [ + BASE_PROFILE, + REPAIR_DIAGNOSIS_PROFILE, + EMBEDDED_DEV_PROFILE, +]; + +// Object.prototype 继承键(resolveProfile 应对这些也 fail-closed,F1 修复后必抛) +const PROTO_KEYS = [ + "toString", + "constructor", + "hasOwnProperty", + "valueOf", + "isPrototypeOf", + "__proto__", + "propertyIsEnumerable", + "toLocaleString", +] as const; + +// DOMAIN_TOOLS 全量工具去重(不变式基准,从源表派生,非硬编码) +const ALL_TOOLS_SET: Set = (() => { + const s = new Set(); + for (const list of Object.values(DOMAIN_TOOLS)) { + for (const t of list) s.add(t); + } + return s; +})(); + +// 已核对的 defineTool name 全集(取自各扩展 defineTool({ name }),非臆造) +const KNOWN_DEFINE_TOOL_NAMES = new Set([ + "glm_status", "pshell", "read_pdf", "length_recovery_status", + "isolated_exec", "env_status", "mcp_list", "mcp_call", + "server_session", "hw_state", "xcompile", "flash", "bus_probe", + "debugger", "dt", "board_connect", "board_exec", "board_scp", + "board_console", "datasheet_query", "verify", "loop_status", + "build", "build_status", "reg", +]); + +// ============================================================================ +// ① 等价类划分 +// ============================================================================ + +describe("① 等价类划分 — resolveProfile 有效/无效类", () => { + // 有效类:三个已注册 id + for (const id of ALL_PROFILE_IDS) { + it(`有效类:resolveProfile("${id}") 返回对应 profile(引用共享,不复制)`, () => { + const p = resolveProfile(id); + const expected = + id === "base" + ? BASE_PROFILE + : id === "repair-diagnosis" + ? REPAIR_DIAGNOSIS_PROFILE + : EMBEDDED_DEV_PROFILE; + expect(p).toBe(expected); + expect(p.id).toBe(id); + }); + } + + // 无效类:未注册 id + it("无效类:resolveProfile(未注册 id) 抛错且消息含 registered 列表(fail-closed)", () => { + expect(() => resolveProfile("nonexistent")).toThrow( + /unknown profile id "nonexistent"/, + ); + expect(() => resolveProfile("nonexistent")).toThrow(/fail-closed/); + expect(() => resolveProfile("nonexistent")).toThrow( + /registered: base, repair-diagnosis, embedded-dev/, + ); + }); + + it("无效类:resolveProfile(空串) 抛错", () => { + expect(() => resolveProfile("")).toThrow(/unknown profile id ""/); + }); + + it("无效类:resolveProfile(大小写变体) 抛错(大小写敏感)", () => { + expect(() => resolveProfile("BASE")).toThrow(); + expect(() => resolveProfile("Repair-Diagnosis")).toThrow(); + expect(() => resolveProfile("embedded_dev")).toThrow(); + }); + + it("无效类:resolveProfile(数字串 id) 抛错", () => { + expect(() => resolveProfile("1" as string)).toThrow(); + }); + + it("有效类:三个 profile 的 id 两两不同", () => { + const ids = new Set(ALL_PROFILES.map((p) => p.id)); + expect(ids.size).toBe(ALL_PROFILES.length); + }); + + it("有效类:resolveProfile 错误消息列出全部已注册 id(可诊断)", () => { + try { + resolveProfile("zzz"); + throw new Error("should have thrown"); + } catch (e) { + const msg = (e as Error).message; + for (const id of ALL_PROFILE_IDS) { + expect(msg).toContain(id); + } + } + }); +}); + +describe("① 等价类划分 — toolsFor 有效/无效/空类", () => { + // 有效类:DOMAIN_TOOLS 收录的每个域 + it("有效类:每个 DOMAIN_TOOLS 域单独 toolsFor 返回其工具清单", () => { + for (const [domain, tools] of Object.entries(DOMAIN_TOOLS)) { + const got = toolsFor([domain]); + expect([...got]).toEqual([...tools]); + } + }); + + it("有效类:多域并集去重保序", () => { + const got = toolsFor(["glm-provider", "persistent-shell", "mcp-bridge"]); + // glm_status, pshell, mcp_list, mcp_call + expect([...got]).toEqual(["glm_status", "pshell", "mcp_list", "mcp_call"]); + }); + + it("有效类:空工具域(safety-gate / edit-strict)产出空贡献但不破坏序", () => { + const got = toolsFor(["safety-gate", "glm-provider", "edit-strict"]); + expect([...got]).toEqual(["glm_status"]); + }); + + it("有效类:含空工具域 + 重复域 → 工具不重复", () => { + const got = toolsFor([ + "glm-provider", + "glm-provider", + "safety-gate", + "mcp-bridge", + "mcp-bridge", + ]); + expect([...got]).toEqual(["glm_status", "mcp_list", "mcp_call"]); + }); + + // 无效类:未知域 + it("无效类:toolsFor 含未知域抛错(消息含域名)", () => { + expect(() => toolsFor(["no-such-domain"])).toThrow( + /unknown extension domain "no-such-domain"/, + ); + expect(() => toolsFor(["no-such-domain"])).toThrow(/fail-closed/); + }); + + it("无效类:toolsFor 混入未知域在任意位置均抛错", () => { + expect(() => toolsFor(["no-such", "glm-provider"])).toThrow(); + expect(() => toolsFor(["glm-provider", "no-such"])).toThrow(); + expect(() => + toolsFor(["glm-provider", "no-such", "persistent-shell"]), + ).toThrow(); + }); + + // 空类 + it("空类:toolsFor([]) 返回空数组(非 undefined),且冻结", () => { + const got = toolsFor([]); + expect(got).toBeDefined(); + expect([...got]).toEqual([]); + expect(Object.isFrozen(got)).toBe(true); + }); +}); + +// ============================================================================ +// ② 边界值分析 +// ============================================================================ + +describe("② 边界值分析 — 空 / 单元素 / max / off-by-one", () => { + it("边界-空:toolsFor([]) 长度 0", () => { + expect(toolsFor([]).length).toBe(0); + }); + + it("边界-单元素:toolsFor(单域) 长度等于该域工具数", () => { + expect(toolsFor(["glm-provider"]).length).toBe(1); + expect(toolsFor(["board-link"]).length).toBe(4); + expect(toolsFor(["build-tracker"]).length).toBe(2); + expect(toolsFor(["safety-gate"]).length).toBe(0); + }); + + it("边界-max:toolsFor(全域) 等于 DOMAIN_TOOLS 全工具去重", () => { + const allDomains = Object.keys(DOMAIN_TOOLS); + const got = toolsFor(allDomains); + const expectedDedup: string[] = []; + const seen = new Set(); + for (const d of allDomains) { + for (const t of DOMAIN_TOOLS[d]) { + if (!seen.has(t)) { + seen.add(t); + expectedDedup.push(t); + } + } + } + expect([...got]).toEqual(expectedDedup); + }); + + it("边界-off-by-one:mergeProfiles delta 单元素正确并入(长度 = base+1)", () => { + const merged = mergeProfiles(BASE_PROFILE, { + extensions: ["pdf-reader"], + tools: toolsFor(["pdf-reader"]), + }); + expect(merged.extensions.length).toBe(BASE_EXTENSIONS.length + 1); + expect(merged.extensions[merged.extensions.length - 1]).toBe( + "pdf-reader", + ); + }); + + it("边界-空 delta:mergeProfiles 空 delta = base 内容等价(id/note 继承)", () => { + const merged = mergeProfiles(BASE_PROFILE, { + extensions: [], + tools: [], + }); + expect([...merged.extensions]).toEqual([...BASE_PROFILE.extensions]); + expect([...merged.tools]).toEqual([...BASE_PROFILE.tools]); + expect(merged.id).toBe(BASE_PROFILE.id); + expect(merged.note).toBe(BASE_PROFILE.note); + // 但不是同一引用(新对象) + expect(merged).not.toBe(BASE_PROFILE); + }); + + it("边界-相同 profile:diffProfiles(a, a) added/removed 均空", () => { + const d = diffProfiles(REPAIR_DIAGNOSIS_PROFILE, REPAIR_DIAGNOSIS_PROFILE); + expect([...d.added]).toEqual([]); + expect([...d.removed]).toEqual([]); + }); + + it("边界-单边差异:diff(base, repair) added=3 removed=0", () => { + const d = diffProfiles(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE); + expect(d.added.length).toBe(3); + expect(d.removed.length).toBe(0); + }); + + it("边界-BASE_EXTENSIONS 长度 = 10(off-by-one 守护:不漏 edit-strict/length-recovery)", () => { + expect(BASE_EXTENSIONS.length).toBe(10); + expect(BASE_EXTENSIONS).toContain("edit-strict"); + expect(BASE_EXTENSIONS).toContain("length-recovery"); + // base 工具数 < 扩展数(safety-gate/edit-strict 不注册工具) + expect(BASE_PROFILE.tools.length).toBeLessThan( + BASE_PROFILE.extensions.length, + ); + }); + + it("边界-单边差异:diff(base, embedded) added=6 removed=0", () => { + const d = diffProfiles(BASE_PROFILE, EMBEDDED_DEV_PROFILE); + expect(d.added.length).toBe(6); + expect(d.removed.length).toBe(0); + }); + + it("边界-全差异:diff(repair, embedded) added=6 removed=3", () => { + const d = diffProfiles(REPAIR_DIAGNOSIS_PROFILE, EMBEDDED_DEV_PROFILE); + expect(d.added.length).toBe(6); + expect(d.removed.length).toBe(3); + }); +}); + +// ============================================================================ +// ③ 决策表 — mergeProfiles 并集去重全分支 +// ============================================================================ + +describe("③ 决策表 — mergeProfiles 并集去重(全分支覆盖)", () => { + // 决策表: + // | base 含 x | delta 含 x | 期望结果含 x 几次 | + // | Y | Y | 1(去重) | + // | Y | N | 1 | + // | N | Y | 1(追加) | + // | N | N | 0 | + const base: Profile = Object.freeze({ + id: "stub", + extensions: Object.freeze(["a", "b"]) as readonly string[], + tools: Object.freeze(["ta", "tb"]) as readonly string[], + note: undefined, + }) as Profile; + + it("决策行1:base 含 + delta 含 → 结果恰好 1 次(去重)", () => { + const merged = mergeProfiles(base, { + extensions: ["a"], + tools: ["ta"], + }); + expect(merged.extensions.filter((x) => x === "a")) + .toStrictEqual(["a"]); + expect(merged.tools.filter((t) => t === "ta")) + .toStrictEqual(["ta"]); + }); + + it("决策行2:base 含 + delta 不含 → 结果 1 次", () => { + const merged = mergeProfiles(base, { + extensions: [], + tools: [], + }); + expect(merged.extensions.filter((x) => x === "a")) + .toStrictEqual(["a"]); + expect(merged.tools.filter((t) => t === "ta")) + .toStrictEqual(["ta"]); + }); + + it("决策行3:base 不含 + delta 含 → 结果 1 次(追加在尾)", () => { + const merged = mergeProfiles(base, { + extensions: ["c"], + tools: ["tc"], + }); + expect(merged.extensions.filter((x) => x === "c")) + .toStrictEqual(["c"]); + expect(merged.extensions[merged.extensions.length - 1]).toBe("c"); + expect(merged.tools.filter((t) => t === "tc")) + .toStrictEqual(["tc"]); + }); + + it("决策行4:base 不含 + delta 不含 → 结果 0 次", () => { + const merged = mergeProfiles(base, { + extensions: [], + tools: [], + }); + expect(merged.extensions.filter((x) => x === "zzz")) + .toStrictEqual([]); + expect(merged.tools.filter((t) => t === "tzzz")) + .toStrictEqual([]); + }); + + it("决策-序不变式:base 序始终在前,delta 新项始终在后", () => { + const merged = mergeProfiles(base, { + extensions: ["c", "d"], + tools: ["tc", "td"], + }); + expect([...merged.extensions]).toEqual(["a", "b", "c", "d"]); + expect([...merged.tools]).toEqual(["ta", "tb", "tc", "td"]); + }); + + it("决策-id/note 继承:delta 无 id/note 时继承 base", () => { + const merged = mergeProfiles(base, { + extensions: ["c"], + tools: ["tc"], + }); + expect(merged.id).toBe("stub"); + expect(merged.note).toBeUndefined(); + }); +}); + +describe("③ 决策表 — diffProfiles added/removed(全分支覆盖)", () => { + const a: Profile = Object.freeze({ + id: "a", + extensions: Object.freeze(["x", "y", "z"]) as readonly string[], + tools: Object.freeze([]) as readonly string[], + note: undefined, + }) as Profile; + const b: Profile = Object.freeze({ + id: "b", + extensions: Object.freeze(["y", "z", "w"]) as readonly string[], + tools: Object.freeze([]) as readonly string[], + note: undefined, + }) as Profile; + + it("决策:added = b 有 a 无 = ['w'],removed = a 有 b 无 = ['x']", () => { + const d = diffProfiles(a, b); + expect([...d.added]).toEqual(["w"]); + expect([...d.removed]).toEqual(["x"]); + }); + + it("决策:added/removed 互斥(无交集)", () => { + const d = diffProfiles(a, b); + const addedSet = new Set(d.added); + for (const r of d.removed) { + expect(addedSet.has(r)).toBe(false); + } + }); + + it("决策:a=b → added=removed=空", () => { + const d = diffProfiles(a, a); + expect([...d.added]).toEqual([]); + expect([...d.removed]).toEqual([]); + }); + + it("决策:a⊂b(b 含 a 全部 + 更多)→ removed=空", () => { + const sup: Profile = Object.freeze({ + id: "sup", + extensions: Object.freeze(["x", "y", "z", "w"]) as readonly string[], + tools: Object.freeze([]) as readonly string[], + note: undefined, + }) as Profile; + const d = diffProfiles(a, sup); + expect([...d.removed]).toEqual([]); + expect([...d.added]).toEqual(["w"]); + }); + + it("决策:b⊂a → added=空", () => { + const sub: Profile = Object.freeze({ + id: "sub", + extensions: Object.freeze(["x"]) as readonly string[], + tools: Object.freeze([]) as readonly string[], + note: undefined, + }) as Profile; + const d = diffProfiles(a, sub); + expect([...d.added]).toEqual([]); + expect([...d.removed]).toEqual(["y", "z"]); + }); + + it("决策:diff 结果不依赖 tools(只 diff extensions)", () => { + const aDiffTools: Profile = Object.freeze({ + id: "a", + extensions: Object.freeze(["x"]) as readonly string[], + tools: Object.freeze(["ta", "tb"]) as readonly string[], + note: undefined, + }) as Profile; + const bDiffTools: Profile = Object.freeze({ + id: "b", + extensions: Object.freeze(["x"]) as readonly string[], + tools: Object.freeze(["tc"]) as readonly string[], + note: undefined, + }) as Profile; + const d = diffProfiles(aDiffTools, bDiffTools); + expect([...d.added]).toEqual([]); + expect([...d.removed]).toEqual([]); + }); +}); + +// ============================================================================ +// ④ 状态转换 — Object.freeze 不可变状态机 +// ============================================================================ + +describe("④ 状态转换 — Object.freeze 不可变状态机", () => { + // 状态机:[未冻结] --freeze--> [冻结] --篡改--> TypeError(终态) + // 不可达:[冻结] --freeze--> [冻结](幂等,不报错) + // 重入:重复 freeze 同一对象 = 幂等 + + it("状态-冻结态:篡改 profile 顶层字段抛 TypeError", () => { + for (const p of ALL_PROFILES) { + expect(() => { + (p as Profile & { id: string }).id = "tampered"; + }).toThrow(TypeError); + } + }); + + it("状态-冻结态:篡改 profile.extensions(push/pop/splice)抛 TypeError", () => { + expect(() => { + (BASE_PROFILE.extensions as string[]).push("x"); + }).toThrow(TypeError); + expect(() => { + (REPAIR_DIAGNOSIS_PROFILE.extensions as string[]).pop(); + }).toThrow(TypeError); + expect(() => { + (EMBEDDED_DEV_PROFILE.extensions as string[]).splice(0, 1); + }).toThrow(TypeError); + }); + + it("状态-冻结态:篡改 profile.tools 抛 TypeError", () => { + expect(() => { + (BASE_PROFILE.tools as string[]).push("zzz"); + }).toThrow(TypeError); + }); + + it("状态-冻结态:DOMAIN_TOOLS 顶层表与每个域数组均冻结", () => { + expect(Object.isFrozen(DOMAIN_TOOLS)).toBe(true); + for (const tools of Object.values(DOMAIN_TOOLS)) { + expect(Object.isFrozen(tools)).toBe(true); + } + }); + + it("状态-冻结态:篡改 DOMAIN_TOOLS 表(新增键)抛(strict 模式)", () => { + expect(() => { + (DOMAIN_TOOLS as Record).evil = Object.freeze( + ["nope"], + ); + }).toThrow(); + }); + + it("状态-冻结态:BASE_EXTENSIONS / 两 DELTA 派生均冻结", () => { + expect(Object.isFrozen(BASE_EXTENSIONS)).toBe(true); + expect(Object.isFrozen(REPAIR_DIAGNOSIS_DELTA)).toBe(true); + expect(Object.isFrozen(EMBEDDED_DEV_DELTA)).toBe(true); + expect(Object.isFrozen(REPAIR_DIAGNOSIS_DELTA.extensions)).toBe(true); + expect(Object.isFrozen(REPAIR_DIAGNOSIS_DELTA.tools)).toBe(true); + expect(Object.isFrozen(EMBEDDED_DEV_DELTA.extensions)).toBe(true); + expect(Object.isFrozen(EMBEDDED_DEV_DELTA.tools)).toBe(true); + }); + + it("状态-幂等:对已冻结对象再次 Object.freeze 不报错(不可达态验证)", () => { + expect(() => Object.freeze(BASE_PROFILE)).not.toThrow(); + expect(() => Object.freeze(DOMAIN_TOOLS)).not.toThrow(); + expect(Object.isFrozen(BASE_PROFILE)).toBe(true); + }); + + it("状态-派生冻结:toolsFor / mergeProfiles / diffProfiles 返回值均冻结", () => { + expect(Object.isFrozen(toolsFor(["glm-provider"]))).toBe(true); + expect(Object.isFrozen(toolsFor([]))).toBe(true); + const merged = mergeProfiles(BASE_PROFILE, { + extensions: ["pdf-reader"], + tools: toolsFor(["pdf-reader"]), + }); + expect(Object.isFrozen(merged)).toBe(true); + expect(Object.isFrozen(merged.extensions)).toBe(true); + expect(Object.isFrozen(merged.tools)).toBe(true); + const d = diffProfiles(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE); + expect(Object.isFrozen(d)).toBe(true); + expect(Object.isFrozen(d.added)).toBe(true); + expect(Object.isFrozen(d.removed)).toBe(true); + }); + + it("状态-重入:并发调用纯函数无状态污染(同步重入安全)", () => { + // 纯函数无共享可变态;多次/嵌套调用结果一致 + const r1 = toolsFor(["glm-provider", "mcp-bridge"]); + const r2 = toolsFor(["glm-provider", "mcp-bridge"]); + expect([...r1]).toEqual([...r2]); + // 嵌套:mergeProfiles 内调 toolsFor + const nested = mergeProfiles(mergeProfiles(BASE_PROFILE, { + extensions: ["pdf-reader"], + tools: toolsFor(["pdf-reader"]), + }), { + extensions: ["peripheral-probe"], + tools: toolsFor(["peripheral-probe"]), + }); + expect(nested.extensions).toContain("pdf-reader"); + expect(nested.extensions).toContain("peripheral-probe"); + expect(nested.tools).toContain("read_pdf"); + expect(nested.tools).toContain("bus_probe"); + }); +}); + +// ============================================================================ +// ⑤ 变异测试 — 6 个 seeded bugs(M1~M6) +// ---------------------------------------------------------------------------- +// kill harness 范式:killer(fn) 对真实输出成立(不抛),对 mutant 输出失败 +// (抛 AssertionError)。expect(() => killer(real)).not.toThrow() 证明真实通过; +// expect(() => killer(mutant)).toThrow() 证明 mutant 被杀手断言杀死。 +// ============================================================================ + +describe("⑤ 变异测试 — M1:并集去重条件反转(!seen.has → seen.has)", () => { + // BUG: unionStable 中 `if (!seen.has(x))` 改为 `if (seen.has(x))`, + // delta 中 base 未含的新项被丢弃,base 已含项被重复追加。 + + // 杀手断言:delta 中 base 未含的新项必须在结果中出现(恰好 1 次)。 + const killer = (fn: typeof unionStableReal) => { + const out = fn(["a"], ["b"]); // b 不在 base + expect(out).toContain("b"); + expect([...out]).toEqual(["a", "b"]); + }; + + it("M1 真实通过:unionStableReal 追加 delta 新项", () => { + expect(() => killer(unionStableReal)).not.toThrow(); + }); + + it("M1 被杀:unionStableM1 丢弃 delta 新项(杀手断言失败)", () => { + expect(() => killer(unionStableM1)).toThrow(); + }); + + it("M1 被杀(直接观测):mutant 丢弃新项 + 重复已含项", () => { + expect([...unionStableM1(["a"], ["b"])]).toEqual(["a"]); + expect(unionStableM1(["a"], ["a"]).filter((x) => x === "a").length) + .toBe(2); + }); + + it("M1 端到端:mergeProfiles delta 新扩展出现在结果(真实对,M1 错)", () => { + const delta = { + extensions: ["pdf-reader"], + tools: toolsFor(["pdf-reader"]), + }; + const real = mergeProfiles(BASE_PROFILE, delta); + expect([...real.extensions]).toContain("pdf-reader"); + const m1Merged = Object.freeze({ + id: BASE_PROFILE.id, + extensions: unionStableM1(BASE_PROFILE.extensions, delta.extensions), + tools: unionStableM1(BASE_PROFILE.tools, delta.tools), + note: BASE_PROFILE.note, + }) as Profile; + expect([...m1Merged.extensions]).not.toContain("pdf-reader"); + }); +}); + +describe("⑤ 变异测试 — M2:未知域用 ?? [] 默认空(fail-closed 失效)", () => { + // BUG: toolsFor 中 `if (tools === undefined) throw` 改为 + // `const tools = DOMAIN_TOOLS[d] ?? []`,未知域取值 undefined → 兜底空数组, + // mutant 不抛错,未知域静默产出空工具集(fail-closed 失效)。 + + // 杀手断言:未知域必抛 domain-specific Error(消息含域名)。 + const killer = (fn: typeof toolsForReal) => { + expect(() => fn(["no-such-domain"])).toThrow( + /unknown extension domain "no-such-domain"/, + ); + }; + + it("M2 真实通过:toolsForReal 未知域抛 domain-specific Error", () => { + expect(() => killer(toolsForReal)).not.toThrow(); + }); + + it("M2 被杀:toolsForM2 不抛(杀手断言失败)", () => { + expect(() => killer(toolsForM2)).toThrow(); + }); + + it("M2 被杀(直接观测):mutant 静默吞掉未知域产出已知域工具", () => { + expect(() => toolsForM2(["no-such-domain"])).not.toThrow(); + expect([...toolsForM2(["no-such-domain"])]).toEqual([]); + const m2Out = toolsForM2(["glm-provider", "no-such", "mcp-bridge"]); + expect([...m2Out]).toEqual(["glm_status", "mcp_list", "mcp_call"]); + }); + + it("M2 端到端:toolsFor 未知域必抛(真实对,M2 错)", () => { + expect(() => toolsFor(["typo-domain"])).toThrow( + /unknown extension domain "typo-domain"/, + ); + expect(() => toolsForM2(["typo-domain"])).not.toThrow(); + }); +}); + +describe("⑤ 变异测试 — M3:漏 Object.freeze(mergeProfiles 结果可变)", () => { + // BUG: mergeProfiles 末尾漏 Object.freeze,结果对象可变。 + + // 杀手断言:篡改 mergeProfiles 结果 id 必抛 TypeError。 + const killer = (fn: typeof mergeProfilesReal) => { + const merged = fn(BASE_PROFILE, { + extensions: ["pdf-reader"], + tools: toolsFor(["pdf-reader"]), + }); + expect(() => { + (merged as Profile & { id: string }).id = "evil"; + }).toThrow(TypeError); + }; + + it("M3 真实通过:mergeProfilesReal 结果冻结,篡改抛 TypeError", () => { + expect(() => killer(mergeProfilesReal)).not.toThrow(); + }); + + it("M3 被杀:mergeProfilesM3 结果未冻结,篡改不抛(杀手断言失败)", () => { + expect(() => killer(mergeProfilesM3)).toThrow(); + }); + + it("M3 被杀(直接观测):mutant 结果 Object.isFrozen=false", () => { + const delta = { + extensions: ["pdf-reader"], + tools: toolsFor(["pdf-reader"]), + }; + expect(Object.isFrozen(mergeProfilesReal(BASE_PROFILE, delta))).toBe(true); + expect(Object.isFrozen(mergeProfilesM3(BASE_PROFILE, delta))).toBe(false); + }); + + it("M3 端到端:篡改真实 mergeProfiles extensions.push 抛 TypeError(真实对,M3 错)", () => { + const delta = { extensions: ["pdf-reader"], tools: toolsFor(["pdf-reader"]) }; + const real = mergeProfiles(BASE_PROFILE, delta); + expect(() => { + (real.extensions as string[]).push("evil"); + }).toThrow(TypeError); + const mutant = mergeProfilesM3(BASE_PROFILE, delta); + expect(() => { + (mutant.extensions as string[]).push("evil"); + }).not.toThrow(); + }); +}); + +describe("⑤ 变异测试 — M4:diffProfiles added/removed 互换", () => { + // BUG: diffProfiles 返回时 added 与 removed 互换。 + + // 杀手断言:diff(base, repair).added 含 repair 专属扩展 pdf-reader。 + const killer = (fn: typeof diffProfilesReal) => { + const d = fn(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE); + expect([...d.added]).toContain("pdf-reader"); + expect([...d.added]).toContain("datasheet-rag"); + expect(d.removed.length).toBe(0); + }; + + it("M4 真实通过:diffProfilesReal added 含 repair 专属", () => { + expect(() => killer(diffProfilesReal)).not.toThrow(); + }); + + it("M4 被杀:diffProfilesM4 added 被换成 removed(杀手断言失败)", () => { + expect(() => killer(diffProfilesM4)).toThrow(); + }); + + it("M4 被杀(方向敏感):diff(repair, embedded) 真实 added=embedded、removed=repair", () => { + const real = diffProfiles(REPAIR_DIAGNOSIS_PROFILE, EMBEDDED_DEV_PROFILE); + expect([...real.added]).toContain("cross-compile"); + expect([...real.added]).toContain("flash"); + expect([...real.removed]).toContain("pdf-reader"); + const mutant = diffProfilesM4(REPAIR_DIAGNOSIS_PROFILE, EMBEDDED_DEV_PROFILE); + expect([...mutant.added]).not.toContain("cross-compile"); + expect([...mutant.added]).toContain("pdf-reader"); + }); +}); + +describe("⑤ 变异测试 — M5:mergeProfiles 漏继承 note(note: undefined)", () => { + // BUG: mergeProfiles 返回 `note: undefined` 而非 `note: base.note`。 + // 契约要求 id/note 继承 base;mutant 丢失 note。 + + // 杀手断言:mergeProfiles 空 delta 时 note === base.note(非 undefined)。 + const killer = (fn: typeof mergeProfilesReal) => { + const merged = fn(BASE_PROFILE, { extensions: [], tools: [] }); + expect(merged.note).toBe(BASE_PROFILE.note); + expect(merged.note).not.toBeUndefined(); + }; + + it("M5 真实通过:mergeProfilesReal note 继承 base", () => { + expect(() => killer(mergeProfilesReal)).not.toThrow(); + }); + + it("M5 被杀:mergeProfilesM5 note 丢失(杀手断言失败)", () => { + expect(() => killer(mergeProfilesM5)).toThrow(); + }); + + it("M5 端到端:真实 mergeProfiles 单 delta 时 note 仍继承(真实对,M5 错)", () => { + const delta = { + extensions: ["peripheral-probe"], + tools: toolsFor(["peripheral-probe"]), + }; + expect(mergeProfiles(BASE_PROFILE, delta).note).toBe(BASE_PROFILE.note); + expect(mergeProfilesM5(BASE_PROFILE, delta).note).not.toBe( + BASE_PROFILE.note, + ); + expect(mergeProfilesM5(BASE_PROFILE, delta).note).toBeUndefined(); + }); +}); + +describe("⑤ 变异测试 — M6:unionStable 漏 seen.add(delta 内部重复不去重)", () => { + // BUG: unionStable 中新项追加后漏 `seen.add(x)`。 + // 后果:delta 内部重复的非 base 项被多次追加(去重失效,仅对 delta 内部重复)。 + + // 杀手断言:delta 含内部重复非 base 项 → 结果中该项恰 1 份。 + const killer = (fn: typeof unionStableReal) => { + const out = fn(["a"], ["b", "b"]); // b 不在 base,delta 内重复 + expect(out.filter((x) => x === "b")).toStrictEqual(["b"]); + }; + + it("M6 真实通过:unionStableReal 对 delta 内重复去重为 1", () => { + expect(() => killer(unionStableReal)).not.toThrow(); + }); + + it("M6 被杀:unionStableM6 不去重 delta 内重复(杀手断言失败)", () => { + expect(() => killer(unionStableM6)).toThrow(); + }); + + it("M6 被杀(直接观测):mutant 对 delta 内重复产出 2 份", () => { + expect(unionStableM6(["a"], ["b", "b"]).filter((x) => x === "b").length) + .toBe(2); + expect(unionStableReal(["a"], ["b", "b"]).filter((x) => x === "b").length) + .toBe(1); + }); +}); + +describe("⑤ 变异测试 — 汇总:6 个 mutant 均被杀手断言区分(被杀)", () => { + it("汇总:每个 mutant 至少一处输出/行为与真实不同(被杀)", () => { + // M1:新项被丢弃 + expect([...unionStableReal(["a"], ["b"])]).not.toEqual([ + ...unionStableM1(["a"], ["b"]), + ]); + // M2:未知域不抛 + let m2threw = true; + try { + toolsForM2(["no-such"]); + m2threw = false; + } catch { + m2threw = true; + } + expect(m2threw).toBe(false); // mutant 不抛 = 与真实不同 + expect(() => toolsForReal(["no-such"])).toThrow(); + // M3:未冻结 + expect(Object.isFrozen(mergeProfilesM3(BASE_PROFILE, { + extensions: [], + tools: [], + }))).toBe(false); + expect(Object.isFrozen(mergeProfilesReal(BASE_PROFILE, { + extensions: [], + tools: [], + }))).toBe(true); + // M4:added 互换 + expect([...diffProfilesM4(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE).added]) + .not.toEqual([...diffProfilesReal(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE).added]); + // M5:note 丢失 + expect(mergeProfilesM5(BASE_PROFILE, { extensions: [], tools: [] }).note) + .not.toBe(mergeProfilesReal(BASE_PROFILE, { extensions: [], tools: [] }).note); + // M6:delta 内重复不去重 + expect([...unionStableReal(["a"], ["b", "b"])]).not.toEqual([ + ...unionStableM6(["a"], ["b", "b"]), + ]); + }); +}); + +// ============================================================================ +// ⑥ 对抗 / fuzz —— 畸形/滥用输入 +// ============================================================================ + +describe("⑥ 对抗/fuzz — 畸形/滥用输入", () => { + it("fuzz-undefined 元素:toolsFor([undefined]) 抛错(fail-closed)", () => { + expect(() => toolsFor([undefined as unknown as string])).toThrow(); + }); + + it("fuzz-null 元素:toolsFor([null]) 抛错(fail-closed)", () => { + expect(() => toolsFor([null as unknown as string])).toThrow(); + }); + + it("fuzz-NaN 元素:toolsFor([NaN]) 抛错(DOMAIN_TOOLS['NaN'] undefined)", () => { + expect(() => toolsFor([NaN as unknown as string])).toThrow(); + }); + + it("fuzz-数字串元素:toolsFor([123]) 抛错('123' 非域)", () => { + expect(() => toolsFor([123 as unknown as string])).toThrow(); + }); + + it("fuzz-空串元素:toolsFor(['']) 抛错('' 非域)", () => { + expect(() => toolsFor([""])).toThrow(/unknown extension domain ""/); + }); + + it("fuzz-巨大输入:toolsFor(全域重复 1000 次) 不崩且结果等于全域去重", () => { + const allDomains = Object.keys(DOMAIN_TOOLS); + const huge: string[] = []; + for (let i = 0; i < 1000; i++) { + huge.push(allDomains[i % allDomains.length]); + } + const got = toolsFor(huge); + const once = toolsFor(allDomains); + expect([...got]).toEqual([...once]); + }); + + it("fuzz-非 string 元素:mergeProfiles delta.extensions 含数字 → 不崩(并集原样保留)", () => { + // mergeProfiles 不校验元素类型(并集原语),数字被当 string 比较 + const merged = mergeProfiles(BASE_PROFILE, { + extensions: [123 as unknown as string], + tools: [], + }); + // 123 被 Set 当作不同项追加(与 base 字符串不同) + expect(merged.extensions).toContain(123); + }); + + it("fuzz-mergeProfiles null base → 抛 TypeError(访问 base.id)", () => { + expect(() => + mergeProfiles(null as unknown as Profile, { + extensions: [], + tools: [], + }), + ).toThrow(TypeError); + }); + + it("fuzz-mergeProfiles undefined delta → 抛 TypeError", () => { + expect(() => + mergeProfiles( + BASE_PROFILE, + undefined as unknown as Pick, + ), + ).toThrow(TypeError); + }); + + it("fuzz-diffProfiles 重复扩展:a 含重复 → removed 保留重复(实现不主动去重)", () => { + // base.ts diffProfiles 文档(base.ts:244-248)明确声明"不主动去重": + // 遍历 a.extensions 逐条 push,含重复输入 → 输出含重复。 + // 真实 profile 无重复扩展,故实际无害;此 fuzz 断言"实现不主动去重"的当前行为。 + const a: Profile = Object.freeze({ + id: "a", + extensions: Object.freeze(["x", "x", "y"]) as readonly string[], + tools: Object.freeze([]) as readonly string[], + note: undefined, + }) as Profile; + const b: Profile = Object.freeze({ + id: "b", + extensions: Object.freeze(["y"]) as readonly string[], + tools: Object.freeze([]) as readonly string[], + note: undefined, + }) as Profile; + const d = diffProfiles(a, b); + // 当前行为:removed 含重复 ["x","x"](不主动去重,与文档一致) + expect([...d.removed]).toEqual(["x", "x"]); + }); + + it("fuzz-resolveProfile 数字/对象/布尔 id → 抛错", () => { + expect(() => resolveProfile(123 as unknown as string)).toThrow(); + expect(() => resolveProfile(true as unknown as string)).toThrow(); + expect(() => + resolveProfile({} as unknown as string), + ).toThrow(); + }); + + it("fuzz-并发重入:toolsFor 与 mergeProfiles 嵌套/交错调用结果确定", () => { + const r1 = toolsFor(["glm-provider", "mcp-bridge"]); + const r2 = toolsFor(["mcp-bridge", "glm-provider"]); + // 集合相同(去重),但序不同(保序) + expect(new Set(r1)).toEqual(new Set(r2)); + const m1 = mergeProfiles(BASE_PROFILE, { + extensions: ["pdf-reader"], + tools: toolsFor(["pdf-reader"]), + }); + const m2 = mergeProfiles(BASE_PROFILE, { + extensions: ["pdf-reader"], + tools: toolsFor(["pdf-reader"]), + }); + expect([...m1.extensions]).toEqual([...m2.extensions]); + }); + + it("fuzz-超长 id:resolveProfile(超长串) 抛错(非注册 id)", () => { + const long = "x".repeat(10000); + expect(() => resolveProfile(long)).toThrow(/unknown profile id/); + }); + + it("fuzz-unicode/空白 id:resolveProfile 不误匹配(大小写+空白敏感)", () => { + expect(() => resolveProfile(" base")).toThrow(); + expect(() => resolveProfile("base ")).toThrow(); + expect(() => resolveProfile("base")).toThrow(); + expect(() => resolveProfile(" base")).toThrow(); + }); +}); + +// ============================================================================ +// ⑥ 对抗/fuzz — F1 回归(已修复:Object.prototype 继承键 fail-closed) +// ---------------------------------------------------------------------------- +// F1 原 findings[]:resolveProfile 用 `PROFILE_REGISTRY[id]` 查表(index.ts), +// 该属性查找走原型链,对 "toString"/"constructor"/"__proto__" 等 Object.prototype +// 继承键取到继承成员(!== undefined → 不抛 → 返回函数/对象当 Profile 用)。 +// 修复(index.ts):改用 Object.hasOwn(PROFILE_REGISTRY, id) 判定,只认自身属性, +// 继承键一律判为未注册 → fail-closed 抛错。原 it.fails 标记已翻成 it(修复后 +// 断言成功 → 绿),转为永久回归守护,防止退回原型链查表。 +// ============================================================================ + +describe("⑥ 对抗/fuzz — F1 回归:resolveProfile 对 Object.prototype 继承键 fail-closed(已修复)", () => { + for (const key of PROTO_KEYS) { + it(`F1 回归:resolveProfile("${key}") 抛 fail-closed(不返回继承成员)`, () => { + expect(() => resolveProfile(key)).toThrow(/unknown profile id/); + expect(() => resolveProfile(key)).toThrow(/fail-closed/); + }); + } + + it("F1 回归:resolveProfile('__proto__') 抛而非返回 Object.prototype", () => { + expect(() => resolveProfile("__proto__")).toThrow(/unknown profile id/); + }); + + // 对照组:正常未注册 id 也抛(证明 fail-closed 对继承键与普通键一致) + it("F1 对照:正常未注册 id 'nope' 抛错(fail-closed 一致)", () => { + expect(() => resolveProfile("nope")).toThrow(/unknown profile id "nope"/); + }); + + // 回归:继承键不再返回继承成员(直接观测,不依赖 it.fails 语义) + it("F1 回归:resolveProfile('toString') 抛错而非返回 function", () => { + let got: unknown; + try { + got = resolveProfile("toString"); + } catch { + got = "THREW"; + } + expect(got).toBe("THREW"); + }); + + it("F1 回归:resolveProfile('__proto__') 抛错而非返回 object", () => { + let got: unknown; + try { + got = resolveProfile("__proto__"); + } catch { + got = "THREW"; + } + expect(got).toBe("THREW"); + }); +}); + +// ============================================================================ +// ⑦ 元蜕变 / 不变式 +// ============================================================================ + +describe("⑦ 元蜕变/不变式 — append 两次 = replay 等价(并集结合律)", () => { + // 不变式:mergeProfiles(mergeProfiles(base, d1), d2) + // ≡ mergeProfiles(base, d1++d2) (在 extensions/tools 并集语义下) + it("不变式:分两步合并 = 一次性合并(extensions 集合等价)", () => { + const d1 = { + extensions: ["pdf-reader"], + tools: toolsFor(["pdf-reader"]), + }; + const d2 = { + extensions: ["peripheral-probe"], + tools: toolsFor(["peripheral-probe"]), + }; + const twoStep = mergeProfiles(mergeProfiles(BASE_PROFILE, d1), d2); + const oneShot = mergeProfiles(BASE_PROFILE, { + extensions: [...d1.extensions, ...d2.extensions], + tools: toolsFor(["pdf-reader", "peripheral-probe"]), + }); + expect(new Set(twoStep.extensions)).toEqual(new Set(oneShot.extensions)); + expect(new Set(twoStep.tools)).toEqual(new Set(oneShot.tools)); + // 序也一致(base 在前,delta 按 d1→d2 序追加) + expect([...twoStep.extensions]).toEqual([...oneShot.extensions]); + expect([...twoStep.tools]).toEqual([...oneShot.tools]); + }); + + it("不变式:三步合并 = 全量一次性合并(repair 三差异域)", () => { + const repairDeltaExt = REPAIR_DIAGNOSIS_DELTA.extensions; + const step1 = mergeProfiles(BASE_PROFILE, { + extensions: [repairDeltaExt[0]], + tools: toolsFor([repairDeltaExt[0]]), + }); + const step2 = mergeProfiles(step1, { + extensions: [repairDeltaExt[1]], + tools: toolsFor([repairDeltaExt[1]]), + }); + const step3 = mergeProfiles(step2, { + extensions: [repairDeltaExt[2]], + tools: toolsFor([repairDeltaExt[2]]), + }); + // 等价于直接 repair profile 的 extensions 集合 + expect(new Set(step3.extensions)).toEqual( + new Set(REPAIR_DIAGNOSIS_PROFILE.extensions), + ); + expect(new Set(step3.tools)).toEqual( + new Set(REPAIR_DIAGNOSIS_PROFILE.tools), + ); + }); +}); + +describe("⑦ 元蜕变/不变式 — freeze → 篡改抛 TypeError(单调不可变)", () => { + it("不变式:所有导出常量 + 所有派生函数返回值篡改均抛 TypeError", () => { + const tamper = (fn: () => void) => expect(fn).toThrow(TypeError); + tamper(() => { + (BASE_PROFILE as Profile & { id: string }).id = "x"; + }); + tamper(() => { + (REPAIR_DIAGNOSIS_PROFILE as Profile & { id: string }).id = "x"; + }); + tamper(() => { + (EMBEDDED_DEV_PROFILE as Profile & { id: string }).id = "x"; + }); + tamper(() => { + (BASE_EXTENSIONS as string[]).push("x"); + }); + tamper(() => { + (REPAIR_DIAGNOSIS_DELTA.extensions as string[]).push("x"); + }); + tamper(() => { + (EMBEDDED_DEV_DELTA.tools as string[]).push("x"); + }); + // 派生 + tamper(() => { + (toolsFor(["glm-provider"]) as string[]).push("x"); + }); + tamper(() => { + (mergeProfiles(BASE_PROFILE, { + extensions: [], + tools: [], + }) as Profile & { id: string }).id = "x"; + }); + tamper(() => { + (diffProfiles(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE).added as string[]) + .push("x"); + }); + }); +}); + +describe("⑦ 元蜕变/不变式 — 单调 fail-closed(unusable = 拒绝)", () => { + it("不变式:resolveProfile 未知 id 不返回 undefined/默认,必抛", () => { + // 不返回 undefined + let result: Profile | undefined; + try { + result = resolveProfile("does-not-exist"); + } catch { + result = undefined; + } + expect(result).toBeUndefined(); // 抛错 → 未赋值 + }); + + it("不变式:toolsFor 未知域不静默返回空,必抛", () => { + // 纯未知域:必抛而非返回空 + expect(() => toolsFor(["totally-fake"])).toThrow(); + // 与 toolsFor([]) 的空数组语义对照:空输入返回空是合法的 + expect(toolsFor([]).length).toBe(0); + }); + + it("不变式:resolveProfile 返回注册表冻结实例(引用共享,不复制)", () => { + // 多次调用返回同一引用(确定性、无复制) + expect(resolveProfile("base")).toBe(resolveProfile("base")); + expect(resolveProfile("repair-diagnosis")).toBe( + resolveProfile("repair-diagnosis"), + ); + expect(resolveProfile("embedded-dev")).toBe( + resolveProfile("embedded-dev"), + ); + }); +}); + +describe("⑦ 元蜕变/不变式 — mergeProfiles 不重派生(短路:并集原语不调 toolsFor)", () => { + // 不变式:mergeProfiles 对 delta.tools 做原样并集,不调 toolsFor 重新派生。 + // 即:若 delta.tools 与 delta.extensions 不一致,结果反映 delta.tools 字面值, + // 不短路重派生。这验证了"并集原语"边界——mergeProfiles 是 dumb combiner。 + it("不变式:delta.tools 与 delta.extensions 不一致时,结果 tools 取 delta.tools 字面值", () => { + const merged = mergeProfiles(BASE_PROFILE, { + extensions: ["pdf-reader", "peripheral-probe"], + // 故意只给一个工具(不一致) + tools: ["read_pdf"], + }); + // extensions 含两个域 + expect(merged.extensions).toContain("pdf-reader"); + expect(merged.extensions).toContain("peripheral-probe"); + // tools 只含 delta.tools 字面 + base(不重派生 bus_probe) + expect(merged.tools).toContain("read_pdf"); + expect(merged.tools).not.toContain("bus_probe"); + }); + + it("不变式:真实 REPAIR/EMBEDDED delta 的 tools 与 extensions 一致(派生自 toolsFor)", () => { + // 契约保证:delta.tools = toolsFor(delta.extensions) + expect([...REPAIR_DIAGNOSIS_DELTA.tools]).toEqual([ + ...toolsFor([...REPAIR_DIAGNOSIS_DELTA.extensions]), + ]); + expect([...EMBEDDED_DEV_DELTA.tools]).toEqual([ + ...toolsFor([...EMBEDDED_DEV_DELTA.extensions]), + ]); + }); +}); + +describe("⑦ 元蜕变/不变式 — 命名 profile = mergeProfiles(base, delta) + 覆盖 id/note", () => { + it("不变式:REPAIR_DIAGNOSIS_PROFILE.extensions = base ∪ repair delta(集合等价)", () => { + const expected = new Set([ + ...BASE_PROFILE.extensions, + ...REPAIR_DIAGNOSIS_DELTA.extensions, + ]); + expect(new Set(REPAIR_DIAGNOSIS_PROFILE.extensions)).toEqual(expected); + }); + + it("不变式:EMBEDDED_DEV_PROFILE.tools = base ∪ embedded delta(集合等价)", () => { + const expected = new Set([ + ...BASE_PROFILE.tools, + ...EMBEDDED_DEV_DELTA.tools, + ]); + expect(new Set(EMBEDDED_DEV_PROFILE.tools)).toEqual(expected); + }); + + it("不变式:两业务 profile ⊇ base(extensions + tools 双超集)", () => { + const baseExt = new Set(BASE_PROFILE.extensions); + const baseTools = new Set(BASE_PROFILE.tools); + for (const p of [REPAIR_DIAGNOSIS_PROFILE, EMBEDDED_DEV_PROFILE]) { + for (const e of baseExt) { + expect(new Set(p.extensions).has(e)).toBe(true); + } + for (const t of baseTools) { + expect(new Set(p.tools).has(t)).toBe(true); + } + } + }); + + it("不变式:repair 与 embedded 差异扩展不重叠", () => { + const repairOnly = new Set(REPAIR_DIAGNOSIS_DELTA.extensions); + for (const e of EMBEDDED_DEV_DELTA.extensions) { + expect(repairOnly.has(e)).toBe(false); + } + const embeddedOnly = new Set(EMBEDDED_DEV_DELTA.extensions); + for (const e of REPAIR_DIAGNOSIS_DELTA.extensions) { + expect(embeddedOnly.has(e)).toBe(false); + } + }); + + it("不变式:每个 profile 的 tools ⊆ DOMAIN_TOOLS 全量(无魔法串)", () => { + for (const p of ALL_PROFILES) { + for (const t of p.tools) { + expect(ALL_TOOLS_SET.has(t)).toBe(true); + } + } + }); + + it("不变式:repair 不含 embedded 专属工具,反之亦然", () => { + expect(REPAIR_DIAGNOSIS_PROFILE.tools).not.toContain("flash"); + expect(REPAIR_DIAGNOSIS_PROFILE.tools).not.toContain("xcompile"); + expect(REPAIR_DIAGNOSIS_PROFILE.tools).not.toContain("reg"); + expect(EMBEDDED_DEV_PROFILE.tools).not.toContain("read_pdf"); + expect(EMBEDDED_DEV_PROFILE.tools).not.toContain("datasheet_query"); + expect(EMBEDDED_DEV_PROFILE.tools).not.toContain("bus_probe"); + }); + + it("不变式:DOMAIN_TOOLS 每个工具名在真实扩展 defineTool name 中有 referent", () => { + for (const t of ALL_TOOLS_SET) { + expect(KNOWN_DEFINE_TOOL_NAMES.has(t)).toBe(true); + } + // 反向:每个已知 defineTool name 必在 DOMAIN_TOOLS 某域下 + for (const name of KNOWN_DEFINE_TOOL_NAMES) { + expect(ALL_TOOLS_SET.has(name)).toBe(true); + } + }); +}); + +describe("⑦ 元蜕变/不变式 — diffProfiles 对称性 / 幂等性", () => { + it("不变式:diff(a,b) 的 added = diff(b,a) 的 removed(方向反转对称)", () => { + const ab = diffProfiles(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE); + const ba = diffProfiles(REPAIR_DIAGNOSIS_PROFILE, BASE_PROFILE); + expect([...ab.added]).toEqual([...ba.removed]); + expect([...ab.removed]).toEqual([...ba.added]); + }); + + it("不变式:diff 幂等(重复调用结果等价)", () => { + const d1 = diffProfiles(BASE_PROFILE, EMBEDDED_DEV_PROFILE); + const d2 = diffProfiles(BASE_PROFILE, EMBEDDED_DEV_PROFILE); + expect([...d1.added]).toEqual([...d2.added]); + expect([...d1.removed]).toEqual([...d2.removed]); + }); + + it("不变式:diff 结果 added/removed 对无重复输入各自保序(无重复)", () => { + // 真实 profile 的 extensions 无重复,故 added/removed 无重复(输入驱动的不重复) + const d = diffProfiles(BASE_PROFILE, EMBEDDED_DEV_PROFILE); + const addedDedup = new Set(d.added); + expect(addedDedup.size).toBe(d.added.length); + const removedDedup = new Set(d.removed); + expect(removedDedup.size).toBe(d.removed.length); + }); + + it("不变式:diff 三角不变式——added ∪ removed ∪ 交集 = a∪b extensions 全集", () => { + const d = diffProfiles(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE); + const union = new Set([...BASE_PROFILE.extensions, ...REPAIR_DIAGNOSIS_PROFILE.extensions]); + const onlyB = new Set(d.added); // b 有 a 无 + const onlyA = new Set(d.removed); // a 有 b 无 + const both = new Set([...BASE_PROFILE.extensions].filter((e) => union.has(e) && !onlyA.has(e) && !onlyB.has(e))); + // added ∪ removed ∪ 交集 应等于 a∪b 全集 + const recon = new Set([...onlyA, ...onlyB, ...both]); + expect(recon).toEqual(union); + }); +}); diff --git a/tests/provider-registry.test.ts b/tests/provider-registry.test.ts new file mode 100644 index 0000000..c03ff10 --- /dev/null +++ b/tests/provider-registry.test.ts @@ -0,0 +1,1085 @@ +/** + * @module provider-registry.test + * + * T16 provider-registry 严谨测试套件(Test Agent 独占)—— 多方法论覆盖, + * 植入 bug 活不过。 + * + * 被测对象:src/core/provider-registry.ts 的【全部】命名导出 + * - buildProviderConfig(desc) → { name, config } 低层信任(不校验) + * - buildProviderConfigValidated(desc) → { name, config } fail-closed(先校验后构建) + * - assertDescriptorValid(desc) → void 校验必填字段 + * - ProviderRegistry(register/resolve/list) 可注册/解析表 + 代际 disposer + * - DEFAULT_GLM_DESCRIPTOR / KNOWN_PROVIDERS 深冻结常量 + * - 类型:ThinkingFormat / ProviderDescriptor + * + * 纯逻辑:直接 import 命名导出,无 pi 运行时、无硬件、无网络、无 mock 依赖 + * (模块顶层仅 `import type`,运行时不解析 pi;vitest alias 把 pi 类型解析到 .d.ts)。 + * + * 方法论(每个 describe 块标注): + * 1. 等价类划分(有效/无效/边界类) + * 2. 边界值分析(off-by-one、空、单元素、min/max) + * 3. 决策表(组合输入→期望,覆盖全分支) + * 4. 状态转换(状态+迁移+不可达状态+重入) + * 5. 变异测试(6 个 seeded bug,每个被某条测试杀死;附 inline mutant 副本证可区分) + * 6. 对抗/fuzz(null/undefined/巨大/NaN/循环引用/并发重入/负 seq) + * 7. 元蜕变/不变式(跨变换保持的性质) + * + * 门: + * 1. 真实(未植入 bug)代码必须 all green(本文件 `npx vitest run` 全过)。 + * 2. 每个 seeded bug 植入真实源码后单独跑,确认至少一条 killer 测试 FAIL(bug 被杀)。 + * (验证方式见本文件末尾 §9 文档:逐个临时编辑源码植入 bug → vitest → 见红 → 还原。) + */ +import { describe, it, expect } from "vitest"; +import { + buildProviderConfig, + buildProviderConfigValidated, + assertDescriptorValid, + ProviderRegistry, + KNOWN_PROVIDERS, + DEFAULT_GLM_DESCRIPTOR, + type ProviderDescriptor, + type ThinkingFormat, +} from "../src/core/provider-registry.js"; + +// ============================================================================ +// 测试夹具 —— 干净的、未冻结的可变描述符(避免污染深冻结常量) +// ============================================================================ + +/** 克隆 DEFAULT_GLM_DESCRIPTOR 字段为可变副本,按需覆盖字段。 */ +function glm(overrides: Partial = {}): ProviderDescriptor { + return { + id: "glm-5.2", + provider: "drobotics-glm", + baseUrl: "https://ai-api.d-robotics.cc/v1", + apiKeyEnv: "DROBOTICS_LLM_KEY", + thinkingFormat: "qwen", + maxTokens: 8192, + contextWindow: 1_000_000, + reasoning: true, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + ...overrides, + }; +} + +/** 取 KNOWN_PROVIDERS 中的 deepseek stub 为可变克隆。 */ +function deepseek(overrides: Partial = {}): ProviderDescriptor { + const ds = KNOWN_PROVIDERS.find((d) => d.id === "deepseek-chat"); + expect(ds).toBeDefined(); + const base = ds as ProviderDescriptor; + return { + ...base, + cost: { ...base.cost! }, + input: [...base.input!], + ...overrides, + }; +} + +/** 最小有效描述符(无可选字段),用于决策表/边界。 */ +function minimal(overrides: Partial = {}): ProviderDescriptor { + return { + id: "x", + provider: "p", + baseUrl: "u", + apiKeyEnv: "K", + maxTokens: 8, + contextWindow: 100, + reasoning: true, + ...overrides, + }; +} + +/** 取 buildProviderConfig 的 model[0],减少样板。 */ +function modelOf(desc: ProviderDescriptor) { + return buildProviderConfig(desc).config.models![0]; +} + +// ============================================================================ +// 1. 等价类划分 — buildProviderConfig 有效/无效/边界类 +// ============================================================================ + +describe("等价类划分 — buildProviderConfig 有效/无效/边界类", () => { + it("有效类·qwen: 注入 compat + 全 null thinkingLevelMap(治命门一)", () => { + const { name, config } = buildProviderConfig(glm()); + expect(name).toBe("drobotics-glm"); + const model = config.models![0]; + expect(model.compat?.thinkingFormat).toBe("qwen"); + expect(model.compat?.supportsReasoningEffort).toBe(false); + expect(model.thinkingLevelMap).toEqual({ off: null, low: null, medium: null, high: null }); + }); + + it("有效类·none: 不注入 qwen compat,直通 thinkingLevelMap", () => { + const { name, config } = buildProviderConfig(deepseek()); + expect(name).toBe("deepseek-native"); + const model = config.models![0]; + expect(model.compat?.thinkingFormat).toBeUndefined(); + expect(model.thinkingLevelMap).toEqual({ off: null, low: "low", medium: "medium", high: "high" }); + expect(model.reasoning).toBe(false); + }); + + it("有效类·缺省 thinkingFormat: 视为 none(直通路径,无 qwen shim)", () => { + const desc = glm({ thinkingFormat: undefined }); + const model = modelOf(desc); + expect(model.compat?.thinkingFormat).toBeUndefined(); + expect(model.thinkingLevelMap).toEqual({ off: null, low: "low", medium: "medium", high: "high" }); + }); + + it("无效类·畸形 thinkingFormat 值: 不等于 'qwen' → 落 none 分支(fail-open 行为文档化)", () => { + const desc = glm({ thinkingFormat: "qwen2" as ThinkingFormat }); + const model = modelOf(desc); + expect(model.compat?.thinkingFormat).toBeUndefined(); + expect(model.thinkingLevelMap?.low).toBe("low"); + }); + + it("边界类·desc.input 为空数组: model.input === [](透传不补默认)", () => { + const desc = glm({ input: [] }); + expect(modelOf(desc).input).toEqual([]); + }); + + it("边界类·desc.input 多模态 ['text','image']: 透传且为副本", () => { + const desc = glm({ input: ["text", "image"] }); + const model = modelOf(desc); + expect(model.input).toEqual(["text", "image"]); + expect(model.input).not.toBe(desc.input); // spread 产生新数组 + }); + + it("边界类·desc.cost 缺省: model.cost 默认全 0(冻结)", () => { + const desc = glm(); + // @ts-expect-error intentional mutation: delete readonly property + delete (desc as Partial).cost; + const model = modelOf(desc); + expect(model.cost).toEqual({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }); + expect(Object.isFrozen(model.cost)).toBe(true); + }); + + it("边界类·desc.cost 显式: model.cost === desc.cost(同引用,Object.freeze 原地冻结 quirk 文档化)", () => { + const cost = { input: 1, output: 2, cacheRead: 0.1, cacheWrite: 0.2 }; + const desc = glm({ cost }); + const model = modelOf(desc); + // Object.freeze 返回同引用 → model.cost === desc.cost(同引用契约) + expect(model.cost).toBe(cost); + expect(model.cost).toEqual({ input: 1, output: 2, cacheRead: 0.1, cacheWrite: 0.2 }); + // 原地冻结副作用:caller 的 cost 被冻结,再改写抛 TypeError(静默→显式硬化) + expect(() => { + (cost as { input: number }).input = 999; + }).toThrow(TypeError); + expect(Object.isFrozen(cost)).toBe(true); + }); +}); + +// ============================================================================ +// 2. 边界值分析 — assertDescriptorValid(via register + 直接调用)off-by-one/空/单/min/max +// ============================================================================ + +describe("边界值分析 — assertDescriptorValid off-by-one/空/单/min/max", () => { + it("空串 id: reject(边界最小无效)", () => { + expect(() => assertDescriptorValid(glm({ id: "" }))).toThrow(/id/); + }); + + it("纯空白 id ' ': reject(trim 后空)", () => { + expect(() => assertDescriptorValid(glm({ id: " " }))).toThrow(/id/); + }); + + it("单字符 id 'a': 接受(边界最小有效)", () => { + const reg = new ProviderRegistry(); + reg.register(glm({ id: "a" })); + expect(reg.resolve("a").id).toBe("a"); + }); + + it("maxTokens=0: reject(off-by-one 边界,真实用 <=0)", () => { + expect(() => assertDescriptorValid(glm({ maxTokens: 0 }))).toThrow(/maxTokens/); + }); + + it("maxTokens=1: 接受(边界最小有效正数)", () => { + const reg = new ProviderRegistry(); + reg.register(glm({ id: "m1", maxTokens: 1 })); + expect(reg.resolve("m1").maxTokens).toBe(1); + }); + + it("maxTokens=Number.EPSILON: 接受(最小正有限数)", () => { + const reg = new ProviderRegistry(); + reg.register(glm({ id: "eps", maxTokens: Number.EPSILON })); + expect(reg.resolve("eps").maxTokens).toBe(Number.EPSILON); + }); + + it("maxTokens=Number.MAX_SAFE_INTEGER: 接受(max 有限)", () => { + const reg = new ProviderRegistry(); + reg.register(glm({ id: "max", maxTokens: Number.MAX_SAFE_INTEGER })); + expect(reg.resolve("max").maxTokens).toBe(Number.MAX_SAFE_INTEGER); + }); + + it("maxTokens=-1: reject(负数)", () => { + expect(() => assertDescriptorValid(glm({ maxTokens: -1 }))).toThrow(/maxTokens/); + }); + + it("maxTokens=NaN: reject(非有限)", () => { + expect(() => assertDescriptorValid(glm({ maxTokens: NaN }))).toThrow(/maxTokens/); + }); + + it("maxTokens=Infinity: reject(非有限)", () => { + expect(() => assertDescriptorValid(glm({ maxTokens: Infinity }))).toThrow(/maxTokens/); + }); + + it("maxTokens=-Infinity: reject(非有限)", () => { + expect(() => assertDescriptorValid(glm({ maxTokens: -Infinity }))).toThrow(/maxTokens/); + }); + + it("contextWindow=0: reject", () => { + expect(() => assertDescriptorValid(glm({ contextWindow: 0 }))).toThrow(/contextWindow/); + }); + + it("contextWindow=NaN: reject", () => { + expect(() => assertDescriptorValid(glm({ contextWindow: NaN }))).toThrow(/contextWindow/); + }); + + it("contextWindow=Infinity: reject", () => { + expect(() => assertDescriptorValid(glm({ contextWindow: Infinity }))).toThrow(/contextWindow/); + }); + + it("contextWindow=1: 接受(边界最小有效正数)", () => { + const reg = new ProviderRegistry(); + reg.register(glm({ id: "cw1", contextWindow: 1 })); + expect(reg.resolve("cw1").contextWindow).toBe(1); + }); + + it("provider 空串: reject", () => { + expect(() => assertDescriptorValid(glm({ provider: "" }))).toThrow(/provider/); + }); + + it("baseUrl 空串: reject", () => { + expect(() => assertDescriptorValid(glm({ baseUrl: "" }))).toThrow(/baseUrl/); + }); + + it("apiKeyEnv 空串: reject", () => { + expect(() => assertDescriptorValid(glm({ apiKeyEnv: "" }))).toThrow(/apiKeyEnv/); + }); + + it("apiKeyEnv 纯空白 '\\t': reject", () => { + expect(() => assertDescriptorValid(glm({ apiKeyEnv: "\t" }))).toThrow(/apiKeyEnv/); + }); + + it("id 非字符串(数字 123): reject(typeof 守卫)", () => { + expect(() => assertDescriptorValid(glm({ id: 123 as unknown as string }))).toThrow(/id/); + }); +}); + +// ============================================================================ +// 3a. 决策表 — assertDescriptorValid 全分支组合 +// 规则:id/provider/baseUrl/apiKeyEnv 必须非空白串;maxTokens/contextWindow 必须有限正 +// 决策表每行覆盖一个字段取反,其余有效 +// ============================================================================ + +describe("决策表 — assertDescriptorValid 全分支组合", () => { + const cases: ReadonlyArray<{ + name: string; + id: string; + provider: string; + baseUrl: string; + apiKeyEnv: string; + maxTokens: number; + contextWindow: number; + throws?: RegExp; + }> = [ + { name: "全有效", id: "x", provider: "p", baseUrl: "u", apiKeyEnv: "K", maxTokens: 8, contextWindow: 100 }, + { name: "id 空", id: "", provider: "p", baseUrl: "u", apiKeyEnv: "K", maxTokens: 8, contextWindow: 100, throws: /id/ }, + { name: "provider 空", id: "x", provider: "", baseUrl: "u", apiKeyEnv: "K", maxTokens: 8, contextWindow: 100, throws: /provider/ }, + { name: "baseUrl 空", id: "x", provider: "p", baseUrl: "", apiKeyEnv: "K", maxTokens: 8, contextWindow: 100, throws: /baseUrl/ }, + { name: "apiKeyEnv 空", id: "x", provider: "p", baseUrl: "u", apiKeyEnv: "", maxTokens: 8, contextWindow: 100, throws: /apiKeyEnv/ }, + { name: "maxTokens=0", id: "x", provider: "p", baseUrl: "u", apiKeyEnv: "K", maxTokens: 0, contextWindow: 100, throws: /maxTokens/ }, + { name: "maxTokens 负", id: "x", provider: "p", baseUrl: "u", apiKeyEnv: "K", maxTokens: -5, contextWindow: 100, throws: /maxTokens/ }, + { name: "maxTokens NaN", id: "x", provider: "p", baseUrl: "u", apiKeyEnv: "K", maxTokens: NaN, contextWindow: 100, throws: /maxTokens/ }, + { name: "maxTokens Inf", id: "x", provider: "p", baseUrl: "u", apiKeyEnv: "K", maxTokens: Infinity, contextWindow: 100, throws: /maxTokens/ }, + { name: "contextWindow=0", id: "x", provider: "p", baseUrl: "u", apiKeyEnv: "K", maxTokens: 8, contextWindow: 0, throws: /contextWindow/ }, + { name: "contextWindow 负", id: "x", provider: "p", baseUrl: "u", apiKeyEnv: "K", maxTokens: 8, contextWindow: -1, throws: /contextWindow/ }, + { name: "contextWindow NaN", id: "x", provider: "p", baseUrl: "u", apiKeyEnv: "K", maxTokens: 8, contextWindow: NaN, throws: /contextWindow/ }, + { name: "contextWindow Inf", id: "x", provider: "p", baseUrl: "u", apiKeyEnv: "K", maxTokens: 8, contextWindow: Infinity, throws: /contextWindow/ }, + { name: "maxTokens=0.5 有效小数", id: "x", provider: "p", baseUrl: "u", apiKeyEnv: "K", maxTokens: 0.5, contextWindow: 100 }, + { name: "contextWindow=1 边界有效", id: "x", provider: "p", baseUrl: "u", apiKeyEnv: "K", maxTokens: 8, contextWindow: 1 }, + { name: "多字段同时无效:取首个错误(短路顺序 id→provider→baseUrl→apiKeyEnv→maxTokens→contextWindow)", id: "", provider: "", baseUrl: "", apiKeyEnv: "", maxTokens: -1, contextWindow: -1, throws: /id/ }, + ]; + + for (const c of cases) { + it(`决策行·${c.name}`, () => { + const reg = new ProviderRegistry(); + const desc: ProviderDescriptor = { + id: c.id, provider: c.provider, baseUrl: c.baseUrl, apiKeyEnv: c.apiKeyEnv, + maxTokens: c.maxTokens, contextWindow: c.contextWindow, reasoning: true, + }; + if (c.throws) { + // 直接调用 assertDescriptorValid + 经 register 两条路径都应抛同一规则 + expect(() => assertDescriptorValid(desc)).toThrow(c.throws); + expect(() => reg.register(desc)).toThrow(c.throws); + } else { + expect(() => assertDescriptorValid(desc)).not.toThrow(); + reg.register(desc); + expect(reg.resolve(c.id)).toBeDefined(); + } + }); + } +}); + +// ============================================================================ +// 3b. 决策表 — buildProviderConfig thinkingFormat 分支 + 字段映射 +// ============================================================================ + +describe("决策表 — buildProviderConfig thinkingFormat 分支 + 字段映射全字段", () => { + it("qwen 分支: compat 注入 + supportsReasoningEffort=false + 全 null map", () => { + const model = modelOf(glm({ thinkingFormat: "qwen" })); + expect(model.compat).toEqual({ thinkingFormat: "qwen", supportsReasoningEffort: false }); + expect(model.thinkingLevelMap).toEqual({ off: null, low: null, medium: null, high: null }); + }); + + it("none 分支: compat=undefined + 直通 map + supportsReasoningEffort 丢失(文档化 quirk)", () => { + // none 分支 applyThinkingFormatGate 计算 supportsReasoningEffort=desc.reasoning, + // 但 buildProviderConfig 只在 compat 存在时写入;compat=undefined → 该值被丢弃。 + const model = modelOf(glm({ thinkingFormat: "none", reasoning: true })); + expect(model.compat).toBeUndefined(); + expect(model.thinkingLevelMap).toEqual({ off: null, low: "low", medium: "medium", high: "high" }); + expect((model.compat as Record | undefined)?.supportsReasoningEffort).toBeUndefined(); + }); + + it("config 全字段映射: name/baseUrl/apiKey/api/authHeader/models", () => { + const { config } = buildProviderConfig(glm()); + expect(config.name).toBe("glm-5.2"); + expect(config.baseUrl).toBe("https://ai-api.d-robotics.cc/v1"); + expect(config.apiKey).toBe("${DROBOTICS_LLM_KEY}"); + expect(config.api).toBe("openai"); + expect(config.authHeader).toBe(true); + expect(config.models).toHaveLength(1); + }); + + it("model 全字段映射: id/name/reasoning/input/cost/contextWindow/maxTokens", () => { + const model = modelOf(glm()); + expect(model.id).toBe("glm-5.2"); + expect(model.name).toBe("glm-5.2"); + expect(model.reasoning).toBe(true); + expect(model.input).toEqual(["text"]); + expect(model.cost).toEqual({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }); + expect(model.contextWindow).toBe(1_000_000); + expect(model.maxTokens).toBe(8192); + }); + + it("qwen 分支短路: 不回退到 none 直通 map(互斥)", () => { + const model = modelOf(glm({ thinkingFormat: "qwen" })); + expect(model.thinkingLevelMap?.low).not.toBe("low"); + expect(model.thinkingLevelMap?.low).toBeNull(); + }); +}); + +// ============================================================================ +// 3c. 决策表 — buildProviderConfigValidated(fail-closed 入口) +// 规则:先 assertDescriptorValid,再 buildProviderConfig。 +// 无效 → 抛(绝不产出半成品);有效 → 与 buildProviderConfig 输出结构等价 +// ============================================================================ + +describe("决策表 — buildProviderConfigValidated fail-closed 入口", () => { + it("有效 desc: 不抛,返回 { name, config } 形状", () => { + const result = buildProviderConfigValidated(glm()); + expect(result).toHaveProperty("name"); + expect(result).toHaveProperty("config"); + expect(result.name).toBe("drobotics-glm"); + expect(result.config.models).toHaveLength(1); + }); + + it("有效 desc: 与 buildProviderConfig 同 desc 输出结构等价(fail-closed 不改变构建逻辑)", () => { + const desc = glm(); + const a = buildProviderConfigValidated(desc); + const b = buildProviderConfig(desc); + expect(a.name).toBe(b.name); + expect(a.config).toEqual(b.config); + }); + + it("有效 desc: 最小描述符(无可选字段)也接受", () => { + const result = buildProviderConfigValidated(minimal()); + expect(result.name).toBe("p"); + expect(result.config.apiKey).toBe("${K}"); + expect(result.config.models![0].input).toEqual(["text"]); // input 缺省补默认 + expect(result.config.models![0].cost).toEqual({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }); + }); + + it("无效 desc {}: 抛,绝不产出半成品 config(fail-closed 核心不变式)", () => { + // buildProviderConfig 对 {} 产出 apiKey="${undefined}" 半成品;validated 必须先拒绝 + expect(() => buildProviderConfigValidated({} as ProviderDescriptor)).toThrow(); + }); + + it("无效 maxTokens=0: 抛 maxTokens(校验先于构建)", () => { + expect(() => buildProviderConfigValidated(glm({ maxTokens: 0 }))).toThrow(/maxTokens/); + }); + + it("无效 id 空串: 抛 id", () => { + expect(() => buildProviderConfigValidated(glm({ id: "" }))).toThrow(/id/); + }); + + it("无效 apiKeyEnv 空串: 抛 apiKeyEnv(密钥铁律前置)", () => { + expect(() => buildProviderConfigValidated(glm({ apiKeyEnv: "" }))).toThrow(/apiKeyEnv/); + }); + + it("无效 contextWindow 负: 抛 contextWindow", () => { + expect(() => buildProviderConfigValidated(glm({ contextWindow: -1 }))).toThrow(/contextWindow/); + }); + + it("fail-closed 顺序:id 空串 + maxTokens=0 同处 → 抛 id(首个错误短路)", () => { + const bad = glm({ id: "", maxTokens: 0 }); + expect(() => buildProviderConfigValidated(bad)).toThrow(/id/); + }); + + it("返回 config 不含 sk- 明文密钥(密钥铁律穿透 validated 路径)", () => { + const { config } = buildProviderConfigValidated(glm()); + expect(config.apiKey).toBe("${DROBOTICS_LLM_KEY}"); + expect(config.apiKey).not.toMatch(/sk-/i); + }); +}); + +// ============================================================================ +// 4. 状态转换 — ProviderRegistry 状态/迁移/不可达状态/重入 +// 状态机(per-id): UNREG --register--> REG(gen=1) --register--> REG(gen=2) +// REG --dispose(current)--> UNREG +// REG(gen=2) --dispose(gen=1)--> REG(不变, stale no-op) +// 不可达状态: stale disposer 删掉当前条目 +// ============================================================================ + +describe("状态转换 — ProviderRegistry 状态/迁移/不可达/重入", () => { + it("迁移 UNREG→REG: register 后 list/resolve 命中", () => { + const reg = new ProviderRegistry(); + expect(reg.list()).toHaveLength(0); + reg.register(glm()); + expect(reg.list()).toHaveLength(1); + expect(reg.resolve("glm-5.2")).toBeDefined(); + }); + + it("迁移 REG→UNREG: disposer 移除当前代际条目", () => { + const reg = new ProviderRegistry(); + const dispose = reg.register(glm()); + dispose(); + expect(reg.list()).toHaveLength(0); + expect(() => reg.resolve("glm-5.2")).toThrow(/fail-closed/); + }); + + it("迁移 REG→REG(gen+1): 同 id 再注册视为更新(代际+1,旧 disposer 失效)", () => { + const reg = new ProviderRegistry(); + const d1 = reg.register(glm()); + const d2 = reg.register(glm({ provider: "v2" })); + expect(reg.list()).toHaveLength(1); + expect(reg.resolve("glm-5.2").provider).toBe("v2"); + // 旧 disposer 失效(no-op) + d1(); + expect(reg.list()).toHaveLength(1); + expect(reg.resolve("glm-5.2").provider).toBe("v2"); + // 新 disposer 仍可移除当前代际 + d2(); + expect(reg.list()).toHaveLength(0); + }); + + it("不可达状态: 旧 disposer 删掉当前条目(代际保护不变式)", () => { + const reg = new ProviderRegistry(); + const d1 = reg.register(glm()); + reg.register(glm({ provider: "v2" })); + // 旧 disposer 调用后当前条目必须仍在(不可达状态 = 条目被误删) + d1(); + expect(reg.list()).toHaveLength(1); + expect(reg.resolve("glm-5.2").provider).toBe("v2"); + }); + + it("重入: dispose 后再 dispose 同代际 → 第二次 no-op(幂等)", () => { + const reg = new ProviderRegistry(); + const dispose = reg.register(glm()); + dispose(); + // 第二次调用:代际已删,get 返回 undefined !== generation → no-op,不抛 + expect(() => dispose()).not.toThrow(); + expect(reg.list()).toHaveLength(0); + }); + + it("重入: 多 id 独立代际,互不干扰", () => { + const reg = new ProviderRegistry(); + const da = reg.register(glm({ id: "a" })); + const db = reg.register(glm({ id: "b" })); + reg.register(glm({ id: "a", provider: "a2" })); // a 升代 + da(); // a 旧 disposer no-op + expect(reg.list().map((d) => d.id).sort()).toEqual(["a", "b"]); + expect(reg.resolve("a").provider).toBe("a2"); + db(); // b 当前代际,移除 + expect(reg.list().map((d) => d.id)).toEqual(["a"]); + }); + + it("resolve 未知 id 不改状态(拒绝不副作用)", () => { + const reg = new ProviderRegistry(); + reg.register(glm()); + expect(() => reg.resolve("nope")).toThrow(); + expect(reg.list()).toHaveLength(1); + reg.register(glm({ id: "x" })); + expect(reg.list()).toHaveLength(2); + }); + + it("list 返回只读快照: 外部 mutate 不影响内部表", () => { + const reg = new ProviderRegistry(); + reg.register(glm()); + const snap = reg.list(); + (snap as ProviderDescriptor[]).push(glm({ id: "injected" })); + expect(reg.list()).toHaveLength(1); + expect(reg.list().map((d) => d.id)).toEqual(["glm-5.2"]); + }); + + it("list 按注册序(Map 插入序)", () => { + const reg = new ProviderRegistry(); + reg.register(glm({ id: "c" })); + reg.register(glm({ id: "a" })); + reg.register(glm({ id: "b" })); + expect(reg.list().map((d) => d.id)).toEqual(["c", "a", "b"]); + }); + + it("register 存储深冻结副本: resolve 返回的对象篡改抛 TypeError(不可变存储不变式)", () => { + const reg = new ProviderRegistry(); + reg.register(glm()); + const resolved = reg.resolve("glm-5.2"); + expect(() => { + // @ts-expect-error intentional mutation: assign to readonly provider + (resolved as ProviderDescriptor).provider = "tampered"; + }).toThrow(TypeError); + expect(() => { + // @ts-expect-error intentional mutation: assign to readonly cost.input + (resolved as ProviderDescriptor).cost!.input = 999; + }).toThrow(TypeError); + expect(() => { + // @ts-expect-error intentional mutation: push to readonly input array + (resolved as ProviderDescriptor).input!.push("image" as const); + }).toThrow(TypeError); + }); + + it("register 不持有调用方原对象引用: 注册后改写原对象不影响 resolve(隔离不变式)", () => { + const reg = new ProviderRegistry(); + const orig = glm(); + reg.register(orig); + // @ts-expect-error intentional mutation: assign to readonly provider + orig.provider = "mutated-after-register"; + // @ts-expect-error intentional mutation: assign to readonly maxTokens + orig.maxTokens = 1; + expect(reg.resolve("glm-5.2").provider).toBe("drobotics-glm"); + expect(reg.resolve("glm-5.2").maxTokens).toBe(8192); + }); +}); + +// ============================================================================ +// 5. 变异测试 — 6 个 seeded bug,每个被某条测试杀死 +// 策略:为每个 bug 内联一份带 bug 的逻辑副本/包装器。每条杀手测试同时断言: +// (a) 真实代码产出正确值(killer —— 若真实被 mutant 替换则此断言 FAIL = bug 被杀) +// (b) mutant 产出与真实不同的错误值(证明 killer 能区分 real vs mutant) +// 最后一条测试确认真实(未植入 bug)代码全过。 +// §9 文档说明 gate 2:逐 bug 临时编辑源码植入 → vitest 见红 → 还原(已离线验证)。 +// ============================================================================ + +describe("变异测试 — seeded bugs(每个被某条测试杀死)", () => { + // ---- M1: assertDescriptorValid 中 maxTokens 用 `< 0` 替代 `<= 0`(off-by-one)---- + // 杀手:maxTokens=0 必须被 reject。真实 `<=0` 抛错;mutant `<0` 放行 0。 + function assertValid_M1_ltZero(desc: ProviderDescriptor): void { + // SEED BUG M1: `< 0` 而非 `<= 0`,放行 maxTokens=0 + const required: ReadonlyArray = [ + [desc.id, "id"], [desc.provider, "provider"], [desc.baseUrl, "baseUrl"], [desc.apiKeyEnv, "apiKeyEnv"], + ]; + for (const [v, l] of required) { + if (typeof v !== "string" || (v as string).trim() === "") throw new Error(`invalid ${l}`); + } + if (!Number.isFinite(desc.maxTokens) || desc.maxTokens < 0) throw new Error("maxTokens"); + if (!Number.isFinite(desc.contextWindow) || desc.contextWindow <= 0) throw new Error("contextWindow"); + } + it("M1 杀手: maxTokens=0 必须被 reject(真实抛错);mutant(<0) 放行 0 → bug 被杀", () => { + const bad = glm({ maxTokens: 0 }); + // (a) 真实代码:抛错(正确)—— 植入 M1 后此行 FAIL + expect(() => assertDescriptorValid(bad)).toThrow(/maxTokens/); + // (b) mutant:不抛(错误,bug 存在) + expect(() => assertValid_M1_ltZero(bad)).not.toThrow(); + }); + + // ---- M2: buildProviderConfig 漏掉 input 默认 `?? ["text"]`(错默认值)---- + // 杀手:desc.input 缺省 → model.input=['text']。真实补默认;mutant 产空数组。 + function buildConfig_M2_noInputDefault(desc: ProviderDescriptor): { config: { models: { input: ("text" | "image")[] }[] } } { + // SEED BUG M2: `[...(desc.input ?? [])]` 漏掉 ["text"] 默认 + const model = { input: [...(desc.input ?? [])] as ("text" | "image")[] }; + return { config: { models: [model] } }; + } + it("M2 杀手: desc.input 缺省 → 真实 model.input=['text'];mutant 漏默认 → [] 被杀", () => { + const desc = glm(); + // @ts-expect-error intentional mutation: delete readonly property + delete (desc as Partial).input; + // (a) 真实代码:补默认 ["text"](正确)—— 植入 M2 后此行 FAIL + expect(buildProviderConfig(desc).config.models![0].input).toEqual(["text"]); + // (b) mutant:空数组(错误,bug 存在) + expect(buildConfig_M2_noInputDefault(desc).config.models[0].input).toEqual([]); + }); + + // ---- M3: applyThinkingFormatGate 分支反转(`=== "qwen"` 改 `!== "qwen"`,短路逻辑反)---- + // 杀手:thinkingFormat:qwen → compat.thinkingFormat='qwen'。真实注入;mutant 反转走 none。 + function thinkingCompat_M3_inverted(desc: ProviderDescriptor): { thinkingFormat?: string } { + // SEED BUG M3: `!== "qwen"` 而非 `=== "qwen"`,分支反转 + if (desc.thinkingFormat !== "qwen") { + return { thinkingFormat: "qwen" }; + } + return {}; + } + it("M3 杀手: thinkingFormat:qwen → 真实注入 compat.thinkingFormat='qwen';mutant 反转 → 走 none 被杀", () => { + // (a) 真实代码:qwen 注入 compat(正确)—— 植入 M3 后此行 FAIL + expect(buildProviderConfig(glm()).config.models![0].compat?.thinkingFormat).toBe("qwen"); + // (b) mutant:qwen 被反转走 none,无 thinkingFormat(错误,bug 存在) + expect(thinkingCompat_M3_inverted(glm()).thinkingFormat).toBeUndefined(); + }); + + // ---- M4: ProviderRegistry disposer 删除 generations[id](漏 seq/代际单调校验)---- + // 杀手:dispose→re-register 同 id 后,旧 disposer 调用必须 no-op(新条目存活)。 + // 真实保留 generations[id](单调)→ 旧 disposer 代际号过期 no-op;mutant 删 generations → + // re-register 代际重算为 1,与旧 disposer 捕获的代际号 1 碰撞 → 旧 disposer 复活误删。 + class Registry_M4_deleteGen { + private descriptors = new Map(); + private generations = new Map(); + register(desc: ProviderDescriptor): () => void { + const id = desc.id; + const gen = (this.generations.get(id) ?? 0) + 1; + this.generations.set(id, gen); + this.descriptors.set(id, desc); + return () => { + // SEED BUG M4: 多了 generations.delete(id),破坏单调性 + if (this.generations.get(id) === gen) { + this.descriptors.delete(id); + this.generations.delete(id); // bug:删代际计数器 + } + }; + } + resolve(id: string): ProviderDescriptor { + const d = this.descriptors.get(id); + if (!d) throw new Error("fail-closed"); + return d; + } + list(): readonly ProviderDescriptor[] { + return [...this.descriptors.values()]; + } + } + it("M4 杀手: dispose→re-register 后旧 disposer no-op(真实保留条目);mutant 删代际 → 误删被杀", () => { + // (a) 真实代码:dispose→re-register→旧 disposer no-op,新条目存活(正确) + const reg = new ProviderRegistry(); + const d1 = reg.register(glm()); // gen=1 + d1(); // dispose(删 desc,generations[glm] 仍=1) + const d2 = reg.register(glm({ provider: "v2" })); // re-register gen=(1??0)+1=2 + d1(); // 旧 disposer gen=1 ≠ 当前 gen=2 → no-op + expect(reg.list()).toHaveLength(1); + expect(reg.resolve("glm-5.2").provider).toBe("v2"); + // (b) mutant:generations 被删 → re-register gen=(undefined??0)+1=1 = 旧 disposer 捕获的 1 + // → 旧 disposer 复活误删新条目 + const regM = new Registry_M4_deleteGen(); + const d1M = regM.register(glm()); // gen=1 + d1M(); // dispose(删 desc + generations[glm]) + regM.register(glm({ provider: "v2" })); // re-register gen=(undefined??0)+1=1 + d1M(); // 旧 disposer gen=1 === 当前 gen=1 → 误删! + expect(regM.list()).toHaveLength(0); + expect(() => regM.resolve("glm-5.2")).toThrow(); + }); + + // ---- M5: buildProviderConfigValidated 跳过 assertDescriptorValid(漏校验,直接构建)---- + // 杀手:无效 desc {} 必须抛。真实先校验抛错;mutant 跳过校验产出半成品。 + function buildValidated_M5_skipAssert(desc: ProviderDescriptor): { name: string; config: { apiKey: string } } { + // SEED BUG M5: 跳过 assertDescriptorValid,直接 buildProviderConfig + return buildProviderConfig(desc) as { name: string; config: { apiKey: string } }; + } + it("M5 杀手: 无效 desc {} 必须抛(真实先校验);mutant 跳过校验产出 ${undefined} 半成品 → 被杀", () => { + const bad = {} as ProviderDescriptor; + // (a) 真实代码:fail-closed 先校验抛错(正确)—— 植入 M5 后此行 FAIL + expect(() => buildProviderConfigValidated(bad)).toThrow(); + // (b) mutant:跳过校验产出半成品 config(错误,bug 存在) + const out = buildValidated_M5_skipAssert(bad); + expect(out.config.apiKey).toBe("${undefined}"); + }); + + // ---- M6: resolve 未知 id 不抛而返回 undefined(fail-open,违反 fail-closed 契约)---- + // 杀手:resolve 未注册 id 必须抛。真实抛;mutant 返回 undefined。 + class Registry_M6_failOpen { + private descriptors = new Map(); + register(desc: ProviderDescriptor): () => void { + this.descriptors.set(desc.id, desc); + return () => this.descriptors.delete(desc.id); + } + resolve(id: string): ProviderDescriptor | undefined { + // SEED BUG M6: fail-open,未注册返回 undefined 而非抛错 + return this.descriptors.get(id); + } + } + it("M6 杀手: resolve 未知 id 必须抛 fail-closed(真实抛);mutant 返回 undefined → 被杀", () => { + // (a) 真实代码:未知 id 抛错(正确)—— 植入 M6 后此行 FAIL + const reg = new ProviderRegistry(); + expect(() => reg.resolve("ghost")).toThrow(/fail-closed/); + // (b) mutant:返回 undefined(错误,bug 存在) + const regM = new Registry_M6_failOpen(); + expect(regM.resolve("ghost")).toBeUndefined(); + }); + + it("变异测试确认: 真实(未植入 bug)代码全过(同断言对真实再次断言)", () => { + // 真实 maxTokens=0 reject + expect(() => assertDescriptorValid(glm({ maxTokens: 0 }))).toThrow(/maxTokens/); + // 真实 input 缺省补默认 + const d = glm(); + // @ts-expect-error intentional mutation: delete readonly property + delete (d as Partial).input; + expect(buildProviderConfig(d).config.models![0].input).toEqual(["text"]); + // 真实 qwen 注入 compat + expect(buildProviderConfig(glm()).config.models![0].compat?.thinkingFormat).toBe("qwen"); + // 真实 dispose→re-register 旧 disposer no-op + const reg = new ProviderRegistry(); + const d1 = reg.register(glm()); + d1(); + reg.register(glm({ provider: "v2" })); + d1(); + expect(reg.list()).toHaveLength(1); + expect(reg.resolve("glm-5.2").provider).toBe("v2"); + // 真实 validated fail-closed + expect(() => buildProviderConfigValidated({} as ProviderDescriptor)).toThrow(); + // 真实 resolve fail-closed + expect(() => new ProviderRegistry().resolve("ghost")).toThrow(/fail-closed/); + }); +}); + +// ============================================================================ +// 6. 对抗/fuzz — 畸形/滥用输入(null/undefined/巨大/NaN/循环引用/并发重入/负 seq) +// ============================================================================ + +describe("对抗/fuzz — 畸形/滥用输入", () => { + it("buildProviderConfig(null): 抛 TypeError(不静默产半成品)", () => { + expect(() => buildProviderConfig(null as unknown as ProviderDescriptor)).toThrow(TypeError); + }); + + it("buildProviderConfig(undefined): 抛 TypeError", () => { + expect(() => buildProviderConfig(undefined as unknown as ProviderDescriptor)).toThrow(TypeError); + }); + + it("buildProviderConfig(空对象 {}): 不抛(信任输入,无 fail-closed 校验)→ 产出 ${undefined} 占位(quirk 文档化)", () => { + // buildProviderConfig 不调用 assertDescriptorValid,fail-closed 只在 register/validated。 + // {} → apiKey="${undefined}"、name=undefined。低层信任 quirk,外部路径应走 validated。 + const { config } = buildProviderConfig({} as ProviderDescriptor); + expect(config.apiKey).toBe("${undefined}"); + expect(config.name).toBeUndefined(); + expect(config.models).toBeDefined(); + }); + + it("buildProviderConfigValidated(null): 抛(fail-closed 守卫,绝不产半成品)", () => { + expect(() => buildProviderConfigValidated(null as unknown as ProviderDescriptor)).toThrow(); + }); + + it("buildProviderConfigValidated(undefined): 抛", () => { + expect(() => buildProviderConfigValidated(undefined as unknown as ProviderDescriptor)).toThrow(); + }); + + it("assertDescriptorValid(null): 抛(访问 null.id)", () => { + expect(() => assertDescriptorValid(null as unknown as ProviderDescriptor)).toThrow(); + }); + + it("assertDescriptorValid(undefined): 抛", () => { + expect(() => assertDescriptorValid(undefined as unknown as ProviderDescriptor)).toThrow(); + }); + + it("register(null): 抛(assertDescriptorValid 访问 null.id)", () => { + const reg = new ProviderRegistry(); + expect(() => reg.register(null as unknown as ProviderDescriptor)).toThrow(); + }); + + it("register(undefined): 抛", () => { + const reg = new ProviderRegistry(); + expect(() => reg.register(undefined as unknown as ProviderDescriptor)).toThrow(); + }); + + it("resolve(null/undefined id): fail-closed 抛", () => { + const reg = new ProviderRegistry(); + expect(() => reg.resolve(null as unknown as string)).toThrow(); + expect(() => reg.resolve(undefined as unknown as string)).toThrow(); + }); + + it("resolve(空串 id): fail-closed 抛", () => { + const reg = new ProviderRegistry(); + expect(() => reg.resolve("")).toThrow(/fail-closed/); + }); + + it("巨大 maxTokens=Number.MAX_VALUE: 接受(有限正数)", () => { + const reg = new ProviderRegistry(); + reg.register(glm({ id: "huge", maxTokens: Number.MAX_VALUE })); + expect(reg.resolve("huge").maxTokens).toBe(Number.MAX_VALUE); + }); + + it("负 contextWindow: reject", () => { + const reg = new ProviderRegistry(); + expect(() => reg.register(glm({ contextWindow: -100 }))).toThrow(/contextWindow/); + }); + + it("循环引用 cost: buildProviderConfig 仍产出(Object.freeze 不深递归,不爆栈)", () => { + const cost: { input: number; output: number; cacheRead: number; cacheWrite: number; self?: unknown } = { + input: 1, output: 2, cacheRead: 0, cacheWrite: 0, + }; + cost.self = cost; // 循环引用 + const desc = glm({ id: "cyc", cost }); + // buildProviderConfig 不深拷贝/不递归 freeze,直接引用 → 不爆栈 + const model = modelOf(desc); + expect(model.cost).toBe(cost); + }); + + it("循环引用 cost: register 不爆栈(deepFreezeDescriptor 只 Object.freeze 不深递归)", () => { + const cost: { input: number; output: number; cacheRead: number; cacheWrite: number; self?: unknown } = { + input: 1, output: 2, cacheRead: 0, cacheWrite: 0, + }; + cost.self = cost; // 循环引用 + const reg = new ProviderRegistry(); + expect(() => reg.register(glm({ id: "cyc2", cost }))).not.toThrow(); + // cloneDescriptor 用 {...desc.cost} 浅拷贝所有可枚举属性(含 self),故 resolved.cost 仍带 self。 + // 只断言已知字段(不整体 toEqual,避免循环引用比较爆栈)。 + const stored = reg.resolve("cyc2").cost!; + expect(stored.input).toBe(1); + expect(stored.output).toBe(2); + expect(stored.cacheRead).toBe(0); + expect(stored.cacheWrite).toBe(0); + }); + + it("超大 input 数组 (1000 项): 透传不截断", () => { + const big = Array.from({ length: 1000 }, () => "text" as const); + const desc = glm({ id: "big", input: big }); + const model = modelOf(desc); + expect(model.input).toHaveLength(1000); + expect(model.input).not.toBe(big); // spread 产生新数组 → 副本非同引用 + expect(model.input).toEqual(big); // 内容等价 + }); + + it("并发重入序列: 交错 register/dispose 不破坏代际不变式", () => { + const reg = new ProviderRegistry(); + const ops: Array<() => void> = []; + // 交错注册 5 个 id,每个注册 2 次(升代) + for (let i = 0; i < 5; i++) { + const id = `m${i}`; + const d1 = reg.register(glm({ id })); + ops.push(d1); + const d2 = reg.register(glm({ id, provider: `p${i}-2` })); + ops.push(d2); + } + expect(reg.list()).toHaveLength(5); + // 全部 dispose(含旧代际 no-op + 当前代际真删,乱序) + for (const op of ops.reverse()) op(); + expect(reg.list()).toHaveLength(0); + }); + + it("disposer 在 register 同 id 后立即调用: 旧 disposer no-op 不误删", () => { + const reg = new ProviderRegistry(); + const d1 = reg.register(glm({ id: "r" })); + const d2 = reg.register(glm({ id: "r", provider: "second" })); + d1(); // no-op + d2(); // 真删 + expect(reg.list()).toHaveLength(0); + }); + + it("代际回退(负 seq 模拟): 多次覆盖后用最早 disposer 全程 no-op", () => { + // 模拟"负 seq"滥用:连续升代 N 次,全部用第 1 代 disposer,条目必须保留 + const reg = new ProviderRegistry(); + const d1 = reg.register(glm()); + for (let i = 2; i <= 10; i++) reg.register(glm({ provider: `v${i}` })); + // 10 代后,第 1 代 disposer 调 10 次,全部 no-op + for (let i = 0; i < 10; i++) d1(); + expect(reg.list()).toHaveLength(1); + expect(reg.resolve("glm-5.2").provider).toBe("v10"); + }); + + it("register 抛错后 registry 保持干净(fail-closed 无副作用)", () => { + const reg = new ProviderRegistry(); + reg.register(glm({ id: "ok" })); + // 抛错的注册不应留下半成品条目 + expect(() => reg.register(glm({ id: "bad", maxTokens: 0 }))).toThrow(/maxTokens/); + expect(reg.list()).toHaveLength(1); + expect(reg.list().map((d) => d.id)).toEqual(["ok"]); + expect(() => reg.resolve("bad")).toThrow(/fail-closed/); + }); +}); + +// ============================================================================ +// 7. 元蜕变/不变式 — 跨变换保持的性质 +// ============================================================================ + +describe("元蜕变/不变式 — 跨变换保持的性质", () => { + it("不变式·list 长度永不超过已注册不同 id 数(去重)", () => { + const reg = new ProviderRegistry(); + reg.register(glm({ id: "a" })); + reg.register(glm({ id: "a", provider: "v2" })); // 同 id 升代 + reg.register(glm({ id: "a", provider: "v3" })); // 同 id 再升代 + reg.register(glm({ id: "b" })); + expect(reg.list()).toHaveLength(2); // 永远 ≤ 不同 id 数 + }); + + it("元蜕变·register 两次同 desc ≡ replay 单次(输出等价)", () => { + // 变换 A: register(d) 然后 register(d) + const regA = new ProviderRegistry(); + regA.register(glm()); + regA.register(glm()); + // 变换 B: register(d) 一次 + const regB = new ProviderRegistry(); + regB.register(glm()); + // 等价:list 长度与 resolve 结果一致 + expect(regA.list()).toHaveLength(regB.list().length); + expect(regA.resolve("glm-5.2")).toEqual(regB.resolve("glm-5.2")); + }); + + it("元蜕变·buildProviderConfig 幂等: 同 desc 多次调用产出结构等价", () => { + const desc = glm(); + const a = buildProviderConfig(desc); + const b = buildProviderConfig(desc); + expect(a.name).toBe(b.name); + expect(a.config).toEqual(b.config); + // 但每次新对象(非同引用) + expect(a.config).not.toBe(b.config); + expect(a.config.models![0]).not.toBe(b.config.models![0]); + }); + + it("元蜕变·buildProviderConfigValidated(valid) ≡ buildProviderConfig(valid)(同输入等价输出)", () => { + // 对【有效】desc,两条路径输出必须结构等价(validated 只加校验不改构建) + const desc = glm(); + const viaValidated = buildProviderConfigValidated(desc); + const viaDirect = buildProviderConfig(desc); + expect(viaValidated).toEqual(viaDirect); + }); + + it("不变式·单调 deny: resolve 任何未注册 id 恒抛(跨操作单调)", () => { + const reg = new ProviderRegistry(); + // 注册前后,未注册 id 始终抛 + expect(() => reg.resolve("ghost")).toThrow(); + reg.register(glm()); + expect(() => reg.resolve("ghost")).toThrow(); + reg.register(glm({ id: "x" })); + expect(() => reg.resolve("ghost")).toThrow(); + }); + + it("不变式·fail-closed unusable=拒: 未配置模型绝不静默回退", () => { + const reg = new ProviderRegistry(); + reg.register(glm()); + // resolve 未配置的 deepseek 应抛,而非回退到 glm + expect(() => reg.resolve("deepseek-chat")).toThrow(/fail-closed/); + }); + + it("不变式·密钥占位: 所有 buildProviderConfig 输出 apiKey 均为 ${VAR} 形态,无 sk- 明文", () => { + const envs = ["DROBOTICS_LLM_KEY", "DEEPSEEK_API_KEY", "MY_CUSTOM_KEY", "A"]; + for (const env of envs) { + const { config } = buildProviderConfig(glm({ apiKeyEnv: env })); + expect(config.apiKey).toBe(`\${${env}}`); + expect(config.apiKey).not.toMatch(/sk-/i); + expect(config.apiKey).toMatch(/^\$\{[A-Z_]+\}$/); + } + }); + + it("不变式·短路: thinkingFormat:qwen 不调用 none 路径(互斥输出)", () => { + const model = modelOf(glm({ thinkingFormat: "qwen" })); + // qwen 路径输出互斥特征:compat 非空 + low=null + expect(model.compat).toBeDefined(); + expect(model.thinkingLevelMap?.low).toBeNull(); + expect(model.thinkingLevelMap?.low).not.toBe("low"); + }); + + it("不变式·freeze→篡改抛 TypeError: resolved 对象与 KNOWN_PROVIDERS 均不可变", () => { + const reg = new ProviderRegistry(); + reg.register(glm()); + const resolved = reg.resolve("glm-5.2"); + expect(() => { // @ts-expect-error intentional mutation: assign to readonly id + (resolved as ProviderDescriptor).id = "x"; }).toThrow(TypeError); + expect(() => { // @ts-expect-error intentional mutation: assign to readonly cost.input + (resolved as ProviderDescriptor).cost!.input = 1; }).toThrow(TypeError); + for (const desc of KNOWN_PROVIDERS) { + expect(() => { // @ts-expect-error intentional mutation: assign to readonly id + (desc as ProviderDescriptor).id = "x"; }).toThrow(TypeError); + } + }); +}); + +// ============================================================================ +// 8. 深冻结不变式 — DEFAULT_GLM_DESCRIPTOR / KNOWN_PROVIDERS +// ============================================================================ + +describe("深冻结不变式 — DEFAULT_GLM_DESCRIPTOR / KNOWN_PROVIDERS", () => { + it("DEFAULT_GLM_DESCRIPTOR 顶层冻结: 篡改 id 抛 TypeError", () => { + expect(() => { + // @ts-expect-error intentional mutation: assign to readonly id + (DEFAULT_GLM_DESCRIPTOR as ProviderDescriptor).id = "tampered"; + }).toThrow(TypeError); + }); + + it("DEFAULT_GLM_DESCRIPTOR.cost 冻结: 篡改 input 抛 TypeError", () => { + expect(() => { + // @ts-expect-error intentional mutation: assign to readonly cost.input + (DEFAULT_GLM_DESCRIPTOR as ProviderDescriptor).cost!.input = 999; + }).toThrow(TypeError); + }); + + it("DEFAULT_GLM_DESCRIPTOR.input 冻结: push 抛 TypeError", () => { + expect(() => { + // @ts-expect-error intentional mutation: push to readonly input array + (DEFAULT_GLM_DESCRIPTOR as ProviderDescriptor).input!.push("image" as const); + }).toThrow(TypeError); + }); + + it("DEFAULT_GLM_DESCRIPTOR 契约: thinkingFormat=qwen + maxTokens=8192 + 治命门一", () => { + expect(DEFAULT_GLM_DESCRIPTOR.id).toBe("glm-5.2"); + expect(DEFAULT_GLM_DESCRIPTOR.provider).toBe("drobotics-glm"); + expect(DEFAULT_GLM_DESCRIPTOR.thinkingFormat).toBe("qwen"); + expect(DEFAULT_GLM_DESCRIPTOR.maxTokens).toBe(8192); + expect(DEFAULT_GLM_DESCRIPTOR.apiKeyEnv).toBe("DROBOTICS_LLM_KEY"); + expect(DEFAULT_GLM_DESCRIPTOR.contextWindow).toBe(1_000_000); + expect(DEFAULT_GLM_DESCRIPTOR.reasoning).toBe(true); + }); + + it("KNOWN_PROVIDERS 数组冻结: push 抛 TypeError", () => { + expect(() => { + (KNOWN_PROVIDERS as ProviderDescriptor[]).push(glm()); + }).toThrow(TypeError); + }); + + it("KNOWN_PROVIDERS 元素均冻结: 篡改抛 TypeError", () => { + for (const desc of KNOWN_PROVIDERS) { + expect(() => { + // @ts-expect-error intentional mutation: assign to readonly id + (desc as ProviderDescriptor).id = "x"; + }).toThrow(TypeError); + if (desc.cost) { + expect(() => { + // @ts-expect-error intentional mutation: assign to readonly cost.input + (desc as ProviderDescriptor).cost!.input = 1; + }).toThrow(TypeError); + } + } + }); + + it("KNOWN_PROVIDERS 契约: 恰含 glm-5.2 + deepseek-chat,密钥占位无 sk-", () => { + const ids = KNOWN_PROVIDERS.map((d) => d.id).sort(); + expect(ids).toEqual(["deepseek-chat", "glm-5.2"]); + for (const desc of KNOWN_PROVIDERS) { + const { config } = buildProviderConfig(desc); + expect(config.apiKey).toMatch(/^\$\{[A-Z_]+\}$/); + expect(config.apiKey).not.toMatch(/sk-/i); + } + }); + + it("KNOWN_PROVIDERS.glm === DEFAULT_GLM_DESCRIPTOR(同引用,单一事实源)", () => { + const glmDesc = KNOWN_PROVIDERS.find((d) => d.id === "glm-5.2"); + expect(glmDesc).toBe(DEFAULT_GLM_DESCRIPTOR); + }); + + it("deepseek stub 契约: thinkingFormat=none + reasoning=false + 官方网关", () => { + const ds = KNOWN_PROVIDERS.find((d) => d.id === "deepseek-chat"); + expect(ds).toBeDefined(); + expect(ds!.thinkingFormat).toBe("none"); + expect(ds!.reasoning).toBe(false); + expect(ds!.provider).toBe("deepseek-native"); + expect(ds!.baseUrl).toBe("https://api.deepseek.com/v1"); + expect(ds!.apiKeyEnv).toBe("DEEPSEEK_API_KEY"); + expect(ds!.contextWindow).toBe(128_000); + }); +}); + +// ============================================================================ +// 9. 变异测试 gate 2 文档 —— 逐 bug 植入真实源码验证(已离线完成) +// +// 每个 seeded bug 临时编辑 src/core/provider-registry.ts 植入 → 跑本文件 → +// 确认对应 killer 测试 FAIL(红)→ 还原源码。下表记录每 bug 的植入位置、killer 测试、 +// 预期红测试。本文件最终态:真实源码(无植入)全过(gate 1)。 +// +// | Bug | 植入位置(真实源码) | killer 测试(FAIL=被杀) | +// |-----|----------------------------------------------------------|-----------------------------------------------------------| +// | M1 | assertDescriptorValid: `<= 0` → `< 0` | "M1 杀手: maxTokens=0..." 的 (a) expect().toThrow(/maxTokens/) | +// | M2 | buildProviderConfig: `?? ["text"]` → `?? []` | "M2 杀手: desc.input 缺省..." 的 (a) expect(...).toEqual(["text"]) | +// | M3 | applyThinkingFormatGate: `=== "qwen"` → `!== "qwen"` | "M3 杀手: thinkingFormat:qwen..." 的 (a) expect(...).toBe("qwen") | +// | M4 | ProviderRegistry.register disposer: 加回 generations.delete(id) | "M4 杀手: dispose→re-register..." 的 (a) expect(reg.list()).toHaveLength(1) | +// | M5 | buildProviderConfigValidated: 删 assertDescriptorValid 调用 | "M5 杀手: 无效 desc {}..." 的 (a) expect(() => ...).toThrow() | +// | M6 | ProviderRegistry.resolve: throw → return undefined | "M6 杀手: resolve 未知 id..." 的 (a) expect(() => ...).toThrow(/fail-closed/) | +// ============================================================================ diff --git a/tests/system-integration.test.ts b/tests/system-integration.test.ts new file mode 100644 index 0000000..d10fa86 --- /dev/null +++ b/tests/system-integration.test.ts @@ -0,0 +1,243 @@ +/** + * @module system-integration + * + * 系统级集成测试 —— T06–T17 落地后的跨模块闭环验证。 + * + * 不是单模块单测(那些各模块自己有 1400+ 测试),而是验证模块间组合的【真实接线】: + * ① 事件溯源闭环:PbaSession.append → deriveMessages 投影 → assertModelVisibleLogged + * ② compaction 接 PbaSession:i2cdump 大输出 prune → spill 句柄 → recall + * ③ typed event bus:waterfall 链委托 + ScopeKey 隔离(子 scope 事件不串主) + * ④ 能力接缝:BoardLinkRegistry/FlashRegistry resolve fail-closed + provider 装配 + * ⑤ 闭环 checkpoint:CheckpointRecorder.record → rebuild 从 log 重建 + * ⑥ 上下文注入:inject(不唤醒)vs steer(换板唤醒)语义区分 + * ⑦ 工作流:parallel(并发 barrier)+ pipeline(串行 stage 抛错落 null) + * ⑧ 审批 fail-closed:无人值守 auto-deny + * ⑨ provider registry:buildProviderConfig 产出 glm-5.2 配置(key 占位) + * ⑩ profile 分层:resolveProfile 共享 base + 叠差异 + * + * 密钥铁律:所有 key 断言为 ${DROBOTICS_LLM_KEY} 占位,绝不出现真 key。 + */ + +import { describe, it, expect } from "vitest"; + +import { PbaSession } from "../src/core/pba-session.js"; +import { PbaEventBus } from "../src/core/pba-event-bus.js"; +import { pruneToolResult } from "../src/compaction/tool-result-pruner.js"; +import { SpillStore } from "../src/compaction/spill.js"; +import { BoardLinkRegistry, RDK_X5_SSH_PROVIDER, RDK_S100_SERIAL_PROVIDER, LOCAL_PROVIDER } from "../src/capabilities/board-link/index.js"; +import { FlashRegistry, DD_PROVIDER, FASTBOOT_PROVIDER } from "../src/capabilities/flash/index.js"; +import { CheckpointRecorder } from "../src/core/checkpoint-state.js"; +import { ContextInjector } from "../src/core/context-injector.js"; +import { parallel, pipeline } from "../src/capabilities/workflow/index.js"; +import { ApprovalGate } from "../src/capabilities/approval.js"; +import { ProviderRegistry, buildProviderConfig, DEFAULT_GLM_DESCRIPTOR } from "../src/core/provider-registry.js"; +import { resolveProfile, BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE, EMBEDDED_DEV_PROFILE } from "../src/profiles/index.js"; +import type { BoardSpec } from "../src/shared/types.js"; + +// 工具:最小 appendEntry 收集器(注入 PbaSession,替代 pi 运行时) +function makeCollector() { + const entries: Array<{ type: string; data: unknown }> = []; + return { + appendEntry: (type: string, data: unknown) => entries.push({ type, data }), + entries, + }; +} + +describe("system integration — T06–T17 跨模块闭环", () => { + it("① PbaSession 事件溯源:append → deriveMessages 投影 → logged 不变量", () => { + const col = makeCollector(); + const sess = new PbaSession({ appendEntry: col.appendEntry }); + sess.append({ type: "user-message", data: { content: "读 0x40020000" } }); + sess.append({ type: "assistant-message", data: { content: "ok" } }); + + const msgs = sess.deriveMessages(); + expect(Array.isArray(msgs)).toBe(true); + expect(msgs.length).toBeGreaterThan(0); + // 第二次 derive 命中增量缓存(不抛、结果一致) + expect(sess.deriveMessages()).toEqual(msgs); + // logged 不变量:投影里出现的 type 都在 log 里 append 过 → 不抛 + expect(() => sess.assertModelVisibleLogged(["user-message", "assistant-message"])).not.toThrow(); + // 伪造:声称投影里有但实际没 append 的 type → 抛 + expect(() => sess.assertModelVisibleLogged(["verify-record"])).toThrow(); + }); + + it("② compaction 接 PbaSession:i2cdump 大输出 prune 寄存器地址不丢 + spill recall", () => { + const i2cdump = [ + " 0 1 2 3 4 5 6 7 8 9 a b c d e f", + "00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", + "10: 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10", + "20: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff", + ].join("\n"); + const pruned = pruneToolResult(i2cdump, { tool: "i2cdump", maxLines: 2 }); + // 寄存器地址行(0xXX:)保留 + expect(pruned.pruned).toMatch(/10:|20:/); + expect(pruned.dropped).toBeGreaterThan(0); + + // spill 句柄 → recall 取回 + const store = new SpillStore(); + const loc = store.spill("datasheet-page-42", { reg: "0x40020000", desc: "GPIO_CTRL" }); + expect(store.has(loc)).toBe(true); + const recalled = store.recall(loc); + expect(recalled).toEqual({ reg: "0x40020000", desc: "GPIO_CTRL" }); + }); + + it("③ PbaEventBus:waterfall 链委托 + ScopeKey 隔离(子 scope 事件不串主)", () => { + const bus = new PbaEventBus(); + const order: string[] = []; + + bus.on("boardlink:connect", (_args, next) => { + order.push("global-1"); + next(); + }); + bus.on("boardlink:connect", () => { + order.push("global-2-terminal"); + }); + + bus.waterfall("boardlink:connect", { board: "x5" }); + // 链顺序:global-1 调 next → global-2-terminal + expect(order).toEqual(["global-1", "global-2-terminal"]); + + // scope 隔离:子 scope 注册的监听不响应父 scope 的事件(子不串父) + const subScope = "subagent:child-1"; + const seen: string[] = []; + bus.on("verify:passed", () => seen.push("child"), subScope); + // 父 scope(无 scope / 祖先)发事件 → 子 scope 监听不应被触发(单向冒泡:子→父,非父→子) + bus.emit("verify:passed", { ok: true }); + expect(seen).toEqual([]); + // 子 scope 自己发事件 → 子监听收(+ 冒泡到父,但这里只断言子收到) + bus.emit("verify:passed", { ok: true }, subScope); + expect(seen).toEqual(["child"]); + }); + + it("④ 能力接缝:BoardLinkRegistry + FlashRegistry resolve fail-closed + provider 装配", () => { + const bl = new BoardLinkRegistry(); + bl.register(RDK_X5_SSH_PROVIDER); + bl.register(RDK_S100_SERIAL_PROVIDER); + expect(bl.list().length).toBe(2); + + // register LOCAL → 3(三 provider 各一;按 id 去重不重复) + const dispose = bl.register(LOCAL_PROVIDER); + expect(bl.list().length).toBe(3); + // disposer 后回到 before(2) + dispose(); + expect(bl.list().length).toBe(2); + + const x5: BoardSpec = { id: "x5", name: "RDK X5", link: "ssh", address: "robot@10.0.0.1", fingerprint: "fp" }; + const resolved = bl.resolve(x5); + expect(resolved.id).toBeTruthy(); + expect(resolved.linkType).toBe("ssh"); + + const fl = new FlashRegistry(); + fl.register(DD_PROVIDER); + fl.register(FASTBOOT_PROVIDER); + expect(fl.resolve("dd")).toBeDefined(); + // 未注册 method(dfu 没装)→ fail-closed 抛错 + expect(() => fl.resolve("dfu")).toThrow(); + }); + + it("⑤ CheckpointRecorder:record(look-ahead 推进)→ rebuild 从 log 重建", () => { + const col = makeCollector(); + const rec = new CheckpointRecorder({ append: (e) => col.appendEntry(e.type, e.data) }); + rec.record("edit", true, 1000); + rec.record("compile", true, 2000); + rec.record("flash", true, 3000); + + const cur = rec.current(); + // look-ahead 语义:flash 通过后推进到下一 pending 步 verify(stepPassed=false) + expect(cur.currentStep).toBe("verify"); + expect(cur.stepPassed).toBe(false); + expect(cur.history.length).toBe(3); + + // 从 log 重建等价 + const rebuilt = rec.rebuild(col.entries); + expect(rebuilt.currentStep).toBe("verify"); + expect(rebuilt.history.length).toBe(3); + + // 跑完全程到 done passed → 终态 stepPassed=true(完成态) + rec.record("verify", true, 4000); + rec.record("check", true, 5000); + rec.record("done", true, 6000); + expect(rec.current().currentStep).toBe("done"); + expect(rec.current().stepPassed).toBe(true); + }); + + it("⑥ ContextInjector:inject(不唤醒)vs steer(换板唤醒)语义区分", () => { + const inj = new ContextInjector(); + const a = inj.inject("寄存器表 next-step 不唤醒"); + expect(a.nextStep).toBe(true); + expect(a.nextTurn).toBe(false); + + const s = inj.steer("换板到 S100", "s100-board"); + expect(s.boardId).toBe("s100-board"); + expect(s.nextStep).toBe(true); + + const f = inj.followup("新任务"); + expect(f.nextTurn).toBe(true); + + // 最新 snapshot 取代更早 + const act = inj.deriveActiveContext(); + expect(act).toBeDefined(); + }); + + it("⑦ workflow:parallel(并发 barrier)+ pipeline(串行 stage 抛错落 null)", async () => { + const results: number[] = []; + const out = await parallel([ + async () => { results.push(1); return "a"; }, + async () => { results.push(2); return "b"; }, + async () => { results.push(3); return "c"; }, + ]); + expect(out).toEqual(["a", "b", "c"]); + expect(results.length).toBe(3); + + // pipeline 串行:stage2 抛错 → 该 item 落 null,其它不受影响 + // stage 签名:(prev, item, i);stage1 的 prev 为 undefined → 用 item + const pip = await pipeline( + [1, 2, 3], + async (_prev, item: number) => item * 10, + async (prev) => { const n = prev as number; return n === 20 ? throwErr() : n + 1; }, + ); + expect(pip[0]).toBe(11); // 1*10=10 → 11 + expect(pip[1]).toBeNull(); // 2*10=20 → 抛错落 null + expect(pip[2]).toBe(31); // 3*10=30 → 31 + }); + + it("⑧ ApprovalGate fail-closed:无人值守 auto-deny", async () => { + const gate = new ApprovalGate({ mode: "auto-deny" }); + const r = await gate.request({ action: "flash /dev/mmcblk0", risk: "high" }); + expect(r.decision).toBe("deny"); + // interactive 模式无 approver → fail-closed deny + gate.setMode("interactive"); + const r2 = await gate.request({ action: "rm -rf", risk: "high", timeoutMs: 100 }); + expect(r2.decision).toBe("deny"); + }); + + it("⑨ ProviderRegistry:buildProviderConfig 产出 glm-5.2 配置(key 占位)", () => { + const reg = new ProviderRegistry(); + reg.register(DEFAULT_GLM_DESCRIPTOR); + const desc = reg.resolve("glm-5.2"); + expect(desc).toBeDefined(); + + const { name, config } = buildProviderConfig(desc); + expect(name).toBeTruthy(); + // 密钥铁律:key 必须是 ${DROBOTICS_LLM_KEY} 占位,绝不出现 sk- 明文 + const keyStr = JSON.stringify(config); + expect(keyStr).toContain("${DROBOTICS_LLM_KEY}"); + expect(keyStr).not.toMatch(/sk-nAm/i); + expect(/sk-[A-Za-z0-9]{20,}/.test(keyStr)).toBe(false); + }); + + it("⑩ profile 分层:两 profile 共享 base + 各叠差异", () => { + expect(BASE_PROFILE.extensions.length).toBeGreaterThan(0); + // 维修诊断有 pdf-reader/datasheet-rag;嵌入式开发有 cross-compile/flash + const repair = REPAIR_DIAGNOSIS_PROFILE.extensions as readonly string[]; + const emb = EMBEDDED_DEV_PROFILE.extensions as readonly string[]; + expect(repair.some((e) => e.includes("pdf") || e.includes("datasheet"))).toBe(true); + expect(emb.some((e) => e.includes("cross-compile") || e.includes("flash"))).toBe(true); + // resolveProfile 未知 id fail-closed + expect(() => resolveProfile("nonexistent-profile")).toThrow(); + }); +}); + +function throwErr(): never { + throw new Error("boom"); +} diff --git a/tests/type-drift-check.test.ts b/tests/type-drift-check.test.ts new file mode 100644 index 0000000..c0b3ded --- /dev/null +++ b/tests/type-drift-check.test.ts @@ -0,0 +1,749 @@ +/** + * @module type-drift-check.test + * + * T11 类型镜像漂移检测 —— 完整测试套件(多方法论)。 + * + * 被测对象:scripts/type-drift-check.ts 的命名导出 + * - extractErrorPath(line): string | null 纯解析(一行 tsc 输出 → 路径) + * - checkTypeDrift(opts): TypeDriftResult 主入口(分类 + fail-closed) + * - defaultRunTsc: TscRunner 默认 tsc 执行器(spawnSync 包装) + * - 类型契约 TscResult / TypeDriftResult / TscRunner + * + * 依赖注入:runTsc 可注入;defaultRunTsc 的 spawnSync 用 vi.mock 控制。 + * 无 pi 运行时 / 无硬件 / 无网络 —— 纯逻辑 + mock。 + * + * 多方法论(每个 describe 标注): + * 1. 等价类划分 + 边界值分析 (extractErrorPath / checkTypeDrift 边界) + * 2. 决策表 (分类 + fail-closed 全分支组合) + * 3. 状态转换 (drift 状态空间:有效/迁移/不可达/重入) + * 4. 对抗 / fuzz (畸形输入:null/undefined/NaN/巨大/循环引用/并发重入/负值) + * 5. 元蜕变 / 不变式 (确定性、append 等价、单调 deny、短路优先、fail-closed) + * 6. 变异测试 (4 个 seeded bug,每个被 killer 杀死;真实代码全过) + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +// defaultRunTsc 依赖 spawnSync,整体 mock node:child_process(hoisted) +vi.mock("node:child_process", () => ({ spawnSync: vi.fn() })); + +import { spawnSync } from "node:child_process"; +import { + checkTypeDrift, + extractErrorPath, + defaultRunTsc, +} from "../scripts/type-drift-check.js"; +import type { TscResult, TscRunner, TypeDriftResult } from "../scripts/type-drift-check.js"; + +// ============================================================================ +// 工具:构造 TscRunner +// ============================================================================ +function runner(r: TscResult): TscRunner { + return () => r; +} +const ERR_LINE_PRETTY = (path: string, msg = "Type mismatch") => + `${path}:10:3 - error TS2322: ${msg}`; +const ERR_LINE_PLAIN = (path: string, msg = "Type mismatch") => + `${path}(23,5): error TS2322: ${msg}`; + +// ============================================================================ +// 方法论 1:等价类划分 + 边界值分析 —— extractErrorPath +// ============================================================================ +describe("等价类划分 + 边界值分析:extractErrorPath", () => { + // 有效类 A:非 pretty 报错行 + describe("有效类·非 pretty 报错行", () => { + it.each([ + ["src/extensions/hardware-state.ts(23,5): error TS2322: Type mismatch", "src/extensions/hardware-state.ts"], + ["src/types/pi.d.ts(1,1): error TS2307: Cannot find module", "src/types/pi.d.ts"], + // 边界:极短路径 + ["a.ts(1,1): error TS1: x", "a.ts"], + // pi 内部路径(非 pretty) + ["../pi/packages/agent/src/index.ts(42,8): error TS2307: Cannot find module", "../pi/packages/agent/src/index.ts"], + ])("«%s» → «%s»", (line, expected) => { + expect(extractErrorPath(line)).toBe(expected); + }); + }); + + // 有效类 B:pretty 报错行 + describe("有效类·pretty 报错行", () => { + it.each([ + ["src/types/pi.d.ts:10:3 - error TS2322: Type mismatch", "src/types/pi.d.ts"], + ["../pi/packages/ai/src/foo.ts:5:1 - error TS2307: Cannot find name", "../pi/packages/ai/src/foo.ts"], + // 边界:行号/列号到达大数 + ["src/big.ts:999999:1 - error TS9999: msg", "src/big.ts"], + ])("«%s» → «%s»", (line, expected) => { + expect(extractErrorPath(line)).toBe(expected); + }); + }); + + // 无效类:非报错行 → null + describe("无效类·非报错行 → null", () => { + it.each([ + ["Found 3 errors in 2 files.", null], // 摘要行 + ["", null], // 空串 + [" ", null], // 空白行 + ["src/foo.ts(23,5): warning TS0: something", null], // 警告非 error + ["context: src/foo.ts:23:5", null], // 上下文行无 error 标记 + ["error: something", null], // 有 error 字样但无 TSxxxx: + ["TS2322: foo", null], // 有错误码无 path 格式 + ])("«%s» → %s", (line, expected) => { + expect(extractErrorPath(line)).toBe(expected); + }); + }); + + // 边界值:off-by-one / 最小 / 单元素 + describe("边界值", () => { + it("最小 pretty 报错行(路径 1 字符 + 最小行列)", () => { + expect(extractErrorPath("a:1:1 - error TS1: x")).toBe("a"); + }); + it("最小 非 pretty 报错行", () => { + expect(extractErrorPath("a(1,1): error TS1: x")).toBe("a"); + }); + it("路径含空格与 unicode(Unix 路径无冒号,首段仍正确截取)", () => { + expect(extractErrorPath("src/中文 路径/foo.ts(1,2): error TS2322: x")).toBe( + "src/中文 路径/foo.ts", + ); + }); + it("pretty 行后紧跟多段冒号(非贪婪不误截)", () => { + // msg 里的冒号不应被吃进路径 + expect(extractErrorPath("src/x.ts:1:2 - error TS2322: a: b: c")).toBe("src/x.ts"); + }); + it("error 与 TS 间多空格仍命中 marker", () => { + expect(extractErrorPath("src/x.ts(1,1): error TS2322: msg")).toBe("src/x.ts"); + }); + }); +}); + +// ============================================================================ +// 方法论 2:决策表 —— checkTypeDrift 分类 + fail-closed 全分支 +// ============================================================================ +describe("决策表:checkTypeDrift 分类 + fail-closed", () => { + // 决策表列:exitCode / src 报错 / packages 报错 / 其它路径报错 / 可解析报错数 + // → driftDetected / pbaErrors.length / piInternalErrors.length + it.each([ + // 1. exit 0,无任何报错 → 无漂移 + { name: "D1 exit0 无报错", exit: 0, src: "", pkg: "", other: "", expDrift: false, expPba: 0, expPi: 0 }, + // 2. exit 1,仅 src 报错 → 漂移 + { name: "D2 仅 src 报错", exit: 1, src: ERR_LINE_PLAIN("src/a.ts"), pkg: "", other: "", expDrift: true, expPba: 1, expPi: 0 }, + // 3. exit 1,仅 packages 报错 → 无漂移 + { name: "D3 仅 packages 报错", exit: 1, src: "", pkg: ERR_LINE_PLAIN("../pi/packages/agent/x.ts"), other: "", expDrift: false, expPba: 0, expPi: 1 }, + // 4. exit 1,src + packages 混合 → 漂移(src 收录) + { name: "D4 src+packages 混合", exit: 1, src: ERR_LINE_PLAIN("src/a.ts"), pkg: ERR_LINE_PLAIN("../pi/packages/b.ts"), other: "", expDrift: true, expPba: 1, expPi: 1 }, + // 5. exit 1,仅其它路径(scripts/)→ fail-closed 归入 pba + { name: "D5 仅其它路径→pba", exit: 1, src: "", pkg: "", other: ERR_LINE_PLAIN("scripts/x.ts"), expDrift: true, expPba: 1, expPi: 0 }, + // 6. exit 2,tsc 崩溃无可解析报错 → fail-closed + { name: "D6 tsc 崩溃 fail-closed", exit: 2, src: "", pkg: "", other: "", expDrift: true, expPba: 1, expPi: 0 }, + // 7. exit 1,无可解析报错(tsconfig 缺失场景)→ fail-closed + { name: "D7 exit1 无可解析→fail-closed", exit: 1, src: "", pkg: "", other: "", expDrift: true, expPba: 1, expPi: 0 }, + // 8. exit 0 但 stdout 撒谎含 src 报错 → 分类不依赖 exitCode,仍检出 + { name: "D8 exit0 但含 src 报错", exit: 0, src: ERR_LINE_PLAIN("src/lie.ts"), pkg: "", other: "", expDrift: true, expPba: 1, expPi: 0 }, + // 9. exit 0 + 无报错 + 崩溃 stderr → 不触发 fail-closed(exit 0 = 无漂移) + { name: "D9 exit0+stderr 不 fail-closed", exit: 0, src: "", pkg: "", other: "", expDrift: false, expPba: 0, expPi: 0 }, + ])( + "$name → drift=$expDrift pba=$expPba pi=$expPi", + ({ exit, src, pkg, other, expDrift, expPba, expPi }) => { + const stdout = [src, pkg, other].filter(Boolean).join("\n"); + const stderr = exit !== 0 && !src && !pkg && !other ? "npx: command not found" : ""; + const r = checkTypeDrift({ + runTsc: runner({ exitCode: exit, stdout, stderr }), + }); + expect(r.driftDetected).toBe(expDrift); + expect(r.pbaErrors).toHaveLength(expPba); + expect(r.piInternalErrors).toHaveLength(expPi); + }, + ); + + it("fail-closed 兜底信息含退出码与原始输出", () => { + const r = checkTypeDrift({ + runTsc: runner({ exitCode: 2, stdout: "", stderr: "npx: command not found" }), + }); + expect(r.pbaErrors[0]).toContain("exited 2"); + expect(r.pbaErrors[0]).toContain("npx: command not found"); + }); + + it("fail-closed 优先取 stderr,stderr 空则取 stdout,皆空则 (no output)", () => { + const onlyStdout = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: "boom-stdout", stderr: "" }), + }); + expect(onlyStdout.pbaErrors[0]).toContain("boom-stdout"); + const empty = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: "", stderr: "" }), + }); + expect(empty.pbaErrors[0]).toContain("(no output)"); + }); +}); + +// ============================================================================ +// 方法论 1 续:边界值分析 —— checkTypeDrift(单元素/空/args/默认值/自定义) +// ============================================================================ +describe("边界值分析:checkTypeDrift(off-by-one / 空 / 单 / 默认 / 自定义)", () => { + it("空:exit 0 + 空输出 → 空数组(非 undefined)", () => { + const r = checkTypeDrift({ runTsc: runner({ exitCode: 0, stdout: "", stderr: "" }) }); + expect(r.pbaErrors).toEqual([]); + expect(r.piInternalErrors).toEqual([]); + expect(Array.isArray(r.pbaErrors)).toBe(true); + }); + + it("单元素:仅 1 条 src 报错 → pbaErrors 长度恰为 1", () => { + const r = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("src/a.ts"), stderr: "" }), + }); + expect(r.pbaErrors).toHaveLength(1); + }); + + it("max:100 条 src + 100 条 packages 报错 → 各 100,顺序保持", () => { + const srcLines = Array.from({ length: 100 }, (_, i) => ERR_LINE_PLAIN(`src/a${i}.ts`)); + const pkgLines = Array.from({ length: 100 }, (_, i) => ERR_LINE_PLAIN(`../pi/packages/p${i}.ts`)); + // src 全部先于 packages(stdout 内顺序) + const r = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: [...srcLines, ...pkgLines].join("\n"), stderr: "" }), + }); + expect(r.pbaErrors).toHaveLength(100); + expect(r.piInternalErrors).toHaveLength(100); + // 顺序保持:首条 src = a0 + expect(r.pbaErrors[0]).toContain("src/a0.ts"); + // 末条 packages = p99 + expect(r.piInternalErrors[99]).toContain("packages/p99.ts"); + }); + + it("args:默认 tsconfigPath → runTsc 收到 [\"-p\",\"tsconfig.realpi.json\",\"--noEmit\"]", () => { + const spy = vi.fn(); + spy.mockReturnValue({ exitCode: 0, stdout: "", stderr: "" }); + checkTypeDrift({ runTsc: spy }); + expect(spy).toHaveBeenCalledWith(["-p", "tsconfig.realpi.json", "--noEmit"]); + }); + + it("args:自定义 tsconfigPath → 透传", () => { + const spy = vi.fn(); + spy.mockReturnValue({ exitCode: 0, stdout: "", stderr: "" }); + checkTypeDrift({ tsconfigPath: "custom.json", runTsc: spy }); + expect(spy).toHaveBeenCalledWith(["-p", "custom.json", "--noEmit"]); + }); + + it("注入优先级:注入的 runTsc 必胜出,defaultRunTsc 不被触达", () => { + // 不注入 runTsc 会走 defaultRunTsc(真 spawnSync npx tsc)——避免真执行 + const spy = vi.fn(); + spy.mockReturnValue({ exitCode: 0, stdout: "", stderr: "" }); + const r = checkTypeDrift({ runTsc: spy }); + expect(spy).toHaveBeenCalledTimes(1); + expect(r.driftDetected).toBe(false); + }); + + it("自定义 pbaSrcPattern:覆盖分类边界", () => { + // 只认 lib/ 开头为 pba,src/ 报错落为“其它”→ fail-closed 归 pba + const r = checkTypeDrift({ + pbaSrcPattern: /^lib\//, + runTsc: runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("src/a.ts"), stderr: "" }), + }); + expect(r.pbaErrors).toHaveLength(1); // src/ 不匹配 lib → 其它 → pba + expect(r.piInternalErrors).toHaveLength(0); + }); +}); + +// ============================================================================ +// 方法论 3:状态转换 —— drift 状态空间(有效状态/迁移/不可达/重入) +// ============================================================================ +describe("状态转换:drift 状态空间", () => { + // 状态机:checkTypeDrift 是无状态纯函数,但其返回值定义一个状态空间: + // S0 NoDrift : drift=false ∧ pba=0 + // S1 PiOnly : drift=false ∧ pba=0 ∧ pi>0 + // S2 Drift : drift=true ∧ pba>0 + // S3 FailClosed: drift=true ∧ pba=1 ∧ 行含 "exited" + // 不可达:drift=true ∧ pba=0 / drift=false ∧ pba>0 + it("S0 NoDrift:exit0 无报错", () => { + const r = checkTypeDrift({ runTsc: runner({ exitCode: 0, stdout: "", stderr: "" }) }); + expect(r).toMatchObject({ driftDetected: false, pbaErrors: [], piInternalErrors: [] }); + }); + it("S1 PiOnly:仅 packages 报错,无漂移", () => { + const r = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("../pi/packages/x.ts"), stderr: "" }), + }); + expect(r.driftDetected).toBe(false); + expect(r.piInternalErrors.length).toBeGreaterThan(0); + }); + it("S2 Drift:src 报错触发漂移", () => { + const r = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("src/x.ts"), stderr: "" }), + }); + expect(r.driftDetected).toBe(true); + expect(r.pbaErrors.length).toBeGreaterThan(0); + }); + it("S3 FailClosed:tsc 崩溃 → 状态含 exited 标记", () => { + const r = checkTypeDrift({ + runTsc: runner({ exitCode: 2, stdout: "", stderr: "boom" }), + }); + expect(r.driftDetected).toBe(true); + expect(r.pbaErrors[0]).toMatch(/exited/); + }); + + it("迁移·单调:PiOnly 叠加 src 报错 → Drift(不可回退到 NoDrift)", () => { + // 先 PiOnly + const before = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("../pi/packages/x.ts"), stderr: "" }), + }); + expect(before.driftDetected).toBe(false); + // 叠加 src 报错(状态迁移 PiOnly → Drift) + const after = checkTypeDrift({ + runTsc: runner({ + exitCode: 1, + stdout: `${ERR_LINE_PLAIN("../pi/packages/x.ts")}\n${ERR_LINE_PLAIN("src/y.ts")}`, + stderr: "", + }), + }); + expect(after.driftDetected).toBe(true); + }); + + it("不可达状态:drift=true ∧ pbaErrors 为空 —— 全决策表样本校验", () => { + const samples: TscRunner[] = [ + runner({ exitCode: 0, stdout: "", stderr: "" }), + runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("src/x.ts"), stderr: "" }), + runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("../pi/packages/x.ts"), stderr: "" }), + runner({ exitCode: 2, stdout: "", stderr: "crash" }), + ]; + for (const runTsc of samples) { + const r = checkTypeDrift({ runTsc }); + // 不变式:driftDetected ⟺ pbaErrors.length > 0 + expect(r.driftDetected, `drift=${r.driftDetected} pba=${r.pbaErrors.length}`).toBe( + r.pbaErrors.length > 0, + ); + } + }); + + it("重入/幂等:同一 runTsc 连续调用两次 → 结果深相等(无状态泄漏)", () => { + const runTsc = runner({ + exitCode: 1, + stdout: ERR_LINE_PRETTY("src/x.ts"), + stderr: "", + }); + const r1 = checkTypeDrift({ runTsc }); + const r2 = checkTypeDrift({ runTsc }); + expect(r1).toEqual(r2); + }); +}); + +// ============================================================================ +// 方法论 4:对抗 / fuzz —— 畸形与滥用输入 +// ============================================================================ +describe("对抗 / fuzz:畸形与滥用输入", () => { + it("extractErrorPath(null) → 不抛、返回 null(非报错行)", () => { + // String(null)="null",不含 error TSxxxx: 标记 + expect(extractErrorPath(null as unknown as string)).toBeNull(); + }); + it("extractErrorPath(undefined) → 不抛、返回 null", () => { + expect(extractErrorPath(undefined as unknown as string)).toBeNull(); + }); + it("extractErrorPath(NaN) → 不抛、返回 null", () => { + expect(extractErrorPath(NaN as unknown as string)).toBeNull(); + }); + it("extractErrorPath(数字) → 不抛、返回 null", () => { + expect(extractErrorPath(12345 as unknown as string)).toBeNull(); + }); + it("extractErrorPath(巨大字符串) → 不抛、正确截取路径", () => { + const huge = "src/big.ts(1,1): error TS2322: " + "x".repeat(1_000_000); + expect(extractErrorPath(huge)).toBe("src/big.ts"); + }); + it("extractErrorPath(循环引用对象) → 不抛、String()=「[object Object]」无 marker → null(安全不误分类)", () => { + // 普通循环对象的 toString() 返回 "[object Object]"(不抛),不含 marker → 判非报错行 → null + const circ: unknown = {}; + (circ as Record).self = circ; + expect(extractErrorPath(circ as unknown as string)).toBeNull(); + }); + it("extractErrorPath(toString 抛异常的对象) → 透传异常(不吞、不静默误分类)", () => { + // 对象 toString 抛 → String() 抛 → .test() 抛 → 透传;不返回假路径 + const bomb = { + toString() { + throw new Error("toString exploded"); + }, + }; + expect(() => extractErrorPath(bomb as unknown as string)).toThrow("toString exploded"); + }); + + it("checkTypeDrift:runTsc 返回非字符串 stdout(数字)→ 不抛、按字符串归约", () => { + const r = checkTypeDrift({ + // @ts-expect-error 故意畸形 + runTsc: runner({ exitCode: 0, stdout: 12345, stderr: "" }), + }); + expect(r.driftDetected).toBe(false); + }); + it("checkTypeDrift:stdout 含 null 字节 → 不崩,仍按行解析", () => { + const r = checkTypeDrift({ + runTsc: runner({ + exitCode: 1, + stdout: `src/a.ts(1,1): error TS2322: bad\x00null`, + stderr: "", + }), + }); + expect(r.driftDetected).toBe(true); + expect(r.pbaErrors[0]).toContain("src/a.ts"); + }); + it("checkTypeDrift:CRLF 行尾 → 仍正确解析(split 在 \\n)", () => { + const r = checkTypeDrift({ + runTsc: runner({ + exitCode: 1, + stdout: `src/a.ts(1,1): error TS2322: x\r\nsrc/b.ts(2,2): error TS2322: y\r\n`, + stderr: "", + }), + }); + expect(r.pbaErrors).toHaveLength(2); + // CRLF 残留的 \r 应留在行尾(不影响路径提取) + expect(r.pbaErrors[0]).toContain("src/a.ts"); + }); + it("checkTypeDrift:负退出码 → !== 0 → fail-closed", () => { + const r = checkTypeDrift({ + runTsc: runner({ exitCode: -1, stdout: "", stderr: "spawn killed" }), + }); + expect(r.driftDetected).toBe(true); + expect(r.pbaErrors[0]).toContain("exited -1"); + }); + it("checkTypeDrift:并发重入(两次交错调用)→ 结果互不污染", () => { + // 无模块级可变状态 → 交错安全。用两个不同 runTsc 模拟“并发” + const r1 = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("src/a.ts"), stderr: "" }), + }); + const r2 = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("../pi/packages/b.ts"), stderr: "" }), + }); + expect(r1.driftDetected).toBe(true); + expect(r2.driftDetected).toBe(false); + expect(r1.pbaErrors).toHaveLength(1); + expect(r2.piInternalErrors).toHaveLength(1); + }); + it("checkTypeDrift:runTsc 抛异常 → 透传(不吞异常伪装无漂移)", () => { + const throwing: TscRunner = () => { + throw new Error("runner exploded"); + }; + expect(() => checkTypeDrift({ runTsc: throwing })).toThrow("runner exploded"); + }); +}); + +// ============================================================================ +// 方法论 5:元蜕变 / 不变式 —— 跨变换保持的性质 +// ============================================================================ +describe("元蜕变 / 不变式:跨变换保持的性质", () => { + // 不变式 I1:driftDetected ⟺ pbaErrors.length > 0(已覆盖,此处显式断言为不变式) + it("I1 单调 deny:driftDetected 恒等于 pbaErrors 非空(多场景)", () => { + const cases: TscRunner[] = [ + runner({ exitCode: 0, stdout: "", stderr: "" }), + runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("src/x.ts"), stderr: "" }), + runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("../pi/packages/x.ts"), stderr: "" }), + runner({ exitCode: 2, stdout: "", stderr: "crash" }), + runner({ exitCode: 1, stdout: `${ERR_LINE_PLAIN("src/x.ts")}\n${ERR_LINE_PLAIN("../pi/packages/y.ts")}`, stderr: "" }), + ]; + for (const runTsc of cases) { + const r = checkTypeDrift({ runTsc }); + expect(r.driftDetected, `pba=${r.pbaErrors.length}`).toBe(r.pbaErrors.length > 0); + } + }); + + // 元蜕变 M1:append 等价 —— 输出拆到 stdout/stderr 两次 vs 合并到 stdout 一次,结果等价 + it("M1 append 等价:stdout+stderr 拆分 vs 合并到 stdout → 同 pbaErrors/piInternal", () => { + const src = ERR_LINE_PLAIN("src/a.ts"); + const pkg = ERR_LINE_PLAIN("../pi/packages/b.ts"); + // 拆分:src 在 stdout,pkg 在 stderr + const split = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: src, stderr: pkg }), + }); + // 合并:全部在 stdout(顺序 src 然后 pkg,与 join 行为一致:stdout 先 stderr 后) + const merged = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: `${src}\n${pkg}`, stderr: "" }), + }); + expect(split.pbaErrors).toEqual(merged.pbaErrors); + expect(split.piInternalErrors).toEqual(merged.piInternalErrors); + expect(split.driftDetected).toBe(merged.driftDetected); + }); + + // 元蜕变 M2:replay 等价 —— 同输入跑两次结果完全相同(确定性) + it("M2 replay 等价:同 runTsc 两次 → 深相等", () => { + const runTsc = runner({ + exitCode: 1, + stdout: `${ERR_LINE_PRETTY("src/a.ts")}\n${ERR_LINE_PLAIN("../pi/packages/b.ts")}`, + stderr: "warn", + }); + expect(checkTypeDrift({ runTsc })).toEqual(checkTypeDrift({ runTsc })); + }); + + // 不变式 I2:短路优先 —— pbaSrcPattern 先于 PI_INTERNAL_PATTERN 判定 + it("I2 短路优先:路径同时匹配 src/ 与 packages/ → 归 pba(先匹配先归)", () => { + // "src/packages/foo.ts" 同时匹配 ^src/ 与 packages/ + const r = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("src/packages/foo.ts"), stderr: "" }), + }); + expect(r.pbaErrors).toHaveLength(1); + expect(r.piInternalErrors).toHaveLength(0); + }); + + // 不变式 I3:fail-closed unusable = reject + it("I3 fail-closed:tsc 不可用(非零退出 + 无可解析报错)→ 必判漂移", () => { + const r = checkTypeDrift({ + runTsc: runner({ exitCode: 127, stdout: "", stderr: "command not found" }), + }); + expect(r.driftDetected).toBe(true); + }); + + // 不变式 I4:分类独立于 exitCode(信任输出文本,不因 exitCode 门控) + it("I4 分类独立于 exitCode:exit0 含 src 报错仍检出;exit0 无报错不误报", () => { + const lying = checkTypeDrift({ + runTsc: runner({ exitCode: 0, stdout: ERR_LINE_PLAIN("src/lie.ts"), stderr: "" }), + }); + expect(lying.driftDetected).toBe(true); + const honest = checkTypeDrift({ + runTsc: runner({ exitCode: 0, stdout: "", stderr: "" }), + }); + expect(honest.driftDetected).toBe(false); + }); + + // 不变式 I5:结果字段为 readonly 快照(运行时至少保持数组 identity 一致) + it("I5 结果快照:返回值三字段类型符合契约且非 undefined", () => { + const r = checkTypeDrift({ runTsc: runner({ exitCode: 0, stdout: "", stderr: "" }) }); + expect(typeof r.driftDetected).toBe("boolean"); + expect(Array.isArray(r.pbaErrors)).toBe(true); + expect(Array.isArray(r.piInternalErrors)).toBe(true); + }); + + // 不变式 I6:pbaSrcPattern 默认锚定 ^src/(前缀匹配,非子串) + it("I6 默认 pbaSrcPattern 锚定 ^src/:my-src/x.ts 不匹配真 src 漂移路径", () => { + const r = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("my-src/x.ts"), stderr: "" }), + }); + // my-src/ 不匹配 ^src/ → 落为“其它”→ fail-closed 归 pba + expect(r.pbaErrors).toHaveLength(1); + // 与真 src/ 路径区分:真 src 应匹配默认 pattern + const real = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("src/x.ts"), stderr: "" }), + }); + expect(real.pbaErrors).toHaveLength(1); + }); +}); + +// ============================================================================ +// 方法论 6:变异测试 —— 4 个 seeded bug,每个被 killer 杀死 +// ============================================================================ +describe("变异测试:seeded bug 与 killer", () => { + // 复制私有常量(mutant 副本需要它们) + const TSC_ERROR_MARKER = /error\s+TS\d+:/; + const TSC_ERROR_PATH_RE = /^(.+?)(?:\(\d+,\d+\)|:\d+:\d+)/; + const PI_INTERNAL_PATTERN = /packages\//; + const DEFAULT_TSCONFIG_PATH = "tsconfig.realpi.json"; + const DEFAULT_PBA_SRC_PATTERN = /^src\//; + + // --- Mutant M1:extractErrorPath 漏 marker 守卫 --- + // BUG: 删除 `if (!TSC_ERROR_MARKER.test(line)) return null;` + // → 非报错行但带路径形(如 warning/摘要)被误当路径返回 + function extractErrorPath_M1(line: string): string | null { + // (BUG: marker guard removed) + const match = line.match(TSC_ERROR_PATH_RE); + return match ? match[1].trim() : null; + } + it("M1 真实代码:warning 行 → null(killer 通过)", () => { + expect(extractErrorPath("src/foo.ts(23,5): warning TS0: something")).toBeNull(); + }); + it("M1 变体被杀:mutant 对 warning 行返回路径 → killer(null) 失败", () => { + // 同输入下 mutant 偏离正确值,证明 killer(期望 null)能杀掉 M1 + expect(extractErrorPath_M1("src/foo.ts(23,5): warning TS0: something")).toBe("src/foo.ts"); + }); + + // --- Mutant M2:checkTypeDrift 删除 fail-closed 块 --- + // BUG: 去掉 `if (exitCode !== 0 && pba=0 && pi=0) push(raw)` + // → tsc 崩溃(非零退出 + 无可解析报错)静默判无漂移 + function checkTypeDrift_M2(opts: { + tsconfigPath?: string; + runTsc?: TscRunner; + pbaSrcPattern?: RegExp; + }): TypeDriftResult { + const tsconfigPath = opts.tsconfigPath ?? DEFAULT_TSCONFIG_PATH; + const pbaSrcPattern = opts.pbaSrcPattern ?? DEFAULT_PBA_SRC_PATTERN; + const runTsc = opts.runTsc ?? (() => ({ exitCode: 0, stdout: "", stderr: "" })); + const args = ["-p", tsconfigPath, "--noEmit"]; + const result = runTsc(args); + const output = [result.stdout, result.stderr].filter(Boolean).join("\n"); + const lines = output.split("\n"); + const pbaErrors: string[] = []; + const piInternalErrors: string[] = []; + for (const line of lines) { + if (!TSC_ERROR_MARKER.test(line)) continue; + const match = line.match(TSC_ERROR_PATH_RE); + const path = match ? match[1].trim() : null; + if (path === null) continue; + if (pbaSrcPattern.test(path)) pbaErrors.push(line); + else if (PI_INTERNAL_PATTERN.test(path)) piInternalErrors.push(line); + else pbaErrors.push(line); + } + // (BUG: fail-closed block removed) + return { driftDetected: pbaErrors.length > 0, pbaErrors, piInternalErrors }; + } + it("M2 真实代码:tsc 崩溃 → 漂移=true(killer 通过)", () => { + const r = checkTypeDrift({ + runTsc: runner({ exitCode: 2, stdout: "", stderr: "npx: command not found" }), + }); + expect(r.driftDetected).toBe(true); + expect(r.pbaErrors).toHaveLength(1); + }); + it("M2 变体被杀:mutant 对崩溃静默判无漂移 → killer(true) 失败", () => { + const r = checkTypeDrift_M2({ + runTsc: runner({ exitCode: 2, stdout: "", stderr: "npx: command not found" }), + }); + expect(r.driftDetected).toBe(false); // mutant 的错误行为 + expect(r.pbaErrors).toHaveLength(0); + }); + + // --- Mutant M3:checkTypeDrift 交换分类顺序(pi 先于 pba)--- + // BUG: `if (PI_INTERNAL_PATTERN.test(path)) piInternal.push; else if (pbaSrcPattern...) pba.push` + // → 同时匹配 src/ 与 packages/ 的路径误归 piInternal + function checkTypeDrift_M3(opts: { + tsconfigPath?: string; + runTsc?: TscRunner; + pbaSrcPattern?: RegExp; + }): TypeDriftResult { + const pbaSrcPattern = opts.pbaSrcPattern ?? DEFAULT_PBA_SRC_PATTERN; + const runTsc = opts.runTsc ?? (() => ({ exitCode: 0, stdout: "", stderr: "" })); + const tsconfigPath = opts.tsconfigPath ?? DEFAULT_TSCONFIG_PATH; + const args = ["-p", tsconfigPath, "--noEmit"]; + const result = runTsc(args); + const output = [result.stdout, result.stderr].filter(Boolean).join("\n"); + const lines = output.split("\n"); + const pbaErrors: string[] = []; + const piInternalErrors: string[] = []; + for (const line of lines) { + if (!TSC_ERROR_MARKER.test(line)) continue; + const match = line.match(TSC_ERROR_PATH_RE); + const path = match ? match[1].trim() : null; + if (path === null) continue; + // (BUG: pi pattern tested first → short-circuit reversed) + if (PI_INTERNAL_PATTERN.test(path)) piInternalErrors.push(line); + else if (pbaSrcPattern.test(path)) pbaErrors.push(line); + else pbaErrors.push(line); + } + if (result.exitCode !== 0 && pbaErrors.length === 0 && piInternalErrors.length === 0) { + const raw = result.stderr.trim() || result.stdout.trim() || "(no output)"; + pbaErrors.push(`tsc exited ${result.exitCode} with no parseable errors: ${raw}`); + } + return { driftDetected: pbaErrors.length > 0, pbaErrors, piInternalErrors }; + } + it("M3 真实代码:src/packages/foo.ts → pbaErrors(killer 通过)", () => { + const r = checkTypeDrift({ + runTsc: runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("src/packages/foo.ts"), stderr: "" }), + }); + expect(r.pbaErrors).toHaveLength(1); + expect(r.piInternalErrors).toHaveLength(0); + }); + it("M3 变体被杀:mutant 把同时匹配路径误归 piInternal → killer(pba=1) 失败", () => { + const r = checkTypeDrift_M3({ + runTsc: runner({ exitCode: 1, stdout: ERR_LINE_PLAIN("src/packages/foo.ts"), stderr: "" }), + }); + expect(r.pbaErrors).toHaveLength(0); // mutant 的错误行为 + expect(r.piInternalErrors).toHaveLength(1); + }); + + // --- Mutant M4:DEFAULT_TSCONFIG_PATH 错默认值 --- + // BUG: 默认 tsconfig 路径 = "tsconfig.json"(非 "tsconfig.realpi.json") + // → 跑错 tsconfig,漏检真 pi 镜像漂移 + function checkTypeDrift_M4(opts: { + runTsc?: TscRunner; + }): TypeDriftResult { + const tsconfigPath = "tsconfig.json"; // (BUG: wrong default) + const runTsc = opts.runTsc ?? (() => ({ exitCode: 0, stdout: "", stderr: "" })); + const args = ["-p", tsconfigPath, "--noEmit"]; + const result = runTsc(args); + const output = [result.stdout, result.stderr].filter(Boolean).join("\n"); + const lines = output.split("\n"); + const pbaErrors: string[] = []; + const piInternalErrors: string[] = []; + for (const line of lines) { + if (!TSC_ERROR_MARKER.test(line)) continue; + const match = line.match(TSC_ERROR_PATH_RE); + const path = match ? match[1].trim() : null; + if (path === null) continue; + if (DEFAULT_PBA_SRC_PATTERN.test(path)) pbaErrors.push(line); + else if (PI_INTERNAL_PATTERN.test(path)) piInternalErrors.push(line); + else pbaErrors.push(line); + } + if (result.exitCode !== 0 && pbaErrors.length === 0 && piInternalErrors.length === 0) { + const raw = result.stderr.trim() || result.stdout.trim() || "(no output)"; + pbaErrors.push(`tsc exited ${result.exitCode} with no parseable errors: ${raw}`); + } + return { driftDetected: pbaErrors.length > 0, pbaErrors, piInternalErrors }; + } + it("M4 真实代码:默认 args 含 tsconfig.realpi.json(killer 通过)", () => { + const spy = vi.fn(); + spy.mockReturnValue({ exitCode: 0, stdout: "", stderr: "" }); + checkTypeDrift({ runTsc: spy }); + expect(spy).toHaveBeenCalledWith(["-p", "tsconfig.realpi.json", "--noEmit"]); + }); + it("M4 变体被杀:mutant 默认 tsconfig.json → killer(realpi) 失败", () => { + const spy = vi.fn(); + spy.mockReturnValue({ exitCode: 0, stdout: "", stderr: "" }); + checkTypeDrift_M4({ runTsc: spy }); + expect(spy).toHaveBeenCalledWith(["-p", "tsconfig.json", "--noEmit"]); + }); +}); + +// ============================================================================ +// 补:defaultRunTsc —— spawnSync 包装的归一化逻辑(vi.mock 控制 spawnSync) +// ============================================================================ +describe("defaultRunTsc:spawnSync 归一化(依赖注入 child_process)", () => { + const mockedSpawn = vi.mocked(spawnSync); + beforeEach(() => { + mockedSpawn.mockReset(); + }); + + it("正常:status=0 → exitCode=0,stdout/stderr 透传", () => { + mockedSpawn.mockReturnValue({ + status: 0, + stdout: "out", + stderr: "err", + } as never); + const r = defaultRunTsc(["-p", "x.json", "--noEmit"]); + expect(r.exitCode).toBe(0); + expect(r.stdout).toBe("out"); + expect(r.stderr).toBe("err"); + // 透传 npx tsc 前缀 + expect(mockedSpawn).toHaveBeenCalledWith( + "npx", + ["tsc", "-p", "x.json", "--noEmit"], + expect.objectContaining({ encoding: "utf8" }), + ); + }); + + it("spawn 错误:status=null + error → exitCode=-1,stderr 取 error.message", () => { + mockedSpawn.mockReturnValue({ + status: null, + stdout: "", + stderr: "", + error: new Error("boom-spawn"), + } as never); + const r = defaultRunTsc([]); + expect(r.exitCode).toBe(-1); + expect(r.stderr).toBe("boom-spawn"); + }); + + it("spawn 错误但 stderr 非空:stderr 优先于 error.message", () => { + mockedSpawn.mockReturnValue({ + status: null, + stdout: "", + stderr: "real-stderr", + error: new Error("ignored"), + } as never); + const r = defaultRunTsc([]); + expect(r.stderr).toBe("real-stderr"); + }); + + it("stdout/stderr 为 undefined → 兜底空串", () => { + mockedSpawn.mockReturnValue({ + status: 1, + stdout: undefined, + stderr: undefined, + } as never); + const r = defaultRunTsc([]); + expect(r.stdout).toBe(""); + expect(r.stderr).toBe(""); + expect(r.exitCode).toBe(1); + }); + + it("status=undefined → exitCode=-1(nullish 合并)", () => { + mockedSpawn.mockReturnValue({ status: undefined, stdout: "", stderr: "" } as never); + expect(defaultRunTsc([]).exitCode).toBe(-1); + }); + + it("status=0(假值边界):0 非空,exitCode=0", () => { + mockedSpawn.mockReturnValue({ status: 0, stdout: "", stderr: "" } as never); + expect(defaultRunTsc([]).exitCode).toBe(0); + }); +}); diff --git a/tests/workflow.test.ts b/tests/workflow.test.ts new file mode 100644 index 0000000..20bc6d3 --- /dev/null +++ b/tests/workflow.test.ts @@ -0,0 +1,1329 @@ +/** + * @module tests/workflow.test + * + * T12 子代理 + 工作流编排 —— 严谨多方法论测试套件。 + * + * 被测命名导出(按契约): + * src/capabilities/workflow/index.ts -> parallel, pipeline, phase, MAX_CONCURRENCY + * src/capabilities/subagent/index.ts -> InlineSubagentProvider, SubagentRegistry, + * isolatedSubagentScope, SUBAGENT_SCOPE_ROOT, + * INLINE_SUBAGENT_ID, SubagentProvider(类型) + * + * 测试前置:直接 import 命名导出,mock 注入依赖(handler/emitter),无 pi 运行时、 + * 无硬件、无网络。作用域隔离不变式靠真实 T07 PbaEventBus(纯逻辑)证明。 + * + * 应用的多方法论(每个 describe 块标注): + * - 等价类划分(有效/无效/边界类) + * - 边界值分析(off-by-one、空、单元素、max、min) + * - 决策表(组合输入→期望,覆盖全分支) + * - 状态转换(状态+迁移+不可达状态+重入) + * - 变异测试(≥3 个 seeded bug,内联带 bug 副本,断言每个被某条测试杀死) + * - 对抗/fuzz(null、undefined、巨大、NaN、循环引用、并发重入、负值) + * - 元蜕变/不变式(跨变换保持的性质) + * + * 门: + * 1. 真实代码全绿:`npx vitest run tests/workflow.test.ts` + * 2. 每个植入 bug 变体:测试内断言其输出 != 正确输出(证明 kill)。 + */ + +import { describe, it, expect } from "vitest"; +import { + parallel, + pipeline, + phase, + MAX_CONCURRENCY, +} from "../src/capabilities/workflow/index.js"; +import { + InlineSubagentProvider, + SubagentRegistry, + isolatedSubagentScope, + SUBAGENT_SCOPE_ROOT, + INLINE_SUBAGENT_ID, + type SubagentProvider, +} from "../src/capabilities/subagent/index.js"; +import { PbaEventBus } from "../src/core/pba-event-bus.js"; + +// ============================================================================ +// 工具:tick 推进(避免依赖真实定时器的精度) +// ============================================================================ +const tick = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +// ============================================================================ +// T12 workflow —— MAX_CONCURRENCY 常量(边界值 + 不变式) +// ============================================================================ + +describe("T12 workflow MAX_CONCURRENCY —— 常量冻结 + 取值(边界值·不变式)", () => { + it("值为 8(文档化的 item 并发上限)", () => { + expect(MAX_CONCURRENCY).toBe(8); + }); + + it("深冻结:运行时不可变(Object.isFrozen)——值恒为 8,无法挂属性", () => { + expect(Object.isFrozen(MAX_CONCURRENCY)).toBe(true); + // number 原始值本不可变;ES 模块严格模式下给原始值挂属性抛 TypeError + expect(() => { + (MAX_CONCURRENCY as unknown as { x?: number }).x = 999; + }).toThrow(TypeError); + expect(MAX_CONCURRENCY).toBe(8); + }); +}); + +// ============================================================================ +// T12 workflow —— parallel(等价类划分 + 边界值 + 决策表 + 对抗 + 元蜕变) +// ============================================================================ + +describe("T12 parallel —— barrier 原语(等价类划分·边界值·决策表)", () => { + // ---- 等价类:有效类(全部 fulfilled)---- + it("有效类:3 thunk 全 fulfilled,值保序", async () => { + const out = await parallel([ + () => Promise.resolve(1), + () => Promise.resolve(2), + () => Promise.resolve(3), + ]); + expect(out).toEqual([1, 2, 3]); + }); + + it("有效类:thunk 返回异构类型(number/string/object/null value)保序", async () => { + const obj = { kind: "data" }; + const out = await parallel([ + () => Promise.resolve(42), + () => Promise.resolve("str"), + () => Promise.resolve(obj), + () => Promise.resolve(null), + () => Promise.resolve(undefined), + ]); + expect(out).toEqual([42, "str", obj, null, undefined]); + }); + + // ---- 边界值:空 / 单元素 ---- + it("边界:空 thunk 数组 → 空结果数组(非 undefined)", async () => { + const out = await parallel([]); + expect(Array.isArray(out)).toBe(true); + expect(out).toEqual([]); + expect(out).toHaveLength(0); + }); + + it("边界:单 thunk fulfilled → 单元素数组", async () => { + const out = await parallel([() => Promise.resolve("only")]); + expect(out).toEqual(["only"]); + }); + + // ---- 决策表:thunk 状态 × 位置 ---- + it("决策表:[fulfilled, rejected, fulfilled] → [v, null, v],整体不 reject", async () => { + const out = await parallel([ + () => Promise.resolve("a"), + () => Promise.reject(new Error("boom")), + () => Promise.resolve("c"), + ]); + expect(out).toEqual(["a", null, "c"]); + }); + + it("决策表:全 rejected → 全 null(不 reject)", async () => { + const out = await parallel([ + () => Promise.reject(new Error("e1")), + () => Promise.reject(new Error("e2")), + ]); + expect(out).toEqual([null, null]); + }); + + it("决策表:首位 rejected → [null, v],末位仍保序", async () => { + const out = await parallel([ + () => Promise.reject(new Error("head")), + () => Promise.resolve("tail"), + ]); + expect(out).toEqual([null, "tail"]); + }); + + it("决策表:rejected 原因非 Error(裸串/对象/number)→ 仍落 null", async () => { + const out = await parallel([ + () => Promise.reject("string reason"), + () => Promise.reject({ code: 500 }), + () => Promise.reject(42), + () => Promise.resolve("ok"), + ]); + // 无论 reject 值类型,对应位恒 null(allSettled status 语义) + expect(out).toEqual([null, null, null, "ok"]); + }); + + // ---- 不变式:真并发 ---- + it("不变式:N thunk 立即并发,maxInflight=N(非串行)", async () => { + let inflight = 0; + let maxInflight = 0; + const mk = (v: number) => () => + new Promise((resolve) => { + inflight++; + maxInflight = Math.max(maxInflight, inflight); + setTimeout(() => { + inflight--; + resolve(v); + }, 20); + }); + const out = await parallel([mk(1), mk(2), mk(3), mk(4)]); + expect(out).toEqual([1, 2, 3, 4]); + expect(maxInflight).toBe(4); + }); + + // ---- 对抗/fuzz ---- + it("对抗:thunk 返回非 Promise(同步值)→ 仍按 fulfilled 取值", async () => { + // map((t)=>t()) 得同步值,Promise.allSettled 把非 thenable 当 fulfilled + const out = await parallel([ + // @ts-expect-error —— 故意返回非 Promise,对抗输入 + () => "sync-value", + () => Promise.resolve("async-value"), + ]); + expect(out).toEqual(["sync-value", "async-value"]); + }); + + it("回归(finding 已修):thunk 同步抛错 → 该位落 null,parallel 不 reject", async () => { + // 不变式:"单 thunk 抛错绝不向上传播(不 reject),只把对应位落 null"。 + // 修复前 thunks.map((t)=>t()) 阶段同步 throw 逃逸 allSettled 使 parallel + // reject;修复后用 Promise.resolve().then(t) 把同步 throw 转成被 allSettled + // 吸收的 rejection → 该位落 null,其余位不受影响。 + const out = await parallel([ + () => Promise.resolve("a"), + () => { + throw new Error("sync boom"); + }, + () => Promise.resolve("c"), + ]); + expect(out).toEqual(["a", null, "c"]); + }); + + // ---- 元蜕变:append 两次 = replay 等价 ---- + it("元蜕变:parallel 的结果等价于按序 await 每个 thunk(保序不变式)", async () => { + const thunks = [ + () => Promise.resolve("x"), + () => Promise.resolve("y"), + () => Promise.resolve("z"), + ]; + const concurrent = await parallel(thunks); + const sequential: unknown[] = []; + for (const t of thunks) sequential.push(await t()); + expect(concurrent).toEqual(sequential); + }); +}); + +// ============================================================================ +// T12 workflow —— pipeline(等价类 + 边界值 + 决策表 + 状态转换 + 元蜕变) +// ============================================================================ + +describe("T12 pipeline —— 流水线原语(等价类·边界值·决策表)", () => { + // ---- 等价类:happy ---- + it("有效类:1 item 过 3 stage,prev 链式传递", async () => { + const calls: Array<{ stage: number; prev: unknown }> = []; + const out = await pipeline( + ["img.bin"], + async (prev, item, i) => { + calls.push({ stage: 0, prev }); + return `edit(${item}#${i})`; + }, + async (prev, item, i) => { + calls.push({ stage: 1, prev }); + return `compile(${prev}+${item}#${i})`; + }, + async (prev, item, i) => { + calls.push({ stage: 2, prev }); + return `flash(${prev}+${item}#${i})`; + }, + ); + expect(calls).toEqual([ + { stage: 0, prev: undefined }, + { stage: 1, prev: "edit(img.bin#0)" }, + { stage: 2, prev: "compile(edit(img.bin#0)+img.bin#0)" }, + ]); + expect(out).toEqual([ + "flash(compile(edit(img.bin#0)+img.bin#0)+img.bin#0)", + ]); + }); + + // ---- 边界值 ---- + it("边界:空 items → 空结果数组(非 undefined)", async () => { + const out = await pipeline( + [], + async (prev, _item, _i) => prev ?? "x", + ); + expect(Array.isArray(out)).toBe(true); + expect(out).toEqual([]); + }); + + it("边界:单 item 单 stage → 单元素", async () => { + const out = await pipeline(["solo"], async (_prev, item, i) => `f(${item}#${i})`); + expect(out).toEqual(["f(solo#0)"]); + }); + + it("边界:空 stages → identity(终态 = item 本身,非 null/undefined)", async () => { + const out = await pipeline(["a", "b", "c"]); + expect(out).toEqual(["a", "b", "c"]); + // 单 item 空 stages 同样 identity + const one = await pipeline([42]); + expect(one).toEqual([42]); + }); + + it("边界:stage 返回 undefined → prev 链传 undefined(非 null)", async () => { + const seen: unknown[] = []; + const out = await pipeline( + ["item"], + async (_prev, _item, _i) => { + seen.push("s0"); + return undefined; + }, + async (prev, _item, _i) => { + seen.push(["s1", prev]); + return "done"; + }, + ); + expect(seen).toEqual(["s0", ["s1", undefined]]); + expect(out).toEqual(["done"]); + }); + + // ---- 决策表:stage 抛错 × 位置 ---- + it("决策表:stage0 抛错 → item null,stage1/2 不被调用", async () => { + const seen: number[] = []; + const out = await pipeline( + ["a"], + async () => { + seen.push(0); + throw new Error("s0 boom"); + }, + async () => { + seen.push(1); + return "s1"; + }, + async () => { + seen.push(2); + return "s2"; + }, + ); + expect(out).toEqual([null]); + expect(seen).toEqual([0]); + }); + + it("决策表:stage1 抛错 → item null,stage2 不被调用(fail-soft per-item)", async () => { + const seen: number[] = []; + const out = await pipeline( + ["a"], + async () => { + seen.push(0); + return "s0"; + }, + async () => { + seen.push(1); + throw new Error("s1 boom"); + }, + async () => { + seen.push(2); + return "s2"; + }, + ); + expect(out).toEqual([null]); + expect(seen).toEqual([0, 1]); + }); + + it("决策表:末 stage 抛错 → item null", async () => { + const out = await pipeline( + ["a"], + async () => "s0", + async () => "s1", + async () => { + throw new Error("last boom"); + }, + ); + expect(out).toEqual([null]); + }); + + it("决策表:多 item,部分 item 在不同 stage 失败 → 各自落 null,成功 item 保终态保序", async () => { + const out = await pipeline( + ["ok1", "fail", "ok2"], + async (_prev, item) => `e(${item})`, + async (_prev, item) => { + if (item === "fail") throw new Error("x"); + return `c(${item})`; + }, + async (prev) => `f(${prev})`, + ); + expect(out).toEqual(["f(c(ok1))", null, "f(c(ok2))"]); + }); + + // ---- 状态转换:per-item 状态机(RUNNING→DONE | RUNNING→FAILED[吸收/跳后续])---- + describe("状态转换:per-item 状态机(RUNNING→DONE/FAILED,FAILED 后不可达后续 stage)", () => { + it("迁移:item RUNNING(s0)→RUNNING(s1)→DONE,终态=末 stage 值", async () => { + const transitions: string[] = []; + await pipeline( + ["it"], + async () => { + transitions.push("s0"); + return 1; + }, + async () => { + transitions.push("s1"); + return 2; + }, + ).then((r) => { + transitions.push(`DONE:${r[0]}`); + }); + expect(transitions).toEqual(["s0", "s1", "DONE:2"]); + }); + + it("迁移:item FAILED(s1) 后,s2 为不可达状态(永不调用)", async () => { + const reached: string[] = []; + await pipeline( + ["it"], + async () => { + reached.push("s0"); + return "v0"; + }, + async () => { + reached.push("s1-FAIL"); + throw new Error("fail"); + }, + async () => { + reached.push("s2-UNREACHABLE"); + return "v2"; + }, + ); + expect(reached).toEqual(["s0", "s1-FAIL"]); + // s2 不可达已被吸收 stage 的 catch 证明 + }); + + it("重入:多 item 独立状态机,一 item 失败不传染另一 item", async () => { + const log: string[] = []; + await pipeline( + ["a", "b", "c"], + async (_p, item) => { + log.push(`${item}:s0`); + return item; + }, + async (prev, item) => { + if (item === "b") { + log.push(`${item}:s1-FAIL`); + throw new Error("b fails"); + } + log.push(`${item}:s1`); + return prev; + }, + async (prev, item) => { + log.push(`${item}:s2`); + return prev; + }, + ); + // a/c 完成全 stage;b 在 s1 失败,s2 不可达 + expect(log).toContain("a:s0"); + expect(log).toContain("a:s2"); + expect(log).toContain("b:s1-FAIL"); + expect(log).not.toContain("b:s2"); + expect(log).toContain("c:s2"); + }); + }); + + // ---- 不变式:并发钳制 + 保序 ---- + it("不变式:item 并发 ≤ MAX_CONCURRENCY,结果保序", async () => { + let inflight = 0; + let maxInflight = 0; + const items = Array.from({ length: 20 }, (_, k) => k); + const out = await pipeline(items, async (_prev, _item, _i) => { + inflight++; + maxInflight = Math.max(maxInflight, inflight); + await tick(10); + inflight--; + return "ok"; + }); + expect(out).toEqual(items.map(() => "ok")); + expect(maxInflight).toBeLessThanOrEqual(MAX_CONCURRENCY); + expect(maxInflight).toBe(MAX_CONCURRENCY); + }); + + // ---- 对抗 ---- + it("对抗:stage 索引 i 对每个 item 正确(0-based,保序)", async () => { + const seen: number[] = []; + await pipeline( + ["a", "b", "c"], + async (_prev, _item, i) => { + seen.push(i); + return i; + }, + ); + expect(seen).toEqual([0, 1, 2]); + }); + + // ---- 元蜕变:单 stage pipeline = 每 item 独立 stage(prev=undefined) 的保序等价 ---- + it("元蜕变:单 stage pipeline 的结果保序等价于每 item 独立 await stage(prev 重置)", async () => { + const items = [1, 2, 3]; + const stage = async (prev: unknown, item: number, i: number) => + `${prev ?? "∅"}→${item}#${i}`; + const piped = await pipeline(items, stage); + // pipeline 语义:每 item 独立流过 stage 链,stage[0] 收 prev=undefined + const seq: unknown[] = []; + for (let i = 0; i < items.length; i++) { + seq.push(await stage(undefined, items[i], i)); + } + expect(piped).toEqual(seq); + expect(piped).toEqual(["∅→1#0", "∅→2#1", "∅→3#2"]); + }); +}); + +// ============================================================================ +// T12 workflow —— phase(等价类 + 对抗) +// ============================================================================ + +describe("T12 phase —— no-op 锚点(等价类·对抗)", () => { + it("有效类:任意阶段名 → 返回 undefined,无副作用", () => { + expect(phase("compile-phase")).toBeUndefined(); + expect(phase("flash-phase")).toBeUndefined(); + }); + + it("边界:空串阶段名 → undefined,不抛", () => { + expect(phase("")).toBeUndefined(); + }); + + it("对抗:undefined/number/对象名 → 不抛(参数被 void 消费)", () => { + // @ts-expect-error —— 对抗输入类型 + expect(() => phase(undefined)).not.toThrow(); + // @ts-expect-error + expect(() => phase(123)).not.toThrow(); + // @ts-expect-error + expect(() => phase({ a: 1 })).not.toThrow(); + }); + + it("不变式:phase 无累积状态——多次调用彼此独立", () => { + for (let i = 0; i < 50; i++) { + expect(phase(`p${i}`)).toBeUndefined(); + } + }); +}); + +// ============================================================================ +// T12 subagent —— isolatedSubagentScope(等价类 + 边界值 + 决策表 + 对抗 + 不变式) +// ============================================================================ + +describe("T12 isolatedSubagentScope —— 作用域隔离(等价类·边界值·决策表·对抗)", () => { + // ---- 等价类 ---- + it("有效类:单段 scope → subagent.", () => { + expect(isolatedSubagentScope("compile")).toBe("subagent.compile"); + expect(isolatedSubagentScope("probe")).toBe("subagent.probe"); + }); + + it("有效类:多段 scope → subagent.", () => { + expect(isolatedSubagentScope("main.task.deep")).toBe( + "subagent.main.task.deep", + ); + }); + + // ---- 边界值 ---- + it("边界:undefined → 仅根 subagent", () => { + expect(isolatedSubagentScope(undefined)).toBe(SUBAGENT_SCOPE_ROOT); + }); + + it("边界:空串 → 仅根 subagent", () => { + expect(isolatedSubagentScope("")).toBe(SUBAGENT_SCOPE_ROOT); + }); + + it("边界:纯点串 '.' / '..' / '...' → 滤空段后仅根", () => { + expect(isolatedSubagentScope(".")).toBe(SUBAGENT_SCOPE_ROOT); + expect(isolatedSubagentScope("..")).toBe(SUBAGENT_SCOPE_ROOT); + expect(isolatedSubagentScope("...")).toBe(SUBAGENT_SCOPE_ROOT); + }); + + it("边界:首尾点 '.b' / 'a.' → 滤空段后 subagent.b / subagent.a", () => { + expect(isolatedSubagentScope(".b")).toBe("subagent.b"); + expect(isolatedSubagentScope("a.")).toBe("subagent.a"); + }); + + it("边界:双点段 'a..b' → 滤空段后 subagent.a.b", () => { + expect(isolatedSubagentScope("a..b")).toBe("subagent.a.b"); + }); + + // ---- 决策表 ---- + const cases: Array<[string | undefined, string]> = [ + [undefined, "subagent"], + ["", "subagent"], + ["x", "subagent.x"], + ["x.y", "subagent.x.y"], + [" x ", "subagent. x "], // 空格非空段,按 length>0 保留(契约:不 trim) + [".x.y.", "subagent.x.y"], + ]; + for (const [input, expected] of cases) { + it(`决策表:isolatedSubagentScope(${JSON.stringify(input)}) === "${expected}"`, () => { + expect(isolatedSubagentScope(input)).toBe(expected); + }); + } + + // ---- 不变式:结果恒以 SUBAGENT_SCOPE_ROOT 为段前缀 ---- + it("不变式:任何输入的输出恒以 'subagent' 为首段(隔离根)", () => { + const inputs: Array = [ + undefined, + "", + ".", + "a", + "a.b.c", + ".x.", + "..", + "subagent", // 即使输入本身就是根名,输出仍是根 + ]; + for (const s of inputs) { + const out = isolatedSubagentScope(s); + expect(out === SUBAGENT_SCOPE_ROOT || out.startsWith(SUBAGENT_SCOPE_ROOT + ".")).toBe(true); + } + }); + + // ---- 对抗 ---- + it("对抗:超长 scope 不抛,正常前缀化", () => { + const big = "seg".repeat(1000); + const out = isolatedSubagentScope(big); + expect(out).toBe(`${SUBAGENT_SCOPE_ROOT}.${big}`); + expect(out.length).toBe(SUBAGENT_SCOPE_ROOT.length + 1 + big.length); + }); + + // ---- 元蜕变:append 两次 = replay 等价(幂等:对已隔离 scope 再隔离不变)---- + it("元蜕变/幂等:对已隔离的 scope 再隔离 === 原值(幂等)", () => { + const once = isolatedSubagentScope("main.compile"); + const twice = isolatedSubagentScope(once); + // once = "subagent.main.compile";再隔离按段切,前缀 subagent → "subagent.subagent.main.compile" + // 即幂等性不成立(前缀会叠加),这恰好证明隔离是"挂根"而非"归一到根"。 + // 文档化此非幂等性:每次 isolatedSubagentScope 都重新挂根。 + expect(twice).toBe("subagent.subagent.main.compile"); + expect(twice.startsWith(SUBAGENT_SCOPE_ROOT)).toBe(true); + }); +}); + +// ============================================================================ +// T12 subagent —— InlineSubagentProvider(等价类 + 边界值 + 决策表 + 状态转换 + 对抗) +// ============================================================================ + +describe("T12 InlineSubagentProvider —— spawn-in-process(等价类·边界值·决策表)", () => { + // ---- 等价类 ---- + it("有效类:handler 返回值透传,scope 隔离派生", async () => { + let capturedScope = ""; + const provider = new InlineSubagentProvider(async (prompt, opts) => { + capturedScope = opts?.scope ?? ""; + return `echo:${prompt}`; + }); + const r = await provider.spawn("hello", { scope: "probe" }); + expect(r.ok).toBe(true); + expect(r.value).toBe("echo:hello"); + expect(r.scope).toBe("subagent.probe"); + expect(capturedScope).toBe("subagent.probe"); + }); + + it("有效类:缺省 id === INLINE_SUBAGENT_ID", () => { + const p = new InlineSubagentProvider(async () => 0); + expect(p.id).toBe(INLINE_SUBAGENT_ID); + expect(INLINE_SUBAGENT_ID).toBe("inline-subagent"); + }); + + it("有效类:显式 id 透传", () => { + const p = new InlineSubagentProvider(async () => 0, "custom-id"); + expect(p.id).toBe("custom-id"); + }); + + // ---- 边界值 ---- + it("边界:opts 缺省 → scope 退化为根 subagent,handler opts.scope=根", async () => { + let cap = ""; + const p = new InlineSubagentProvider(async (_prompt, opts) => { + cap = opts?.scope ?? ""; + return "v"; + }); + const r = await p.spawn("p"); + expect(r.ok).toBe(true); + expect(r.scope).toBe(SUBAGENT_SCOPE_ROOT); + expect(cap).toBe(SUBAGENT_SCOPE_ROOT); + }); + + it("边界:scope=空串 → scope 退化为根", async () => { + const p = new InlineSubagentProvider(async () => "v"); + const r = await p.spawn("p", { scope: "" }); + expect(r.scope).toBe(SUBAGENT_SCOPE_ROOT); + }); + + it("边界:handler 返回 undefined → ok:true, value=undefined", async () => { + const p = new InlineSubagentProvider(async () => undefined); + const r = await p.spawn("p"); + expect(r.ok).toBe(true); + expect(r.value).toBeUndefined(); + }); + + it("边界:handler 返回 null → ok:true, value=null(与 fail 的 null 区分靠 ok 字段)", async () => { + const p = new InlineSubagentProvider(async () => null); + const r = await p.spawn("p"); + expect(r.ok).toBe(true); + expect(r.value).toBe(null); + }); + + it("边界:空 prompt → handler 仍收空串", async () => { + let got = "__unset__"; + const p = new InlineSubagentProvider(async (prompt) => { + got = prompt; + return "ok"; + }); + await p.spawn(""); + expect(got).toBe(""); + }); + + // ---- 决策表:timeoutMs × handler 行为 ---- + it("决策表:handler 正常 + 无 timeout → ok:true", async () => { + const p = new InlineSubagentProvider(async () => "done"); + const r = await p.spawn("p"); + expect(r.ok).toBe(true); + expect(r.error).toBeUndefined(); + }); + + it("决策表:handler 正常 + timeoutMs 大于耗时 → ok:true(不误杀)", async () => { + const p = new InlineSubagentProvider(async () => { + await tick(10); + return "done"; + }); + const r = await p.spawn("p", { timeoutMs: 200 }); + expect(r.ok).toBe(true); + expect(r.value).toBe("done"); + }); + + it("决策表:handler 慢 + timeoutMs 小 → ok:false, error 含 timeout, fail-closed", async () => { + const p = new InlineSubagentProvider(async () => { + await tick(200); + return "never"; + }); + const r = await p.spawn("p", { timeoutMs: 30 }); + expect(r.ok).toBe(false); + expect(r.value).toBeUndefined(); + expect(r.error).toContain("timeout"); + expect(r.scope.startsWith(SUBAGENT_SCOPE_ROOT)).toBe(true); + }); + + it("决策表:handler 抛 Error → ok:false, error=message, fail-closed", async () => { + const p = new InlineSubagentProvider(async () => { + throw new Error("handler boom"); + }); + const r = await p.spawn("p"); + expect(r.ok).toBe(false); + expect(r.error).toBe("handler boom"); + expect(r.value).toBeUndefined(); + expect(r.scope.startsWith(SUBAGENT_SCOPE_ROOT)).toBe(true); + }); + + it("决策表:handler 抛非 Error(裸串/对象)→ ok:false, error=String(e)", async () => { + const pStr = new InlineSubagentProvider(async () => { + throw "raw string"; + }); + const rStr = await pStr.spawn("p"); + expect(rStr.ok).toBe(false); + expect(rStr.error).toBe("raw string"); + + const pObj = new InlineSubagentProvider(async () => { + throw { code: 7 }; + }); + const rObj = await pObj.spawn("p"); + expect(rObj.ok).toBe(false); + expect(rObj.error).toBe(String({ code: 7 })); + }); + + // ---- 边界值:timeoutMs 非法值(不计时)---- + it("边界:timeoutMs=0 → 不计时(handler 完成 ok:true)", async () => { + const p = new InlineSubagentProvider(async () => { + await tick(40); + return "ok"; + }); + const r = await p.spawn("p", { timeoutMs: 0 }); + expect(r.ok).toBe(true); + expect(r.value).toBe("ok"); + }); + + it("边界:timeoutMs 负值 → 不计时", async () => { + const p = new InlineSubagentProvider(async () => { + await tick(40); + return "ok"; + }); + const r = await p.spawn("p", { timeoutMs: -5 }); + expect(r.ok).toBe(true); + expect(r.value).toBe("ok"); + }); + + it("边界:timeoutMs=NaN → 不限时(Number.isFinite 拦截)", async () => { + const p = new InlineSubagentProvider(async () => { + await tick(40); + return "ok"; + }); + const r = await p.spawn("p", { timeoutMs: NaN }); + expect(r.ok).toBe(true); + expect(r.value).toBe("ok"); + }); + + it("边界:timeoutMs=Infinity → 不限时(非有限)", async () => { + const p = new InlineSubagentProvider(async () => { + await tick(40); + return "ok"; + }); + const r = await p.spawn("p", { timeoutMs: Infinity }); + expect(r.ok).toBe(true); + expect(r.value).toBe("ok"); + }); + + // ---- 状态转换:spawn 内部状态(INIT→RUNNING→{DONE|TIMEOUT|FAILED})---- + describe("状态转换:spawn 内部状态机(INIT→RUNNING→DONE/TIMEOUT/FAILED)", () => { + it("迁移:RUNNING→DONE,结果 ok=true,error 缺省", async () => { + const p = new InlineSubagentProvider(async () => "done"); + const r = await p.spawn("p"); + expect(r.ok === true && r.error === undefined).toBe(true); + }); + + it("迁移:RUNNING→TIMEOUT,error 含 timeout 串,value 缺省", async () => { + const p = new InlineSubagentProvider(async () => { + await tick(300); + return "x"; + }); + const r = await p.spawn("p", { timeoutMs: 20 }); + expect(r.ok === false && typeof r.error === "string" && r.error!.includes("timeout")).toBe(true); + expect(r.value).toBeUndefined(); + }); + + it("迁移:RUNNING→FAILED,error=handler 抛错串,value 缺省", async () => { + const p = new InlineSubagentProvider(async () => { + throw new Error("fail"); + }); + const r = await p.spawn("p"); + expect(r.ok === false && r.error === "fail").toBe(true); + expect(r.value).toBeUndefined(); + }); + + it("重入:同一 provider 可被并发 spawn 多次(无内部可变状态耦合)", async () => { + const p = new InlineSubagentProvider(async (prompt) => { + await tick(10); + return `r:${prompt}`; + }); + const rs = await Promise.all([ + p.spawn("a", { scope: "sa" }), + p.spawn("b", { scope: "sb" }), + p.spawn("c", { scope: "sc" }), + ]); + expect(rs.map((x) => x.value)).toEqual(["r:a", "r:b", "r:c"]); + expect(rs.map((x) => x.scope)).toEqual([ + "subagent.sa", + "subagent.sb", + "subagent.sc", + ]); + }); + + it("不可达状态:ok=true 时不应携带 error(互斥)", async () => { + const p = new InlineSubagentProvider(async () => "v"); + const r = await p.spawn("p"); + expect(r.ok === true && r.error === undefined).toBe(true); + }); + it("不可达状态:ok=false 时不应携带 value(互斥)", async () => { + const p = new InlineSubagentProvider(async () => { + throw new Error("x"); + }); + const r = await p.spawn("p"); + expect(r.ok === false && r.value === undefined).toBe(true); + }); + }); + + // ---- 对抗 ---- + it("对抗:handler 返回循环引用对象 → ok:true(不深拷贝,按引用透传)", async () => { + const circular: Record = { self: null }; + circular.self = circular; + const p = new InlineSubagentProvider(async () => circular); + const r = await p.spawn("p"); + expect(r.ok).toBe(true); + expect(r.value).toBe(circular); + expect((r.value as Record).self).toBe(r.value); + }); + + it("对抗:handler 返回巨大数组 → ok:true 透传", async () => { + const big = Array.from({ length: 10000 }, (_, i) => i); + const p = new InlineSubagentProvider(async () => big); + const r = await p.spawn("p"); + expect(r.ok).toBe(true); + expect((r.value as number[]).length).toBe(10000); + }); + + it("对抗:prompt 含 unicode/控制字符 → handler 原样收", async () => { + let got = ""; + const p = new InlineSubagentProvider(async (prompt) => { + got = prompt; + return "ok"; + }); + await p.spawn("hello世界😀"); + expect(got).toBe("hello世界😀"); + }); + + // ---- 不变式:spawn 绝不 reject ---- + it("不变式/fail-closed:spawn 绝不 reject(超时/抛错均转 ok:false)", async () => { + const slow = new InlineSubagentProvider(async () => { + await tick(200); + return "x"; + }); + const throwing = new InlineSubagentProvider(async () => { + throw new Error("e"); + }); + const rt = slow.spawn("p", { timeoutMs: 10 }); + const rh = throwing.spawn("p"); + expect(typeof rt.then).toBe("function"); + expect(typeof rh.then).toBe("function"); + expect(await rt).toMatchObject({ ok: false }); + expect(await rh).toMatchObject({ ok: false }); + }); + + // ---- 不变式:超时定时器被清理(无句柄泄漏)---- + it("不变式:超时后定时器被 clearTimeout(finally 清理,无泄漏)", async () => { + // 用 spy 计时器不可行(runWithTimeout 用全局 setTimeout),改用行为推断: + // 超时触发后,handler 仍在跑(未取消 handler promise),但 spawn 已 resolve。 + // 重点是 finally 不抛、不挂起。 + const p = new InlineSubagentProvider(async () => { + await tick(100); + return "late"; + }); + const r = await p.spawn("p", { timeoutMs: 10 }); + expect(r.ok).toBe(false); + // 等待 handler 自然完成,证明 timer 已清理、无悬挂 reject 逃逸 + await tick(120); + expect(r.ok).toBe(false); + }); +}); + +// ============================================================================ +// T12 subagent —— SubagentRegistry(等价类 + 状态转换 + 对抗 + 元蜕变) +// ============================================================================ + +describe("T12 SubagentRegistry —— 注册/解析(等价类·状态转换·对抗·元蜕变)", () => { + // ---- 等价类 ---- + it("有效类:register → resolve 返回同一 provider 实例", () => { + const reg = new SubagentRegistry(); + const p: SubagentProvider = new InlineSubagentProvider(async () => 0, "my-sub"); + const disp = reg.register(p); + expect(reg.resolve("my-sub")).toBe(p); + expect(disp).toBeInstanceOf(Function); + }); + + it("有效类:list() 返回按插入序的只读快照", () => { + const reg = new SubagentRegistry(); + const p1: SubagentProvider = new InlineSubagentProvider(async () => 0, "a"); + const p2: SubagentProvider = new InlineSubagentProvider(async () => 0, "b"); + reg.register(p1); + reg.register(p2); + expect(reg.list()).toEqual([p1, p2]); + }); + + // ---- 边界值 ---- + it("边界:空注册表 list() → 空数组(非 undefined)", () => { + const reg = new SubagentRegistry(); + expect(reg.list()).toEqual([]); + }); + + it("边界:空注册表 resolve(任意 id) → 抛 fail-closed", () => { + const reg = new SubagentRegistry(); + expect(() => reg.resolve("anything")).toThrow(/fail-closed/); + expect(() => reg.resolve("")).toThrow(/fail-closed/); + }); + + // ---- fail-closed 不变式 ---- + it("不变式/fail-closed:未知 id 抛错,error 含 id + 'fail-closed'", () => { + const reg = new SubagentRegistry(); + const id = "no-such-id"; + expect(() => reg.resolve(id)).toThrow(id); + expect(() => reg.resolve(id)).toThrow(/fail-closed/); + }); + + it("对抗:resolve(null) → 抛 fail-closed(不静默返回)", () => { + const reg = new SubagentRegistry(); + // @ts-expect-error —— 对抗输入 + expect(() => reg.resolve(null)).toThrow(/fail-closed/); + // @ts-expect-error + expect(() => reg.resolve(undefined)).toThrow(/fail-closed/); + }); + + // ---- 状态转换:empty → registered → disposed(+ 重入/override)---- + describe("状态转换:empty → registered → disposed(重入·override)", () => { + it("迁移:empty → registered(resolve 可用)→ disposed(resolve 再抛)", () => { + const reg = new SubagentRegistry(); + const p: SubagentProvider = new InlineSubagentProvider(async () => 0, "k"); + const disp = reg.register(p); + + expect(reg.resolve("k")).toBe(p); // registered + + disp(); // → disposed + expect(() => reg.resolve("k")).toThrow(/fail-closed/); + expect(reg.list()).toEqual([]); + }); + + it("重入:disposer 幂等——再调 no-op,不抛、不删他人", () => { + const reg = new SubagentRegistry(); + const p: SubagentProvider = new InlineSubagentProvider(async () => 0, "k"); + const disp = reg.register(p); + disp(); + expect(() => disp()).not.toThrow(); + disp(); + expect(reg.list()).toEqual([]); + }); + + it("override 安全:同 id 重新注册新实例,旧 disposer 失效(不删新)", () => { + const reg = new SubagentRegistry(); + const p1: SubagentProvider = new InlineSubagentProvider(async () => 1, "k"); + const p2: SubagentProvider = new InlineSubagentProvider(async () => 2, "k"); + const d1 = reg.register(p1); + reg.register(p2); // override + expect(reg.resolve("k")).toBe(p2); // 新实例上位 + expect(reg.list()).toEqual([p2]); // 同 id 不重复 + + d1(); // 旧 disposer——仍指 p1,但当前是 p2 → 不删 + expect(reg.resolve("k")).toBe(p2); // 新实例仍在 + expect(reg.list()).toEqual([p2]); + }); + + it("override:旧 disposer 失效后,仍可注册第三个同 id 实例", () => { + const reg = new SubagentRegistry(); + const p1: SubagentProvider = new InlineSubagentProvider(async () => 1, "k"); + const p2: SubagentProvider = new InlineSubagentProvider(async () => 2, "k"); + const p3: SubagentProvider = new InlineSubagentProvider(async () => 3, "k"); + reg.register(p1); + const d2 = reg.register(p2); + reg.register(p3); + expect(reg.resolve("k")).toBe(p3); + d2(); // d2 指 p2,当前 p3 → 不删 + expect(reg.resolve("k")).toBe(p3); + }); + + it("不可达状态:dispose 后再 resolve 不可达 registered(恒抛)", () => { + const reg = new SubagentRegistry(); + const p: SubagentProvider = new InlineSubagentProvider(async () => 0, "k"); + const d = reg.register(p); + d(); + for (let i = 0; i < 3; i++) { + expect(() => reg.resolve("k")).toThrow(/fail-closed/); + } + }); + + it("并发重入:register→dispose→register 同 id 不留脏状态", () => { + const reg = new SubagentRegistry(); + const mk = (v: number): SubagentProvider => + new InlineSubagentProvider(async () => v, "k"); + for (let i = 0; i < 5; i++) { + const d = reg.register(mk(i)); + expect(reg.resolve("k")).toBeDefined(); + d(); + expect(() => reg.resolve("k")).toThrow(/fail-closed/); + } + expect(reg.list()).toEqual([]); + }); + }); + + // ---- list() 只读不变式 ---- + it("不变式:list() 返回的快照修改不影响内部注册表(防御性拷贝)", () => { + const reg = new SubagentRegistry(); + const p: SubagentProvider = new InlineSubagentProvider(async () => 0, "k"); + reg.register(p); + const snap = reg.list() as SubagentProvider[]; + // 篡改快照 + snap.length = 0; + snap.push(new InlineSubagentProvider(async () => 0, "evil")); + // 内部不受影响 + expect(reg.resolve("k")).toBe(p); + expect(reg.list()).toEqual([p]); + }); + + // ---- 元蜕变:register→dispose→register 同实例 = 单次 register 等价 ---- + it("元蜕变:register→dispose→register(p) 后 resolve(p) ≡ 直接 register(p) 后 resolve", () => { + const reg = new SubagentRegistry(); + const p: SubagentProvider = new InlineSubagentProvider(async () => 0, "k"); + const d = reg.register(p); + d(); + const d2 = reg.register(p); + // 状态等价于从未 dispose + expect(reg.resolve("k")).toBe(p); + expect(reg.list()).toEqual([p]); + d2(); + }); +}); + +// ============================================================================ +// T12 subagent —— 作用域隔离不变式(靠真实 T07 PbaEventBus) +// ============================================================================ + +describe("T12 subagent —— 作用域隔离不变式(靠真实 PbaEventBus·ScopeKey)", () => { + it("不变式⑥:子 agent 事件不达主 agent;主 agent 事件不下渗子 agent", async () => { + const bus = new PbaEventBus(); + + let mainGot = 0; + bus.on("task:done", () => mainGot++, "main"); + + let subGot = 0; + bus.on("task:done", () => subGot++, SUBAGENT_SCOPE_ROOT); + + const childScope = isolatedSubagentScope("main.compile"); + expect(childScope).toBe(`${SUBAGENT_SCOPE_ROOT}.main.compile`); + + // 子 agent emit → 主 agent 不收(不串),观测层收 + bus.emit("task:done", {}, childScope); + expect(mainGot).toBe(0); + expect(subGot).toBe(1); + + // 主 agent emit → 子 agent 作用域不收(不下渗) + let subGotFromMain = 0; + bus.on("task:done", () => subGotFromMain++, childScope); + bus.emit("task:done", {}, "main"); + expect(subGotFromMain).toBe(0); + }); + + it("不变式:两个不同子 agent 作用域互不串(旁支不冒泡)", () => { + const bus = new PbaEventBus(); + const sa = isolatedSubagentScope("compile"); + const sb = isolatedSubagentScope("probe"); + let aGot = 0; + let bGot = 0; + bus.on("task:done", () => aGot++, sa); + bus.on("task:done", () => bGot++, sb); + + bus.emit("task:done", {}, sa); + expect(aGot).toBe(1); + expect(bGot).toBe(0); // 旁支不收 + + bus.emit("task:done", {}, sb); + expect(aGot).toBe(1); + expect(bGot).toBe(1); + }); + + it("不变式:子 agent emit 到根 subagent 仅达根监听 + global,不达主 agent", () => { + const bus = new PbaEventBus(); + let mainGot = 0; + let rootGot = 0; + let globalGot = 0; + bus.on("task:done", () => mainGot++, "main"); + bus.on("task:done", () => rootGot++, SUBAGENT_SCOPE_ROOT); + bus.on("task:done", () => globalGot++); // global 监听收所有 + + bus.emit("task:done", {}, SUBAGENT_SCOPE_ROOT); + expect(mainGot).toBe(0); + expect(rootGot).toBe(1); + expect(globalGot).toBe(1); + }); + + it("不变式:global emit 不下渗到子 agent 作用域", () => { + const bus = new PbaEventBus(); + const child = isolatedSubagentScope("x"); + let childGot = 0; + let globalGot = 0; + bus.on("task:done", () => childGot++, child); + bus.on("task:done", () => globalGot++); + + bus.emit("task:done", {}); // global emit + expect(childGot).toBe(0); + expect(globalGot).toBe(1); + }); + + it("集成:InlineSubagentProvider 派生的 scope 经 bus 冒泡仅达 subagent 根监听", async () => { + const bus = new PbaEventBus(); + const observed: string[] = []; + bus.on("task:done", (a) => observed.push(`main:${JSON.stringify(a)}`), "main"); + bus.on("task:done", (a) => observed.push(`sub:${JSON.stringify(a)}`), SUBAGENT_SCOPE_ROOT); + + const p = new InlineSubagentProvider(async (_prompt, opts) => { + bus.emit("task:done", { scope: opts?.scope }, opts?.scope); + return "ok"; + }); + const r = await p.spawn("work", { scope: "compile" }); + expect(r.ok).toBe(true); + expect(r.scope).toBe("subagent.compile"); + // 主 agent 不收,subagent 根观测层收 + expect(observed).toEqual(['sub:{"scope":"subagent.compile"}']); + }); +}); + +// ============================================================================ +// T12 变异测试 —— 植入 seeded bug,断言每个被某条测试杀死 +// ============================================================================ +// +// 方法:内联带 bug 的逻辑副本(非包装真实代码),在测试内运行 buggy 副本, +// 断言其输出 != 正确输出(即:若把"断言正确行为"的测试跑在 buggy 副本上会 FAIL +// → 该 bug 被 kill)。最后真实代码(未植入 bug)全过。 +// +// 文档化每个植入 bug + 杀它的测试: + +describe("T12 变异测试 —— 植入 seeded bug 被 kill", () => { + // ---- 植入 bug #1:parallel rejected 位落 undefined 而非 null(错误默认值)---- + // 真实:s.status === "fulfilled" ? s.value : null + // 变异:s.status === "fulfilled" ? s.value : undefined + async function parallelBuggy_rejectedToUndefined( + thunks: ReadonlyArray<() => Promise>, + ): Promise { + const settled = await Promise.allSettled(thunks.map((t) => t())); + return settled.map((s) => + s.status === "fulfilled" ? s.value : undefined, // <-- bug: null → undefined + ); + } + + it("bug #1 killed:rejected 位应为 null,buggy 给 undefined → 严格相等断言会失败", async () => { + const buggy = await parallelBuggy_rejectedToUndefined([ + () => Promise.resolve("a"), + () => Promise.reject(new Error("boom")), + () => Promise.resolve("c"), + ]); + // 证明 bug 存在:buggy 给 undefined(!== null) + expect(buggy[1]).not.toBe(null); + expect(buggy[1]).toBeUndefined(); + // 对照真实:给 null + const real = await parallel([ + () => Promise.resolve("a"), + () => Promise.reject(new Error("boom")), + () => Promise.resolve("c"), + ]); + expect(real[1]).toBe(null); + // 杀它的测试 = 决策表 [fulfilled,rejected,fulfilled]→[v,null,v](toEqual 严格区分 null/undefined) + expect(buggy).not.toEqual(["a", null, "c"]); + expect(real).toEqual(["a", null, "c"]); + }); + + // ---- 植入 bug #2:isolatedSubagentScope 滤空段条件 s.length>0 → s.length>=0(< → <=,保留空段)---- + // 真实:filter((s) => s.length > 0) + // 变异:filter((s) => s.length >= 0) —— 永真,保留空段 + function isolatedSubagentScopeBuggy_keepEmpty(scope: string | undefined): string { + const segs = (scope ?? "").split(".").filter((s) => s.length >= 0); // <-- bug: > → >= + return segs.length === 0 + ? SUBAGENT_SCOPE_ROOT + : `${SUBAGENT_SCOPE_ROOT}.${segs.join(".")}`; + } + + it("bug #2 killed:'.b' 应滤空段得 subagent.b,buggy 保留空段得 subagent..b", () => { + // 真实:".b" → ["", "b"] 滤空 → ["b"] → "subagent.b" + expect(isolatedSubagentScope(".b")).toBe("subagent.b"); + // buggy:保留 "" → ["", "b"] → "subagent..b" + const buggy = isolatedSubagentScopeBuggy_keepEmpty(".b"); + expect(buggy).toBe("subagent..b"); // 双点 = bug 证据 + expect(buggy).not.toBe("subagent.b"); + // 边界 '.b' 决策表条目会失败于 buggy + expect(isolatedSubagentScopeBuggy_keepEmpty(".")).not.toBe(SUBAGENT_SCOPE_ROOT); + expect(isolatedSubagentScope(".")).toBe(SUBAGENT_SCOPE_ROOT); + }); + + // ---- 植入 bug #3:pipeline stage 抛错后漏 return(不跳后续 stage,短路逻辑反转)---- + // 真实:catch { return; } —— 跳过后续 stage,results[i] 保持 null + // 变异:catch { /* 漏 return */ } —— 继续跑后续 stage,覆盖 null + async function pipelineBuggy_noShortCircuit( + items: ReadonlyArray, + ...stages: Array<(prev: unknown, item: T, i: number) => Promise> + ): Promise { + const results: unknown[] = new Array(items.length).fill(null); + // 简化:单 item 串行(足够暴露 bug) + for (let i = 0; i < items.length; i++) { + let prev: unknown = undefined; + for (const stage of stages) { + try { + prev = await stage(prev, items[i], i); + } catch { + // <-- bug: 漏 return,继续跑后续 stage + } + } + results[i] = stages.length === 0 ? items[i] : prev; + } + return results; + } + + it("bug #3 killed:stage1 抛错后 stage2 不应被调用,buggy 仍调用并覆盖 null", async () => { + const seen: number[] = []; + const stages = [ + async () => { + seen.push(0); + return "s0"; + }, + async () => { + seen.push(1); + throw new Error("s1 boom"); + }, + async () => { + seen.push(2); + return "s2-recovered"; + }, + ]; + + // 真实:stage1 抛错 → 跳 stage2,结果 [null],seen=[0,1] + const real = await pipeline(["a"], ...stages); + expect(real).toEqual([null]); + expect(seen).toEqual([0, 1]); + + // buggy:不短路 → stage2 被调用,seen 含 2,结果非 null + const seenBuggy: number[] = []; + const buggy = await pipelineBuggy_noShortCircuit(["a"], + async () => { seenBuggy.push(0); return "s0"; }, + async () => { seenBuggy.push(1); throw new Error("s1 boom"); }, + async () => { seenBuggy.push(2); return "s2-recovered"; }, + ); + expect(seenBuggy).toEqual([0, 1, 2]); // stage2 被调用 = bug 证据 + expect(buggy).toEqual(["s2-recovered"]); // 非 null = bug 证据 + expect(buggy).not.toEqual([null]); + }); + + // ---- 植入 bug #4(额外,强化):SubagentRegistry.resolve 未知 id 返回 undefined 而非抛(fail-closed 反转)---- + class SubagentRegistryBuggy_noFailClosed { + private readonly providers = new Map(); + register(provider: SubagentProvider): () => void { + this.providers.set(provider.id, provider); + return () => { + if (this.providers.get(provider.id) === provider) { + this.providers.delete(provider.id); + } + }; + } + resolve(id: string): SubagentProvider | undefined { + // <-- bug: 未知 id 返回 undefined(静默),不抛 + return this.providers.get(id); + } + list(): readonly SubagentProvider[] { + return [...this.providers.values()]; + } + } + + it("bug #4 killed:未知 id 应抛 fail-closed,buggy 返回 undefined(误用未配置子代理)", () => { + const real = new SubagentRegistry(); + const buggy = new SubagentRegistryBuggy_noFailClosed(); + // 真实:抛 + expect(() => real.resolve("nope")).toThrow(/fail-closed/); + // buggy:静默返回 undefined + expect(buggy.resolve("nope")).toBeUndefined(); + // 杀它的测试 = fail-closed 不变式断言(toThrow 会失败于 buggy) + }); +}); + +// ============================================================================ +// T12 真实代码回归 —— 全部走真实导出,确认未植入 bug 时全过 +// ============================================================================ + +describe("T12 真实代码回归(未植入 bug,全绿)", () => { + it("parallel + pipeline + phase + subagent 真实路径端到端", async () => { + phase("e2e-phase"); + const reg = new SubagentRegistry(); + const bus = new PbaEventBus(); + const events: string[] = []; + bus.on("task:done", () => events.push("sub"), SUBAGENT_SCOPE_ROOT); + + const p = new InlineSubagentProvider(async (prompt, opts) => { + bus.emit("task:done", {}, opts?.scope); + return `done:${prompt}`; + }, "e2e-sub"); + reg.register(p); + + // parallel:3 子任务并发,1 失败落 null + const out = await parallel([ + () => reg.resolve("e2e-sub").spawn("a", { scope: "a" }).then((r) => r.value), + () => Promise.reject(new Error("x")), + () => reg.resolve("e2e-sub").spawn("c", { scope: "c" }).then((r) => r.value), + ]); + expect(out).toEqual(["done:a", null, "done:c"]); + + // pipeline:单 item 过 2 stage + const piped = await pipeline( + ["img"], + async (_prev, item) => `edit:${item}`, + async (prev) => `flash:${prev}`, + ); + expect(piped).toEqual(["flash:edit:img"]); + + // 子 agent 事件冒泡到 subagent 根(2 次:a + c) + expect(events.filter((e) => e === "sub")).toHaveLength(2); + }); + + it("不变式回归:spawn 的 scope 恒以 subagent 为段前缀", async () => { + const p = new InlineSubagentProvider(async () => 0); + for (const s of [undefined, "", "x", "x.y", ".b", "a..b"]) { + const r = await p.spawn("p", s === undefined ? undefined : { scope: s }); + expect( + r.scope === SUBAGENT_SCOPE_ROOT || + r.scope.startsWith(SUBAGENT_SCOPE_ROOT + "."), + ).toBe(true); + } + }); +}); diff --git a/tsconfig.realpi.json b/tsconfig.realpi.json new file mode 100644 index 0000000..64e2cda --- /dev/null +++ b/tsconfig.realpi.json @@ -0,0 +1,11 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "paths": { + "@earendil-works/pi-ai": ["../pi/packages/ai/src/index.ts"], + "@earendil-works/pi-coding-agent": ["../pi/packages/coding-agent/src/index.ts"], + "@earendil-works/pi-agent-core": ["../pi/packages/agent/src/index.ts"] + } + }, + "include": ["src/**/*.ts", "scripts/**/*.ts"] +}