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.
- package/README.md +140 -2
- package/bin/lemma.mjs +60 -0
- package/dist/acceptance.js +63 -0
- package/dist/admin.js +1482 -0
- package/dist/agents.js +245 -0
- package/dist/api-member.js +537 -0
- package/dist/app.js +161 -0
- package/dist/board.js +185 -0
- package/dist/business-tools.js +153 -0
- package/dist/change-ops.js +91 -0
- package/dist/changes.js +46 -0
- package/dist/cli-runner.js +106 -0
- package/dist/code-tools.js +396 -0
- package/dist/coding-benchmark-fixtures.js +1049 -0
- package/dist/coding-benchmark-suite.js +1252 -0
- package/dist/collaboration-benchmark.js +349 -0
- package/dist/config.js +392 -0
- package/dist/context-benchmark.js +91 -0
- package/dist/conventions.js +282 -0
- package/dist/conversation.js +39 -0
- package/dist/credentials.js +44 -0
- package/dist/deliverables.js +43 -0
- package/dist/digest.js +129 -0
- package/dist/dispatch.js +801 -0
- package/dist/execution-settings.js +24 -0
- package/dist/git-workbench.js +800 -0
- package/dist/git.js +149 -0
- package/dist/integration-git.js +108 -0
- package/dist/integrations.js +557 -0
- package/dist/jobs.js +100 -0
- package/dist/lead.js +263 -0
- package/dist/learning.js +36 -0
- package/dist/main.js +1459 -0
- package/dist/mcp-settings.js +45 -0
- package/dist/mcp-tools.js +102 -0
- package/dist/member-settings.js +245 -0
- package/dist/model-selection.js +48 -0
- package/dist/models.js +145 -0
- package/dist/native-selectors.js +45 -0
- package/dist/native-terminal-components.js +100 -0
- package/dist/ood-benchmark.js +660 -0
- package/dist/operations.js +21 -0
- package/dist/printer.js +113 -0
- package/dist/projects.js +282 -0
- package/dist/repair.js +102 -0
- package/dist/resources.js +31 -0
- package/dist/result-summary.js +8 -0
- package/dist/results.js +41 -0
- package/dist/scope.js +114 -0
- package/dist/sessions.js +95 -0
- package/dist/settings.js +32 -0
- package/dist/task-commands.js +37 -0
- package/dist/task-lifecycle.js +49 -0
- package/dist/task-readiness.js +22 -0
- package/dist/task-recovery.js +116 -0
- package/dist/task-review.js +70 -0
- package/dist/task-workflow.js +424 -0
- package/dist/terminal-layout.js +27 -0
- package/dist/terminal-state.js +145 -0
- package/dist/terminal.js +800 -0
- package/dist/tool-settings.js +111 -0
- package/dist/tools.js +1043 -0
- package/dist/ux-telemetry.js +127 -0
- package/dist/view.js +114 -0
- package/package.json +80 -6
- package/web/index.html +136 -0
- package/web/js/conversations.js +312 -0
- package/web/js/dag.js +495 -0
- package/web/js/drawer.js +139 -0
- package/web/js/editors.js +424 -0
- package/web/js/gitlens.js +844 -0
- package/web/js/main.js +152 -0
- package/web/js/sankey.js +476 -0
- package/web/js/store.js +291 -0
- package/web/js/ticket.js +151 -0
- package/web/js/timeline.js +183 -0
- package/web/js/topology.js +454 -0
- package/web/js/util.js +232 -0
- package/web/js/views.js +1496 -0
- package/web/style.css +5299 -0
package/dist/app.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// 打开 Pi Durable Harness:SQLite 持久化 + 本机 agent 工具 + 总调度模型。
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { createRegistry, Harness, MemoryStorage } from "@earendil-works/pi-durable";
|
|
5
|
+
import { restoreControllerModel } from "./model-selection.js";
|
|
6
|
+
import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
|
|
7
|
+
import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
|
|
8
|
+
import { registerApiMembers } from "./api-member.js";
|
|
9
|
+
import { Board, ProjectFiles } from "./board.js";
|
|
10
|
+
import { ChangeStore } from "./changes.js";
|
|
11
|
+
import { JobHub } from "./jobs.js";
|
|
12
|
+
import { writeLine } from "./printer.js";
|
|
13
|
+
import { createLocalAgentsExtension } from "./tools.js";
|
|
14
|
+
import { Workflow } from "./task-workflow.js";
|
|
15
|
+
import { Integrations } from "./integrations.js";
|
|
16
|
+
/**
|
|
17
|
+
* Pi Durable 要求一个存储同一时间只有一个进程写入(没有跨进程锁)。
|
|
18
|
+
* 同一个存储只能开一个终端进程,这里用 pid 锁文件防止两边同时打开。
|
|
19
|
+
*/
|
|
20
|
+
function acquireLock(storagePath) {
|
|
21
|
+
const lock = `${storagePath}.lock`;
|
|
22
|
+
if (existsSync(lock)) {
|
|
23
|
+
const pid = Number(readFileSync(lock, "utf8"));
|
|
24
|
+
let alive = false;
|
|
25
|
+
if (pid > 0 && pid !== process.pid) {
|
|
26
|
+
try {
|
|
27
|
+
process.kill(pid, 0);
|
|
28
|
+
alive = true;
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
alive = error.code === "EPERM";
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (alive) {
|
|
35
|
+
throw new Error(`会话存储 ${storagePath} 正被进程 ${pid} 使用(同一个存储只能开一个 Lemma 终端)。`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
writeFileSync(lock, String(process.pid));
|
|
39
|
+
let released = false;
|
|
40
|
+
const release = () => {
|
|
41
|
+
if (released)
|
|
42
|
+
return;
|
|
43
|
+
released = true;
|
|
44
|
+
try {
|
|
45
|
+
if (readFileSync(lock, "utf8") === String(process.pid))
|
|
46
|
+
rmSync(lock);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
/* 已删除 */
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
process.once("exit", release);
|
|
53
|
+
return release;
|
|
54
|
+
}
|
|
55
|
+
export async function openApp(config, orchestrator, context, options = {}) {
|
|
56
|
+
if (!options.memory)
|
|
57
|
+
mkdirSync(dirname(config.storage), { recursive: true });
|
|
58
|
+
const changes = new ChangeStore(`${config.storage}.changes.json`);
|
|
59
|
+
const project = new ProjectFiles(config.workdir, config.projectStateDir);
|
|
60
|
+
const jobs = new JobHub();
|
|
61
|
+
let confirmApply;
|
|
62
|
+
const getConfirmApply = () => confirmApply;
|
|
63
|
+
let { extension, agents, memberExtensions, recover, fastDispatch, ensureWorkflow, integrations } = createLocalAgentsExtension(config, changes, project, jobs, getConfirmApply);
|
|
64
|
+
const registry = createRegistry();
|
|
65
|
+
registry.install(extension);
|
|
66
|
+
for (const extra of options.extensions ?? [])
|
|
67
|
+
registry.install(extra);
|
|
68
|
+
for (const ext of memberExtensions)
|
|
69
|
+
registry.install(ext);
|
|
70
|
+
// API 成员(如 DeepSeek)的模型和总调度放在同一个模型目录里
|
|
71
|
+
registerApiMembers(orchestrator.models, config);
|
|
72
|
+
const releaseLock = options.memory || options.readOnly ? () => { } : acquireLock(config.storage);
|
|
73
|
+
const storage = options.memory ? new MemoryStorage() : await openNodeSqliteStorage(config.storage);
|
|
74
|
+
const harness = await Harness.open(storage, {
|
|
75
|
+
models: orchestrator.models,
|
|
76
|
+
registry,
|
|
77
|
+
// API 成员的读写工具通过执行环境访问文件和命令(工作目录 = 子对话的 cwd,即它的 worktree)
|
|
78
|
+
env: ({ cwd }) => new NodeExecutionEnv({ cwd: cwd ?? config.workdir }),
|
|
79
|
+
readOnly: options.readOnly,
|
|
80
|
+
identity: { attribution: null },
|
|
81
|
+
settings: {
|
|
82
|
+
toolExecution: "parallel", // 同一轮里派给多个 agent 的任务并行执行
|
|
83
|
+
// 默认只选派工扩展:API 成员的读写工具不给总调度(它只派活,不自己改代码)
|
|
84
|
+
extensions: [extension],
|
|
85
|
+
retry: { maxRetries: 4, baseDelayMs: 3000, maxAgentDelayMs: 30_000 },
|
|
86
|
+
afterFailedRun: "continue",
|
|
87
|
+
...options.settings,
|
|
88
|
+
},
|
|
89
|
+
onReport: (report) => {
|
|
90
|
+
const message = report.error instanceof Error ? report.error.message : String(report.error ?? "");
|
|
91
|
+
writeLine(`\n[pi-durable] ${report.kind}${message ? `: ${message}` : ""}`);
|
|
92
|
+
},
|
|
93
|
+
}, context);
|
|
94
|
+
void harness.closed.then(releaseLock, releaseLock);
|
|
95
|
+
const root = await harness.root(context, {
|
|
96
|
+
agent: { model: orchestrator.ref, maxTurns: config.orchestrator.maxTurns ?? 40, cwd: config.workdir },
|
|
97
|
+
});
|
|
98
|
+
if (!options.readOnly) {
|
|
99
|
+
// 配置文件改了模型时,让已存在的会话跟着更新
|
|
100
|
+
await restoreControllerModel(harness, root, orchestrator.models, orchestrator.ref, context);
|
|
101
|
+
await root.configure({ maxTurns: config.orchestrator.maxTurns ?? 40, cwd: config.workdir }, context);
|
|
102
|
+
const board = await harness.snapshot(Board, context);
|
|
103
|
+
if (board)
|
|
104
|
+
try {
|
|
105
|
+
project.writeAssign(board);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
writeLine("分工数据已恢复,ASSIGN.md 暂时无法导出。");
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
jobs.harness = harness;
|
|
112
|
+
if (!options.readOnly)
|
|
113
|
+
for (const record of Object.values((await harness.snapshot(Integrations, context))?.records ?? {})) {
|
|
114
|
+
if (!["applied", "dropped"].includes(changes.get(record.id)?.status ?? ""))
|
|
115
|
+
try {
|
|
116
|
+
changes.upsert(record);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
writeLine("集成状态已保存,改动索引暂时无法导出。");
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (!options.readOnly)
|
|
123
|
+
await harness.commit((tx) => ensureWorkflow(tx, root.id), context);
|
|
124
|
+
return { harness, root, agents, changes, project, jobs,
|
|
125
|
+
get confirmApply() { return confirmApply; },
|
|
126
|
+
set confirmApply(fn) { confirmApply = fn; },
|
|
127
|
+
integrate: (...args) => integrations.start(...args), rerunIntegration: (...args) => integrations.startRerun(...args), repairIntegration: (...args) => integrations.startRepair(...args), cancelIntegration: (...args) => integrations.cancel(...args), recoverTask: (...args) => recover(...args), fastDispatch: (...args) => fastDispatch(...args), async workflow(action, context) {
|
|
128
|
+
if (action === "status")
|
|
129
|
+
return { paused: (await harness.snapshot(Workflow, context))?.controllers[String(root.id)]?.paused ?? false };
|
|
130
|
+
await harness.commit(async (tx) => {
|
|
131
|
+
const state = await tx.doc(Workflow);
|
|
132
|
+
state.controllers[String(root.id)] ??= {};
|
|
133
|
+
state.controllers[String(root.id)].paused = action === "pause";
|
|
134
|
+
if (action === "resume")
|
|
135
|
+
await ensureWorkflow(tx, root.id);
|
|
136
|
+
}, context);
|
|
137
|
+
harness.resume();
|
|
138
|
+
return { paused: action === "pause" };
|
|
139
|
+
}, prepareMembers(next) {
|
|
140
|
+
const prepared = createLocalAgentsExtension(next, changes, project, jobs, getConfirmApply);
|
|
141
|
+
return () => {
|
|
142
|
+
for (const old of memberExtensions)
|
|
143
|
+
registry.uninstall(old);
|
|
144
|
+
for (const [id, member] of Object.entries(config.agents))
|
|
145
|
+
if (member.api)
|
|
146
|
+
orchestrator.models.deleteProvider(`member-${id}`);
|
|
147
|
+
registerApiMembers(orchestrator.models, next);
|
|
148
|
+
registry.install(prepared.extension);
|
|
149
|
+
for (const member of prepared.memberExtensions)
|
|
150
|
+
registry.install(member);
|
|
151
|
+
extension = prepared.extension;
|
|
152
|
+
memberExtensions = prepared.memberExtensions;
|
|
153
|
+
recover = prepared.recover;
|
|
154
|
+
fastDispatch = prepared.fastDispatch;
|
|
155
|
+
ensureWorkflow = prepared.ensureWorkflow;
|
|
156
|
+
integrations = prepared.integrations;
|
|
157
|
+
agents.splice(0, agents.length, ...prepared.agents);
|
|
158
|
+
Object.assign(config, next);
|
|
159
|
+
};
|
|
160
|
+
} };
|
|
161
|
+
}
|
package/dist/board.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// 项目的共同目标 + 分工表。
|
|
2
|
+
// - GOAL.md:最终目标、验收标准、约束。以文件为准(人写,AI 读;没有时总调度可以起草,标明待确认)。
|
|
3
|
+
// - 分工表:以 Pi Durable 里的数据为准(总调度通过工具维护,和派工在同一个事务里),
|
|
4
|
+
// 每次变化后写出 .pi-agent/ASSIGN.md 给人和任何 AI 看。ASSIGN.md 由 AI 写;有人手动改过时不覆盖,先另存。
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { EventEmitter } from "node:events";
|
|
7
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { defineDoc } from "@earendil-works/pi-durable";
|
|
10
|
+
import { formatScopeSummary } from "./scope.js";
|
|
11
|
+
export const Board = defineDoc({
|
|
12
|
+
kind: "pi-agent.board",
|
|
13
|
+
version: 1,
|
|
14
|
+
scope: "session",
|
|
15
|
+
initial: () => ({ tasks: {}, order: [], nextId: 1, updatedAt: 0 }),
|
|
16
|
+
checkpointWhen: () => false,
|
|
17
|
+
});
|
|
18
|
+
export const STATUS_LABEL = {
|
|
19
|
+
todo: "待办",
|
|
20
|
+
doing: "进行中",
|
|
21
|
+
review: "待验收",
|
|
22
|
+
done: "完成",
|
|
23
|
+
blocked: "受阻",
|
|
24
|
+
dropped: "取消",
|
|
25
|
+
};
|
|
26
|
+
const STATUS_MARK = { todo: "[ ]", doing: "[~]", review: "[?]", done: "[x]", blocked: "[!]", dropped: "[-]" };
|
|
27
|
+
export function boardTasks(board) {
|
|
28
|
+
if (!board)
|
|
29
|
+
return [];
|
|
30
|
+
return board.order.map((id) => board.tasks[id]).filter((t) => !!t);
|
|
31
|
+
}
|
|
32
|
+
const GOAL_LIMIT = 6000;
|
|
33
|
+
export class ProjectFiles extends EventEmitter {
|
|
34
|
+
dir;
|
|
35
|
+
goalPath;
|
|
36
|
+
assignPath;
|
|
37
|
+
constructor(workdir, stateDir) {
|
|
38
|
+
super();
|
|
39
|
+
this.dir = join(workdir, ".pi-agent");
|
|
40
|
+
this.goalPath = join(this.dir, "GOAL.md");
|
|
41
|
+
this.assignPath = join(stateDir ?? this.dir, "ASSIGN.md");
|
|
42
|
+
}
|
|
43
|
+
/** GOAL.md 的内容(太长截断);没有返回 undefined */
|
|
44
|
+
goal() {
|
|
45
|
+
if (!existsSync(this.goalPath))
|
|
46
|
+
return undefined;
|
|
47
|
+
const text = readFileSync(this.goalPath, "utf8").trim();
|
|
48
|
+
if (!text)
|
|
49
|
+
return undefined;
|
|
50
|
+
return text.length > GOAL_LIMIT ? `${text.slice(0, GOAL_LIMIT)}\n…(GOAL.md 太长,后面省略)` : text;
|
|
51
|
+
}
|
|
52
|
+
/** 总调度起草目标:只在还没有 GOAL.md、或者明确要求覆盖时写 */
|
|
53
|
+
writeGoal(content, overwrite) {
|
|
54
|
+
if (existsSync(this.goalPath) && !overwrite)
|
|
55
|
+
return { ok: false, message: "GOAL.md 已经存在,以用户写的为准;要改请先征得用户同意(overwrite: true)。" };
|
|
56
|
+
mkdirSync(this.dir, { recursive: true });
|
|
57
|
+
const body = `<!-- 由 Lemma 总调度起草,待你确认:确认后删掉这一行,之后以你写的为准 -->\n${content.trim()}\n`;
|
|
58
|
+
writeFileSync(this.goalPath, body);
|
|
59
|
+
this.emit("change");
|
|
60
|
+
return { ok: true, message: `已写入 ${this.goalPath}(标明待用户确认)` };
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* 把分工表写成 ASSIGN.md。文件开头记下内容的哈希:下次写之前如果发现内容和哈希对不上,
|
|
64
|
+
* 说明有人手动改过,先另存为 ASSIGN.edited-<时间>.md,再写新的,返回另存的路径。
|
|
65
|
+
*/
|
|
66
|
+
writeAssign(board) {
|
|
67
|
+
const tasks = boardTasks(board);
|
|
68
|
+
if (!tasks.length && !existsSync(this.assignPath))
|
|
69
|
+
return {};
|
|
70
|
+
mkdirSync(dirname(this.assignPath), { recursive: true });
|
|
71
|
+
let savedManualEdit;
|
|
72
|
+
if (existsSync(this.assignPath)) {
|
|
73
|
+
const current = readFileSync(this.assignPath, "utf8");
|
|
74
|
+
const m = current.match(/^<!-- pi-agent:hash=([0-9a-f]+) -->\n([\s\S]*)$/);
|
|
75
|
+
if (!m || hash(m[2]) !== m[1]) {
|
|
76
|
+
savedManualEdit = join(dirname(this.assignPath), `ASSIGN.edited-${new Date().toISOString().replace(/[:.]/g, "-")}.md`);
|
|
77
|
+
copyFileSync(this.assignPath, savedManualEdit);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const body = renderAssign(tasks, board.updatedAt);
|
|
81
|
+
const tmp = `${this.assignPath}.tmp`;
|
|
82
|
+
writeFileSync(tmp, `<!-- pi-agent:hash=${hash(body)} -->\n${body}`);
|
|
83
|
+
renameSync(tmp, this.assignPath);
|
|
84
|
+
this.emit("change");
|
|
85
|
+
return { savedManualEdit };
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function hash(text) {
|
|
89
|
+
return createHash("sha1").update(text.replace(/\r\n/g, "\n")).digest("hex").slice(0, 12);
|
|
90
|
+
}
|
|
91
|
+
/** ASSIGN.md:给人和任何 AI 读的分工表 */
|
|
92
|
+
export function renderAssign(tasks, updatedAt) {
|
|
93
|
+
const count = (s) => tasks.filter((t) => t.status === s).length;
|
|
94
|
+
const active = tasks.filter((t) => t.status !== "dropped");
|
|
95
|
+
const lines = [
|
|
96
|
+
"# 分工表(ASSIGN.md)",
|
|
97
|
+
"",
|
|
98
|
+
"> 由 Lemma 总调度维护,**不要手动编辑**(手动改动会被另存为 ASSIGN.edited-*.md)。最终目标见同目录的 GOAL.md。",
|
|
99
|
+
`> 更新于 ${updatedAt ? new Date(updatedAt).toLocaleString("zh-CN", { hour12: false }) : "—"} · 共 ${active.length} 项:完成 ${count("done")}、进行中 ${count("doing")}、待验收 ${count("review")}、待办 ${count("todo")}、受阻 ${count("blocked")}`,
|
|
100
|
+
"",
|
|
101
|
+
"| 编号 | 状态 | 任务 | 角色 | 负责 | 依赖 |",
|
|
102
|
+
"|---|---|---|---|---|---|",
|
|
103
|
+
...tasks.map((t) => `| ${t.id} | ${STATUS_MARK[t.status]} ${STATUS_LABEL[t.status]} | ${cell(t.title)} | ${cell(t.role ?? "—")} | ${cell(t.owner ?? "—")} | ${t.deps.length ? t.deps.join(", ") : "—"} |`),
|
|
104
|
+
"",
|
|
105
|
+
"## 任务详情",
|
|
106
|
+
"",
|
|
107
|
+
];
|
|
108
|
+
for (const t of tasks) {
|
|
109
|
+
lines.push(`### ${t.id} · ${t.title}`, "");
|
|
110
|
+
lines.push(`- 状态:${STATUS_LABEL[t.status]}${t.role ? ` · 角色:${t.role}` : ""}${t.owner ? ` · 负责:${t.owner}` : ""}`);
|
|
111
|
+
if (t.deps.length)
|
|
112
|
+
lines.push(`- 依赖:${t.deps.join("、")}`);
|
|
113
|
+
if (t.acceptance)
|
|
114
|
+
lines.push(`- 验收标准:${t.acceptance}`);
|
|
115
|
+
if (t.scope && (t.scope.allow?.length || t.scope.forbid?.length))
|
|
116
|
+
lines.push(`- 路径契约:${formatScopeSummary(t.scope)}`);
|
|
117
|
+
if (t.automation)
|
|
118
|
+
lines.push(`- 就绪自动执行:${t.automation.member};独立复核返工上限 ${t.automation.maxReworks} 次`);
|
|
119
|
+
if (t.reviewer)
|
|
120
|
+
lines.push(`- 独立复核成员:${t.reviewer.member}${t.reviewer.model ? ` / ${t.reviewer.model}` : ""}${t.reviewer.blind ? "(代码盲审)" : ""}`);
|
|
121
|
+
for (const check of t.checksByMember?.slice(-3) ?? [])
|
|
122
|
+
lines.push(`- 独立复核:${check.sourceResultId} → ${check.member} · ${check.status}${check.evidence ? ` · ${check.evidence.replace(/\n+/g, " ")}` : ""}`);
|
|
123
|
+
if (t.latestResult)
|
|
124
|
+
lines.push(`- 最新结果:${t.latestResult}(终端 /result ${t.latestResult} 查看)`);
|
|
125
|
+
if (t.activeDispatch)
|
|
126
|
+
lines.push(`- 当前派工:${t.activeDispatch}(执行与收尾由 Durable 管理)`);
|
|
127
|
+
if (t.verification)
|
|
128
|
+
lines.push(`- 机器检查:${t.verification.passed ? "通过,仍需复核依据" : "未通过"};${t.verification.checks.map((check) => `${check.name}:${check.passed ? "通过" : "失败"}(${check.evidence})`).join(";")}`);
|
|
129
|
+
if (t.review)
|
|
130
|
+
lines.push(`- 复核:${t.review.verdict} · ${t.review.evidence.replace(/\n+/g, " ")}`);
|
|
131
|
+
for (const recovery of t.recoveries?.slice(-3) ?? [])
|
|
132
|
+
lines.push(`- 恢复:${recovery.action} → ${recovery.member} · ${recovery.status} · 原结果 ${recovery.fromResult ?? "无"} · ${recovery.note.replace(/\n+/g, " ")}`);
|
|
133
|
+
if (t.detail)
|
|
134
|
+
lines.push(`- 说明:${t.detail.replace(/\n+/g, " ")}`);
|
|
135
|
+
if (t.changes.length)
|
|
136
|
+
lines.push(`- 改动:${t.changes.map((c) => `#${c}`).join("、")}(终端 /changes 查看)`);
|
|
137
|
+
for (const n of t.notes.slice(-5))
|
|
138
|
+
lines.push(`- 记录:${n}`);
|
|
139
|
+
lines.push("");
|
|
140
|
+
}
|
|
141
|
+
return `${lines.join("\n").trimEnd()}\n`;
|
|
142
|
+
}
|
|
143
|
+
function cell(text) {
|
|
144
|
+
return text.replace(/\|/g, "\\|").replace(/\s+/g, " ").slice(0, 80);
|
|
145
|
+
}
|
|
146
|
+
/** 放进总调度系统提示的分工摘要(每次请求都按最新状态渲染) */
|
|
147
|
+
export function boardSummary(board) {
|
|
148
|
+
const tasks = boardTasks(board).filter((t) => t.status !== "dropped");
|
|
149
|
+
if (!tasks.length)
|
|
150
|
+
return "(当前没有项目任务;普通对话无需创建分工表。)";
|
|
151
|
+
const selected = tasks.length > 25 ? [...tasks.filter((t) => t.status !== "done").slice(-20), ...tasks.filter((t) => t.status === "done").slice(-5)] : tasks;
|
|
152
|
+
return (tasks.length > selected.length ? `共 ${tasks.length} 项,完成 ${tasks.filter((t) => t.status === "done").length} 项;显示最近活动与完成项。\n` : "") + selected
|
|
153
|
+
.map((t) => `- ${t.id} [${STATUS_LABEL[t.status]}] ${t.title.slice(0, 160)}${t.role ? ` ·${t.role}` : ""}${t.owner ? ` ·${t.owner}` : ""}${t.parent ? ` ·属于 ${t.parent}` : ""}${t.deps.length ? ` ·依赖 ${t.deps.join(",")}` : ""}${t.latestResult ? ` ·结果 ${t.latestResult}` : ""}${t.recoveries?.length ? ` ·恢复 ${t.recoveries.at(-1).status}` : ""}${t.changes.length ? ` ·改动 ${t.changes.slice(-3).map((c) => `#${c}`).join(",")}` : ""}`)
|
|
154
|
+
.join("\n");
|
|
155
|
+
}
|
|
156
|
+
/** 派工时放在成员任务前面的上下文:共同目标 + 这项任务 + 分工全貌(成员据此理解自己在全局里的位置) */
|
|
157
|
+
export function taskBrief(goal, board, taskId, mode = "relevant") {
|
|
158
|
+
const parts = [];
|
|
159
|
+
if (goal)
|
|
160
|
+
parts.push(`【项目最终目标(GOAL.md)】\n${goal}`);
|
|
161
|
+
const tasks = boardTasks(board).filter((t) => t.status !== "dropped");
|
|
162
|
+
const task = taskId ? board?.tasks[taskId] : undefined;
|
|
163
|
+
if (task) {
|
|
164
|
+
const deps = task.deps.map((d) => board?.tasks[d]).filter(Boolean);
|
|
165
|
+
parts.push([
|
|
166
|
+
`【你负责的任务】${task.id} · ${task.title}${task.role ? `(角色:${task.role})` : ""}`,
|
|
167
|
+
task.acceptance ? `验收标准:${task.acceptance}` : "",
|
|
168
|
+
task.scope && (task.scope.allow?.length || task.scope.forbid?.length) ? `代码路径契约(硬性边界,首次派工后锁定):${formatScopeSummary(task.scope)}` : "",
|
|
169
|
+
task.detail ? `任务说明:${task.detail}` : "",
|
|
170
|
+
task.checks?.length ? `机器验收规则(首次派工后锁定):${JSON.stringify(task.checks)}` : "",
|
|
171
|
+
deps.length ? `前置任务:${deps.map((d) => `${d.id} ${d.title}(${STATUS_LABEL[d.status]})`).join(";")}` : "",
|
|
172
|
+
]
|
|
173
|
+
.filter(Boolean)
|
|
174
|
+
.join("\n"));
|
|
175
|
+
}
|
|
176
|
+
if (tasks.length > 1) {
|
|
177
|
+
const selected = mode === "full" || !task ? tasks : tasks.filter((candidate) => candidate.id === task.id || task.deps.includes(candidate.id) || candidate.id === task.parent || candidate.deps.includes(task.id));
|
|
178
|
+
parts.push(`【相关团队分工】(只读;共 ${tasks.length} 项,显示 ${Math.min(selected.length, 20)} 项;不要修改分工表)\n${selected.slice(0, 20)
|
|
179
|
+
.map((t) => `- ${t.id} [${STATUS_LABEL[t.status]}] ${t.title.slice(0, 120)}${t.owner ? ` — ${t.owner}` : ""}${t.id === taskId ? " ← 你" : ""}`)
|
|
180
|
+
.join("\n")}`);
|
|
181
|
+
}
|
|
182
|
+
if (!parts.length)
|
|
183
|
+
return "";
|
|
184
|
+
return `${parts.join("\n\n")}\n\n【本次要做的事】\n`;
|
|
185
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
3
|
+
import { defineTool } from "@earendil-works/pi-durable";
|
|
4
|
+
import { compile, unsafe } from "@earendil-works/pi-schema";
|
|
5
|
+
import { readCredential } from "./credentials.js";
|
|
6
|
+
import { Operations, unresolved } from "./operations.js";
|
|
7
|
+
export function validateBusinessTools(tools) {
|
|
8
|
+
if (tools === undefined)
|
|
9
|
+
return;
|
|
10
|
+
if (!Array.isArray(tools))
|
|
11
|
+
throw new Error("httpTools 需要工具数组。");
|
|
12
|
+
const ids = new Set();
|
|
13
|
+
for (const tool of tools) {
|
|
14
|
+
if (!tool || !/^[a-z][a-z0-9_]{0,47}$/.test(tool.id) || ["read", "write", "edit", "bash", "constructor", "prototype"].includes(tool.id) || ids.has(tool.id))
|
|
15
|
+
throw new Error("业务工具 ID 无效或重复。");
|
|
16
|
+
ids.add(tool.id);
|
|
17
|
+
if (typeof tool.description !== "string" || !tool.description.trim() || !["GET", "POST"].includes(tool.method))
|
|
18
|
+
throw new Error("业务工具需要说明与 GET/POST 方法。");
|
|
19
|
+
let url;
|
|
20
|
+
try {
|
|
21
|
+
url = new URL(tool.url);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
throw new Error("业务工具地址无效。");
|
|
25
|
+
}
|
|
26
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash)
|
|
27
|
+
throw new Error("业务工具需要固定 HTTP(S) 地址,不含凭据、查询参数或片段。");
|
|
28
|
+
if (!tool.parameters || tool.parameters.type !== "object")
|
|
29
|
+
throw new Error("业务工具参数需要 object JSON Schema。");
|
|
30
|
+
try {
|
|
31
|
+
compile(tool.parameters);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
throw new Error("业务工具参数 JSON Schema 无效。");
|
|
35
|
+
}
|
|
36
|
+
if (tool.auth && ((tool.auth.env !== undefined && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(tool.auth.env)) || (tool.auth.credential !== undefined && !/^local-[a-f0-9-]{36}$/.test(tool.auth.credential)) || (!tool.auth.env && !tool.auth.credential)))
|
|
37
|
+
throw new Error("业务工具凭据引用无效。");
|
|
38
|
+
if (tool.idempotencyHeader !== undefined && (!/^[A-Za-z0-9-]{1,80}$/.test(tool.idempotencyHeader) || /^(authorization|cookie|host|content-type|content-length)$/i.test(tool.idempotencyHeader)))
|
|
39
|
+
throw new Error("幂等请求头名称无效。");
|
|
40
|
+
if (tool.timeoutSeconds !== undefined && (!Number.isFinite(tool.timeoutSeconds) || tool.timeoutSeconds <= 0 || tool.timeoutSeconds > 300))
|
|
41
|
+
throw new Error("业务工具超时需要在 0–300 秒内。");
|
|
42
|
+
if (tool.maxResultChars !== undefined && (!Number.isSafeInteger(tool.maxResultChars) || tool.maxResultChars < 100 || tool.maxResultChars > 20000))
|
|
43
|
+
throw new Error("业务工具结果长度需要为 100–20000。");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export async function callBusinessTool(tool, args, signal, key) {
|
|
47
|
+
const fail = (kind, message, retryable = false, retryAt) => ({ text: message, isError: true, failure: { kind, message, retryable, ...(retryAt !== undefined ? { retryAt } : {}) } });
|
|
48
|
+
if (!compile(tool.parameters).check(args))
|
|
49
|
+
return fail("validation", "业务工具参数不符合已配置的 JSON Schema,未发送请求。");
|
|
50
|
+
if (signal.aborted)
|
|
51
|
+
return fail("cancelled", "业务请求已取消,未发送请求。");
|
|
52
|
+
const secret = (tool.auth?.env ? process.env[tool.auth.env] : undefined) || readCredential(tool.auth?.credential);
|
|
53
|
+
if (tool.auth && !secret)
|
|
54
|
+
return fail("authentication", "业务工具缺少凭据;请在终端配置,未发送请求。");
|
|
55
|
+
const redact = (value) => secret ? value.split(secret).join("[REDACTED]") : value;
|
|
56
|
+
const headers = { Accept: "application/json" };
|
|
57
|
+
if (secret)
|
|
58
|
+
headers.Authorization = `Bearer ${secret}`;
|
|
59
|
+
if (tool.method === "POST")
|
|
60
|
+
headers["Content-Type"] = "application/json";
|
|
61
|
+
if (tool.method === "POST" && tool.idempotencyHeader)
|
|
62
|
+
headers[tool.idempotencyHeader] = createHash("sha256").update(key).digest("hex");
|
|
63
|
+
const url = new URL(tool.url);
|
|
64
|
+
if (tool.method === "GET")
|
|
65
|
+
for (const [name, value] of Object.entries(args)) {
|
|
66
|
+
if (!["string", "number", "boolean"].includes(typeof value))
|
|
67
|
+
return fail("validation", "GET 查询参数只支持字符串、数字和布尔值。");
|
|
68
|
+
url.searchParams.set(name, String(value));
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
const response = await fetch(url, { method: tool.method, headers, ...(tool.method === "POST" ? { body: JSON.stringify(args) } : {}), redirect: "error", signal: AbortSignal.any([signal, AbortSignal.timeout((tool.timeoutSeconds ?? 30) * 1000)]) });
|
|
72
|
+
const reader = response.body?.getReader();
|
|
73
|
+
const chunks = [];
|
|
74
|
+
let size = 0;
|
|
75
|
+
let oversized = false;
|
|
76
|
+
if (reader)
|
|
77
|
+
try {
|
|
78
|
+
while (true) {
|
|
79
|
+
const chunk = await reader.read();
|
|
80
|
+
if (chunk.done)
|
|
81
|
+
break;
|
|
82
|
+
size += chunk.value.byteLength;
|
|
83
|
+
if (size > 131072) {
|
|
84
|
+
oversized = true;
|
|
85
|
+
await reader.cancel();
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
chunks.push(chunk.value);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
reader.releaseLock();
|
|
93
|
+
}
|
|
94
|
+
if (oversized)
|
|
95
|
+
return fail(tool.method === "POST" ? "outcome_unknown" : "response_invalid", "响应超过 128 KiB,未将不完整数据当作结果;POST 远端操作状态未知,请先核对。");
|
|
96
|
+
const body = redact(Buffer.concat(chunks).toString("utf8"));
|
|
97
|
+
const limit = tool.maxResultChars ?? 8000;
|
|
98
|
+
const text = JSON.stringify({ status: response.status, body: body.slice(0, limit), truncated: body.length > limit });
|
|
99
|
+
if (response.ok)
|
|
100
|
+
return { text, isError: false };
|
|
101
|
+
if ([401, 403].includes(response.status))
|
|
102
|
+
return { ...fail("authentication", "接口认证或权限失败,请修正凭据后再继续。"), text };
|
|
103
|
+
if (tool.method === "POST" && (response.status >= 500 || response.status === 408))
|
|
104
|
+
return { ...fail("outcome_unknown", "外部操作返回服务端错误或超时,远端状态未知,请先核对。"), text };
|
|
105
|
+
if (response.status === 429 || response.status === 503) {
|
|
106
|
+
const header = response.headers.get("retry-after");
|
|
107
|
+
const at = header ? /^\d+$/.test(header) ? Date.now() + Number(header) * 1000 : Date.parse(header) : NaN;
|
|
108
|
+
return { ...fail(response.status === 429 ? "rate_limit" : "temporary", "接口暂时不可用,等待后可重试查询;不自动重复外部写操作。", tool.method === "GET", Number.isFinite(at) ? Math.max(Date.now(), at) : undefined), text };
|
|
109
|
+
}
|
|
110
|
+
return { ...fail(response.status >= 500 || response.status === 408 ? "temporary" : "rejected", "接口拒绝请求,请按错误修正后继续。", tool.method === "GET" && response.status >= 500), text };
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return tool.method === "POST" ? fail("outcome_unknown", "业务请求失败、取消或超时,远端操作状态未知;请先核对,勿盲目重试。") : fail(signal.aborted ? "cancelled" : "temporary", signal.aborted ? "业务请求已取消。" : "业务请求失败或超时,可稍后重试查询。", !signal.aborted);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
export function createBusinessTools(member, tools = []) {
|
|
117
|
+
return tools.map((tool) => defineTool({
|
|
118
|
+
name: tool.id, description: `${tool.description}(${tool.method === "GET" ? "只读查询" : "会执行外部操作"};失败不自动重试)`,
|
|
119
|
+
parameters: unsafe(tool.parameters),
|
|
120
|
+
replay: tool.method === "GET" || tool.idempotencyHeader ? "safe" : "unsafe",
|
|
121
|
+
execute: async (args, api, context) => {
|
|
122
|
+
// Conversation/task IDs are only unique inside one database. Memoize a globally unique key.
|
|
123
|
+
const requestKey = await api.memo("http-request-key", randomUUID(), context);
|
|
124
|
+
const canonical = (value) => Array.isArray(value) ? value.map(canonical) : value && typeof value === "object" ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])])) : value;
|
|
125
|
+
const argumentsHash = createHash("sha256").update(JSON.stringify(canonical(args))).digest("hex");
|
|
126
|
+
const blocked = await api.commit(async (tx) => {
|
|
127
|
+
const operations = (await tx.doc(Operations)).operations;
|
|
128
|
+
const own = operations[requestKey];
|
|
129
|
+
if (own?.result)
|
|
130
|
+
return { result: JSON.parse(JSON.stringify(own.result)) };
|
|
131
|
+
const uncertain = Object.values(operations).find((entry) => entry.method === "POST" && entry.endpoint === tool.url && ((unresolved(entry) && (entry.id !== requestKey || !tool.idempotencyHeader)) || (entry.argumentsHash === argumentsHash && entry.resolution?.outcome === "succeeded")));
|
|
132
|
+
if (tool.method === "POST" && uncertain)
|
|
133
|
+
return { result: { text: `外部操作 ${uncertain.id} 状态待核对或已确认成功,禁止重复提交。终端 /operations 查看并人工核对远端状态。`, isError: true, failure: { kind: "outcome_unknown", message: "外部操作需要先核对远端结果。", retryable: false } } };
|
|
134
|
+
const cooldown = Object.values(operations).find((entry) => entry.endpoint === tool.url && entry.result?.failure?.retryAt && entry.result.failure.retryAt > api.now());
|
|
135
|
+
if (cooldown)
|
|
136
|
+
return { result: { text: `接口正在限流等待,请在 ${new Date(cooldown.result.failure.retryAt).toISOString()} 后重试。`, isError: true, failure: JSON.parse(JSON.stringify(cooldown.result.failure)) } };
|
|
137
|
+
if (!own)
|
|
138
|
+
operations[requestKey] = { id: requestKey, member, tool: tool.id, method: tool.method, endpoint: tool.url, argumentsHash, taskId: String(api.taskId), conversationId: String(api.conversationId), status: "pending", createdAt: api.now(), updatedAt: api.now() };
|
|
139
|
+
return null;
|
|
140
|
+
}, context);
|
|
141
|
+
if (blocked)
|
|
142
|
+
return { output: [{ type: "text", text: JSON.stringify({ ...blocked.result, operationId: requestKey }) }], isError: blocked.result.isError };
|
|
143
|
+
const result = await callBusinessTool(tool, args, context.abortSignal ?? new AbortController().signal, `${requestKey}:${member}:${tool.id}`);
|
|
144
|
+
await api.commit(async (tx) => {
|
|
145
|
+
const operation = (await tx.doc(Operations)).operations[requestKey];
|
|
146
|
+
operation.status = result.failure?.kind === "outcome_unknown" ? "unknown" : result.isError ? "failed" : "succeeded";
|
|
147
|
+
operation.result = result;
|
|
148
|
+
operation.updatedAt = api.now();
|
|
149
|
+
}, BACKGROUND_CONTEXT);
|
|
150
|
+
return { output: [{ type: "text", text: JSON.stringify({ ...result, operationId: requestKey }) }], isError: result.isError };
|
|
151
|
+
},
|
|
152
|
+
}));
|
|
153
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { applyRange, removeWorktree, git } from "./git.js";
|
|
2
|
+
import { integrationStale, integrationGit } from "./integration-git.js";
|
|
3
|
+
function find(store, id) {
|
|
4
|
+
return id ? store.get(id) : undefined;
|
|
5
|
+
}
|
|
6
|
+
/** 待处理的改动:有文件改动、还没合并也没丢弃(已被新集成替代或由集成覆盖的来源/修复副本不单独重复列出) */
|
|
7
|
+
export function pendingChanges(store) {
|
|
8
|
+
const bundles = store.list().filter((c) => c.integration && !c.integration.supersededBy && !["applied", "dropped"].includes(c.status));
|
|
9
|
+
const covered = new Set(bundles.flatMap((c) => [...c.integration.sources.map((source) => source.id), ...(c.integration.repair?.changeId ? [c.integration.repair.changeId] : [])]));
|
|
10
|
+
return store.list().filter((c) => (c.status === "pending" || c.status === "conflict") && !c.integration?.supersededBy && (!covered.has(c.id) || !!c.integration));
|
|
11
|
+
}
|
|
12
|
+
export async function applyChange(store, id) {
|
|
13
|
+
const c = find(store, id);
|
|
14
|
+
if (!c)
|
|
15
|
+
return { ok: false, message: `找不到改动 ${id}` };
|
|
16
|
+
if (c.status === "running")
|
|
17
|
+
return { ok: false, message: `改动 #${c.id} 还在进行中,等它完成再合并` };
|
|
18
|
+
if (c.status === "dropped")
|
|
19
|
+
return { ok: false, message: `改动 #${c.id} 已经丢弃` };
|
|
20
|
+
if (c.status === "applied" || c.status === "empty")
|
|
21
|
+
return { ok: false, message: `改动 #${c.id} 没有需要合并的内容` };
|
|
22
|
+
const parent = store.list().find((bundle) => bundle.integration && !bundle.integration.supersededBy && !["applied", "dropped"].includes(bundle.status) && (bundle.integration.sources.some((source) => source.id === c.id) || bundle.integration.repair?.changeId === c.id));
|
|
23
|
+
if (parent)
|
|
24
|
+
return { ok: false, message: `改动 #${c.id} 属于集成 #${parent.id},请检查并应用集成结果;要单独应用需先 /drop ${parent.id}。` };
|
|
25
|
+
if (c.integration) {
|
|
26
|
+
if (c.integration.supersededBy)
|
|
27
|
+
return { ok: false, message: `集成 #${c.id} 已被新集成 #${c.integration.supersededBy} 替代,请检查并应用新集成结果。` };
|
|
28
|
+
if (c.integration.status !== "passed" || !c.verification?.passed || c.verification.head !== c.head || c.integration.reports.length !== c.integration.checks.length || c.integration.reports.some((report) => !report.passed))
|
|
29
|
+
return { ok: false, message: "联合集成尚未完整通过检查,不能应用。" };
|
|
30
|
+
const stale = await integrationStale(store, c);
|
|
31
|
+
if (stale)
|
|
32
|
+
return { ok: false, message: stale };
|
|
33
|
+
if (await integrationGit(c.path, ["rev-parse", "HEAD"]) !== c.head || await integrationGit(c.path, ["status", "--porcelain"]))
|
|
34
|
+
return { ok: false, message: "集成工作区在验证后发生变化,拒绝应用旧的测试结论。" };
|
|
35
|
+
const patch = await git(c.root, ["diff", "--binary", "--no-color", "--no-renames", c.base, c.head]);
|
|
36
|
+
if (patch.code)
|
|
37
|
+
return { ok: false, message: patch.stderr };
|
|
38
|
+
if (patch.stdout.trim()) {
|
|
39
|
+
const canApply = await git(c.root, ["apply", "--check", "--whitespace=nowarn", "-"], patch.stdout);
|
|
40
|
+
if (canApply.code)
|
|
41
|
+
return { ok: false, message: `主目录无法无冲突应用,未修改文件:${canApply.stderr}` };
|
|
42
|
+
const result = await git(c.root, ["apply", "--whitespace=nowarn", "-"], patch.stdout);
|
|
43
|
+
if (result.code)
|
|
44
|
+
return { ok: false, message: result.stderr };
|
|
45
|
+
}
|
|
46
|
+
store.upsert({ ...c, status: "applied", appliedHead: c.head, message: "联合验证改动已应用到主目录,等待人工提交。" });
|
|
47
|
+
for (const source of c.integration.sources) {
|
|
48
|
+
const item = store.get(source.id);
|
|
49
|
+
if (item?.head === source.head)
|
|
50
|
+
store.upsert({ ...item, status: "applied", appliedHead: source.head, message: `已随集成 #${c.id} 应用。` });
|
|
51
|
+
}
|
|
52
|
+
if (c.integration.repair?.changeId) {
|
|
53
|
+
const fix = store.get(c.integration.repair.changeId);
|
|
54
|
+
if (fix && fix.head === c.head)
|
|
55
|
+
store.upsert({ ...fix, status: "applied", appliedHead: fix.head, message: `已随集成 #${c.id} 应用。` });
|
|
56
|
+
}
|
|
57
|
+
return { ok: true, message: `集成 #${c.id} 已整体应用,${c.integration.sources.length} 项来源标为已应用;主目录未自动提交。` };
|
|
58
|
+
}
|
|
59
|
+
const [from, to] = store.range(c);
|
|
60
|
+
const r = await applyRange(c.root, from, to);
|
|
61
|
+
if (!r.ok) {
|
|
62
|
+
store.upsert({ ...c, status: "conflict", message: r.message });
|
|
63
|
+
return {
|
|
64
|
+
ok: false,
|
|
65
|
+
message: `改动 #${c.id} 和主目录当前的内容冲突,没有应用:\n${r.message}\n可以让成员基于最新代码重做,或者手动处理(分支 ${c.branch})。`,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
store.upsert({ ...c, status: "applied", appliedHead: c.head, message: r.message });
|
|
69
|
+
return { ok: true, message: `改动 #${c.id} ${r.message}(${c.files.length} 个文件 +${c.add} −${c.del},没有提交,请检查后自行 commit)` };
|
|
70
|
+
}
|
|
71
|
+
export async function dropChange(store, id) {
|
|
72
|
+
const c = find(store, id);
|
|
73
|
+
if (!c)
|
|
74
|
+
return { ok: false, message: `找不到改动 ${id}` };
|
|
75
|
+
if (c.status === "running")
|
|
76
|
+
return { ok: false, message: `改动 #${c.id} 还在进行中,先中止本轮再丢弃` };
|
|
77
|
+
if (c.status === "dropped")
|
|
78
|
+
return { ok: false, message: `改动 #${c.id} 已经丢弃过了` };
|
|
79
|
+
await removeWorktree(c.root, c.path, c.branch);
|
|
80
|
+
store.upsert({ ...c, status: "dropped" });
|
|
81
|
+
return { ok: true, message: `已丢弃改动 #${c.id},删除了 worktree 和分支 ${c.branch}` };
|
|
82
|
+
}
|
|
83
|
+
/** 清理:已合并 / 没改动的改动,删掉 worktree 和分支(之后不能再续接它们的会话) */
|
|
84
|
+
export async function cleanChanges(store) {
|
|
85
|
+
const targets = store.list().filter((c) => c.status === "applied" || c.status === "empty");
|
|
86
|
+
for (const c of targets) {
|
|
87
|
+
await removeWorktree(c.root, c.path, c.branch);
|
|
88
|
+
store.upsert({ ...c, status: "dropped", message: c.status === "applied" ? "已合并,worktree 已清理" : "没有改动,worktree 已清理" });
|
|
89
|
+
}
|
|
90
|
+
return { ok: true, message: targets.length ? `清理了 ${targets.length} 个 worktree` : "没有需要清理的 worktree" };
|
|
91
|
+
}
|
package/dist/changes.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// 改动记录:每次隔离派工在哪个 worktree / 分支、改了哪些文件、是否已经合并回主目录。
|
|
2
|
+
// 存成会话存储旁边的一个 JSON 文件(同一个存储只有一个进程,进程锁保护)。
|
|
3
|
+
// 终端的 /apply /drop 和后台网页都读它;工具执行时写它。
|
|
4
|
+
import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { EventEmitter } from "node:events";
|
|
6
|
+
export class ChangeStore extends EventEmitter {
|
|
7
|
+
records = new Map();
|
|
8
|
+
file;
|
|
9
|
+
constructor(file) {
|
|
10
|
+
super();
|
|
11
|
+
this.file = file;
|
|
12
|
+
if (existsSync(file)) {
|
|
13
|
+
try {
|
|
14
|
+
for (const r of JSON.parse(readFileSync(file, "utf8")))
|
|
15
|
+
this.records.set(r.id, r);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
/* 文件损坏时从空开始,不影响派工 */
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
list() {
|
|
23
|
+
return [...this.records.values()].sort((a, b) => b.createdAt - a.createdAt);
|
|
24
|
+
}
|
|
25
|
+
get(id) {
|
|
26
|
+
return this.records.get(id) ?? [...this.records.values()].find((r) => r.id.startsWith(id) || r.branch === id);
|
|
27
|
+
}
|
|
28
|
+
/** worktree 里的某个目录属于哪次改动(续接会话时用) */
|
|
29
|
+
byPath(dir) {
|
|
30
|
+
const norm = (p) => p.replace(/[\\/]+/g, "/").toLowerCase();
|
|
31
|
+
return this.list().find((r) => norm(dir).startsWith(norm(r.path)));
|
|
32
|
+
}
|
|
33
|
+
upsert(record) {
|
|
34
|
+
record.updatedAt = Date.now();
|
|
35
|
+
this.records.set(record.id, record);
|
|
36
|
+
const tmp = `${this.file}.tmp`;
|
|
37
|
+
writeFileSync(tmp, JSON.stringify(this.list(), null, 1));
|
|
38
|
+
renameSync(tmp, this.file);
|
|
39
|
+
this.emit("change", record);
|
|
40
|
+
return record;
|
|
41
|
+
}
|
|
42
|
+
/** 改动的差异区间:已合并过的从合并点算起 */
|
|
43
|
+
range(r) {
|
|
44
|
+
return [r.appliedHead ?? r.base, r.head];
|
|
45
|
+
}
|
|
46
|
+
}
|