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,557 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
5
+ import { defineDoc, defineTask, defineTool } from "@earendil-works/pi-durable";
6
+ import { arr, bool, obj, opt, str } from "@earendil-works/pi-schema";
7
+ import { memberToolNames } from "./api-member.js";
8
+ import { Board } from "./board.js";
9
+ import { autonomyChecksForRoot, sameConfigRepoRoot } from "./config.js";
10
+ import { addWorktree, linkIgnoredDirs, numstat } from "./git.js";
11
+ import { cleanEnv, runCli } from "./cli-runner.js";
12
+ import { findConflictMarkers, integrationGit, integrationStale, mergeIntegrationSource, workspaceTree } from "./integration-git.js";
13
+ import { Jobs } from "./jobs.js";
14
+ import { Learning, relevantLessons } from "./learning.js";
15
+ export const Integrations = defineDoc({ kind: "lemma.integrations", version: 1, scope: "session", initial: () => ({ records: {}, byKey: {} }), checkpointWhen: () => false });
16
+ const clone = (value) => JSON.parse(JSON.stringify(value));
17
+ const ended = (change) => !["preparing", "merging", "repairing", "testing"].includes(change.integration.status);
18
+ export function integrationSummary(change) {
19
+ const repair = change.integration?.repair
20
+ ? { fromId: change.integration.repair.fromId, member: change.integration.repair.member, ...(change.integration.repair.model ? { model: change.integration.repair.model } : {}), ...(change.integration.repair.jobId ? { jobId: change.integration.repair.jobId } : {}), ...(change.integration.repair.changeId ? { changeId: change.integration.repair.changeId } : {}), ...(change.integration.repair.note ? { note: change.integration.repair.note } : {}) }
21
+ : undefined;
22
+ return {
23
+ id: change.id,
24
+ status: change.integration?.status,
25
+ changeStatus: change.status,
26
+ head: change.head,
27
+ sources: change.integration?.sources,
28
+ ...(change.integration?.replacesId ? { replacesId: change.integration.replacesId } : {}),
29
+ ...(change.integration?.supersededBy ? { supersededBy: change.integration.supersededBy } : {}),
30
+ ...(repair ? { repair } : {}),
31
+ checks: change.integration?.reports,
32
+ conflicts: change.integration?.conflicts ?? [],
33
+ message: change.message ?? null,
34
+ path: change.path,
35
+ next: change.status === "applied"
36
+ ? "已应用到主目录,等待人工检查提交。"
37
+ : change.status === "dropped"
38
+ ? "集成副本已丢弃,历史检查记录保留。"
39
+ : change.integration?.supersededBy
40
+ ? `已被新集成 #${change.integration.supersededBy} 替代,请查看最新集成记录。`
41
+ : change.integration?.status === "passed"
42
+ ? `/diff ${change.id} 查看;/apply ${change.id} 由用户确认应用;主目录或来源变化后可用 /integrate rerun ${change.id} 重验`
43
+ : ["conflict", "failed"].includes(change.integration?.status ?? "")
44
+ ? `/integrate repair ${change.id} <成员ID> [修复说明] 在独立副本修复并重跑全量检查,或修复来源后 /integrate rerun ${change.id}`
45
+ : `正在运行(${change.integration?.status ?? change.status}),可用 /integrate cancel ${change.id} 取消`,
46
+ };
47
+ }
48
+ export function createIntegrations(deps, hooks = {}) {
49
+ const { config, changes, hub } = deps;
50
+ const publish = (record) => { try {
51
+ changes.upsert(clone(record));
52
+ }
53
+ catch {
54
+ hub.output(`integration:${record.id}`, "集成状态已持久保存,改动索引暂时无法更新,重启后恢复。");
55
+ } };
56
+ const phaseHandler = (phase) => async (running, runtime, context) => {
57
+ await runPhase(phase, running, runtime, context);
58
+ };
59
+ const task = defineTask({
60
+ name: "lemma.integration", version: 1, initial: () => ({ phase: "prepare", index: 0 }),
61
+ phases: { prepare: phaseHandler("prepare"), merge: phaseHandler("merge"), repair: phaseHandler("repair"), test: phaseHandler("test") },
62
+ abort: async (running, runtime, context) => {
63
+ let record;
64
+ await runtime.commit(async (tx) => {
65
+ const item = (await tx.doc(Integrations)).records[running.input.id];
66
+ if (item?.integration) {
67
+ item.integration.status = "cancelled";
68
+ item.status = "pending";
69
+ item.message = "集成已取消,测试和来源证据保留,未修改主目录。";
70
+ record = clone(item);
71
+ }
72
+ return { status: "terminal", outcome: { status: "aborted" } };
73
+ }, context);
74
+ if (record)
75
+ publish(record);
76
+ },
77
+ });
78
+ async function runPhase(phase, running, runtime, context) {
79
+ const saved = (await runtime.snapshot(Integrations, context))?.records[running.input.id];
80
+ if (!saved?.integration)
81
+ throw new Error("集成记录不存在。");
82
+ let record = clone(saved);
83
+ const checkpoint = running.state.checkpoint;
84
+ const finish = async (status, message) => {
85
+ record = { ...record, status: status === "conflict" ? "conflict" : "pending", message, updatedAt: runtime.now(), integration: { ...record.integration, status } };
86
+ const controller = Number(record.integration.controllerId);
87
+ await runtime.commit(async (tx) => {
88
+ (await tx.doc(Integrations)).records[record.id] = clone(record);
89
+ if (hooks.ensureWorkflow)
90
+ await hooks.ensureWorkflow(tx, controller);
91
+ return { status: "terminal", outcome: { status: "completed", result: { id: record.id, passed: status === "passed" } } };
92
+ }, context);
93
+ publish(record);
94
+ };
95
+ const advance = async (next) => {
96
+ await runtime.commit(async (tx) => { (await tx.doc(Integrations)).records[record.id] = clone(record); return { status: "running", checkpoint: next }; }, context);
97
+ publish(record);
98
+ };
99
+ try {
100
+ if (ended(record)) {
101
+ await finish(record.integration.status, record.message ?? "集成已收尾");
102
+ return;
103
+ }
104
+ if (phase === "prepare") {
105
+ const baseline = await runtime.memo("baseline", context) ?? await runtime.memo("baseline", await workspaceTree(record.root), context);
106
+ record.base = baseline.head;
107
+ record.head = baseline.head;
108
+ record.integration.baselineTree = baseline.tree;
109
+ const stale = await integrationStale(changes, record);
110
+ if (stale) {
111
+ await finish("failed", stale);
112
+ return;
113
+ }
114
+ if (!existsSync(record.path))
115
+ await addWorktree(record.root, record.path, record.branch, record.base);
116
+ if (resolve(await integrationGit(record.path, ["rev-parse", "--show-toplevel"])).toLowerCase() !== resolve(record.path).toLowerCase())
117
+ throw new Error("集成工作区不匹配。");
118
+ record.integration.status = "merging";
119
+ await advance({ phase: "merge", index: 0 });
120
+ return;
121
+ }
122
+ const stale = await integrationStale(changes, record);
123
+ if (stale) {
124
+ await finish("failed", stale);
125
+ return;
126
+ }
127
+ const board = await runtime.snapshot(Board, context);
128
+ if (record.integration.sources.some((source) => Object.values(board?.tasks ?? {}).some((item) => item.changes.includes(source.id) && (item.status !== "done" || item.activeDispatch)))) {
129
+ await finish("failed", "来源任务验收状态已变化,联合检查结果不能继续使用。");
130
+ return;
131
+ }
132
+ if (phase === "merge") {
133
+ const source = record.integration.sources[checkpoint.index];
134
+ const repairing = !!record.integration.repair;
135
+ if (source) {
136
+ const merged = await mergeIntegrationSource(record, source, checkpoint.index, repairing);
137
+ if (merged.error) {
138
+ record.integration.conflicts = merged.conflicts;
139
+ await finish("conflict", `来源 #${source.id} 无法联合合并:${merged.error}`);
140
+ return;
141
+ }
142
+ if (merged.conflicts.length)
143
+ record.integration.conflicts = [...new Set([...(record.integration.conflicts ?? []), ...merged.conflicts])];
144
+ record.head = merged.head;
145
+ await advance({ phase: "merge", index: checkpoint.index + 1 });
146
+ return;
147
+ }
148
+ record.files = await numstat(record.root, record.base, record.head);
149
+ record.add = record.files.reduce((sum, file) => sum + file.add, 0);
150
+ record.del = record.files.reduce((sum, file) => sum + file.del, 0);
151
+ record.linked = await linkIgnoredDirs(record.root, record.path, record.subdir, config.isolation.linkDirs);
152
+ if (repairing) {
153
+ record.integration.status = "repairing";
154
+ await advance({ phase: "repair", index: 0 });
155
+ return;
156
+ }
157
+ record.integration.status = "testing";
158
+ await advance({ phase: "test", index: 0 });
159
+ return;
160
+ }
161
+ if (phase === "repair") {
162
+ const rep = record.integration.repair;
163
+ if (!rep || !hooks.enqueue) {
164
+ await finish("failed", "集成修复运行时尚未就绪。");
165
+ return;
166
+ }
167
+ const controller = Number(record.integration.controllerId);
168
+ if (!rep.jobId) {
169
+ const sourceBrief = record.integration.sources.map((s) => {
170
+ const src = changes.get(s.id);
171
+ return `- 来源 #${s.id}(${s.base.slice(0, 12)}..${s.head.slice(0, 12)}):${src?.task.replace(/\s+/g, " ").slice(0, 200) ?? s.id}`;
172
+ }).join("\n");
173
+ const conflictBrief = record.integration.conflicts?.length
174
+ ? `\n当前合并冲突文件(已写入标准 <<<<<<< / ======= / >>>>>>> 标记):\n${record.integration.conflicts.map((f) => ` - ${f}`).join("\n")}\n请阅读冲突文件及各来源改动意图,保留所有来源的正确功能并彻底清除冲突标记。`
175
+ : "";
176
+ const failBrief = rep.previousFailure ? `\n前次集成失败证据:\n${rep.previousFailure.slice(-3000)}` : "";
177
+ const checkBrief = record.integration.checks.map((c) => `${c.name}: ${c.command} ${c.args.join(" ")}`).join(";");
178
+ const lessons = (await runtime.snapshot(Learning, context))?.lessons ?? [];
179
+ const sourceFiles = [...new Set([...(record.integration.conflicts ?? []), ...record.integration.sources.flatMap((s) => changes.get(s.id)?.files.map((f) => f.path) ?? [])])];
180
+ const relevant = relevantLessons(lessons, `${record.task}\n${failBrief}`, sourceFiles);
181
+ const prompt = [
182
+ `联合集成修复 #${record.id}(源自失败集成 #${rep.fromId})。`,
183
+ "你在独立修复工作副本中工作,原始来源分支与主目录均不会受影响。",
184
+ "来源分支:",
185
+ sourceBrief,
186
+ conflictBrief,
187
+ failBrief,
188
+ relevant ? `\n相关历史修复经验(仅参考,以当前代码和检查为准):\n${relevant}` : "",
189
+ rep.note ? `\n补充修复要求:${rep.note}` : "",
190
+ `\n联合验收将自动重跑全量检查(${checkBrief})。请最小化修改解决冲突或跨模块接口/类型/测试不兼容问题,禁止删除正常功能或弱化测试标准。`,
191
+ ].filter(Boolean).join("\n");
192
+ await runtime.commit(async (tx) => {
193
+ const current = (await tx.doc(Integrations)).records[record.id];
194
+ if (!current?.integration?.repair || current.integration.repair.jobId) {
195
+ record = clone(current ?? record);
196
+ return;
197
+ }
198
+ // Publish current record before enqueueing so based_on sees repairing status & head.
199
+ publish(record);
200
+ const job = await hooks.enqueue(tx, controller, rep.callId, rep.member, { task: prompt, based_on: record.id, ...(rep.model ? { model: rep.model } : {}) }, rep.model);
201
+ (await tx.doc(Jobs)).jobs[job.id].workflow = true;
202
+ record.integration.repair.jobId = job.id;
203
+ (await tx.doc(Integrations)).records[record.id] = clone(record);
204
+ }, context);
205
+ publish(record);
206
+ await runtime.sleepUntil(runtime.now() + 250, { phase: "repair", index: 0 }, context);
207
+ return;
208
+ }
209
+ const job = (await runtime.snapshot(Jobs, context))?.jobs[rep.jobId];
210
+ if (!job || job.status === "running") {
211
+ await runtime.sleepUntil(runtime.now() + 250, { phase: "repair", index: 0 }, context);
212
+ return;
213
+ }
214
+ if (job.status === "cancelled") {
215
+ await finish("cancelled", "集成修复派工已取消,保留现场。");
216
+ return;
217
+ }
218
+ if (job.status !== "done" || !job.changeId) {
219
+ await finish("failed", `集成修复派工 #${job.id} 未能完成修复(status=${job.status}, change=${job.changeId ?? "none"}):${job.result ?? ""}`);
220
+ return;
221
+ }
222
+ const fix = changes.get(job.changeId);
223
+ if (!fix || fix.status === "dropped" || fix.message) {
224
+ await finish("failed", "修复代码副本缺失或提交异常,未进入联合检查。");
225
+ return;
226
+ }
227
+ const markers = await findConflictMarkers(record.root, record.base, fix.head);
228
+ if (markers.length) {
229
+ record.integration.conflicts = markers;
230
+ await finish("conflict", `修复后文件中仍残留合并冲突标记:${markers.join("、")}`);
231
+ return;
232
+ }
233
+ const actualRoot = await integrationGit(record.path, ["rev-parse", "--show-toplevel"]);
234
+ if (resolve(actualRoot).toLowerCase() !== resolve(record.path).toLowerCase() || resolve(record.path).toLowerCase() === resolve(record.root).toLowerCase())
235
+ throw new Error("集成工作区路径验证失败。");
236
+ await integrationGit(record.path, ["reset", "--hard", fix.head]);
237
+ record.head = fix.head;
238
+ record.integration.repair.changeId = fix.id;
239
+ record.integration.conflicts = [];
240
+ record.integration.reports = [];
241
+ record.files = await numstat(record.root, record.base, record.head);
242
+ record.add = record.files.reduce((sum, file) => sum + file.add, 0);
243
+ record.del = record.files.reduce((sum, file) => sum + file.del, 0);
244
+ record.linked = await linkIgnoredDirs(record.root, record.path, record.subdir, config.isolation.linkDirs);
245
+ record.integration.status = "testing";
246
+ await advance({ phase: "test", index: 0 });
247
+ return;
248
+ }
249
+ if (await integrationGit(record.path, ["rev-parse", "HEAD"]) !== record.head || await integrationGit(record.path, ["status", "--porcelain"])) {
250
+ await finish("failed", "联合检查前工作区已变化,请修复来源后重建集成,保留现场。");
251
+ return;
252
+ }
253
+ const check = record.integration.checks[checkpoint.index];
254
+ if (check) {
255
+ // A crash after an external check started has an unknown outcome; never silently repeat it.
256
+ if (await runtime.memo(`check-started:${checkpoint.index}`, context)) {
257
+ await finish("failed", `联合检查 ${check.name} 中途被打断,未自动重复运行;可用 /integrate rerun ${record.id} 重建验证。`);
258
+ return;
259
+ }
260
+ await runtime.memo(`check-started:${checkpoint.index}`, true, context);
261
+ const cancel = hub.register(`integration:${record.id}`), signal = AbortSignal.any([runtime.signal, cancel]);
262
+ let result;
263
+ try {
264
+ result = await runCli({ command: check.command === "node" ? process.execPath : check.command, args: check.args, cwd: join(record.path, record.subdir), env: cleanEnv(config.stripEnv), timeoutMs: (check.timeoutSeconds ?? 120) * 1000, signal, onLine: (line) => hub.output(`integration:${record.id}`, line) });
265
+ }
266
+ finally {
267
+ hub.release(`integration:${record.id}`);
268
+ }
269
+ if (runtime.signal.aborted || hub.closing)
270
+ return;
271
+ const passed = result.exitCode === 0 && !result.aborted && !result.timedOut;
272
+ record.integration.reports.push({ name: check.name, passed, exitCode: result.exitCode, output: (result.stdout + result.stderr).slice(-12000), at: runtime.now() });
273
+ if (!passed) {
274
+ await finish(result.aborted ? "cancelled" : "failed", `联合检查 ${check.name} ${result.timedOut ? "超时" : result.aborted ? "已取消" : "失败"},保留日志与集成工作区。`);
275
+ return;
276
+ }
277
+ await advance({ phase: "test", index: checkpoint.index + 1 });
278
+ return;
279
+ }
280
+ if (record.integration.reports.length !== record.integration.checks.length || record.integration.reports.some((report) => !report.passed)) {
281
+ await finish("failed", "联合检查结果不完整。");
282
+ return;
283
+ }
284
+ record.verification = { head: record.head, passed: true, at: runtime.now(), checks: record.integration.checks.map((check) => check.name) };
285
+ if (record.integration.repair) {
286
+ const rep = record.integration.repair;
287
+ const lessonKey = `integration:${record.id}`;
288
+ await runtime.commit(async (tx) => {
289
+ const learning = await tx.doc(Learning);
290
+ if (!learning.lessons.some((l) => l.key === lessonKey)) {
291
+ learning.lessons.push({
292
+ key: lessonKey,
293
+ kind: "integration",
294
+ task: record.task.slice(0, 200),
295
+ files: record.files.map((f) => f.path).slice(0, 20),
296
+ checks: record.verification.checks,
297
+ repairs: 1,
298
+ at: runtime.now(),
299
+ failure: rep.previousFailure?.slice(-1200),
300
+ resolution: `由 ${rep.member} 在独立修复副本解决后通过联合检查`,
301
+ changeId: record.id,
302
+ head: record.head,
303
+ });
304
+ learning.lessons = learning.lessons.slice(-50);
305
+ }
306
+ }, context);
307
+ }
308
+ await finish("passed", record.integration.repair ? "冲突/联调问题已在独立副本修复并通过全量联合检查;等待用户 /apply 确认。" : "多成员改动已联合验证通过;等待用户 /apply 确认,不自动修改主目录。");
309
+ }
310
+ catch (error) {
311
+ if (!runtime.signal.aborted && !hub.closing)
312
+ await finish("failed", error instanceof Error ? error.message : String(error));
313
+ }
314
+ }
315
+ async function create(tx, controller, ids, key, extra) {
316
+ const doc = await tx.doc(Integrations), previous = doc.byKey[key];
317
+ if (previous && doc.records[previous])
318
+ return clone(doc.records[previous]);
319
+ if (ids.length < 2 || ids.length > 8 || new Set(ids).size !== ids.length)
320
+ throw new Error("联合集成需要 2–8 个不同的完整改动编号。");
321
+ const signature = ids.map((id) => `${id}:${changes.get(id)?.head}`).sort().join("|");
322
+ if (!extra?.repair) {
323
+ const active = Object.values(doc.records).find((record) => record.integration?.controllerId === String(controller) && !ended(record) && !record.integration.repair && record.integration.sources.map((source) => `${source.id}:${source.head}`).sort().join("|") === signature);
324
+ if (active) {
325
+ doc.byKey[key] = active.id;
326
+ return clone(active);
327
+ }
328
+ }
329
+ const board = await tx.doc(Board);
330
+ const sources = ids.map((id) => {
331
+ const source = changes.list().find((item) => item.id === id);
332
+ if (!source || !["pending", "empty"].includes(source.status) || source.integration || source.message)
333
+ throw new Error(`来源 #${id} 不存在、未成功交付或不是可集成的成员改动。`);
334
+ if (source.sessionId && hub.busySessions.has(source.sessionId))
335
+ throw new Error(`来源 #${id} 的成员会话仍在执行,等待收尾后集成。`);
336
+ const owners = Object.values(board.tasks).filter((item) => item.changes.includes(id));
337
+ if (owners.some((item) => item.status !== "done" || (item.controllerId ?? item.lastAttempt?.controllerId ?? String(controller)) !== String(controller)))
338
+ throw new Error(`来源 #${id} 所属任务尚未验收,或属于其他总控。`);
339
+ return source;
340
+ });
341
+ const first = sources[0];
342
+ if (sources.some((source) => resolve(source.root).toLowerCase() !== resolve(first.root).toLowerCase() || source.subdir !== first.subdir))
343
+ throw new Error("联合集成的来源必须属于同一仓库和工作目录。");
344
+ const checks = autonomyChecksForRoot(first.root, config);
345
+ if (!checks.length) {
346
+ if (!sameConfigRepoRoot(first.root, config))
347
+ throw new Error(`外部仓库 ${first.root} 未配置 autonomy.checks(请在目标仓库添加 pi-agent.config.json 或按目标目录新建会话并配置检查),未误用主仓库检查。`);
348
+ throw new Error("请先配置 autonomy.checks 作为联合测试命令;没有检查不能标记集成通过。");
349
+ }
350
+ for (const check of checks)
351
+ if (!check.name || !check.command || !Array.isArray(check.args) || check.args.some((arg) => typeof arg !== "string") || check.timeoutSeconds !== undefined && (!Number.isFinite(check.timeoutSeconds) || check.timeoutSeconds <= 0))
352
+ throw new Error("联合检查需要有效的名称、命令、参数和正数超时。");
353
+ const id = `I${createHash("sha256").update(`${controller}:${key}`).digest("hex").slice(0, 12)}`;
354
+ const path = join(dirname(config.storage), "worktrees", "integrations", id), branch = `codex/integration-${id}`;
355
+ const taskId = await tx.createTask(task, { id }, { ownership: { kind: "conversation" }, conversationId: controller, background: true });
356
+ const taskLabel = extra?.repair ? `修复集成 #${extra.repair.fromId}(${ids.map((s) => `#${s}`).join(" + ")})` : `联合集成 ${ids.map((s) => `#${s}`).join(" + ")}`;
357
+ const record = {
358
+ id, agent: "integration", callId: key, task: taskLabel, root: first.root, subdir: first.subdir, path, branch, base: "", head: "", files: [], add: 0, del: 0, status: "running", createdAt: Date.now(), updatedAt: Date.now(),
359
+ integration: {
360
+ id, controllerId: String(controller), taskId: String(taskId),
361
+ sources: sources.map((source) => ({ id: source.id, base: changes.range(source)[0], head: source.head })),
362
+ baselineTree: "", checks: clone(checks), status: "preparing", reports: [],
363
+ ...(extra?.replacesId ? { replacesId: extra.replacesId } : {}),
364
+ ...(extra?.repair ? { repair: clone(extra.repair) } : {}),
365
+ },
366
+ };
367
+ doc.records[id] = clone(record);
368
+ doc.byKey[key] = id;
369
+ if (extra?.replacesId && doc.records[extra.replacesId]?.integration) {
370
+ const old = doc.records[extra.replacesId];
371
+ old.integration.supersededBy = id;
372
+ publish(old);
373
+ for (const item of Object.values(board.tasks)) {
374
+ if (item.integrationId === extra.replacesId && item.status === "blocked" && !item.dispatches.length && (item.controllerId ?? String(controller)) === String(controller)) {
375
+ item.integrationId = id;
376
+ item.status = "todo";
377
+ item.notes.push(`已使用新联合集成 #${id} 替代 #${extra.replacesId},等待联合验证通过后继续。`);
378
+ item.updatedAt = Date.now();
379
+ }
380
+ }
381
+ if (hooks.ensureWorkflow)
382
+ await hooks.ensureWorkflow(tx, controller);
383
+ }
384
+ return record;
385
+ }
386
+ async function rerun(tx, controller, targetId, key) {
387
+ const doc = await tx.doc(Integrations), existing = doc.byKey[key];
388
+ if (existing && doc.records[existing])
389
+ return clone(doc.records[existing]);
390
+ const original = doc.records[targetId] ?? Object.values(doc.records).find((r) => r.id.startsWith(targetId));
391
+ if (!original?.integration || original.integration.controllerId !== String(controller))
392
+ throw new Error("找不到本总控的集成记录。");
393
+ if (!ended(original))
394
+ throw new Error(`集成 #${original.id} 仍在运行中;如需重来请先取消。`);
395
+ if (original.status === "applied")
396
+ throw new Error(`集成 #${original.id} 已应用到主目录,无需重验。`);
397
+ return create(tx, controller, original.integration.sources.map((s) => s.id), key, { replacesId: original.id });
398
+ }
399
+ async function repair(tx, controller, targetId, member, note, model, key) {
400
+ const doc = await tx.doc(Integrations), existing = doc.byKey[key];
401
+ if (existing && doc.records[existing])
402
+ return clone(doc.records[existing]);
403
+ const original = doc.records[targetId] ?? Object.values(doc.records).find((r) => r.id.startsWith(targetId));
404
+ if (!original?.integration || original.integration.controllerId !== String(controller))
405
+ throw new Error("找不到本总控的集成记录。");
406
+ if (!["conflict", "failed"].includes(original.integration.status))
407
+ throw new Error(`仅失败(failed)或冲突(conflict)的集成可启动修复;当前状态为 ${original.integration.status}。`);
408
+ if (!config.isolation.enabled)
409
+ throw new Error("集成修复需要启用 Git worktree 隔离(isolation.enabled = true)。");
410
+ if (!hooks.available?.has(member) || !hooks.enqueue)
411
+ throw new Error(`编码成员 ${member} 当前不可用,请检查 /agents。`);
412
+ const agentCfg = config.agents[member];
413
+ if (!agentCfg || agentCfg.workspace === "none")
414
+ throw new Error(`成员 ${member} 不是代码工作区成员(workspace=none),不能执行集成代码修复。`);
415
+ if (agentCfg.api && !memberToolNames(agentCfg.api).some((t) => ["write", "edit"].includes(t)))
416
+ throw new Error(`API 成员 ${member} 缺少 write/edit 权限,不能执行集成代码修复。`);
417
+ if (model && agentCfg.models.length && !agentCfg.models.some((m) => m.id === model))
418
+ throw new Error(`成员 ${member} 没有配置模型 ${model}。`);
419
+ const failedReport = original.integration.reports.find((r) => !r.passed);
420
+ const previousFailure = [
421
+ original.message ?? "",
422
+ failedReport ? `[${failedReport.name} exit ${failedReport.exitCode}]\n${failedReport.output.slice(-2500)}` : "",
423
+ ].filter(Boolean).join("\n");
424
+ return create(tx, controller, original.integration.sources.map((s) => s.id), key, {
425
+ replacesId: original.id,
426
+ repair: {
427
+ fromId: original.id,
428
+ member,
429
+ ...(model ? { model } : {}),
430
+ ...(note?.trim() ? { note: note.trim().slice(0, 2000) } : {}),
431
+ callId: `integration-repair:${key}`,
432
+ ...(previousFailure ? { previousFailure } : {}),
433
+ },
434
+ });
435
+ }
436
+ const tool = defineTool({
437
+ name: "integrate_changes",
438
+ description: "将 2–8 个已验收的成员代码改动放到独立集成 worktree,依次合并并运行配置中的 autonomy.checks;也可传 rerun_id 基于最新基线重验。传 wait:true 时由 Durable 原生挂起等待合流与测试完成并直接返回最终结果,省去额外调用 read_integration 的往返;只有用户终端 /apply 才应用。",
439
+ parameters: obj({
440
+ changes: opt(arr(str(), { minItems: 2, maxItems: 8, description: "2–8 个已验收成员改动编号(与 rerun_id 二选一)" })),
441
+ rerun_id: opt(str({ description: "要基于当前最新主目录与来源基线重新合并验证的旧集成编号" })),
442
+ wait: opt(bool({ description: "为 true 时等待联合集成与全部检查完成后直接返回结果(推荐,减少总调度轮次)" })),
443
+ }),
444
+ replay: "safe",
445
+ execute: async (args, api, context) => {
446
+ try {
447
+ if (api.checkpoint?.id) {
448
+ const current = (await api.snapshot(Integrations, context))?.records[api.checkpoint.id];
449
+ if (current && !ended(current))
450
+ return { sleep: { until: api.now() + 250 }, checkpoint: api.checkpoint };
451
+ const resolved = current ? changes.get(current.id) ?? current : changes.get(api.checkpoint.id);
452
+ return { output: [{ type: "text", text: JSON.stringify(resolved ? integrationSummary(resolved) : { id: api.checkpoint.id, status: "unknown" }) }] };
453
+ }
454
+ if (!args.rerun_id && (!args.changes || args.changes.length < 2))
455
+ throw new Error("请提供 2–8 个 changes 改动编号,或指定 rerun_id 重验已有集成。");
456
+ const record = await api.commit((tx) => args.rerun_id ? rerun(tx, api.conversationId, args.rerun_id, `tool:${api.taskId}`) : create(tx, api.conversationId, args.changes, `tool:${api.taskId}`), context);
457
+ publish(record);
458
+ if (args.wait && !ended(record))
459
+ return { sleep: { until: api.now() + 250 }, checkpoint: { id: record.id } };
460
+ return { output: [{ type: "text", text: JSON.stringify(integrationSummary(record)) }] };
461
+ }
462
+ catch (error) {
463
+ return { output: [{ type: "text", text: String(error) }], isError: true };
464
+ }
465
+ },
466
+ });
467
+ const repairTool = defineTool({
468
+ name: "repair_integration",
469
+ description: "针对处于 conflict(合并冲突)或 failed(联合检查未通过)的联合集成,在独立修复副本中派编码成员解决冲突或跨模块问题,完成后自动重跑全部 autonomy.checks。传 wait:true 时原生等待修复与重验完成并直接返回最终结果。",
470
+ parameters: obj({
471
+ id: str({ description: "处于 conflict 或 failed 状态的集成编号(如 I...)" }),
472
+ member: str({ description: "负责修复的可用编码成员 ID(CLI 或具备写权限的 API 编码成员)" }),
473
+ note: opt(str({ description: "可选修复提示,说明如何取舍冲突或对齐接口" })),
474
+ model: opt(str({ description: "可选指定成员模型 ID" })),
475
+ wait: opt(bool({ description: "为 true 时等待修复与联合检查全部完成后直接返回最终结果" })),
476
+ }),
477
+ replay: "safe",
478
+ execute: async (args, api, context) => {
479
+ try {
480
+ if (api.checkpoint?.id) {
481
+ const current = (await api.snapshot(Integrations, context))?.records[api.checkpoint.id];
482
+ if (current && !ended(current))
483
+ return { sleep: { until: api.now() + 250 }, checkpoint: api.checkpoint };
484
+ const resolved = current ? changes.get(current.id) ?? current : changes.get(api.checkpoint.id);
485
+ return { output: [{ type: "text", text: JSON.stringify(resolved ? integrationSummary(resolved) : { id: api.checkpoint.id, status: "unknown" }) }] };
486
+ }
487
+ const record = await api.commit((tx) => repair(tx, api.conversationId, args.id, args.member, args.note, args.model, `tool:${api.taskId}`), context);
488
+ publish(record);
489
+ if (args.wait && !ended(record))
490
+ return { sleep: { until: api.now() + 250 }, checkpoint: { id: record.id } };
491
+ return { output: [{ type: "text", text: JSON.stringify(integrationSummary(record)) }] };
492
+ }
493
+ catch (error) {
494
+ return { output: [{ type: "text", text: String(error) }], isError: true };
495
+ }
496
+ },
497
+ });
498
+ const read = defineTool({
499
+ name: "read_integration",
500
+ description: "读取当前总控的联合集成进度与检查结果;wait:true 等待完成时由 Durable 原生挂起,不反复调用模型。",
501
+ parameters: obj({ id: opt(str()), wait: opt(bool()) }),
502
+ replay: "safe",
503
+ execute: async (args, api, context) => {
504
+ const records = Object.values((await api.snapshot(Integrations, context))?.records ?? {}).filter((record) => record.integration?.controllerId === String(api.conversationId) && (!args.id || record.id === args.id));
505
+ if (args.wait && records.some((record) => !ended(record)))
506
+ return { sleep: { until: api.now() + 250 } };
507
+ return { output: [{ type: "text", text: JSON.stringify(records.map((record) => integrationSummary(changes.get(record.id) ?? record))) }], isError: !!args.id && !records.length };
508
+ },
509
+ });
510
+ return {
511
+ task,
512
+ tools: [tool, repairTool, read],
513
+ create,
514
+ rerun,
515
+ repair,
516
+ async start(controller, ids, context) {
517
+ if (!hub.harness)
518
+ throw new Error("运行时尚未就绪。");
519
+ const record = await hub.harness.commit((tx) => create(tx, controller, ids, `terminal:${randomUUID()}`), context);
520
+ publish(record);
521
+ hub.harness.resume();
522
+ return record;
523
+ },
524
+ async startRerun(controller, id, context) {
525
+ if (!hub.harness)
526
+ throw new Error("运行时尚未就绪。");
527
+ const record = await hub.harness.commit((tx) => rerun(tx, controller, id, `terminal-rerun:${randomUUID()}`), context);
528
+ publish(record);
529
+ hub.harness.resume();
530
+ return record;
531
+ },
532
+ async startRepair(controller, id, member, note, context) {
533
+ if (!hub.harness)
534
+ throw new Error("运行时尚未就绪。");
535
+ const record = await hub.harness.commit((tx) => repair(tx, controller, id, member, note, undefined, `terminal-repair:${randomUUID()}`), context);
536
+ publish(record);
537
+ hub.harness.resume();
538
+ return record;
539
+ },
540
+ async cancel(controller, id, context) {
541
+ const record = (await hub.harness?.snapshot(Integrations, context))?.records[id];
542
+ if (!record || record.integration?.controllerId !== String(controller))
543
+ throw new Error("找不到本总控的集成记录。");
544
+ if (ended(record))
545
+ return;
546
+ const repairJobId = record.integration.repair?.jobId;
547
+ if (repairJobId) {
548
+ await hub.cancel(repairJobId, "user", context);
549
+ const job = (await hub.harness?.snapshot(Jobs, context))?.jobs[repairJobId];
550
+ if (job?.piTask)
551
+ await hub.harness.abortTask(Number(job.piTask), BACKGROUND_CONTEXT).catch(() => { });
552
+ }
553
+ await hub.cancel(`integration:${record.id}`, "user", context);
554
+ await hub.harness.abortTask(Number(record.integration.taskId), context);
555
+ },
556
+ };
557
+ }
package/dist/jobs.js ADDED
@@ -0,0 +1,100 @@
1
+ // 后台派工(异步):总调度把任务交给成员后不必干等,可以继续派别的活、回复用户;
2
+ // 成员做完后结果自动发回总调度(【后台结果 Jn】),或者由 wait_jobs 一次收齐。
3
+ // 每个后台派工是一个 Pi Durable 后台任务:进程崩溃 / 重启后会续接成员的会话接着做。
4
+ import { EventEmitter } from "node:events";
5
+ import { defineDoc, defineSignal } from "@earendil-works/pi-durable";
6
+ import { obj, str } from "@earendil-works/pi-schema";
7
+ export const Jobs = defineDoc({
8
+ kind: "pi-agent.jobs",
9
+ version: 1,
10
+ scope: "session",
11
+ initial: () => ({ jobs: {}, nextId: 1, byCall: {} }),
12
+ checkpointWhen: () => false,
13
+ });
14
+ /** 后台派工结束时发给正在等它的 wait_jobs */
15
+ export const JobDone = defineSignal({ name: "pi-agent.job-done", version: 1, schema: obj({ id: str() }) });
16
+ /** 后台结果消息的 requestId 前缀:由它开始的运行不重置花费(仍算用户那一轮的) */
17
+ export const JOB_REQUEST_PREFIX = "pi-agent:job:";
18
+ /** 后台结果在对话里的条目类型(网页和终端据此显示成「后台结果」而不是「你」) */
19
+ export const JOB_REPORT_ENTRY = "pi-agent.job-report";
20
+ const STATUS_WORD = { running: "进行中", done: "完成", failed: "失败", cancelled: "已取消" };
21
+ export function jobLabel(job) {
22
+ return [job.agent, job.model ? `模型 ${job.model}` : undefined, job.taskId ? `任务 ${job.taskId}` : undefined].filter(Boolean).join(" · ");
23
+ }
24
+ /** 一次后台派工的结果:自动发回和 wait_jobs 用同一个格式 */
25
+ export function jobReport(job) {
26
+ const head = `【后台结果 ${job.id} · ${STATUS_WORD[job.status]}】${jobLabel(job)}`;
27
+ const meta = [
28
+ job.durationMs !== undefined ? `耗时 ${Math.round(job.durationMs / 1000)}s` : undefined,
29
+ job.costUsd !== undefined ? `花费 $${job.costUsd.toFixed(4)}${job.costEstimated ? "(估算)" : ""}` : undefined,
30
+ job.sessionId ? `session_id: ${job.sessionId}` : undefined,
31
+ ].filter(Boolean);
32
+ const body = job.status === "cancelled" ? `已被${job.cancelledBy === "user" ? "用户" : "你"}取消。${job.result ? `\n${job.result}` : ""}` : (job.result ?? "(没有输出)");
33
+ return `${head}${meta.length ? `(${meta.join(",")})` : ""}\n任务:${clip(job.task, 120)}\n\n${body}`;
34
+ }
35
+ export function clip(text, max) {
36
+ const t = text.replace(/\s+/g, " ").trim();
37
+ return t.length > max ? `${t.slice(0, max)}…` : t;
38
+ }
39
+ /**
40
+ * 本进程里后台派工的运行时状态(不持久化):取消开关、成员的实时输出、正在使用的会话。
41
+ * 终端、网页、工具共用一个实例。
42
+ */
43
+ export class JobHub extends EventEmitter {
44
+ controllers = new Map();
45
+ lines = new Map();
46
+ /** 正在执行的会话:同一个会话不能同时被两次派工续接 */
47
+ busySessions = new Map();
48
+ /** 进程正在关闭:被打断的派工不收尾,重启后续接 */
49
+ closing = false;
50
+ harness;
51
+ register(id) {
52
+ const controller = new AbortController();
53
+ this.controllers.set(id, { controller });
54
+ return controller.signal;
55
+ }
56
+ release(id) {
57
+ const entry = this.controllers.get(id);
58
+ this.controllers.delete(id);
59
+ return entry?.by;
60
+ }
61
+ running(id) {
62
+ return this.controllers.has(id);
63
+ }
64
+ cancelledBy(id) {
65
+ return this.controllers.get(id)?.by;
66
+ }
67
+ /** 取消一次后台派工:本进程里在跑的直接停掉(由任务自己收尾);否则走 Pi Durable 的中止 */
68
+ async cancel(id, by, context) {
69
+ const entry = this.controllers.get(id);
70
+ if (entry) {
71
+ entry.by = by;
72
+ entry.controller.abort();
73
+ return "cancelled";
74
+ }
75
+ const doc = this.harness ? (await this.harness.snapshot(Jobs, context)) : undefined;
76
+ const job = doc?.jobs[id];
77
+ if (!job)
78
+ return "not_found";
79
+ if (job.status !== "running")
80
+ return "not_running";
81
+ await this.harness.abortTask(Number(job.piTask), context);
82
+ return "cancelled";
83
+ }
84
+ output(id, chunk) {
85
+ const list = this.lines.get(id) ?? [];
86
+ for (const line of chunk.split("\n")) {
87
+ if (!line.trim())
88
+ continue;
89
+ list.push(line);
90
+ this.emit("output", id, line);
91
+ }
92
+ this.lines.set(id, list.slice(-80));
93
+ }
94
+ recent(id) {
95
+ return this.lines.get(id) ?? [];
96
+ }
97
+ changed() {
98
+ this.emit("change");
99
+ }
100
+ }