feat: add durable isolated Git workspaces and source-bound delivery

This commit is contained in:
Agent Workbench Dev
2026-10-29 23:22:30 +08:00
parent 7d60dc9c55
commit 7d9bfb85da
22 changed files with 1038 additions and 26 deletions
+42 -6
View File
@@ -7,6 +7,7 @@ import { StateDatabase, runtimeOwnerAlive } from '../core/storage/state-database
import { ArtifactStore } from '../core/storage/artifact-store.mjs';
import { collectLegacy, cleanConfig } from '../core/storage/legacy-import.mjs';
import { ACTIVE_STATES, CORE_KINDS, createTask, createRun, ownedRecord, emptyUsage, accumulateUsage, accountedTokens, isId } from '../shared/contracts/execution.mjs';
import { WORKSPACE_ACTIVE, projectWorkspaceIdentity, assertWorkspacePath } from '../shared/contracts/workspaces.mjs';
export const now = () => new Date().toISOString();
@@ -210,6 +211,11 @@ export class Store extends EventEmitter {
set.summary = '文件批次在执行中断;请核对实际原文/建议字节,不会自动续写或回退。';
session.status = 'paused'; session.recoveryNotice = set.summary; changed = true;
}
for (const workspace of this.core.workspace.values()) if (workspace.sessionId === session.id && WORKSPACE_ACTIVE.has(workspace.status)) {
workspace.status = 'unknown'; workspace.requiresVerification = true; workspace.finishedAt = now();
workspace.summary = '隔离工作区创建中断,请核对实际目录、分支和Git登记。不会重放创建、删除或重置。';
session.status = 'paused'; session.recoveryNotice = workspace.summary; changed = true;
}
for (const event of session.events ?? []) {
if (['running', 'waiting', 'retrying'].includes(event.phase)) {
const invocation = [...this.core.tool.values()].find(item => item.sessionId === session.id && item.callId === event.toolCallId);
@@ -291,13 +297,27 @@ export class Store extends EventEmitter {
return this.config;
}
addProject(root) {
addProject(root, { id = null, name = null, workspace = null } = {}) {
if (id !== null && !isId(id) || name !== null && (typeof name !== 'string' || !name.trim() || name.length > 200 || /[\x00-\x1f]/.test(name))) throw new Error('内部项目身份或名称无效。');
const resolved = fs.realpathSync.native(path.resolve(root));
if (!fs.statSync(resolved).isDirectory()) throw new Error('请选择项目文件夹。');
const key = process.platform === 'win32' ? resolved.toLowerCase() : resolved;
const existing = this.projects.find(project => (process.platform === 'win32' ? project.root.toLowerCase() : project.root) === key);
if (existing) return existing;
const project = { id: randomUUID(), root: resolved, name: path.basename(resolved), addedAt: now() };
if (existing) {
if (id && existing.id !== id || workspace && JSON.stringify(existing.workspace) !== JSON.stringify(workspace)) throw Object.assign(new Error('目标目录已经属于另一个项目身份,不能替换。'), { status: 409 });
return existing;
}
if (id && this.projects.some(project => project.id === id)) throw Object.assign(new Error('项目身份已经用于另一个目录。'), { status: 409 });
if (workspace) {
const record = this.core.workspace.get(workspace.id), source = record && this.project(record.projectId);
const expected = record && { id: record.id, sourceProjectId: record.projectId, sourceSessionId: record.sessionId, sourceRoot: record.source.root,
sourceWorkspaceId: source.workspace?.id ?? null, baseCommit: record.source.head, branch: record.branch,
commonGitDir: record.source.commonDir, gitDir: record.observation?.gitDir, fingerprint: record.fingerprint };
if (!record || record.status !== 'registering' || record.childProjectId !== id || record.root !== resolved
|| JSON.stringify(workspace) !== JSON.stringify(expected)) throw Object.assign(new Error('工作区项目必须来自已验证的持久创建记录。'), { status: 409 });
assertWorkspacePath({ root: resolved, workspace });
}
const project = { id: id ?? randomUUID(), root: resolved, name: name ?? path.basename(resolved), addedAt: now(), ...(workspace ? { workspace: structuredClone(workspace) } : {}) };
const next = [project, ...this.projects];
this.storage.transaction(() => this.storage.writeProjects(next));
this.projects = next;
@@ -310,10 +330,16 @@ export class Store extends EventEmitter {
return project;
}
createSession(projectId, title = '新任务') {
createSession(projectId, title = '新任务', { id = null } = {}) {
this.project(projectId);
if (id !== null && !isId(id)) throw new Error('内部会话身份无效。');
if (id && this.sessions.has(id)) {
const existing = this.sessions.get(id);
if (existing.projectId !== projectId) throw Object.assign(new Error('会话身份已经属于另一个项目。'), { status: 409 });
return existing;
}
const session = {
id: randomUUID(), projectId, title, status: 'idle', createdAt: now(), updatedAt: now(),
id: id ?? randomUUID(), projectId, title, status: 'idle', createdAt: now(), updatedAt: now(),
messages: [], providerMessages: [], events: [], changes: [], approvals: [],
failure: null, lastFailure: null,
compactions: 0, estimatedTokens: 0, usage: null, archived: false,
@@ -340,7 +366,11 @@ export class Store extends EventEmitter {
if (task.readProgress) {
task.readProgress.repeated = 0; task.readProgress.changingIndexes = []; task.readProgress.warning = null; task.readProgress.pause = false;
}
const workspaceIdentity = projectWorkspaceIdentity(this.project(session.projectId));
task.workspaceIdentity ??= structuredClone(workspaceIdentity);
if (JSON.stringify(task.workspaceIdentity) !== JSON.stringify(workspaceIdentity)) throw Object.assign(new Error('任务的工作区身份已变化,不能将原任务移动到另一个工作区。'), { status: 409 });
const run = createRun(session, task, config, resume ? previousRunId : null);
run.workspaceIdentity = structuredClone(workspaceIdentity);
this.core.run.set(run.id, run); task.activeRunId = run.id;
session.taskId = task.id; session.runId = run.id; session.status = 'running';
this.save(session, { type: 'run.started', detail: { resumeOf: run.resumeOf } });
@@ -467,11 +497,17 @@ export class Store extends EventEmitter {
const tools = [...this.core.tool.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id);
const artifacts = [...this.core.artifact.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-30);
const jobs = [...this.core.check_job.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-10);
const projectWorkspaces = [...this.core.workspace.values()].filter(value => value.projectId === session.projectId);
const recentWorkspaceIds = new Set(projectWorkspaces.slice(-12).map(value => value.id));
return {
schemaVersion: 1, task: task ?? null, run: run ?? null,
workspaceIdentity: projectWorkspaceIdentity(this.project(session.projectId)),
workspaces: projectWorkspaces.filter(value => recentWorkspaceIds.has(value.id) || value.requiresVerification
|| ['prepared', 'creating', 'verifying', 'registering'].includes(value.status)),
runs: [...this.core.run.values()].filter(value => value.sessionId === session.id).slice(-20).map(value => ({ id: value.id, taskId: value.taskId,
status: value.status, startedAt: value.startedAt, finishedAt: value.finishedAt, steps: value.steps, toolCalls: value.toolCalls,
usage: value.usage, stopReason: value.stopReason, model: value.model, budget: value.budget, resumeOf: value.resumeOf })),
usage: value.usage, stopReason: value.stopReason, model: value.model, budget: value.budget, resumeOf: value.resumeOf,
...(value.workspaceIdentity ? { workspaceIdentity: value.workspaceIdentity } : {}), ...(value.review ? { review: value.review } : {}) })),
progress: { totalTools: tools.length, completedTools: tools.filter(value => value.state === 'completed').length,
requiresVerification: tools.filter(value => value.requiresVerification).map(value => ({ id: value.id, tool: value.tool, callId: value.callId, state: value.state })) },
artifacts, checks: jobs,