lemma-agent 0.0.0-stage → 1.0.1

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 (80) hide show
  1. package/README.md +140 -2
  2. package/bin/lemma.mjs +60 -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 +1459 -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/projects.js +282 -0
  45. package/dist/repair.js +102 -0
  46. package/dist/resources.js +31 -0
  47. package/dist/result-summary.js +8 -0
  48. package/dist/results.js +41 -0
  49. package/dist/scope.js +114 -0
  50. package/dist/sessions.js +95 -0
  51. package/dist/settings.js +32 -0
  52. package/dist/task-commands.js +37 -0
  53. package/dist/task-lifecycle.js +49 -0
  54. package/dist/task-readiness.js +22 -0
  55. package/dist/task-recovery.js +116 -0
  56. package/dist/task-review.js +70 -0
  57. package/dist/task-workflow.js +424 -0
  58. package/dist/terminal-layout.js +27 -0
  59. package/dist/terminal-state.js +145 -0
  60. package/dist/terminal.js +800 -0
  61. package/dist/tool-settings.js +111 -0
  62. package/dist/tools.js +1043 -0
  63. package/dist/ux-telemetry.js +127 -0
  64. package/dist/view.js +114 -0
  65. package/package.json +80 -6
  66. package/web/index.html +136 -0
  67. package/web/js/conversations.js +312 -0
  68. package/web/js/dag.js +495 -0
  69. package/web/js/drawer.js +139 -0
  70. package/web/js/editors.js +424 -0
  71. package/web/js/gitlens.js +844 -0
  72. package/web/js/main.js +152 -0
  73. package/web/js/sankey.js +476 -0
  74. package/web/js/store.js +291 -0
  75. package/web/js/ticket.js +151 -0
  76. package/web/js/timeline.js +183 -0
  77. package/web/js/topology.js +454 -0
  78. package/web/js/util.js +232 -0
  79. package/web/js/views.js +1496 -0
  80. package/web/style.css +5299 -0
@@ -0,0 +1,349 @@
1
+ import { createServer } from "node:http";
2
+ import { execFileSync } from "node:child_process";
3
+ import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { performance } from "node:perf_hooks";
7
+ import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
8
+ import { defineExtension, defineTool } from "@earendil-works/pi-durable";
9
+ import { fauxAssistantMessage, fauxProvider, fauxText, fauxToolCall } from "@earendil-works/pi-ai/providers/faux";
10
+ import { createModels } from "@earendil-works/pi-ai";
11
+ import { obj } from "@earendil-works/pi-schema";
12
+ import { openApp } from "./app.js";
13
+ import { normalizeConfig } from "./config.js";
14
+ import { Board } from "./board.js";
15
+ import { callBusinessTool } from "./business-tools.js";
16
+ import { resolveOrchestratorKey } from "./models.js";
17
+ import { Operations } from "./operations.js";
18
+ export const COLLABORATION_FIXTURES = [
19
+ { id: "aggregate", records: [{ id: "a", amount: 18 }, { id: "b", amount: 24 }], expected: { total: 42, missing: [] }, question: "Sum the amounts and list records missing amount." },
20
+ { id: "missing-evidence", records: [{ id: "a", amount: 18 }, { id: "b" }], expected: { total: 18, missing: ["b"] }, question: "Sum only available amounts; list IDs missing amount. Never invent missing values." },
21
+ { id: "negative-adjustment", records: [{ id: "a", amount: 50 }, { id: "b", amount: -8 }, { id: "c", amount: 0 }], expected: { total: 42, missing: [] }, question: "Sum all amounts including negatives and zero; list records missing amount." },
22
+ ];
23
+ export async function runCollaborationBenchmark(options) {
24
+ if (!Number.isInteger(options.repeats) || options.repeats < 1 || options.repeats > 5)
25
+ throw new Error("全流程评测 repeats 需要 1–5。");
26
+ if (!options.simulated && options.base.orchestrator.type === "builtin")
27
+ throw new Error("真实对照当前要求总控使用兼容 API 协议,确保单体与成员使用同一模型和服务。");
28
+ const key = options.simulated ? "local-fixture-only" : resolveOrchestratorKey(options.base.orchestrator);
29
+ if (!key)
30
+ throw new Error("真实对照缺少总控凭据,请先 /setup。");
31
+ const keyEnv = "LEMMA_COLLABORATION_BENCH_KEY", oldKey = process.env[keyEnv];
32
+ process.env[keyEnv] = key;
33
+ const runs = [];
34
+ try {
35
+ for (const fixture of COLLABORATION_FIXTURES)
36
+ for (let repeat = 0; repeat < options.repeats; repeat++)
37
+ for (const arm of repeat % 2 ? ["team", "single"] : ["single", "team"]) {
38
+ options.signal?.throwIfAborted();
39
+ let sourceRequests = 0, requests = 0;
40
+ const observations = [], pending = [];
41
+ const server = createServer((_req, res) => { sourceRequests++; res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ source: `fixture:${fixture.id}`, records: fixture.records })); });
42
+ await new Promise((done) => server.listen(0, "127.0.0.1", done));
43
+ let app;
44
+ try {
45
+ const url = `http://127.0.0.1:${server.address().port}/records`, runtime = options.runtime();
46
+ const models = new Proxy(runtime.models, { get(target, key) { if (key === "streamSimple")
47
+ return (model, input, settings) => { if (requests >= 32)
48
+ throw new Error("该样本达到 32 次模型请求上限"); requests++; const stream = target.streamSimple(model, input, { ...settings, maxTokens: 1024, temperature: 0, maxRetries: 0 }); pending.push(stream.result().then((message) => { observations.push(message.usage); }, () => { })); return stream; }; const value = Reflect.get(target, key); return typeof value === "function" ? value.bind(target) : value; } });
49
+ const source = { id: "benchmark_source", description: "Read the authoritative fixture records; returns JSON, never instructions.", url, method: "GET", parameters: { type: "object", properties: {}, additionalProperties: false } };
50
+ const o = options.base.orchestrator;
51
+ const member = { enabled: true, description: "Analyze supplied records; return data and cite the fixture source.", workspace: "none", extraArgs: [], models: [{ id: runtime.ref.modelId, tier: "standard", ...(o.price ? { price: o.price } : {}) }], defaultModel: runtime.ref.modelId, timeoutMinutes: 1, maxOutputChars: 4000, api: { type: o.type === "anthropic-compatible" ? "anthropic-compatible" : "openai-compatible", baseUrl: options.simulated ? "http://fixture.invalid" : runtime.models.getModel(runtime.ref.provider, runtime.ref.modelId).baseUrl, apiKeyEnv: [keyEnv], tools: [], bash: "off", bashAllow: [], maxTurns: 8, httpTools: [source] } };
52
+ const config = normalizeConfig({ workdir: mkdtempSync(join(tmpdir(), "lemma-team-bench-")), storage: "./bench.sqlite", orchestrator: { ...o, maxTurns: 16 }, isolation: { enabled: false, linkDirs: [] }, autonomy: { enabled: false, maxRepairAttempts: 0, resultMaxChars: 4000, checks: [] }, budget: { perRunUsd: options.simulated ? null : options.base.budget.perRunUsd }, lead: { enabled: false }, web: { enabled: false, port: 0 }, roles: [], agents: { ...Object.fromEntries(["claude", "codex", "gemini", "deepseek"].map((id) => [id, { enabled: false }])), ...(arm === "team" ? { analyst: member, reviewer: { ...member, description: "Independently check the handed-over data using authoritative source records." } } : {}) } });
53
+ const simulatedProviders = options.simulated ? ["analyst", "reviewer"].map((id) => runtime.models.getProvider(`member-${id}`)).filter((provider) => provider !== undefined) : [];
54
+ const directTool = defineTool({ name: "benchmark_source", description: source.description, parameters: obj({}), replay: "safe", execute: async (_args, _api, context) => { const result = await callBusinessTool(source, {}, context.abortSignal ?? AbortSignal.timeout(10000), "benchmark"); return { output: [{ type: "text", text: result.text }], isError: result.isError }; } });
55
+ const extension = defineExtension({ name: "benchmark-source", tools: [directTool] });
56
+ app = await openApp(config, { models, ref: runtime.ref }, BACKGROUND_CONTEXT, { memory: true, extensions: [extension], settings: { retry: { enabled: false, maxRetries: 0 }, stream: { timeoutMs: 30000, maxRetries: 0, cacheRetention: "none" }, compaction: { enabled: false }, afterFailedRun: "keep" } });
57
+ // Simulated callers install matching providers; production uses normal configured HTTP adapters.
58
+ for (const provider of simulatedProviders)
59
+ models.setProvider(provider);
60
+ await app.root.configure({ compaction: { enabled: false } }, BACKGROUND_CONTEXT);
61
+ if (arm === "single")
62
+ await app.root.configure({ extensions: [extension], tools: [directTool] }, BACKGROUND_CONTEXT);
63
+ const started = performance.now();
64
+ let answer = "", error, fieldHandoff = false, settledDone = false;
65
+ const signal = AbortSignal.any([AbortSignal.timeout(90000), ...(options.signal ? [options.signal] : [])]);
66
+ try {
67
+ const prompt = `${fixture.question} Read benchmark_source. Final answer must be exactly JSON {"total":number,"missing":[record IDs]}. ${arm === "team" ? 'Use plan_tasks with two tasks: analysis then independent review dependent on analysis. Ask analyst with structured:true, read source, accept T1 with review_task and evidence; pass result field data to reviewer for independent verification using source, accept T2, then return final JSON. Do not accept before checking source evidence.' : 'Complete this task yourself using benchmark_source. Do not delegate.'}`;
68
+ const submission = await app.root.submit({ type: "input", content: prompt }, BACKGROUND_CONTEXT);
69
+ settledDone = (await submission.wait(withAbortSignal(signal, BACKGROUND_CONTEXT))).status === "done";
70
+ const entries = (await app.root.entries({ order: "descending" }, 100, undefined, BACKGROUND_CONTEXT)).items;
71
+ fieldHandoff = entries.flatMap((entry) => entry.model ?? []).some((message) => message.role === "assistant" && message.content.some((block) => block.type === "toolCall" && block.name === "ask_reviewer" && Array.isArray(block.arguments.inputs) && block.arguments.inputs.some((input) => input?.field === "data")));
72
+ const message = entries.flatMap((entry) => entry.model ?? []).find((message) => message.role === "assistant");
73
+ answer = message?.role === "assistant" ? message.content.filter((block) => block.type === "text").map((block) => block.text).join("") : "";
74
+ if (!answer)
75
+ error = entries.flatMap((entry) => entry.model ?? []).filter((message) => message.role === "toolResult" && message.isError).reverse().slice(0, 3).map((message) => `${message.toolName}: ${JSON.stringify(message.content)}`).join("\n") || "模型未提供最终答案";
76
+ }
77
+ catch (failure) {
78
+ error = failure instanceof Error ? failure.message : String(failure);
79
+ await app.root.abort(BACKGROUND_CONTEXT).catch(() => { });
80
+ }
81
+ {
82
+ await Promise.all(pending);
83
+ const board = await app.harness.snapshot(Board, BACKGROUND_CONTEXT), tasks = Object.values(board?.tasks ?? {});
84
+ const operations = Object.values((await app.harness.snapshot(Operations, BACKGROUND_CONTEXT))?.operations ?? {});
85
+ const sourceReaders = arm === "single" ? (sourceRequests ? ["single"] : []) : [...new Set(operations.filter((operation) => operation.tool === "benchmark_source" && operation.status === "succeeded").map((operation) => operation.member))];
86
+ let correct = false;
87
+ try {
88
+ const result = JSON.parse(answer.trim());
89
+ correct = result.total === fixture.expected.total && JSON.stringify(result.missing) === JSON.stringify(fixture.expected.missing);
90
+ }
91
+ catch { }
92
+ const measured = !options.simulated && requests > 0 && observations.length === requests && observations.every((value) => value.totalTokens > 0);
93
+ const providerPriced = measured && observations.every((value) => value.cost.totalFromProvider);
94
+ const usage = measured ? observations.reduce((sum, value) => ({ input: sum.input + value.input, output: sum.output + value.output, cacheRead: sum.cacheRead + value.cacheRead, cacheWrite: sum.cacheWrite + value.cacheWrite, totalTokens: sum.totalTokens + value.totalTokens }), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0 }) : null;
95
+ const costUsd = measured && (!!o.price || providerPriced) ? observations.reduce((sum, value) => sum + value.cost.total, 0) : null;
96
+ const run = { fixture: fixture.id, arm, repeat, success: settledDone && !error && correct && sourceRequests > 0 && (arm === "single" || (fieldHandoff && ["analyst", "reviewer"].every((member) => sourceReaders.includes(member)) && tasks.length >= 2 && tasks.every((task) => task.status === "done"))), durationMs: Math.round(performance.now() - started), requests, sourceRequests, sourceReaders, fieldHandoff, tokens: usage?.totalTokens ?? null, usage, costUsd, costSource: costUsd === null ? "unavailable" : providerPriced ? "provider" : "configured-estimate", manualInterventions: null, tasks: tasks.length, accepted: tasks.filter((task) => task.status === "done").length, answer, ...(error ? { error } : {}) };
97
+ runs.push(run);
98
+ options.onRun?.(run);
99
+ }
100
+ }
101
+ finally {
102
+ try {
103
+ await app?.harness.close(BACKGROUND_CONTEXT);
104
+ }
105
+ finally {
106
+ server.closeAllConnections();
107
+ await new Promise((done) => server.close(() => done()));
108
+ }
109
+ }
110
+ }
111
+ return runs;
112
+ }
113
+ finally {
114
+ if (oldKey === undefined)
115
+ delete process.env[keyEnv];
116
+ else
117
+ process.env[keyEnv] = oldKey;
118
+ }
119
+ }
120
+ /** Scripted models exercise production tools; their token/cost numbers are deliberately discarded. */
121
+ export function localBenchmarkRuntime() {
122
+ const models = createModels();
123
+ const controller = fauxProvider({ provider: "benchmark-local", models: [{ id: "fixture" }], tokensPerSecond: 100000 });
124
+ models.setProvider(controller.provider);
125
+ const results = (context) => context.messages.filter((message) => message.role === "toolResult").map((message) => ({ name: message.toolName, error: message.isError, text: message.content.filter((block) => block.type === "text").map((block) => block.text).join("") }));
126
+ const compute = (body) => { const records = JSON.parse(body).records; return { total: records.reduce((sum, record) => sum + (record.amount ?? 0), 0), missing: records.filter((record) => record.amount === undefined).map((record) => record.id) }; };
127
+ for (const id of ["analyst", "reviewer"]) {
128
+ const provider = fauxProvider({ provider: `member-${id}`, models: [{ id: "fixture" }], tokensPerSecond: 100000 });
129
+ models.setProvider(provider.provider);
130
+ const reply = (context) => { const entries = results(context), source = entries.findLast((entry) => entry.name === "benchmark_source"); if (!source)
131
+ return fauxAssistantMessage([fauxToolCall("benchmark_source", {})], { stopReason: "toolUse" }); const response = JSON.parse(JSON.parse(source.text).text); return fauxAssistantMessage(fauxText(JSON.stringify({ format: "lemma.delivery.v1", conclusion: "verified", data: compute(response.body), evidence: [{ source: "benchmark_source" }], artifacts: [], incomplete: [] }))); };
132
+ provider.setResponses(Array.from({ length: 20 }, () => reply));
133
+ }
134
+ const controllerReply = (context) => {
135
+ const entries = results(context), single = JSON.stringify(context.messages).includes("Complete this task yourself");
136
+ if (single) {
137
+ const source = entries.findLast((entry) => entry.name === "benchmark_source");
138
+ return source ? fauxAssistantMessage(fauxText(JSON.stringify(compute(JSON.parse(source.text).body)))) : fauxAssistantMessage([fauxToolCall("benchmark_source", {})], { stopReason: "toolUse" });
139
+ }
140
+ const call = (name, args) => fauxAssistantMessage([fauxToolCall(name, args)], { stopReason: "toolUse" });
141
+ if (!entries.length)
142
+ return call("plan_tasks", { tasks: [{ title: "analysis", acceptance: "Read source and compute total" }, { title: "review", deps: ["+1"], acceptance: "independent check" }] });
143
+ const analyst = entries.find((entry) => entry.name === "ask_analyst"), reviewer = entries.find((entry) => entry.name === "ask_reviewer");
144
+ if (!analyst)
145
+ return call("ask_analyst", { task: "Read benchmark_source, calculate total and missing IDs", task_id: "T1", structured: true });
146
+ const id = (entry) => entry.text.match(/result_id: ([^\s|\]]+)/)[1];
147
+ if (!entries.some((entry) => entry.name === "review_task" && entry.text.includes('"task":"T1"')))
148
+ return call("review_task", { id: "T1", action: "accept", result_id: id(analyst), evidence: "fixture source and calculation checked" });
149
+ if (!reviewer)
150
+ return call("ask_reviewer", { task: "Independently read benchmark_source and recompute total and missing IDs", task_id: "T2", structured: true, inputs: [{ result_id: id(analyst), field: "data" }] });
151
+ if (!entries.some((entry) => entry.name === "review_task" && entry.text.includes('"task":"T2"')))
152
+ return call("review_task", { id: "T2", action: "accept", result_id: id(reviewer), evidence: "reviewer independently queried and checked source" });
153
+ const report = JSON.parse(reviewer.text.slice(0, reviewer.text.indexOf("\n\n[任务")));
154
+ return fauxAssistantMessage(fauxText(JSON.stringify(report.data)));
155
+ };
156
+ controller.setResponses(Array.from({ length: 40 }, () => controllerReply));
157
+ return { models, ref: { provider: "benchmark-local", modelId: "fixture" } };
158
+ }
159
+ /**
160
+ * 真实多文件 Coding 协作对照:
161
+ * - single:单 Agent 直接修改实现与测试;
162
+ * - team:L2 契约分流(implementer 限 src/ + tester 限 test/)+ 代码盲审(blind: true)+ 多 worktree 联合集成测试。
163
+ */
164
+ export async function runCodingCollaborationBenchmark(options) {
165
+ const key = options.simulated ? "local-fixture-only" : resolveOrchestratorKey(options.base.orchestrator);
166
+ if (!key)
167
+ throw new Error("真实对照缺少总控凭据,请先 /setup。");
168
+ const keyEnv = "LEMMA_COLLABORATION_BENCH_KEY", oldKey = process.env[keyEnv];
169
+ process.env[keyEnv] = key;
170
+ const runs = [];
171
+ try {
172
+ for (const arm of ["single", "team"]) {
173
+ options.signal?.throwIfAborted();
174
+ const repo = mkdtempSync(join(tmpdir(), `lemma-coding-bench-${arm}-`));
175
+ const git = (...args) => execFileSync("git", ["-C", repo, ...args], { stdio: "pipe", windowsHide: true }).toString().trim();
176
+ git("init", "-q");
177
+ writeFileSync(join(repo, ".gitignore"), "*.sqlite*\nworktrees/\ncalls.jsonl\n.pi-agent/\n");
178
+ writeFileSync(join(repo, "package.json"), JSON.stringify({ name: "bench-fixture", type: "module" }));
179
+ git("add", ".");
180
+ git("-c", "user.name=bench", "-c", "user.email=bench@local", "-c", "commit.gpgsign=false", "commit", "-qm", "init");
181
+ let requests = 0;
182
+ const observations = [], pending = [];
183
+ const runtime = options.runtime();
184
+ const models = new Proxy(runtime.models, {
185
+ get(target, prop) {
186
+ if (prop === "streamSimple")
187
+ return (model, input, settings) => {
188
+ if (requests >= 40)
189
+ throw new Error("该样本达到 40 次模型请求上限");
190
+ requests++;
191
+ const stream = target.streamSimple(model, input, { ...settings, maxTokens: 1024, temperature: 0, maxRetries: 0 });
192
+ pending.push(stream.result().then((message) => { observations.push(message.usage); }, () => { }));
193
+ return stream;
194
+ };
195
+ const value = Reflect.get(target, prop);
196
+ return typeof value === "function" ? value.bind(target) : value;
197
+ },
198
+ });
199
+ const o = options.base.orchestrator;
200
+ const apiBase = { type: o.type === "anthropic-compatible" ? "anthropic-compatible" : "openai-compatible", baseUrl: options.simulated ? "http://fixture.invalid" : runtime.models.getModel(runtime.ref.provider, runtime.ref.modelId).baseUrl, apiKeyEnv: [keyEnv], bash: "off", bashAllow: [], maxTurns: 12 };
201
+ const coderMember = { enabled: true, description: "实现 src/ 模块代码", workspace: "code", extraArgs: [], models: [{ id: runtime.ref.modelId, tier: "standard", ...(o.price ? { price: o.price } : {}) }], defaultModel: runtime.ref.modelId, timeoutMinutes: 1, maxOutputChars: 12000, api: { ...apiBase, tools: ["read", "write", "edit"] } };
202
+ const reviewerMember = { enabled: true, description: "只读代码盲审成员", workspace: "code", extraArgs: [], models: [{ id: runtime.ref.modelId, tier: "standard", ...(o.price ? { price: o.price } : {}) }], defaultModel: runtime.ref.modelId, timeoutMinutes: 1, maxOutputChars: 12000, api: { ...apiBase, tools: ["read"] } };
203
+ const config = normalizeConfig({
204
+ workdir: repo,
205
+ storage: join(repo, "bench.sqlite"),
206
+ orchestrator: { ...o, maxTurns: 16 },
207
+ isolation: { enabled: arm === "team", linkDirs: [] },
208
+ autonomy: { enabled: false, maxRepairAttempts: 0, resultMaxChars: 4000, checks: [{ name: "unit-test", command: "node", args: ["test/discount.test.mjs"], timeoutSeconds: 30 }] },
209
+ budget: { perRunUsd: options.simulated ? null : options.base.budget.perRunUsd },
210
+ lead: { enabled: false },
211
+ web: { enabled: false, port: 0 },
212
+ roles: [],
213
+ agents: {
214
+ ...Object.fromEntries(["claude", "codex", "gemini", "deepseek"].map((id) => [id, { enabled: false }])),
215
+ ...(arm === "team" ? { implementer: coderMember, tester: { ...coderMember, description: "独立编写 test/ 单元测试" }, reviewer: reviewerMember } : { solo: coderMember }),
216
+ },
217
+ });
218
+ const simulatedIds = arm === "team" ? ["implementer", "tester", "reviewer"] : ["solo"];
219
+ const simulatedProviders = options.simulated ? simulatedIds.map((id) => runtime.models.getProvider(`member-${id}`)).filter((p) => p !== undefined) : [];
220
+ const app = await openApp(config, { models, ref: runtime.ref }, BACKGROUND_CONTEXT, { settings: { retry: { enabled: false, maxRetries: 0 }, stream: { timeoutMs: 30000, maxRetries: 0, cacheRetention: "none" }, compaction: { enabled: false }, afterFailedRun: "keep" } });
221
+ for (const p of simulatedProviders)
222
+ models.setProvider(p);
223
+ const started = performance.now();
224
+ let error;
225
+ let success = false;
226
+ let scopeEnforced = false;
227
+ let blindReviewCaught = false;
228
+ let integrationPassed = false;
229
+ try {
230
+ if (arm === "single") {
231
+ await (await app.root.submit({ type: "input", content: "SOLO_DISCOUNT: 让 solo 在 src/discount.mjs 实现 applyDiscount(price, pct),并在 test/discount.test.mjs 写测试。" }, BACKGROUND_CONTEXT)).wait(withAbortSignal(AbortSignal.timeout(20000), BACKGROUND_CONTEXT));
232
+ const targetDir = app.changes.list().find((c) => c.agent === "solo")?.path ?? repo;
233
+ try {
234
+ execFileSync(process.execPath, ["test/discount.test.mjs"], { cwd: targetDir, stdio: "pipe", windowsHide: true });
235
+ success = existsSync(join(targetDir, "src/discount.mjs")) && existsSync(join(targetDir, "test/discount.test.mjs"));
236
+ }
237
+ catch { }
238
+ }
239
+ else {
240
+ await (await app.root.submit({ type: "input", content: "TEAM_DISCOUNT: 拆分为 T1(implementer 限 src/, 禁用 test/, 盲审返工)、T2(tester 限 test/, 禁用 src/) 与 T3(联合集成)。" }, BACKGROUND_CONTEXT)).wait(withAbortSignal(AbortSignal.timeout(30000), BACKGROUND_CONTEXT));
241
+ const end = Date.now() + 40000;
242
+ while ((await app.harness.snapshot(Board, BACKGROUND_CONTEXT))?.tasks.T3?.status !== "done" && Date.now() < end)
243
+ await new Promise((r) => setTimeout(r, 25));
244
+ const board = await app.harness.snapshot(Board, BACKGROUND_CONTEXT);
245
+ const t1 = board?.tasks.T1, t2 = board?.tasks.T2, t3 = board?.tasks.T3;
246
+ const integrated = t3?.integrationId ? app.changes.get(t3.integrationId) : undefined;
247
+ integrationPassed = integrated?.integration?.status === "passed";
248
+ blindReviewCaught = (t1?.checksByMember?.some((c) => c.status === "rework") ?? false) && (t1?.checksByMember?.at(-1)?.status === "accepted");
249
+ scopeEnforced = t1?.scope?.forbid?.includes("test/") === true && existsSync(join(integrated?.path ?? "", "src/discount.mjs")) && existsSync(join(integrated?.path ?? "", "test/discount.test.mjs"));
250
+ success = t3?.status === "done" && integrationPassed && blindReviewCaught && scopeEnforced;
251
+ if (!success)
252
+ error = JSON.stringify({ t1: t1?.status, t2: t2?.status, t3, integration: integrated?.integration?.status });
253
+ }
254
+ }
255
+ catch (err) {
256
+ error = err instanceof Error ? err.message : String(err);
257
+ }
258
+ finally {
259
+ await Promise.all(pending);
260
+ await app.harness.close(BACKGROUND_CONTEXT);
261
+ }
262
+ const measured = !options.simulated && requests > 0 && observations.length === requests && observations.every((v) => v.totalTokens > 0);
263
+ const usage = measured ? observations.reduce((sum, v) => sum + v.totalTokens, 0) : null;
264
+ const costUsd = measured && o.price ? observations.reduce((sum, v) => sum + v.cost.total, 0) : null;
265
+ runs.push({ fixture: "discount-module", arm, success, durationMs: Math.round(performance.now() - started), requests, scopeEnforced, blindReviewCaught, integrationPassed, tokens: usage, costUsd, ...(error ? { error } : {}) });
266
+ }
267
+ return runs;
268
+ }
269
+ finally {
270
+ if (oldKey === undefined)
271
+ delete process.env[keyEnv];
272
+ else
273
+ process.env[keyEnv] = oldKey;
274
+ }
275
+ }
276
+ export function localCodingBenchmarkRuntime() {
277
+ const models = createModels();
278
+ const controller = fauxProvider({ provider: "coding-bench-local", models: [{ id: "fixture" }], tokensPerSecond: 100000 });
279
+ models.setProvider(controller.provider);
280
+ const results = (ctx) => ctx.messages.filter((m) => m.role === "toolResult").map((m) => ({ name: m.toolName, text: m.content.filter((b) => b.type === "text").map((b) => b.text).join("") }));
281
+ // solo:写实现与测试
282
+ const solo = fauxProvider({ provider: "member-solo", models: [{ id: "fixture" }], tokensPerSecond: 100000 });
283
+ solo.setResponses([
284
+ () => fauxAssistantMessage([
285
+ fauxToolCall("write", { path: "src/discount.mjs", content: "export const applyDiscount = (p, pct) => p * (1 - pct / 100);\n" }, { id: "s1" }),
286
+ fauxToolCall("write", { path: "test/discount.test.mjs", content: "import assert from 'node:assert/strict';\nimport { applyDiscount } from '../src/discount.mjs';\nassert.equal(applyDiscount(100, 20), 80);\n" }, { id: "s2" }),
287
+ ], { stopReason: "toolUse" }),
288
+ () => fauxAssistantMessage(fauxText("SOLO_DONE")),
289
+ ]);
290
+ models.setProvider(solo.provider);
291
+ // implementer:第1轮故意越界写 test/ 被拦且少写了边界校验 -> 盲审触发 rework -> 第2轮修好
292
+ const impl = fauxProvider({ provider: "member-implementer", models: [{ id: "fixture" }], tokensPerSecond: 100000 });
293
+ impl.setResponses([
294
+ () => fauxAssistantMessage([
295
+ fauxToolCall("write", { path: "test/discount.test.mjs", content: "// cheat\n" }, { id: "i0" }),
296
+ fauxToolCall("write", { path: "src/discount.mjs", content: "export const applyDiscount = (p, pct) => p * (1 - pct / 100);\n" }, { id: "i1" }),
297
+ ], { stopReason: "toolUse" }),
298
+ () => fauxAssistantMessage(fauxText("完美无缺")),
299
+ () => fauxAssistantMessage([
300
+ fauxToolCall("write", { path: "src/discount.mjs", content: "export const applyDiscount = (p, pct) => { if (pct < 0 || pct > 100) throw new RangeError('pct'); return p * (1 - pct / 100); };\n" }, { id: "i2" }),
301
+ ], { stopReason: "toolUse" }),
302
+ () => fauxAssistantMessage(fauxText("已补充边界校验")),
303
+ () => fauxAssistantMessage([
304
+ fauxToolCall("write", { path: "src/index.mjs", content: "export { applyDiscount } from './discount.mjs';\n" }, { id: "i3" }),
305
+ ], { stopReason: "toolUse" }),
306
+ () => fauxAssistantMessage(fauxText("已集成汇总导出")),
307
+ ]);
308
+ models.setProvider(impl.provider);
309
+ // tester:只写 test/,不碰 src/
310
+ const tester = fauxProvider({ provider: "member-tester", models: [{ id: "fixture" }], tokensPerSecond: 100000 });
311
+ tester.setResponses([
312
+ () => fauxAssistantMessage([
313
+ fauxToolCall("write", { path: "test/discount.test.mjs", content: "import assert from 'node:assert/strict';\nimport { applyDiscount } from '../src/discount.mjs';\nassert.equal(applyDiscount(100, 20), 80);\nassert.throws(() => applyDiscount(100, 150));\n" }, { id: "t1" }),
314
+ ], { stopReason: "toolUse" }),
315
+ () => fauxAssistantMessage(fauxText("测试已独立完成")),
316
+ ]);
317
+ models.setProvider(tester.provider);
318
+ // reviewer:盲审模式下用 git_diff 抓边界缺陷并打回,修复后及测试分支均通过
319
+ const reviewer = fauxProvider({ provider: "member-reviewer", models: [{ id: "fixture" }], tokensPerSecond: 100000 });
320
+ reviewer.setResponses(Array.from({ length: 12 }, () => (ctx) => {
321
+ const diffs = results(ctx).filter((r) => r.name === "git_diff");
322
+ const userText = ctx.messages.filter((m) => m.role === "user").map((m) => typeof m.content === "string" ? m.content : JSON.stringify(m.content)).join("\n");
323
+ const rid = userText.match(/(dispatch:[^"\\\s\]]+)/)?.[1];
324
+ if (!diffs.length)
325
+ return fauxAssistantMessage([fauxToolCall("git_diff", {}, { id: `r-${Math.random().toString(36).slice(2, 7)}` })], { stopReason: "toolUse" });
326
+ const diff = diffs.at(-1).text;
327
+ const ok = diff.includes("RangeError") || diff.includes("discount.test.mjs") || diff.includes("index.mjs");
328
+ return fauxAssistantMessage(fauxText(JSON.stringify(ok ? { verdict: "accept", result_id: rid, evidence: "git_diff 核对实现或测试符合验收标准" } : { verdict: "rework", result_id: rid, evidence: "缺少 pct 边界校验" })));
329
+ }));
330
+ models.setProvider(reviewer.provider);
331
+ controller.setResponses(Array.from({ length: 20 }, () => (ctx) => {
332
+ const user = JSON.stringify(ctx.messages);
333
+ const done = results(ctx);
334
+ if (user.includes("SOLO_DISCOUNT")) {
335
+ return done.length ? fauxAssistantMessage(fauxText("SOLO_OK")) : fauxAssistantMessage([fauxToolCall("ask_solo", { task: "实现并测试折扣函数" })], { stopReason: "toolUse" });
336
+ }
337
+ if (!done.length) {
338
+ return fauxAssistantMessage([fauxToolCall("plan_tasks", {
339
+ tasks: [
340
+ { title: "实现折扣逻辑", scope: { allow: ["src/"], forbid: ["test/"] }, automation: { member: "implementer", maxReworks: 1 }, reviewer: { member: "reviewer", blind: true } },
341
+ { title: "编写独立单测", scope: { allow: ["test/"], forbid: ["src/"] }, automation: { member: "tester" }, reviewer: { member: "reviewer", blind: true } },
342
+ { title: "集成汇总验证", deps: ["+1", "+2"], scope: { allow: ["src/"], forbid: ["test/"] }, automation: { member: "implementer" }, reviewer: { member: "reviewer", blind: true } },
343
+ ],
344
+ })], { stopReason: "toolUse" });
345
+ }
346
+ return fauxAssistantMessage(fauxText("TEAM_OK"));
347
+ }));
348
+ return { models, ref: { provider: "coding-bench-local", modelId: "fixture" } };
349
+ }