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,21 @@
1
+ import { defineDoc } from "@earendil-works/pi-durable";
2
+ /** Intent and reconciliation are Durable documents, shared by members in this work session. */
3
+ export const Operations = defineDoc({
4
+ kind: "lemma.business-operations", version: 1, scope: "session", initial: () => ({ operations: {} }), checkpointWhen: () => false,
5
+ });
6
+ export const operationList = (state) => Object.values(state?.operations ?? {}).sort((a, b) => b.updatedAt - a.updatedAt);
7
+ export const unresolved = (operation) => operation.status === "pending" || operation.status === "unknown";
8
+ export async function resolveOperation(tx, id, outcome, evidence, at) {
9
+ const operation = (await tx.doc(Operations)).operations[id];
10
+ if (!operation || !unresolved(operation))
11
+ throw new Error("操作不存在或已完成核对。");
12
+ if (!evidence.trim())
13
+ throw new Error("需要填写人工查询远端状态的依据。");
14
+ const task = await tx.task(Number(operation.taskId));
15
+ if (task && !["terminal", "completing"].includes(task.state.status))
16
+ throw new Error("操作任务仍在运行,请先等待结束或取消后再核对。");
17
+ operation.status = "resolved";
18
+ operation.updatedAt = at;
19
+ operation.resolution = { outcome, evidence: evidence.trim().slice(0, 3000), at };
20
+ return outcome === "succeeded" ? "已记录远端成功,原失败交付仍保留;请基于远端凭证继续核对,勿重复提交。" : "已记录远端未执行,可在明确原因后重新派工。";
21
+ }
@@ -0,0 +1,113 @@
1
+ import { JOB_REPORT_ENTRY } from "./jobs.js";
2
+ const c = {
3
+ dim: (s) => `\x1b[2m${s}\x1b[0m`,
4
+ cyan: (s) => `\x1b[36m${s}\x1b[0m`,
5
+ yellow: (s) => `\x1b[33m${s}\x1b[0m`,
6
+ green: (s) => `\x1b[32m${s}\x1b[0m`,
7
+ red: (s) => `\x1b[31m${s}\x1b[0m`,
8
+ };
9
+ export const colors = c;
10
+ let sink;
11
+ export function setOutputSink(next) { sink = next; }
12
+ export function writeLine(text = "") {
13
+ if (sink)
14
+ sink(text);
15
+ else
16
+ console.log(text);
17
+ }
18
+ function textOf(content) {
19
+ if (typeof content === "string")
20
+ return content;
21
+ if (!Array.isArray(content))
22
+ return "";
23
+ return content
24
+ .filter((b) => b?.type === "text")
25
+ .map((b) => b.text)
26
+ .join("");
27
+ }
28
+ function clip(text, max) {
29
+ const t = text.trim();
30
+ return t.length > max ? `${t.slice(0, max)}…` : t;
31
+ }
32
+ export function printEntry(entry) {
33
+ const message = entry.model?.[0];
34
+ if (!message)
35
+ return;
36
+ if (entry.kind === JOB_REPORT_ENTRY) {
37
+ // 后台派工的结果发回总调度:标题行醒目,正文截一段
38
+ const [head = "", ...body] = textOf(message.content).split("\n");
39
+ const failed = /· (失败|已取消)】/.test(head);
40
+ writeLine(`\n${failed ? c.red(`◆ ${head}`) : c.yellow(`◆ ${head}`)}\n${c.dim(clip(body.join("\n").replace(/\n*(这是后台派工的结果[\s\S]*$/, ""), 800))}`);
41
+ return;
42
+ }
43
+ if (entry.kind === "pi.assistant") {
44
+ for (const block of message.content ?? []) {
45
+ if (block.type === "text" && block.text?.trim())
46
+ writeLine(`\n${c.green("总调度 ›")} ${block.text.trim()}`);
47
+ if (block.type === "toolCall") {
48
+ const args = block.arguments ?? {};
49
+ const extra = c.dim(`${args.background ? " (后台)" : ""}${args.session_id ? ` (续接 ${args.session_id})` : ""}`);
50
+ writeLine(`\n${c.cyan(`→ ${block.name}`)}${extra}\n${c.dim(clip(String(args.task ?? JSON.stringify(args)), 400))}`);
51
+ }
52
+ }
53
+ if (message.stopReason === "error" && message.errorMessage)
54
+ writeLine(c.red(`\n模型出错:${message.errorMessage}`));
55
+ }
56
+ else if (entry.kind === "pi.tool-result") {
57
+ const text = textOf(message.content);
58
+ const label = message.isError ? c.red(`✗ ${message.toolName} 失败`) : c.yellow(`✓ ${message.toolName} 完成`);
59
+ writeLine(`\n${label}\n${c.dim(clip(text, 1200))}`);
60
+ }
61
+ }
62
+ /** 订阅会话:打印新条目和工具的实时输出。返回停止函数。 */
63
+ export async function follow(root, context, options = {}) {
64
+ const watch = await root.watch(context);
65
+ const seen = new Set(watch.value.entries.map((e) => e.id));
66
+ const printedOutput = new Map();
67
+ if (options.replay) {
68
+ // 只回放最近一次重置(/new)之后的内容:重置前的记录模型已经看不到了,也不该再刷到屏幕上
69
+ const entries = watch.value.entries;
70
+ const lastReset = entries.findLastIndex((e) => e.kind === "pi.reset");
71
+ if (lastReset >= 0)
72
+ writeLine(c.dim("(更早的对话已重置:模型不再看到它们,记录仍在存储里,网页「运行记录」可查看)"));
73
+ for (const entry of entries.slice(lastReset + 1)) {
74
+ if (entry.kind === "pi.user")
75
+ writeLine(`你 › ${textOf(entry.model?.[0]?.content)}`);
76
+ else
77
+ printEntry(entry);
78
+ }
79
+ }
80
+ options.onLive?.(watch.value.docs["pi.live"]);
81
+ watch.start(async (call) => {
82
+ if (call.kind !== "value")
83
+ return;
84
+ const { value } = call;
85
+ for (const entry of value.entries) {
86
+ if (seen.has(entry.id))
87
+ continue;
88
+ seen.add(entry.id);
89
+ printEntry(entry);
90
+ }
91
+ const live = value.docs["pi.live"];
92
+ options.onLive?.(live);
93
+ for (const slot of [...(live?.tools ?? []), ...(live?.nestedTools ?? [])]) {
94
+ const output = slot.output;
95
+ if (!output)
96
+ continue;
97
+ const done = printedOutput.get(slot.callId) ?? 0;
98
+ if (output.length > done) {
99
+ const fresh = output.slice(done);
100
+ printedOutput.set(slot.callId, output.length);
101
+ for (const line of fresh.split("\n"))
102
+ if (line.trim())
103
+ writeLine(c.dim(` [${slot.name}] ${line}`));
104
+ }
105
+ else if (output.length < done) {
106
+ printedOutput.set(slot.callId, output.length); // 输出窗口滚动了
107
+ }
108
+ }
109
+ });
110
+ return async () => {
111
+ await watch.stop();
112
+ };
113
+ }
package/dist/repair.js ADDED
@@ -0,0 +1,102 @@
1
+ import { createHash } from "node:crypto";
2
+ import { checkBudget, RunBudget, runDispatch } from "./dispatch.js";
3
+ import { Learning } from "./learning.js";
4
+ import { Results } from "./results.js";
5
+ export async function managedDispatch(kind, command, deps, args, io, label) {
6
+ const policy = deps.config.autonomy;
7
+ if (!policy.enabled || deps.config.agents[kind].workspace === "none" || deps.config.agents[kind].api?.httpTools?.some((tool) => tool.method === "POST"))
8
+ return runDispatch(kind, command, deps, args, io, label);
9
+ const completed = await io.memo("managed-result");
10
+ if (completed)
11
+ return completed;
12
+ const runKey = await io.commit(async (tx) => (await tx.doc(RunBudget)).runKey);
13
+ const fingerprint = createHash("sha256").update(args.task_id ?? args.task.replace(/\s+/g, " ").trim()).digest("hex").slice(0, 20);
14
+ let key = `${runKey}:${kind}:${fingerprint}`;
15
+ const previous = await io.commit(async (tx) => JSON.parse(JSON.stringify((await tx.doc(Learning)).events.filter((e) => e.key === key))));
16
+ // Freeze this call's starting attempt; replay must revisit an interrupted repair,
17
+ // while a separate repeated call still observes the shared task repair limit.
18
+ const checkpoint = await io.memo("repair-start", { used: previous.reduce((max, event) => Math.max(max, event.attempt), 0), key });
19
+ const used = checkpoint.used;
20
+ key = checkpoint.key;
21
+ if (used >= policy.maxRepairAttempts && previous.some((e) => e.attempt === used && e.status === "failed")) {
22
+ return { text: "这项任务已耗尽本轮自动修复次数,停止重复派工。请汇报失败证据;用户明确调整任务后再继续。", isError: true };
23
+ }
24
+ let result = await runDispatch(kind, command, deps, args, io, label);
25
+ const firstFailure = result.text.slice(-1200);
26
+ let totalCost = result.summary?.costUsd ?? 0;
27
+ let completeCost = result.summary?.costUsd !== undefined;
28
+ let totalTime = result.summary?.durationMs ?? 0;
29
+ let attempts = 0;
30
+ for (let attempt = used + 1; result.isError && !result.aborted && attempt <= policy.maxRepairAttempts; attempt++) {
31
+ if (io.signal.aborted || deps.hub.closing)
32
+ break;
33
+ const summary = result.summary;
34
+ // 没有可续接的执行上下文、权限/认证错误等,交回调度,不盲目重复付费。
35
+ if (!summary?.sessionId && !summary?.changeId)
36
+ break;
37
+ if (/超时|timed? ?out|permission denied|权限拒绝|被权限拒绝|unauthorized|authentication|api.?key|insufficient|余额|没有就绪|不可用|已达上限/i.test(result.text))
38
+ break;
39
+ const repairReceipt = await io.commit(async (tx) => !!(await tx.doc(Results, io.conversationId, `dispatch:${io.taskId}:repair:${attempt}`, null)).result?.dispatch);
40
+ const over = repairReceipt ? undefined : await checkBudget(io, deps.config, false);
41
+ if (over) {
42
+ result.text += `\n\n${over}`;
43
+ if (result.summary)
44
+ result.summary.body += `\n\n${over}`;
45
+ break;
46
+ }
47
+ attempts = attempt;
48
+ await io.commit(async (tx) => {
49
+ const state = await tx.doc(Learning);
50
+ if (!state.events.some((e) => e.key === key && e.attempt === attempt)) {
51
+ state.events.push({ key, task: args.task.slice(0, 200), agent: kind, attempt, status: "repairing", at: io.now() });
52
+ state.events = state.events.slice(-100);
53
+ }
54
+ });
55
+ io.output(`自动修复 ${attempt}/${policy.maxRepairAttempts}:续接 ${kind},只传本次失败摘要\n`);
56
+ const repairIO = {
57
+ ...io, attemptOf: io.callId, callId: `${io.callId}:repair:${attempt}`, taskId: `${io.taskId}:repair:${attempt}`,
58
+ memo: (name, candidate) => io.memo(`repair.${attempt}.${name}`, candidate),
59
+ };
60
+ const next = {
61
+ task: `原任务:${args.task.slice(0, 2500)}\n\n自动修复 ${attempt}/${policy.maxRepairAttempts}。当前代码未通过验收,检查根因并最小修改,保留原有验收标准,不要跳过或弱化检查。\n失败证据(节选):\n${result.text.slice(-3000)}`,
62
+ ...(args.task_id ? { task_id: args.task_id } : {}),
63
+ ...(args.model ? { model: args.model } : {}),
64
+ ...(args.structured ? { structured: true } : {}),
65
+ ...(summary.sessionId ? { session_id: summary.sessionId } : { based_on: summary.changeId }),
66
+ };
67
+ result = await runDispatch(kind, command, deps, next, repairIO, label);
68
+ totalCost += result.summary?.costUsd ?? 0;
69
+ completeCost &&= result.summary?.costUsd !== undefined;
70
+ totalTime += result.summary?.durationMs ?? 0;
71
+ await io.commit(async (tx) => {
72
+ const event = (await tx.doc(Learning)).events.find((e) => e.key === key && e.attempt === attempt);
73
+ if (event)
74
+ event.status = result.aborted ? "cancelled" : result.isError ? "failed" : "completed";
75
+ });
76
+ }
77
+ if (attempts) {
78
+ const change = result.summary?.changeId ? deps.changes.get(result.summary.changeId) : undefined;
79
+ if (!result.isError && change?.verification?.passed && change.verification.head === change.head) {
80
+ await io.commit(async (tx) => {
81
+ const state = await tx.doc(Learning);
82
+ if (!state.lessons.some((l) => l.key === key))
83
+ state.lessons.push({ key, kind: "repair", task: args.task.slice(0, 200), files: change.files.map((f) => f.path).slice(0, 20), checks: change.verification.checks, repairs: attempts, at: io.now(), failure: firstFailure, resolution: result.summary?.body.slice(0, 800) ?? "", changeId: change.id, head: change.head });
84
+ state.lessons = state.lessons.slice(-50);
85
+ });
86
+ }
87
+ const note = `\n\n[自动修复 ${attempts}/${policy.maxRepairAttempts};${result.isError ? "尚未通过,停止重试并交回调度" : "派工完成,仍需对照任务验收"};本次派工已知累计 $${totalCost.toFixed(4)}${completeCost ? "" : ",含费用未知的执行"}]`;
88
+ result.text += note;
89
+ if (result.summary) {
90
+ result.summary.costUsd = completeCost ? totalCost : undefined;
91
+ result.summary.durationMs = totalTime;
92
+ result.summary.body += note;
93
+ }
94
+ if (result.details) {
95
+ result.details.costUsd = completeCost ? totalCost : null;
96
+ result.details.durationMs = totalTime;
97
+ result.details.repairs = attempts;
98
+ }
99
+ }
100
+ await io.memo("managed-result", JSON.parse(JSON.stringify(result)));
101
+ return result;
102
+ }
@@ -0,0 +1,31 @@
1
+ import { defineDoc } from "@earendil-works/pi-durable";
2
+ export const Resources = defineDoc({ kind: "lemma.resources", version: 1, scope: "session", initial: () => ({ claims: {} }), checkpointWhen: () => false });
3
+ export const CostLedger = defineDoc({ kind: "lemma.cost-ledger", version: 1, scope: "session", initial: () => ({ entries: {} }), checkpointWhen: () => false });
4
+ export const resourceService = (config, member) => config.agents[member]?.api ? new URL(config.agents[member].api.baseUrl).origin : `cli:${member}`;
5
+ /** Admission runs in a Durable transaction; sleeping callers retain only queue metadata. */
6
+ export async function admit(tx, config, input) {
7
+ const claims = (await tx.doc(Resources)).claims;
8
+ if (claims[input.id]?.status === "running")
9
+ return { state: "ready" };
10
+ const service = resourceService(config, input.member), reserve = config.budget.reservePerDispatchUsd ?? 0;
11
+ const policy = config.execution ?? {}, live = Object.values(claims).filter((claim) => claim.status === "running");
12
+ const queue = Object.values(claims).filter((claim) => claim.status === "queued").sort((a, b) => a.at - b.at || a.id.localeCompare(b.id));
13
+ const reason = live.length >= (policy.maxConcurrent ?? 8) ? "等待团队并发名额" : live.filter((claim) => claim.member === input.member).length >= (policy.perMember ?? 4) ? "等待成员并发名额" : live.filter((claim) => claim.service === service).length >= (policy.perService ?? 8) ? "等待服务并发名额" : undefined;
14
+ const existing = claims[input.id];
15
+ const reserved = live.filter((claim) => claim.runKey === input.runKey).reduce((sum, claim) => sum + claim.reservedUsd, 0);
16
+ if (config.budget.perRunUsd !== null && (input.spent >= config.budget.perRunUsd || input.spent + reserved + reserve > config.budget.perRunUsd)) {
17
+ claims[input.id] = { id: input.id, member: input.member, service, runKey: input.runKey, status: "released", reservedUsd: 0, at: existing?.at ?? input.at, reason: "预算不足(含并行预留)" };
18
+ return { state: "budget", reason: "已花费与并行预留达到预算,未启动新派工。预留为用户估计,不是实际账单上限。" };
19
+ }
20
+ // FIFO for callers competing for the same member/service; unrelated queues may proceed.
21
+ const ahead = queue.some((claim) => claim.id !== input.id && (claim.at < (existing?.at ?? input.at) || (claim.at === (existing?.at ?? input.at) && claim.id.localeCompare(input.id) < 0)) && (claim.member === input.member || claim.service === service));
22
+ const waiting = reason ?? (ahead ? "等待同服务先到任务" : undefined);
23
+ claims[input.id] = { id: input.id, member: input.member, service, runKey: input.runKey, status: waiting ? "queued" : "running", reservedUsd: waiting ? 0 : reserve, at: existing?.at ?? input.at, ...(waiting ? { reason: waiting } : {}) };
24
+ return waiting ? { state: "queued", reason: waiting } : { state: "ready" };
25
+ }
26
+ export async function releaseClaim(tx, id) { const claim = (await tx.doc(Resources)).claims[id]; if (claim) {
27
+ claim.status = "released";
28
+ claim.reservedUsd = 0;
29
+ delete claim.reason;
30
+ } }
31
+ export const resourceSnapshot = (state) => { const claims = Object.values(state?.claims ?? {}); return { running: claims.filter((claim) => claim.status === "running"), queued: claims.filter((claim) => claim.status === "queued"), reservedUsd: claims.reduce((sum, claim) => sum + claim.reservedUsd, 0) }; };
@@ -0,0 +1,8 @@
1
+ /** Shared by production dispatch and the context-cost ablation benchmark. */
2
+ export function summarizeResult(text, limit) {
3
+ if (!Number.isSafeInteger(limit) || limit < 1)
4
+ throw new Error("摘要长度需要为正整数。");
5
+ if (text.length <= limit)
6
+ return text;
7
+ return `${text.slice(0, Math.floor(limit * 0.6))}\n…(中间已省略,原文 ${text.length} 字符)\n${text.slice(-Math.floor(limit * 0.4))}`;
8
+ }
@@ -0,0 +1,41 @@
1
+ import { defineDocFamily, defineTool } from "@earendil-works/pi-durable";
2
+ import { int, obj, opt, str } from "@earendil-works/pi-schema";
3
+ import { parseDeliverable, resultExcerpt } from "./deliverables.js";
4
+ export const Results = defineDocFamily({
5
+ kind: "lemma.result", version: 1, scope: "conversation", history: "latest", fork: "initial", family: true,
6
+ initial: () => ({ result: null }), checkpointWhen: () => false,
7
+ });
8
+ export function resultPage(result, offset = 0, limit = 8000) {
9
+ if (!Number.isSafeInteger(offset) || offset < 0)
10
+ throw new RangeError("offset must be a nonnegative integer.");
11
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 8000)
12
+ throw new RangeError("limit must be between 1 and 8000.");
13
+ const end = Math.min(result.text.length, offset + limit);
14
+ return { id: result.id, member: result.member, conversationId: result.conversationId, status: result.status,
15
+ text: result.text.slice(offset, end), offset, nextOffset: end < result.text.length ? end : null, totalChars: result.text.length };
16
+ }
17
+ export async function storeResult(tx, controllerId, result) {
18
+ const delivery = parseDeliverable(result.text);
19
+ if (delivery)
20
+ result = { ...result, deliverable: delivery };
21
+ const doc = await tx.doc(Results, controllerId, result.id, null);
22
+ doc.result = result;
23
+ }
24
+ /** Retrieve full reports within the calling controller's scope. */
25
+ export function createReadResultTool() {
26
+ return defineTool({
27
+ name: "read_result", description: "Read a stored member result by result_id. Paginate with nextOffset; at most 8000 characters per call. Only results from this controller are accessible.",
28
+ parameters: obj({ result_id: str(), field: opt(str({ description: "可选结构化字段,如 conclusion、data.total、evidence、artifacts、incomplete" })), offset: opt(int({ minimum: 0 })), limit: opt(int({ minimum: 1, maximum: 8000 })) }),
29
+ replay: "safe",
30
+ execute: async (args, api, context) => {
31
+ const result = (await api.snapshot(Results, api.conversationId, args.result_id, context))?.result;
32
+ if (!result)
33
+ return { output: [{ type: "text", text: "Result not found in this controller." }], isError: true };
34
+ const delivery = result.deliverable ?? parseDeliverable(result.text);
35
+ const payload = delivery && args.field
36
+ ? { ...resultPage(result, args.offset, args.limit), field: args.field, ...resultExcerpt({ ...result, deliverable: delivery }, args), availableFields: Object.keys(delivery) }
37
+ : { ...resultPage(result, args.offset, args.limit), availableFields: delivery ? Object.keys(delivery) : [], ...(args.field ? { note: "该结果未启用结构化交付,已直接返回正文原文片段。" } : {}) };
38
+ return { output: [{ type: "text", text: JSON.stringify(payload) }], isError: false };
39
+ },
40
+ });
41
+ }
package/dist/scope.js ADDED
@@ -0,0 +1,114 @@
1
+ // 任务级路径边界契约(Task Scope Guard):
2
+ // 支持契约先行(Contract-First)与实现/测试分离(Adversarial Test Split)。
3
+ // 在 API 成员 write/edit 工具调用前实时拦截,并在 CLI/API 派工收尾及任务完成验收时硬性核对改动文件列表。
4
+ import { isAbsolute, posix } from "node:path";
5
+ export function normalizeScopePath(raw) {
6
+ return raw
7
+ .trim()
8
+ .replace(/\\/g, "/")
9
+ .replace(/^(?:\.\/)+/, "")
10
+ .replace(/^\/+/, "");
11
+ }
12
+ export function validateTaskScope(scope) {
13
+ if (!scope)
14
+ return;
15
+ for (const [key, list] of [["allow", scope.allow], ["forbid", scope.forbid]]) {
16
+ if (list === undefined)
17
+ continue;
18
+ if (!Array.isArray(list) || list.length === 0 || list.length > 16) {
19
+ throw new Error(`任务 scope.${key} 需要 1–16 条相对路径规则。`);
20
+ }
21
+ for (const item of list) {
22
+ if (typeof item !== "string" || !item.trim() || item.length > 200) {
23
+ throw new Error(`任务 scope.${key} 包含无效路径规则。`);
24
+ }
25
+ const raw = item.trim();
26
+ if (isAbsolute(raw) || /^[a-zA-Z]:[\\/]/.test(raw) || raw.startsWith("~") || /(^|[\\/])\.\.([\\/]|$)/.test(raw)) {
27
+ throw new Error(`任务 scope.${key} 只能使用工作目录内的相对路径,不能包含绝对路径或 "..":${raw}`);
28
+ }
29
+ }
30
+ }
31
+ }
32
+ function globToRegExp(pattern) {
33
+ let out = "^";
34
+ for (let i = 0; i < pattern.length; i++) {
35
+ const ch = pattern[i];
36
+ if (ch === "*") {
37
+ if (pattern[i + 1] === "*") {
38
+ out += ".*";
39
+ i++;
40
+ }
41
+ else {
42
+ out += "[^/]*";
43
+ }
44
+ }
45
+ else if (ch === "?") {
46
+ out += "[^/]";
47
+ }
48
+ else if (/[.+^${}()|[\]\\]/.test(ch)) {
49
+ out += `\\${ch}`;
50
+ }
51
+ else {
52
+ out += ch;
53
+ }
54
+ }
55
+ out += "$";
56
+ return new RegExp(out, "i");
57
+ }
58
+ export function matchesScopeRule(relPath, rawRule) {
59
+ const target = posix.normalize(normalizeScopePath(relPath)).toLowerCase();
60
+ const rule = normalizeScopePath(rawRule).toLowerCase();
61
+ if (!target || target === "." || !rule)
62
+ return false;
63
+ if (rule.includes("*") || rule.includes("?")) {
64
+ return globToRegExp(rule).test(target);
65
+ }
66
+ const cleanRule = rule.replace(/\/+$/, "");
67
+ if (!cleanRule)
68
+ return true;
69
+ if (rule.endsWith("/")) {
70
+ return target === cleanRule || target.startsWith(`${cleanRule}/`);
71
+ }
72
+ return target === cleanRule || target.startsWith(`${cleanRule}/`);
73
+ }
74
+ export function scopeViolation(relPath, scope) {
75
+ if (!scope)
76
+ return undefined;
77
+ const norm = normalizeScopePath(relPath);
78
+ if (!norm || norm === ".")
79
+ return undefined;
80
+ if (scope.forbid?.length) {
81
+ const hit = scope.forbid.find((rule) => matchesScopeRule(norm, rule));
82
+ if (hit) {
83
+ return `路径 ${norm} 命中本任务禁止修改范围(scope.forbid: ${hit})。请严格在任务职责边界内修改,不要触碰受保护的契约或测试文件。`;
84
+ }
85
+ }
86
+ if (scope.allow?.length) {
87
+ const ok = scope.allow.some((rule) => matchesScopeRule(norm, rule));
88
+ if (!ok) {
89
+ return `路径 ${norm} 超出本任务允许修改范围(scope.allow: ${scope.allow.join("、")})。请仅修改任务授权范围内的文件。`;
90
+ }
91
+ }
92
+ return undefined;
93
+ }
94
+ export function checkFilesScope(files, scope) {
95
+ if (!scope || (!scope.allow?.length && !scope.forbid?.length))
96
+ return [];
97
+ const violations = [];
98
+ for (const file of files) {
99
+ const violation = scopeViolation(file.path, scope);
100
+ if (violation)
101
+ violations.push(`${file.path}(${violation})`);
102
+ }
103
+ return violations;
104
+ }
105
+ export function formatScopeSummary(scope) {
106
+ if (!scope || (!scope.allow?.length && !scope.forbid?.length))
107
+ return "";
108
+ const parts = [];
109
+ if (scope.allow?.length)
110
+ parts.push(`允许修改:${scope.allow.join("、")}`);
111
+ if (scope.forbid?.length)
112
+ parts.push(`禁止修改:${scope.forbid.join("、")}`);
113
+ return parts.join(";");
114
+ }
@@ -0,0 +1,95 @@
1
+ // 每个顶层会话独占 SQLite、分工表和改动登记;项目源码通过已有 worktree 隔离。
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
4
+ export class SessionCatalog {
5
+ directory;
6
+ base;
7
+ constructor(base) {
8
+ this.base = base;
9
+ this.directory = `${base.storage}.sessions`;
10
+ }
11
+ get(id) {
12
+ this.validate(id);
13
+ if (id === "default") {
14
+ let title = "默认会话";
15
+ try {
16
+ title = JSON.parse(readFileSync(join(this.directory, "default.json"), "utf8")).title || title;
17
+ }
18
+ catch { }
19
+ const createdAt = existsSync(this.base.storage) ? statSync(this.base.storage).birthtimeMs : 0;
20
+ return { id, title, workdir: this.base.workdir, storage: this.base.storage, createdAt };
21
+ }
22
+ const file = join(this.directory, id, "session.json");
23
+ if (!existsSync(file))
24
+ throw new Error(`没有会话 ${id};用 /session new ${id} 新建。`);
25
+ const info = JSON.parse(readFileSync(file, "utf8"));
26
+ return { ...info, id, storage: join(this.directory, id, "session.sqlite") };
27
+ }
28
+ list() {
29
+ const result = [this.get("default")];
30
+ if (!existsSync(this.directory))
31
+ return result;
32
+ for (const entry of readdirSync(this.directory, { withFileTypes: true })) {
33
+ if (!entry.isDirectory())
34
+ continue;
35
+ try {
36
+ result.push(this.get(entry.name));
37
+ }
38
+ catch { /* 忽略损坏或半写入的目录。 */ }
39
+ }
40
+ return result.sort((a, b) => a.createdAt - b.createdAt);
41
+ }
42
+ create(id, workdir = this.base.workdir) {
43
+ this.validate(id);
44
+ if (id === "default" || existsSync(join(this.directory, id)))
45
+ throw new Error(`会话 ${id} 已存在。`);
46
+ const cwd = isAbsolute(workdir) ? resolve(workdir) : resolve(this.base.workdir, workdir);
47
+ if (!existsSync(cwd) || !statSync(cwd).isDirectory())
48
+ throw new Error(`项目目录不存在:${cwd}`);
49
+ mkdirSync(this.directory, { recursive: true });
50
+ const directory = join(this.directory, id);
51
+ mkdirSync(directory);
52
+ const info = { id, title: id, workdir: cwd, storage: join(directory, "session.sqlite"), createdAt: Date.now() };
53
+ writeFileSync(join(directory, "session.json"), JSON.stringify(info, null, 2));
54
+ return info;
55
+ }
56
+ rename(id, title) {
57
+ if (!title.trim() || title.length > 120)
58
+ throw new Error("标题需要 1–120 个字符。");
59
+ const info = this.get(id);
60
+ mkdirSync(this.directory, { recursive: true });
61
+ const file = id === "default" ? join(this.directory, "default.json") : join(this.directory, id, "session.json");
62
+ writeFileSync(`${file}.tmp`, JSON.stringify({ ...info, title: title.trim() }, null, 2));
63
+ renameSync(`${file}.tmp`, file);
64
+ }
65
+ /** 只保存选中编号;不会 reset、覆盖或删除任何对话存储。 */
66
+ select(id) {
67
+ this.get(id);
68
+ mkdirSync(this.directory, { recursive: true });
69
+ const file = join(this.directory, "selected.json");
70
+ writeFileSync(`${file}.tmp`, JSON.stringify({ id }));
71
+ renameSync(`${file}.tmp`, file);
72
+ }
73
+ selected() {
74
+ try {
75
+ const { id } = JSON.parse(readFileSync(join(this.directory, "selected.json"), "utf8"));
76
+ return this.get(id).id;
77
+ }
78
+ catch {
79
+ return "default";
80
+ }
81
+ }
82
+ config(id) {
83
+ const info = this.get(id);
84
+ return {
85
+ ...structuredClone(this.base), workdir: info.workdir, storage: info.storage,
86
+ ...((process.platform === "win32" ? resolve(info.workdir).toLowerCase() !== resolve(this.base.workdir).toLowerCase() : resolve(info.workdir) !== resolve(this.base.workdir)) ? { autonomy: { ...structuredClone(this.base.autonomy), checks: [] } } : {}),
87
+ ...(id === "default" ? {} : { projectStateDir: join(dirname(info.storage), "project") }),
88
+ };
89
+ }
90
+ validate(id) {
91
+ if (!/^[a-z0-9][a-z0-9_-]{0,47}$/.test(id) || /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/.test(id)) {
92
+ throw new Error("会话编号用 1–48 位小写字母、数字、短横线或下划线,且以字母或数字开头。");
93
+ }
94
+ }
95
+ }
@@ -0,0 +1,30 @@
1
+ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { normalizeConfig } from "./config.js";
4
+ /** Optimistic, atomic config update; preserve unknown fields and never overwrite external edits. */
5
+ export function editSettings(path) {
6
+ const before = existsSync(path) ? readFileSync(path, "utf8") : undefined;
7
+ let raw;
8
+ try {
9
+ raw = before === undefined ? {} : JSON.parse(before);
10
+ }
11
+ catch {
12
+ throw new Error("配置 JSON 无效,未修改原文件。");
13
+ }
14
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
15
+ throw new Error("配置需要对象,未修改原文件。");
16
+ return { raw, apply(change) { change(raw); return normalizeConfig(raw, path); }, save() {
17
+ normalizeConfig(raw, path);
18
+ const current = existsSync(path) ? readFileSync(path, "utf8") : undefined;
19
+ if (current !== before)
20
+ throw new Error("配置在编辑期间已被其他操作修改,请重新执行命令;未覆盖外部改动。");
21
+ const temporary = `${path}.${randomUUID()}.tmp`;
22
+ try {
23
+ writeFileSync(temporary, `${JSON.stringify(raw, null, 2)}\n`, { flag: "wx" });
24
+ renameSync(temporary, path);
25
+ }
26
+ finally {
27
+ rmSync(temporary, { force: true });
28
+ }
29
+ } };
30
+ }
@@ -0,0 +1,37 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { Board } from "./board.js";
3
+ import { prepareRecovery, taskRecoveryView } from "./task-recovery.js";
4
+ export const TASK_HELP = "/task inspect <任务ID> · /task resume <任务ID> <处理依据> · /task supply <任务ID> <新增资料> · /task reassign <任务ID> <成员ID> <交接依据> · /task cancel <任务ID> <原因>";
5
+ export async function taskCommand(line, host) {
6
+ if (!/^\/task(?:\s|$)/.test(line))
7
+ return false;
8
+ const [, action = "help", id, ...rest] = line.trim().split(/\s+/);
9
+ if (action === "help") {
10
+ host.log(TASK_HELP);
11
+ return true;
12
+ }
13
+ if (!id || !["inspect", "resume", "supply", "reassign", "cancel"].includes(action))
14
+ throw new Error(TASK_HELP);
15
+ const { app, context, config } = host;
16
+ if (action === "inspect") {
17
+ if (rest.length)
18
+ throw new Error(TASK_HELP);
19
+ host.log(JSON.stringify(taskRecoveryView(await app.harness.snapshot(Board, context), id, String(app.root.id)), null, 2));
20
+ return true;
21
+ }
22
+ await host.assertIdle();
23
+ const member = action === "reassign" ? rest.shift() : undefined, note = rest.join(" ");
24
+ const args = { id, action: action, note, ...(member ? { member } : {}) };
25
+ if (action === "cancel") {
26
+ const board = await app.harness.commit(async (tx) => { await prepareRecovery(tx, app.root.id, config, app.changes, args, randomUUID(), Date.now()); return JSON.parse(JSON.stringify(await tx.doc(Board))); }, context);
27
+ try {
28
+ app.project.writeAssign(board);
29
+ }
30
+ catch { }
31
+ host.log(`已取消 ${id} 尚未执行的恢复计划。`);
32
+ return true;
33
+ }
34
+ const job = await app.recoverTask(app.root.id, args, randomUUID(), context);
35
+ host.log(`恢复 ${id} 已交给 ${job.agent},后台 ${job.id};${job.resume ? `续接 ${job.resume}` : "新成员会话"}。不重跑已验收依赖;/jobs 查看,/jobs cancel ${job.id} 取消。`);
36
+ return true;
37
+ }
@@ -0,0 +1,49 @@
1
+ import { verifyReport } from "./acceptance.js";
2
+ import { autonomyChecksForRoot } from "./config.js";
3
+ import { checkFilesScope } from "./scope.js";
4
+ /** Shared by both review_task and the backwards-compatible update_task entry. */
5
+ export function completionRefusal(board, task, report, evidence, config, changes) {
6
+ if (!evidence.trim())
7
+ return "完成任务必须记录验收依据。";
8
+ if (!report || task.latestResult !== report.id || report.status !== "done")
9
+ return "没有成功的最新交付结果,不能完成任务。";
10
+ if (task.reviewer && !task.checksByMember?.some((check) => check.sourceResultId === report.id && check.member === task.reviewer.member && check.member !== report.member && check.status === "accepted" && !!check.resultId && !!check.evidence?.trim()))
11
+ return "该任务要求独立复核,当前交付尚无有效通过结论,不能绕过复核标完成。";
12
+ const independent = task.checksByMember?.findLast((check) => check.sourceResultId === report.id && check.status === "accepted");
13
+ if (independent?.sourceChangeId && changes.get(independent.sourceChangeId)?.head !== independent.sourceHead)
14
+ return "代码版本已变化,旧独立复核结论不能验收新的代码版本。";
15
+ if (task.activeDispatch || !["review", "done"].includes(task.status))
16
+ return "任务仍在执行或未进入待验收状态,不能完成。";
17
+ if (task.recoveries?.some((recovery) => ["prepared", "running"].includes(recovery.status)))
18
+ return "任务恢复计划尚未收尾,不能验收旧结果。";
19
+ if (task.deps.some((id) => board.tasks[id]?.status !== "done"))
20
+ return "前置任务尚未验收完成。";
21
+ if (Object.values(board.tasks).some((child) => child.parent === task.id && !["done", "dropped"].includes(child.status)))
22
+ return "还有未验收的子任务,不能完成上级任务。";
23
+ if (task.checks?.length && !verifyReport(report.id, report.text, task.acceptance, task.checks, report.createdAt).passed)
24
+ return "机器验收检查尚未通过,不能完成任务。";
25
+ if (task.scope && task.changes.some((id) => { const change = changes.get(id); return change && change.status !== "dropped" && checkFilesScope(change.files, task.scope).length > 0; }))
26
+ return "代码改动超出任务路径契约(scope),不能完成任务。";
27
+ if (config.autonomy.enabled && task.changes.some((id) => { const change = changes.get(id); return change && change.status !== "dropped" && change.files.length > 0 && autonomyChecksForRoot(change.root, config).length > 0 && (!change.verification || change.verification.head !== change.head || !change.verification.passed); }))
28
+ return "代码验收检查尚未通过,不能完成任务。";
29
+ }
30
+ export function recordReview(task, report, action, evidence, at) {
31
+ if (task.checks?.length)
32
+ task.verification = verifyReport(report.id, report.text, task.acceptance, task.checks, at);
33
+ task.status = action === "accept" ? "done" : action === "rework" ? "todo" : "blocked";
34
+ task.review = { resultId: report.id, verdict: action === "accept" ? "accepted" : action === "rework" ? "rework" : "blocked", evidence: evidence.trim().slice(0, 6000), at };
35
+ const note = `验收 ${action} · ${report.id}:${evidence.trim().slice(0, 1500)}`;
36
+ if (task.notes.at(-1) !== note)
37
+ task.notes.push(note);
38
+ task.updatedAt = at;
39
+ }
40
+ export function manualTransitionRefusal(task, status, note) {
41
+ if (!status || status === task.status)
42
+ return;
43
+ if (task.activeDispatch || task.status === "doing")
44
+ return "任务仍由派工执行;请先取消派工并等待收尾,再调整任务状态。";
45
+ if (["doing", "review"].includes(status))
46
+ return "进行中和待验收状态由真实派工产生,不能手动伪造。";
47
+ if (!note?.trim())
48
+ return "调整任务状态必须写明验收、返工、受阻或取消原因。";
49
+ }