lemma-agent 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +121 -2
  2. package/bin/lemma.mjs +42 -0
  3. package/dist/acceptance.js +63 -0
  4. package/dist/admin.js +1482 -0
  5. package/dist/agents.js +245 -0
  6. package/dist/api-member.js +537 -0
  7. package/dist/app.js +161 -0
  8. package/dist/board.js +185 -0
  9. package/dist/business-tools.js +153 -0
  10. package/dist/change-ops.js +91 -0
  11. package/dist/changes.js +46 -0
  12. package/dist/cli-runner.js +106 -0
  13. package/dist/code-tools.js +396 -0
  14. package/dist/coding-benchmark-fixtures.js +1049 -0
  15. package/dist/coding-benchmark-suite.js +1252 -0
  16. package/dist/collaboration-benchmark.js +349 -0
  17. package/dist/config.js +392 -0
  18. package/dist/context-benchmark.js +91 -0
  19. package/dist/conventions.js +282 -0
  20. package/dist/conversation.js +39 -0
  21. package/dist/credentials.js +44 -0
  22. package/dist/deliverables.js +43 -0
  23. package/dist/digest.js +129 -0
  24. package/dist/dispatch.js +801 -0
  25. package/dist/execution-settings.js +24 -0
  26. package/dist/git-workbench.js +800 -0
  27. package/dist/git.js +149 -0
  28. package/dist/integration-git.js +108 -0
  29. package/dist/integrations.js +557 -0
  30. package/dist/jobs.js +100 -0
  31. package/dist/lead.js +263 -0
  32. package/dist/learning.js +36 -0
  33. package/dist/main.js +1402 -0
  34. package/dist/mcp-settings.js +45 -0
  35. package/dist/mcp-tools.js +102 -0
  36. package/dist/member-settings.js +245 -0
  37. package/dist/model-selection.js +48 -0
  38. package/dist/models.js +145 -0
  39. package/dist/native-selectors.js +45 -0
  40. package/dist/native-terminal-components.js +100 -0
  41. package/dist/ood-benchmark.js +660 -0
  42. package/dist/operations.js +21 -0
  43. package/dist/printer.js +113 -0
  44. package/dist/repair.js +102 -0
  45. package/dist/resources.js +31 -0
  46. package/dist/result-summary.js +8 -0
  47. package/dist/results.js +41 -0
  48. package/dist/scope.js +114 -0
  49. package/dist/sessions.js +95 -0
  50. package/dist/settings.js +30 -0
  51. package/dist/task-commands.js +37 -0
  52. package/dist/task-lifecycle.js +49 -0
  53. package/dist/task-readiness.js +22 -0
  54. package/dist/task-recovery.js +116 -0
  55. package/dist/task-review.js +70 -0
  56. package/dist/task-workflow.js +424 -0
  57. package/dist/terminal-layout.js +27 -0
  58. package/dist/terminal-state.js +145 -0
  59. package/dist/terminal.js +800 -0
  60. package/dist/tool-settings.js +111 -0
  61. package/dist/tools.js +1043 -0
  62. package/dist/ux-telemetry.js +127 -0
  63. package/dist/view.js +114 -0
  64. package/package.json +79 -6
  65. package/web/index.html +136 -0
  66. package/web/js/conversations.js +312 -0
  67. package/web/js/dag.js +495 -0
  68. package/web/js/drawer.js +139 -0
  69. package/web/js/editors.js +424 -0
  70. package/web/js/gitlens.js +844 -0
  71. package/web/js/main.js +152 -0
  72. package/web/js/sankey.js +476 -0
  73. package/web/js/store.js +291 -0
  74. package/web/js/ticket.js +151 -0
  75. package/web/js/timeline.js +183 -0
  76. package/web/js/topology.js +454 -0
  77. package/web/js/util.js +232 -0
  78. package/web/js/views.js +1496 -0
  79. package/web/style.css +5299 -0
@@ -0,0 +1,660 @@
1
+ // OOD 外部仓库基准抽样与评测引擎(对应评测规范维度一:外部仓库盲测通过率、回归破坏率、Diff Minimalism):
2
+ // 1. 支持加载 SWE-bench / Multi-SWE-bench 风格 JSON / JSONL 清单;
3
+ // 2. 按改动跨度映射至 Tier 1–3,使用可复现伪随机数发生器(mulberry32)分层均匀抽样(默认 30–50 题);
4
+ // 3. 严格冻结系统 Prompt 与任务原文(verbatim problem_statement),禁止针对特定外部样本微调 Prompt;
5
+ // 4. 在独立 Git Worktree / 克隆隔离环境中对比 single 与 lemma-adaptive(等预算),并在结束后打上 test_patch
6
+ // 运行 fail_to_pass 与 pass_to_pass 验证,输出 OOD Pass Rate、Regression Rate、Diff Minimalism 与七维归因。
7
+ import { execFileSync, spawnSync } from "node:child_process";
8
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { dirname, join } from "node:path";
11
+ import { performance } from "node:perf_hooks";
12
+ import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
13
+ import { openApp } from "./app.js";
14
+ import { createMemberTools, memberProvider } from "./api-member.js";
15
+ import { Board } from "./board.js";
16
+ import { applyChange } from "./change-ops.js";
17
+ import { normalizeConfig } from "./config.js";
18
+ import { resolveOrchestratorKey } from "./models.js";
19
+ import { analyzeConversationMessages, classifyFailureAttribution, pickLatestActiveChange, } from "./coding-benchmark-suite.js";
20
+ const DEFAULT_OOD_BUDGET = {
21
+ 1: { maxRequests: 16, timeoutMs: 120_000, blindWaitMs: 0 },
22
+ 2: { maxRequests: 28, timeoutMs: 180_000, blindWaitMs: 30_000 },
23
+ 3: { maxRequests: 42, timeoutMs: 240_000, blindWaitMs: 30_000 },
24
+ };
25
+ /** 确定性 32-bit 伪随机数发生器(用于可复现外部基准分层抽样) */
26
+ function mulberry32(seed) {
27
+ let a = seed >>> 0;
28
+ return () => {
29
+ a = (a + 0x6d2b79f5) | 0;
30
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
31
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
32
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
33
+ };
34
+ }
35
+ /** 从 Unified Diff 解析涉及修改的文件列表及净增删行数(+/- 非头行)。 */
36
+ export function extractPatchFilesAndLines(patchText) {
37
+ if (!patchText || !patchText.trim())
38
+ return { files: [], lines: 0 };
39
+ const files = new Set();
40
+ let lines = 0;
41
+ for (const raw of patchText.split(/\r?\n/)) {
42
+ if (raw.startsWith("diff --git ")) {
43
+ const m = raw.match(/^diff --git a\/(.+?) b\/(.+)$/);
44
+ if (m?.[2])
45
+ files.add(m[2].trim());
46
+ continue;
47
+ }
48
+ if (raw.startsWith("+++ ")) {
49
+ const pathPart = raw.slice(4).trim().replace(/^b\//, "");
50
+ if (pathPart && pathPart !== "/dev/null")
51
+ files.add(pathPart);
52
+ continue;
53
+ }
54
+ if (raw.startsWith("--- ") || raw.startsWith("@@"))
55
+ continue;
56
+ if (raw.startsWith("+") || raw.startsWith("-"))
57
+ lines += 1;
58
+ }
59
+ return { files: [...files], lines };
60
+ }
61
+ /** 按修改跨度将外部题目映射为 Lemma Tier 1(单文件)、Tier 2(双文件)或 Tier 3(>=3 文件)。 */
62
+ export function mapOodTier(instance) {
63
+ if (instance.tier_hint === 1 || instance.tier_hint === 2 || instance.tier_hint === 3)
64
+ return instance.tier_hint;
65
+ const explicit = instance.expected_changed_files?.filter(Boolean) ?? [];
66
+ const files = explicit.length ? explicit : extractPatchFilesAndLines(instance.gold_patch).files;
67
+ if (files.length <= 1)
68
+ return 1;
69
+ if (files.length === 2)
70
+ return 2;
71
+ return 3;
72
+ }
73
+ /** 从 JSON / JSONL 清单文件加载外部 SWE-bench / Multi-SWE-bench 题目。 */
74
+ export function loadOodManifest(manifestPath) {
75
+ const raw = readFileSync(manifestPath, "utf8").trim();
76
+ if (!raw)
77
+ return [];
78
+ if (raw.startsWith("[")) {
79
+ const parsed = JSON.parse(raw);
80
+ if (!Array.isArray(parsed))
81
+ throw new Error(`OOD 清单 ${manifestPath} JSON 根节点必须为数组。`);
82
+ return parsed.filter((x) => Boolean(x && typeof x === "object" && typeof x.instance_id === "string"));
83
+ }
84
+ const items = [];
85
+ for (const line of raw.split(/\r?\n/)) {
86
+ const trimmed = line.trim();
87
+ if (!trimmed)
88
+ continue;
89
+ const row = JSON.parse(trimmed);
90
+ if (!row.instance_id || typeof row.problem_statement !== "string") {
91
+ throw new Error(`OOD 清单行缺少 instance_id 或 problem_statement:${trimmed.slice(0, 80)}`);
92
+ }
93
+ items.push(row);
94
+ }
95
+ return items;
96
+ }
97
+ /** 按 Tier 1–3 确定性分层随机抽样 30–50 题(或不超过清单总数)。 */
98
+ export function sampleOodInstances(instances, options = {}) {
99
+ const seed = options.seed ?? 42;
100
+ const targetTiers = options.tiers?.length ? [...new Set(options.tiers)].sort() : [1, 2, 3];
101
+ const buckets = new Map([
102
+ [1, []],
103
+ [2, []],
104
+ [3, []],
105
+ ]);
106
+ for (const inst of instances) {
107
+ const t = mapOodTier(inst);
108
+ if (targetTiers.includes(t))
109
+ buckets.get(t).push(inst);
110
+ }
111
+ const rng = mulberry32(seed);
112
+ const shuffle = (arr) => {
113
+ const copy = [...arr];
114
+ for (let i = copy.length - 1; i > 0; i--) {
115
+ const j = Math.floor(rng() * (i + 1));
116
+ [copy[i], copy[j]] = [copy[j], copy[i]];
117
+ }
118
+ return copy;
119
+ };
120
+ const shuffled = new Map();
121
+ let available = 0;
122
+ for (const t of targetTiers) {
123
+ const s = shuffle(buckets.get(t) ?? []);
124
+ shuffled.set(t, s);
125
+ available += s.length;
126
+ }
127
+ const desired = Math.min(options.count ?? Math.min(30, available), available);
128
+ const picked = [];
129
+ const usedIds = new Set();
130
+ const baseQuota = Math.floor(desired / targetTiers.length);
131
+ for (const t of targetTiers) {
132
+ const list = shuffled.get(t) ?? [];
133
+ for (const item of list.slice(0, baseQuota)) {
134
+ picked.push(item);
135
+ usedIds.add(item.instance_id);
136
+ }
137
+ }
138
+ // 剩余名额按 Tier 轮询补齐,确保某一 Tier 题目偏少时总样本数不缩水
139
+ while (picked.length < desired) {
140
+ let progressed = false;
141
+ for (const t of targetTiers) {
142
+ if (picked.length >= desired)
143
+ break;
144
+ const next = (shuffled.get(t) ?? []).find((x) => !usedIds.has(x.instance_id));
145
+ if (next) {
146
+ picked.push(next);
147
+ usedIds.add(next.instance_id);
148
+ progressed = true;
149
+ }
150
+ }
151
+ if (!progressed)
152
+ break;
153
+ }
154
+ return picked;
155
+ }
156
+ /** 冻结外部 Prompt 原文:严禁添加任何针对特定外部题目或基准集的 Prompt 调整。 */
157
+ export function buildOodTaskPrompt(instance) {
158
+ return instance.problem_statement.trim();
159
+ }
160
+ function runGit(cwd, args, input) {
161
+ const r = spawnSync("git", args, {
162
+ cwd,
163
+ input,
164
+ encoding: "utf8",
165
+ windowsHide: true,
166
+ timeout: 30_000,
167
+ });
168
+ return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
169
+ }
170
+ /** 从本地源码目录或 Git 仓库克隆并切出 base_commit,搭建干净隔离测试仓库。 */
171
+ export function prepareOodWorkspace(instance) {
172
+ const srcRepo = instance.repo_path ?? instance.repo;
173
+ if (!srcRepo || !existsSync(srcRepo)) {
174
+ throw new Error(`样本 ${instance.instance_id} 的本地仓库路径不存在:${srcRepo ?? "(未指定)"}`);
175
+ }
176
+ const root = mkdtempSync(join(tmpdir(), "lemma-ood-"));
177
+ const clone = spawnSync("git", ["clone", "--no-hardlinks", srcRepo, root], {
178
+ encoding: "utf8",
179
+ windowsHide: true,
180
+ timeout: 60_000,
181
+ });
182
+ if (clone.status !== 0) {
183
+ throw new Error(`克隆 OOD 仓库失败(${instance.instance_id}):${clone.stderr ?? clone.stdout}`);
184
+ }
185
+ if (instance.base_commit) {
186
+ const co = runGit(root, ["checkout", "--force", instance.base_commit]);
187
+ if (co.code !== 0)
188
+ throw new Error(`切出 base_commit=${instance.base_commit} 失败:${co.stderr}`);
189
+ }
190
+ runGit(root, ["config", "user.name", "lemma-ood-bench"]);
191
+ runGit(root, ["config", "user.email", "lemma-ood@example.com"]);
192
+ return root;
193
+ }
194
+ /** 统计最终工作区相对 HEAD 的实际增删行数(自动忽略 Lemma 运行期产物),并与 Gold Patch 比较 Diff Minimalism。 */
195
+ export function measureDiffMinimalism(repoDir, goldPatch) {
196
+ const pathspecs = [".", ":(exclude)worktrees", ":(exclude).lemma*", ":(exclude)*.sqlite*"];
197
+ runGit(repoDir, ["add", "-A", "--", ...pathspecs]);
198
+ const stat = runGit(repoDir, ["diff", "--cached", "--numstat", "HEAD", "--", ...pathspecs]);
199
+ let actualLines = 0;
200
+ for (const line of stat.stdout.split(/\r?\n/)) {
201
+ const trimmed = line.trim();
202
+ if (!trimmed)
203
+ continue;
204
+ const [addRaw, delRaw] = trimmed.split(/\s+/);
205
+ const add = addRaw === "-" ? 0 : Number.parseInt(addRaw ?? "0", 10) || 0;
206
+ const del = delRaw === "-" ? 0 : Number.parseInt(delRaw ?? "0", 10) || 0;
207
+ actualLines += add + del;
208
+ }
209
+ runGit(repoDir, ["reset", "HEAD", "--quiet"]);
210
+ const gold = extractPatchFilesAndLines(goldPatch);
211
+ const goldLines = goldPatch && gold.lines > 0 ? gold.lines : null;
212
+ return {
213
+ actualLines,
214
+ goldLines,
215
+ minimalismRatio: goldLines ? Number((actualLines / goldLines).toFixed(3)) : null,
216
+ };
217
+ }
218
+ function runTestSpec(repoDir, spec) {
219
+ const trimmed = spec.trim();
220
+ if (!trimmed)
221
+ return true;
222
+ const tokens = trimmed.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)?.map((t) => t.replace(/^["']|["']$/g, "")) ?? [];
223
+ const hasShellMeta = /[|;&><$`]/.test(trimmed);
224
+ const res = !hasShellMeta && tokens.length > 0
225
+ ? spawnSync(tokens[0], tokens.slice(1), { cwd: repoDir, encoding: "utf8", timeout: 60_000, windowsHide: true })
226
+ : spawnSync(trimmed, { cwd: repoDir, shell: true, encoding: "utf8", timeout: 60_000, windowsHide: true });
227
+ return res.status === 0;
228
+ }
229
+ /** 在成员交卷后应用隐藏 test_patch 并分别验证 fail_to_pass 与 pass_to_pass。 */
230
+ export function runOodVerification(repoDir, instance) {
231
+ if (instance.test_patch && instance.test_patch.trim()) {
232
+ const patch = runGit(repoDir, ["apply", "--whitespace=nowarn", "-"], instance.test_patch);
233
+ if (patch.code !== 0) {
234
+ return {
235
+ failToPassPassed: 0,
236
+ failToPassTotal: instance.fail_to_pass?.length ?? (instance.test_command ? 1 : 0),
237
+ passToPassFailed: instance.pass_to_pass?.length ?? 0,
238
+ passToPassTotal: instance.pass_to_pass?.length ?? 0,
239
+ regressionRate: instance.pass_to_pass?.length ? 1 : 0,
240
+ applyPatchError: patch.stderr.trim() || "test_patch 应用失败",
241
+ };
242
+ }
243
+ }
244
+ const f2pSpecs = instance.fail_to_pass?.length
245
+ ? instance.fail_to_pass
246
+ : instance.test_command
247
+ ? [instance.test_command]
248
+ : [];
249
+ const p2pSpecs = instance.pass_to_pass ?? [];
250
+ let failToPassPassed = 0;
251
+ for (const spec of f2pSpecs) {
252
+ if (runTestSpec(repoDir, spec))
253
+ failToPassPassed += 1;
254
+ }
255
+ let passToPassFailed = 0;
256
+ for (const spec of p2pSpecs) {
257
+ if (!runTestSpec(repoDir, spec))
258
+ passToPassFailed += 1;
259
+ }
260
+ const regressionRate = p2pSpecs.length > 0 ? Number((passToPassFailed / p2pSpecs.length).toFixed(4)) : 0;
261
+ return {
262
+ failToPassPassed,
263
+ failToPassTotal: f2pSpecs.length,
264
+ passToPassFailed,
265
+ passToPassTotal: p2pSpecs.length,
266
+ regressionRate,
267
+ };
268
+ }
269
+ function summarizeArm(arm, runs) {
270
+ const total = runs.length;
271
+ const resolved = runs.filter((r) => r.resolved).length;
272
+ const regressionFailures = runs.filter((r) => r.passToPassFailed > 0).length;
273
+ const p2pTotalAll = runs.reduce((s, r) => s + r.passToPassTotal, 0);
274
+ const p2pFailedAll = runs.reduce((s, r) => s + r.passToPassFailed, 0);
275
+ const ratios = runs.map((r) => r.diffMinimalism.minimalismRatio).filter((x) => x !== null);
276
+ const byTier = {};
277
+ for (const t of [1, 2, 3]) {
278
+ const sub = runs.filter((r) => r.tier === t);
279
+ if (!sub.length)
280
+ continue;
281
+ const subResolved = sub.filter((r) => r.resolved).length;
282
+ const subP2pTotal = sub.reduce((s, r) => s + r.passToPassTotal, 0);
283
+ const subP2pFail = sub.reduce((s, r) => s + r.passToPassFailed, 0);
284
+ byTier[`tier${t}`] = {
285
+ total: sub.length,
286
+ resolved: subResolved,
287
+ resolvedRate: Number((subResolved / sub.length).toFixed(4)),
288
+ regressionRate: subP2pTotal > 0 ? Number((subP2pFail / subP2pTotal).toFixed(4)) : 0,
289
+ };
290
+ }
291
+ const failureAttributionCounts = {};
292
+ for (const r of runs) {
293
+ if (r.failureAttribution) {
294
+ failureAttributionCounts[r.failureAttribution] = (failureAttributionCounts[r.failureAttribution] ?? 0) + 1;
295
+ }
296
+ }
297
+ return {
298
+ arm,
299
+ total,
300
+ resolved,
301
+ resolvedRate: total > 0 ? Number((resolved / total).toFixed(4)) : 0,
302
+ regressionFailures,
303
+ regressionRate: p2pTotalAll > 0 ? Number((p2pFailedAll / p2pTotalAll).toFixed(4)) : 0,
304
+ avgDiffMinimalismRatio: ratios.length ? Number((ratios.reduce((a, b) => a + b, 0) / ratios.length).toFixed(3)) : null,
305
+ avgDurationS: total > 0 ? Number((runs.reduce((s, r) => s + r.durationMs, 0) / total / 1000).toFixed(2)) : 0,
306
+ totalRequests: runs.reduce((s, r) => s + r.requests, 0),
307
+ totalTokens: runs.reduce((s, r) => s + (r.usage?.totalTokens ?? 0), 0),
308
+ byTier,
309
+ failureAttributionCounts,
310
+ };
311
+ }
312
+ /** 对抽样后的 OOD 样本执行单 Agent 与 Lemma 等预算对比评测。 */
313
+ export async function runOodBenchmark(options) {
314
+ const arms = options.arms?.length ? options.arms : ["single", "lemma-adaptive"];
315
+ const simulated = options.simulated ?? false;
316
+ const runs = [];
317
+ const seenScopeIds = new Set();
318
+ const keyEnv = options.base.orchestrator.apiKeyEnv?.[0] ?? "DEEPSEEK_API_KEY";
319
+ const prevKeyVal = process.env[keyEnv];
320
+ const key = simulated
321
+ ? "fixture-placeholder-not-a-real-key"
322
+ : resolveOrchestratorKey(options.base.orchestrator) ?? prevKeyVal;
323
+ if (key)
324
+ process.env[keyEnv] = key;
325
+ try {
326
+ for (const instance of options.instances) {
327
+ const tier = mapOodTier(instance);
328
+ const budget = { ...DEFAULT_OOD_BUDGET[tier], ...options.budgetOverride };
329
+ for (const arm of arms) {
330
+ const repo = prepareOodWorkspace(instance);
331
+ let app;
332
+ const started = performance.now();
333
+ let requests = 0;
334
+ let timedOut = false;
335
+ let loopDetected = false;
336
+ let tokenTruncated = false;
337
+ let multiModulePlanned = false;
338
+ let scopeChecked = false;
339
+ let integrationCalled = false;
340
+ let scopeViolationsCaught = 0;
341
+ let lastToolError;
342
+ let error;
343
+ const observations = [];
344
+ const pending = [];
345
+ const controller = new AbortController();
346
+ const onParentAbort = () => controller.abort();
347
+ options.signal?.addEventListener("abort", onParentAbort, { once: true });
348
+ const timer = setTimeout(() => {
349
+ timedOut = true;
350
+ controller.abort(new Error("TIMEOUT"));
351
+ }, budget.timeoutMs);
352
+ try {
353
+ const rt = options.runtime(instance, arm, repo);
354
+ const models = new Proxy(rt.models, {
355
+ get(target, prop) {
356
+ if (prop === "streamSimple") {
357
+ return (model, input, settings) => {
358
+ const trace = analyzeConversationMessages(input?.messages ?? [], seenScopeIds);
359
+ if (trace.multiModulePlanned)
360
+ multiModulePlanned = true;
361
+ if (trace.scopeChecked)
362
+ scopeChecked = true;
363
+ if (trace.integrationCalled)
364
+ integrationCalled = true;
365
+ if (trace.lastToolError)
366
+ lastToolError = trace.lastToolError;
367
+ if (trace.newScopeViolations > 0)
368
+ scopeViolationsCaught += trace.newScopeViolations;
369
+ if (trace.loopDetected) {
370
+ loopDetected = true;
371
+ const err = new Error(`LOOP_DETECTED${trace.loopDetail ? `: ${trace.loopDetail}` : ""}`);
372
+ controller.abort(err);
373
+ throw err;
374
+ }
375
+ if (requests >= budget.maxRequests) {
376
+ timedOut = true;
377
+ throw new Error(`OOD 请求上限已达 ${budget.maxRequests}`);
378
+ }
379
+ requests += 1;
380
+ const stream = target.streamSimple(model, input, {
381
+ ...settings,
382
+ temperature: 0,
383
+ maxRetries: simulated ? 0 : 2,
384
+ });
385
+ pending.push(stream.result().then((msg) => {
386
+ observations.push(msg.usage);
387
+ if (msg.stopReason === "length")
388
+ tokenTruncated = true;
389
+ }, () => { }));
390
+ return stream;
391
+ };
392
+ }
393
+ const v = Reflect.get(target, prop);
394
+ return typeof v === "function" ? v.bind(target) : v;
395
+ },
396
+ });
397
+ const o = options.base.orchestrator;
398
+ const apiType = o.type === "anthropic-compatible" ? "anthropic-compatible" : "openai-compatible";
399
+ const baseUrl = simulated
400
+ ? "http://fixture.invalid"
401
+ : rt.models.getModel(rt.ref.provider, rt.ref.modelId)?.baseUrl ?? "http://fixture.invalid";
402
+ const makeMember = (desc, tools, bash) => ({
403
+ enabled: true,
404
+ description: desc,
405
+ workspace: "code",
406
+ extraArgs: [],
407
+ models: [{ id: rt.ref.modelId, tier: "standard", ...(o.price ? { price: o.price } : {}) }],
408
+ defaultModel: rt.ref.modelId,
409
+ timeoutMinutes: 3,
410
+ maxOutputChars: 8000,
411
+ api: {
412
+ type: apiType,
413
+ baseUrl,
414
+ apiKeyEnv: [keyEnv],
415
+ tools,
416
+ bash,
417
+ bashAllow: bash === "off" ? [] : ["node", "npm"],
418
+ maxTurns: 14,
419
+ maxTokens: 12_288,
420
+ },
421
+ });
422
+ const config = normalizeConfig({
423
+ workdir: repo,
424
+ storage: join(repo, ".lemma-ood.sqlite"),
425
+ orchestrator: { ...o, maxTurns: 20 },
426
+ isolation: { enabled: arm !== "single", linkDirs: [] },
427
+ autonomy: { enabled: false, checks: [], maxRepairAttempts: 0, resultMaxChars: 4000 },
428
+ budget: { perRunUsd: simulated ? null : options.base.budget.perRunUsd },
429
+ lead: { enabled: false },
430
+ web: { enabled: false, port: 0 },
431
+ roles: [
432
+ { name: "编码", agent: "coder", note: "实现功能修复与修改" },
433
+ ...(tier === 3 ? [{ name: "测试", agent: "tester", note: "补充与验证测试" }] : []),
434
+ ...(tier >= 2 && arm === "lemma-adaptive" ? [{ name: "审查", agent: "auditor", note: "只读盲审" }] : []),
435
+ ],
436
+ agents: {
437
+ ...Object.fromEntries(["claude", "codex", "gemini", "deepseek"].map((id) => [id, { enabled: false }])),
438
+ coder: makeMember("负责修复目标仓库问题", ["read", "write", "edit", "bash"], "allowlist"),
439
+ ...(tier === 3 ? { tester: makeMember("负责独立验证修复", ["read", "write", "edit", "bash"], "allowlist") } : {}),
440
+ ...(tier >= 2 && arm === "lemma-adaptive" ? { auditor: makeMember("只读代码盲审成员", ["read"], "off") } : {}),
441
+ },
442
+ });
443
+ const simulatedProviders = simulated
444
+ ? ["coder", "tester", "auditor"].map((id) => rt.models.getProvider(memberProvider(id))).filter((p) => p !== undefined)
445
+ : [];
446
+ const singleExt = arm === "single"
447
+ ? createMemberTools("single", config.agents.coder.api, { workspace: "code" })
448
+ : undefined;
449
+ app = await openApp(config, { models, ref: rt.ref }, BACKGROUND_CONTEXT, {
450
+ memory: true,
451
+ extensions: singleExt ? [singleExt] : [],
452
+ settings: {
453
+ retry: simulated ? { enabled: false, maxRetries: 0 } : { enabled: true, maxRetries: 4 },
454
+ stream: { timeoutMs: simulated ? 45_000 : 90_000, maxRetries: simulated ? 0 : 2 },
455
+ compaction: { enabled: false },
456
+ afterFailedRun: "keep",
457
+ },
458
+ });
459
+ for (const provider of simulatedProviders)
460
+ models.setProvider(provider);
461
+ await app.root.configure({ compaction: { enabled: false } }, BACKGROUND_CONTEXT);
462
+ if (singleExt)
463
+ await app.root.configure({ extensions: [singleExt], cwd: repo }, BACKGROUND_CONTEXT);
464
+ // 严格保持外部题目原文输入(verbatim problem_statement),绝不做任何特定题型 Prompt 调整
465
+ const promptVerbatim = buildOodTaskPrompt(instance);
466
+ const runCtx = withAbortSignal(controller.signal, BACKGROUND_CONTEXT);
467
+ if (tier === 1 && arm === "lemma-adaptive") {
468
+ const fast = await app.fastDispatch(app.root.id, promptVerbatim, { member: "coder", autoConfirmApply: false, signal: controller.signal });
469
+ if (fast.result.isError)
470
+ error = fast.result.text;
471
+ if (fast.changeId) {
472
+ const applied = await applyChange(app.changes, fast.changeId);
473
+ if (!applied.ok)
474
+ error = applied.message;
475
+ }
476
+ }
477
+ else {
478
+ const submission = await app.root.submit({ type: "input", content: promptVerbatim }, BACKGROUND_CONTEXT);
479
+ await submission.wait(runCtx);
480
+ if (arm !== "single") {
481
+ const allChanges = app.changes.list();
482
+ const intChange = allChanges.find((c) => c.integration?.status === "passed");
483
+ if (intChange) {
484
+ const applied = await applyChange(app.changes, intChange.id);
485
+ if (!applied.ok)
486
+ error = applied.message;
487
+ }
488
+ else {
489
+ const latest = pickLatestActiveChange(allChanges);
490
+ if (latest && latest.status !== "applied") {
491
+ const applied = await applyChange(app.changes, latest.id);
492
+ if (!applied.ok)
493
+ error = applied.message;
494
+ }
495
+ }
496
+ }
497
+ }
498
+ await Promise.all(pending);
499
+ const diffMinimalism = measureDiffMinimalism(repo, instance.gold_patch);
500
+ const verify = runOodVerification(repo, instance);
501
+ if (verify.applyPatchError && !error)
502
+ error = verify.applyPatchError;
503
+ const boardSnap = (await app.harness.snapshot(Board, BACKGROUND_CONTEXT));
504
+ const tasksList = Object.values(boardSnap?.tasks ?? {});
505
+ const blindTriggered = tasksList.some((t) => Boolean(t.reviewer?.blind) || (t.checksByMember?.length ?? 0) > 0);
506
+ const blindSettled = tasksList.some((t) => t.status === "done" || t.checksByMember?.some((c) => c.status === "accepted"));
507
+ const integrationPassed = app.changes.list().some((c) => c.integration?.status === "passed");
508
+ const resolved = !error && !timedOut && !loopDetected &&
509
+ verify.failToPassPassed === verify.failToPassTotal &&
510
+ verify.passToPassFailed === 0;
511
+ const status = loopDetected
512
+ ? "LOOP_DETECTED"
513
+ : timedOut
514
+ ? "TIMEOUT"
515
+ : tokenTruncated && !resolved
516
+ ? "TOKEN_TRUNCATED"
517
+ : resolved
518
+ ? "PASS"
519
+ : "ASSERTION_FAIL";
520
+ const validObs = observations.filter((u) => u.totalTokens > 0);
521
+ const usage = validObs.length
522
+ ? validObs.reduce((acc, v) => ({
523
+ input: acc.input + v.input,
524
+ output: acc.output + v.output,
525
+ cacheRead: acc.cacheRead + v.cacheRead,
526
+ cacheWrite: acc.cacheWrite + v.cacheWrite,
527
+ totalTokens: acc.totalTokens + v.totalTokens,
528
+ }), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0 })
529
+ : null;
530
+ const failureAttribution = resolved
531
+ ? undefined
532
+ : classifyFailureAttribution({
533
+ tier,
534
+ arm,
535
+ status,
536
+ trajectory: {
537
+ routingMatched: true,
538
+ routingDetail: "",
539
+ usedFastPath: tier === 1 && arm === "lemma-adaptive",
540
+ blindReviewTriggered: blindTriggered,
541
+ blindReviewSettled: blindSettled,
542
+ multiModulePlanned,
543
+ scopeChecked,
544
+ integrationCalled,
545
+ loopDetected,
546
+ preFlightIntercepts: 0,
547
+ selfHealed: false,
548
+ tokenTruncated,
549
+ },
550
+ scopeViolationsCaught,
551
+ integrationPassed,
552
+ lastToolError,
553
+ error,
554
+ });
555
+ runs.push({
556
+ instanceId: instance.instance_id,
557
+ repo: instance.repo ?? instance.repo_path ?? "local",
558
+ tier,
559
+ arm,
560
+ status,
561
+ resolved,
562
+ failToPassPassed: verify.failToPassPassed,
563
+ failToPassTotal: verify.failToPassTotal,
564
+ passToPassFailed: verify.passToPassFailed,
565
+ passToPassTotal: verify.passToPassTotal,
566
+ regressionRate: verify.regressionRate,
567
+ diffMinimalism,
568
+ durationMs: Math.round(performance.now() - started),
569
+ requests,
570
+ usage,
571
+ promptVerbatim,
572
+ ...(failureAttribution ? { failureAttribution } : {}),
573
+ ...(error ? { error } : {}),
574
+ });
575
+ }
576
+ catch (err) {
577
+ await Promise.allSettled(pending);
578
+ runs.push({
579
+ instanceId: instance.instance_id,
580
+ repo: instance.repo ?? instance.repo_path ?? "local",
581
+ tier,
582
+ arm,
583
+ status: loopDetected ? "LOOP_DETECTED" : timedOut ? "TIMEOUT" : "ASSERTION_FAIL",
584
+ resolved: false,
585
+ failToPassPassed: 0,
586
+ failToPassTotal: instance.fail_to_pass?.length ?? 0,
587
+ passToPassFailed: 0,
588
+ passToPassTotal: instance.pass_to_pass?.length ?? 0,
589
+ regressionRate: 0,
590
+ diffMinimalism: { actualLines: 0, goldLines: null, minimalismRatio: null },
591
+ durationMs: Math.round(performance.now() - started),
592
+ requests,
593
+ usage: null,
594
+ promptVerbatim: buildOodTaskPrompt(instance),
595
+ failureAttribution: "LOOP_OR_TIMEOUT",
596
+ error: err instanceof Error ? err.message : String(err),
597
+ });
598
+ }
599
+ finally {
600
+ clearTimeout(timer);
601
+ options.signal?.removeEventListener("abort", onParentAbort);
602
+ if (app)
603
+ await app.harness.close(BACKGROUND_CONTEXT).catch(() => { });
604
+ try {
605
+ rmSync(repo, { recursive: true, force: true });
606
+ }
607
+ catch { }
608
+ }
609
+ }
610
+ }
611
+ }
612
+ finally {
613
+ if (prevKeyVal === undefined)
614
+ delete process.env[keyEnv];
615
+ else
616
+ process.env[keyEnv] = prevKeyVal;
617
+ }
618
+ const armSummaries = {};
619
+ for (const arm of arms) {
620
+ armSummaries[arm] = summarizeArm(arm, runs.filter((r) => r.arm === arm));
621
+ }
622
+ const singleSummary = armSummaries["single"];
623
+ const lemmaSummary = armSummaries["lemma-adaptive"];
624
+ const netGainVsSingle = singleSummary && lemmaSummary
625
+ ? Number((lemmaSummary.resolvedRate - singleSummary.resolvedRate).toFixed(4))
626
+ : null;
627
+ return {
628
+ seed: options.seed ?? 42,
629
+ sampleCount: options.instances.length,
630
+ budget: { ...DEFAULT_OOD_BUDGET[2], ...options.budgetOverride },
631
+ frozenPromptPolicy: "verbatim-no-tuning",
632
+ arms: armSummaries,
633
+ netGainVsSingle,
634
+ runs,
635
+ };
636
+ }
637
+ /** 渲染 Markdown 格式的外部盲测评估报告。 */
638
+ export function formatOodMarkdownReport(report) {
639
+ const lines = [
640
+ "# OOD 外部基准评测报告",
641
+ "",
642
+ `- **样本量**: ${report.sampleCount} 题 (seed=${report.seed})`,
643
+ `- **Prompt 策略**: \`${report.frozenPromptPolicy}\`(冻结系统 Prompt,不针对外部题微调)`,
644
+ report.netGainVsSingle !== null
645
+ ? `- **相对 Single 等预算净增益**: ${(report.netGainVsSingle * 100 >= 0 ? "+" : "")}${(report.netGainVsSingle * 100).toFixed(1)} 个百分点`
646
+ : "",
647
+ "",
648
+ "| 实验臂 | 解决率 (Resolved Rate) | 回归破坏率 (Regression Rate) | Diff Minimalism 比值 | 平均耗时 (s) | 总请求数 |",
649
+ "| :--- | ---: | ---: | ---: | ---: | ---: |",
650
+ ].filter(Boolean);
651
+ for (const summary of Object.values(report.arms)) {
652
+ lines.push(`| \`${summary.arm}\` | ${(summary.resolvedRate * 100).toFixed(1)}% (${summary.resolved}/${summary.total}) | ${(summary.regressionRate * 100).toFixed(2)}% | ${summary.avgDiffMinimalismRatio ?? "—"} | ${summary.avgDurationS.toFixed(2)} | ${summary.totalRequests} |`);
653
+ }
654
+ return lines.join("\n");
655
+ }
656
+ /** 写入 OOD 报告 JSON 文件到磁盘(自动建目录)。 */
657
+ export function writeOodReport(outPath, report) {
658
+ mkdirSync(dirname(outPath), { recursive: true });
659
+ writeFileSync(outPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
660
+ }