feat: journal reviewed multi-file changes and recover interrupted batches
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
# 多文件变更集与恢复契约
|
||||
|
||||
1.4.0开发中的M2切片。变更集把同Task的1–32份文本提案封存为一次审查;总原文和建议内容最多4MB。每个实际路径只能出现一次,拒绝文件/目录重叠、链接及Windows路径别名。源码文件的原字节和建议字节分别核对SHA256,保留文件格式和普通权限。
|
||||
|
||||
准备操作保存Task/Run、项目真实根目录、只读Git HEAD/分支、原/新文件哈希及内容快照工件;不写项目。界面按实际差异审核后,将同一个封存指纹提交给应用接口。模型只有准备工具,没有应用或回退工具。已封存的提案不能绕过批次单独应用;撤销未执行批次后可重新准备或逐项审查。
|
||||
|
||||
应用前再次核对全部提案、快照、Git HEAD/分支及全部目标文件,任一基线变化则整批不写入。逐文件写入意图先保存到SQLite,临时文件同步到磁盘后在同目录替换,再持久保存实际结果。普通执行失败或取消时尝试恢复本次已进入写入的文件;只在当前字节仍等于本次建议时回退,外部修改保留。已创建的空目录可保留,恢复不递归删除项目目录。
|
||||
|
||||
文件系统不提供跨文件原子事务;检查与替换之间也没有外部编辑器的通用文件锁。对外区分prepared、applying、completed、rolled_back、unknown/partial和cancelled,不能把半批结果写成成功。
|
||||
|
||||
真实进程中断后,宿主把尚未完成的批次标记为需核对,启动时不执行文件写入。显式核对校验封存快照并读取每个目标的实际哈希,记录原文、建议内容、外部修改或不可读取。完整建议内容且每项有写入意图才记为completed;全部原文则结束为interrupted/rolled_back;混合结果保持partial。用户可以显式回退本批次已写入文件;不自动续写或重放,新的修改从新提案开始。遗留的本批次回退临时文件只有类型/大小/SHA均匹配时才复用;内容不匹配则保留并提示核对。
|
||||
|
||||
其余目标均回到原文、外部修改已读取且当前观察指纹未变时,用户可明确「保留外部改动并结束恢复」,批次结束为resolved_external。该操作不写项目文件,也不记为成功应用;外部字节与原文状态保存在记录中,后续新任务可以继续。无法读取或仍有本次已写入内容时不能使用这个入口。
|
||||
|
||||
结果未核对时阻止同项目新运行、文件应用、检查和Git提交,恢复入口保留所属会话/Task。完成或回退都会使旧检查过期;交付报告引用批次身份、指纹和实际状态。历史批次可查看与核对,普通已完成批次回退仅作用于当前Task且核对封存指纹和当前文件哈希。
|
||||
|
||||
验收包含:整批预检冲突零写入、BOM/CRLF及权限保留、新文件、重复路径/祖先路径/链接、快照损坏、重复请求、同项目隔离、失败回退、owner修改保护,以及准备/写入意图/替换/逐项保存/回退/最终保存的真实进程退出。具体结果完成后登记,当前文档不代替测试证据。
|
||||
@@ -152,3 +152,11 @@ Claude Code 报告已验证工具输入校验、权限决定、队列并发屏
|
||||
- 真实模型用量15请求/280253tokens(输入277387、输出2866),未知用量请求0。正确定位不等于费用下降,当前仍重复投影较长历史;后续须同题对照、保留工具结果可追溯引用的有界上下文投影与预算,不用此样本宣称成本改善。
|
||||
- 实现源码与检查冻结后,最终发行只增加文档/证据;用全部src/tests/public/scripts与6份构建产物对照已离线安装和112项验收的独立源码,避免无依据重复全套测试或覆盖运行发行目录。
|
||||
- 证据复制时误将live.reportPath指向的Markdown另存为JSON,JSON解析检查发现;已改为按同目录delivery-report.json复制并复验,运行代码与样本结果未变。
|
||||
|
||||
## 1.4.0多文件变更集设计依据
|
||||
|
||||
- 现有applyChange只有单文件原哈希/备份/rename;没有封存的整批范围,也没有rename与SQLite完成记录之间的恢复账本。新能力使用change_set持久记录和每文件原/新字节快照工件,全批预检后逐文件保存意图/结果。
|
||||
- Store的recordsFor/ensureStorage支持增加记录kind;recover只标记未知状态,不自动写文件。执行、检查、Git和旧版逐项应用需要统一阻止未核对批次,不能仅在新界面限制。
|
||||
- ChangeSet先完成显式核对/按哈希回退;新文件空父目录可保留,不递归删除。文件系统没有跨文件事务或通用外部编辑器锁,报告区分completed、rolled_back及unknown/partial。
|
||||
- 首轮22项专项21通过/1失败:实际进程在restore_staged退出留下了原字节临时文件,后续wx创建冲突阻挡回退。改为校验本批次临时文件类型/大小/SHA并复用原字节,不删除或覆盖不匹配文件;补充临时文件owner保护与跨Run同Task提案专项。
|
||||
- 实现补丁两次使用长单行的前缀作为完整上下文导致校验失败;改为完整独立行锚点,不重复失效匹配。未应用的补丁没有改变运行服务。
|
||||
|
||||
@@ -132,3 +132,5 @@
|
||||
- 420行说明、BOM/CRLF/LF、10个保护输入及其他工作区/暂存改动全部保留。实际15请求、输入277387/输出2866/合计280253已报告tokens;不能据此宣称降低上下文成本。
|
||||
- 初始1.3.0便携与源码ZIP/112项独立源码验收、43组界面和原PID23080升级均已通过;本轮收集证据后创建最终独立时间戳发行,冻结核心/测试/构建/脚本与独立源码逐字节比对,再保留原进程升级。
|
||||
- 最终包20261029101643317:2138份便携/283份源码清单、CRC与SHA通过,77份运行/测试/全部脚本和6份构建产物与已独立安装/112项验收源码逐字节一致;原PID23080更新保留全部6项目/7会话的消息、事件、提案和execution指纹。下一批进入同Task多文件变更集与可恢复应用。
|
||||
- 1.4.0封存变更集/原新字节快照/整批预检/逐文件意图和结果/显式核对回退/外部改动确认已实现。24/24专项通过,包含13个真实退出切点;首轮restore_staged失败修正为校验并复用原字节暂存文件。模型准备工具和API接入,继续统一审查界面与交付报告证据。
|
||||
- 相关原有文件/运行/存储/Git交付27/27回归与构建通过;保存多文件核心本地提交,继续界面与实际API验收。原4318仍运行已验证的最终1.3.0,不重启或读取内存Key。
|
||||
|
||||
@@ -5,6 +5,7 @@ import { randomUUID } from 'node:crypto';
|
||||
import { StringDecoder } from 'node:string_decoder';
|
||||
import { inspectProject, createCheckList } from './project-inspector.mjs';
|
||||
import { safePath } from '../server/files.mjs';
|
||||
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
|
||||
|
||||
const at = () => new Date().toISOString();
|
||||
const conflict = message => Object.assign(new Error(message), { status: 409 });
|
||||
@@ -52,6 +53,7 @@ export class CheckRunner {
|
||||
projectActive(projectId) { return this.projects.has(projectId); }
|
||||
|
||||
async plan(session, names) {
|
||||
assertChangeSetsResolved(this.store, session.projectId);
|
||||
if (!session.taskId || !session.runId) throw conflict('先发送一个项目任务,再识别本任务的检查计划。');
|
||||
const identity = { taskId: session.taskId, runId: session.runId };
|
||||
const inspection = await inspectProject(this.store.project(session.projectId));
|
||||
@@ -78,6 +80,7 @@ export class CheckRunner {
|
||||
}
|
||||
|
||||
async start(session, planId, { signal, source = 'user' } = {}) {
|
||||
assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true });
|
||||
const plan = this.planFor(session, planId);
|
||||
if (this.projectActive(session.projectId) || this.projectBusy(session.projectId, source === 'agent' ? session.id : null)) throw conflict('同一项目正在执行任务或检查,请等待结束后再运行。');
|
||||
if (session.changes.some(change => ['pending', 'conflict'].includes(change.status))) throw conflict('先应用或撤回本任务的待审查改动,再检查实际工程。');
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { inspectProject } from './project-inspector.mjs';
|
||||
import { ChangeSetManager } from './workspaces/change-sets.mjs';
|
||||
|
||||
const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待文件审查',
|
||||
needs_checks: '需要实际工程检查', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' };
|
||||
@@ -40,6 +41,16 @@ export class DeliveryReporter {
|
||||
const requiresVerification = [...this.store.core.tool.values()].filter(value => value.taskId === taskId && value.requiresVerification)
|
||||
.map(value => ({ id: value.id, tool: value.tool, status: value.state }));
|
||||
const unresolved = jobs.filter(value => value.requiresVerification || value.status === 'unknown');
|
||||
const sets = [...this.store.core.change_set.values()].filter(value => value.sessionId === session.id && value.taskId === taskId);
|
||||
const changeSets = sets.map(set => {
|
||||
let snapshotVerified = true, snapshotError = null;
|
||||
try { new ChangeSetManager(this.store).snapshots(session, set); } catch (error) { snapshotVerified = false; snapshotError = error.message; }
|
||||
return { id: set.id, taskId: set.taskId, runId: set.runId, status: set.status, fingerprint: set.fingerprint,
|
||||
paths: set.files.map(file => file.path), snapshotVerified, snapshotError, requiresVerification: !!set.requiresVerification,
|
||||
summary: set.summary, verifiedAt: set.verifiedAt ?? null, finishedAt: set.finishedAt ?? null };
|
||||
});
|
||||
requiresVerification.push(...changeSets.filter(set => set.requiresVerification || !set.snapshotVerified)
|
||||
.map(set => ({ id: set.id, tool: 'change_set', status: set.status })));
|
||||
const commits = jobs.filter(value => value.status === 'completed' && value.commit && value.sourceFingerprint === inspection.sourceFingerprint);
|
||||
const status = requiresVerification.length || unresolved.length ? 'needs_verification'
|
||||
: ['running', 'awaiting_approval', 'stopping'].includes(session.status) ? 'in_progress'
|
||||
@@ -55,7 +66,8 @@ export class DeliveryReporter {
|
||||
engine: value.engine, status: value.status, model: value.model, startedAt: value.startedAt, finishedAt: value.finishedAt, usage: value.usage, stopReason: value.stopReason })),
|
||||
usage: { ...task.usage, priceStatus: 'not_configured', amount: null, currency: null },
|
||||
changes: changes.map(value => ({ id: value.id, path: value.path, status: value.status, reason: value.reason, baseSha256: value.baseSha256,
|
||||
sha256: value.sha256, appliedAt: value.appliedAt ?? null, additions: value.additions, deletions: value.deletions })),
|
||||
sha256: value.sha256, changeSetId: value.changeSetId ?? null, appliedAt: value.appliedAt ?? null, additions: value.additions, deletions: value.deletions })),
|
||||
changeSets,
|
||||
checks: [...this.store.core.check_job.values()].filter(value => value.taskId === taskId).map(value => ({ id: value.id, status: value.status,
|
||||
stale: !!value.stale || (value.sourceFingerprint ? value.sourceFingerprint !== inspection.sourceFingerprint : value.fingerprint !== inspection.fingerprint),
|
||||
sourceFingerprint: value.sourceFingerprint ?? null, startedAt: value.startedAt, finishedAt: value.finishedAt,
|
||||
@@ -87,6 +99,11 @@ export function renderDeliveryMarkdown(report) {
|
||||
'分支:' + (report.source.branch ?? '未记录'), '', report.task.note, '', '## 改动', '',
|
||||
'| 文件 | 状态 | SHA256 |', '| --- | --- | --- |'];
|
||||
for (const change of report.changes) lines.push('| ' + [change.path, change.status, change.sha256].map(escapeCell).join(' | ') + ' |');
|
||||
if (report.changeSets?.length) {
|
||||
lines.push('', '## 多文件变更集', '', '| 批次 | 实际状态 | 快照 | 审查指纹 |', '| --- | --- | --- | --- |');
|
||||
for (const set of report.changeSets) lines.push('| ' + [set.id, set.status, set.snapshotVerified ? 'SHA256校验通过' : '需要核对', set.fingerprint].map(escapeCell).join(' | ') + ' |',
|
||||
'', set.summary ?? '', '');
|
||||
}
|
||||
lines.push('', '## 实际检查', '', '| Job / 命令 | 状态 | 退出码 | 实际测试 | 日志SHA256 |', '| --- | --- | --- | --- | --- |');
|
||||
for (const job of report.checks) for (const result of job.results) lines.push('| ' + [job.id.slice(0, 8) + ' / ' + result.command,
|
||||
job.stale ? '源码已变化 / ' + result.status : result.status, result.exitCode ?? '未知', result.tests ? result.tests.passed + '/' + result.tests.total : '不适用或未知', result.logSha256 ?? '未知'].map(escapeCell).join(' | ') + ' |');
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { createTwoFilesPatch, diffLines } from 'diff';
|
||||
@@ -68,6 +69,7 @@ export class GitDelivery {
|
||||
return result;
|
||||
}
|
||||
assertTask(session) {
|
||||
assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true });
|
||||
if (!session.taskId || !session.runId) throw conflict('先发送一个项目任务,再准备本任务的Git交付。');
|
||||
const task = this.store.owned('task', session.taskId, session.id), run = this.store.owned('run', session.runId, session.id);
|
||||
if (run.taskId !== task.id) throw conflict('当前Task和Run归属不一致。');
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { safePath, excludedFromInventory, hash } from '../../server/files.mjs';
|
||||
import { inspectProject } from '../project-inspector.mjs';
|
||||
import { assertChangeSetsResolved, CHANGE_SET_OPEN } from '../../shared/contracts/change-sets.mjs';
|
||||
|
||||
const at = () => new Date().toISOString();
|
||||
const conflict = message => Object.assign(new Error(message), { status: 409 });
|
||||
const key = value => process.platform === 'win32' ? value.toLowerCase() : value;
|
||||
const gitBaseline = inspection => ({ available: inspection.git.available, head: inspection.git.head ?? null, branch: inspection.git.branch ?? null });
|
||||
const sealed = set => ({ id: set.id, sessionId: set.sessionId, projectId: set.projectId, taskId: set.taskId, runId: set.runId,
|
||||
root: set.root, baseline: set.baseline, files: set.files.map(file => ({ changeId: file.changeId, path: file.path,
|
||||
baseExists: file.baseExists, baseSha256: file.baseSha256, sha256: file.sha256, baseBytes: file.baseBytes, bytes: file.bytes,
|
||||
mode: file.mode, reason: file.reason, sourceRunId: file.sourceRunId, snapshotArtifactId: file.snapshotArtifactId })) });
|
||||
const observationHash = observations => hash(Buffer.from(JSON.stringify(observations.map(file =>
|
||||
({ path: file.path, state: file.state, exists: file.exists, actualSha256: file.actualSha256, problem: file.problem ?? null })))));
|
||||
|
||||
// A batch rejects links and platform aliases rather than treating two names as
|
||||
// independent files. The project root was canonicalized when it was opened.
|
||||
function targetFor(project, relative) {
|
||||
const target = safePath(project, relative, true), portable = path.relative(project.root, target).replaceAll('\\', '/');
|
||||
if (!portable || excludedFromInventory(portable)) throw conflict('变更集只能包含项目范围内的普通源码文件。');
|
||||
for (const part of portable.split('/')) if (process.platform === 'win32'
|
||||
&& (/[. ]$/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i.test(part))) throw conflict('变更集路径含Windows设备名或不唯一的路径别名。');
|
||||
let current = project.root;
|
||||
for (const part of portable.split('/')) {
|
||||
current = path.join(current, part);
|
||||
try {
|
||||
const stat = fs.lstatSync(current);
|
||||
if (stat.isSymbolicLink() || stat.isFile() && stat.nlink > 1) throw conflict('变更集目标不能经过链接或共享硬链接文件。');
|
||||
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
||||
}
|
||||
return { target, path: portable };
|
||||
}
|
||||
|
||||
function validatePaths(project, files) {
|
||||
const seen = [];
|
||||
for (const file of files) {
|
||||
const target = targetFor(project, file.path), identity = key(target.path);
|
||||
if (seen.some(value => value === identity || value.startsWith(identity + '/') || identity.startsWith(value + '/'))) {
|
||||
throw conflict('同一变更集不能重复修改实际路径,也不能包含文件与其子路径。');
|
||||
}
|
||||
seen.push(identity);
|
||||
}
|
||||
}
|
||||
|
||||
function observe(project, file) {
|
||||
try {
|
||||
const { target } = targetFor(project, file.path);
|
||||
let stat;
|
||||
try { stat = fs.lstatSync(target); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
||||
if (stat && (!stat.isFile() || stat.size > 4 * 1024 * 1024)) throw new Error('目标已不是有界普通文件。');
|
||||
const exists = !!stat, actualSha256 = exists ? hash(fs.readFileSync(target)) : null;
|
||||
const state = exists === file.baseExists && actualSha256 === file.baseSha256 ? 'before'
|
||||
: exists && actualSha256 === file.sha256 ? 'after' : 'external';
|
||||
return { path: file.path, state, exists, actualSha256 };
|
||||
} catch (error) { return { path: file.path, state: 'unavailable', exists: null, actualSha256: null, problem: error.message }; }
|
||||
}
|
||||
|
||||
function base64(value) {
|
||||
if (typeof value !== 'string') throw conflict('变更集快照内容无效。');
|
||||
const bytes = Buffer.from(value, 'base64');
|
||||
if (bytes.toString('base64') !== value) throw conflict('变更集快照编码无效。');
|
||||
return bytes;
|
||||
}
|
||||
|
||||
export class ChangeSetManager {
|
||||
constructor(store, { projectBusy = () => false, faultInjector = null } = {}) {
|
||||
this.store = store; this.projectBusy = projectBusy; this.faultInjector = faultInjector;
|
||||
this.active = new Map(); this.projects = new Map();
|
||||
}
|
||||
projectActive(id) { return this.projects.has(id); }
|
||||
isActive(id) { return [...this.active.values()].some(value => value.sessionId === id); }
|
||||
async cut(phase, set, index = null) {
|
||||
await this.faultInjector?.(phase, set, index);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
}
|
||||
save(session, set, phase) { this.store.save(session, { type: 'change_set.' + phase, detail: { changeSetId: set.id } }); }
|
||||
requireIdle(session, { source = 'user', exceptId = null, includePrepared = false } = {}) {
|
||||
if (this.projectActive(session.projectId) || this.projectBusy(session.projectId, source === 'agent' ? session.id : null)) {
|
||||
throw conflict('同一项目正在执行任务、检查、提交或文件批次,请等待结束后再操作。');
|
||||
}
|
||||
assertChangeSetsResolved(this.store, session.projectId, { exceptId, includePrepared });
|
||||
}
|
||||
own(session, id, fingerprint = null, { current = false } = {}) {
|
||||
const set = this.store.owned('change_set', id, session.id);
|
||||
if (current && set.taskId !== session.taskId) throw conflict('变更集属于此前Task,请在所属任务中核对。');
|
||||
if (fingerprint !== null && fingerprint !== set.fingerprint) throw conflict('审查指纹已变化,请重新打开这个变更集。');
|
||||
return set;
|
||||
}
|
||||
snapshots(session, set, { pending = false } = {}) {
|
||||
const project = this.store.project(session.projectId);
|
||||
if (set.root !== project.root || hash(Buffer.from(JSON.stringify(sealed(set)))) !== set.fingerprint) throw conflict('变更集封存信息校验失败,请核对原批次。');
|
||||
validatePaths(project, set.files);
|
||||
return set.files.map(file => {
|
||||
const change = session.changes.find(value => value.id === file.changeId);
|
||||
if (!change || change.taskId !== set.taskId || change.runId !== file.sourceRunId || targetFor(project, change.path).path !== file.path
|
||||
|| change.baseExists !== file.baseExists || change.baseSha256 !== file.baseSha256 || change.sha256 !== file.sha256
|
||||
|| hash(Buffer.from(change.content, 'utf8')) !== file.sha256 || change.reason !== file.reason
|
||||
|| pending && (change.status !== 'pending' || change.changeSetId !== set.id)) throw conflict('变更集中的原提案已变化,请重新审查。');
|
||||
const artifact = this.store.owned('artifact', file.snapshotArtifactId, session.id);
|
||||
if (artifact.kind !== 'change-set-snapshot' || artifact.taskId !== set.taskId || artifact.runId !== set.runId) throw conflict('变更集快照不属于原Task/Run。');
|
||||
const snapshot = JSON.parse(this.store.artifactStore.read(artifact));
|
||||
if (snapshot.schemaVersion !== 1 || snapshot.changeSetId !== set.id || snapshot.changeId !== file.changeId
|
||||
|| snapshot.path !== file.path || snapshot.mode !== file.mode || snapshot.sourceRunId !== file.sourceRunId) throw conflict('变更集快照身份校验失败。');
|
||||
const before = file.baseExists ? base64(snapshot.before) : null, after = base64(snapshot.after);
|
||||
if (file.baseExists ? hash(before) !== file.baseSha256 || before.length !== file.baseBytes : snapshot.before !== null || file.baseSha256 !== null) throw conflict('变更集原字节快照校验失败。');
|
||||
if (hash(after) !== file.sha256 || after.length !== file.bytes) throw conflict('变更集建议字节快照校验失败。');
|
||||
return { before, after };
|
||||
});
|
||||
}
|
||||
inspect(session, set) {
|
||||
const project = this.store.project(session.projectId), observations = set.files.map(file => {
|
||||
const value = observe(project, file);
|
||||
if (set.attemptedAt && !file.writeAttempted && value.state === 'after') value.state = 'external';
|
||||
return value;
|
||||
});
|
||||
set.observations = observations; set.observationFingerprint = observationHash(observations); set.verifiedAt = at();
|
||||
for (let index = 0; index < set.files.length; index++) set.files[index].state = observations[index].state;
|
||||
return observations;
|
||||
}
|
||||
async prepare(session, changeIds, { source = 'user' } = {}) {
|
||||
if (!Array.isArray(changeIds) || !changeIds.length || changeIds.length > 32 || new Set(changeIds).size !== changeIds.length) throw conflict('变更集需要1到32个不同的提案ID。');
|
||||
this.requireIdle(session, { source });
|
||||
const task = this.store.owned('task', session.taskId, session.id), run = this.store.owned('run', session.runId, session.id);
|
||||
const existing = [...this.store.core.change_set.values()].find(value => value.projectId === session.projectId && value.status === 'prepared');
|
||||
if (existing) {
|
||||
if (existing.sessionId === session.id && existing.taskId === task.id
|
||||
&& JSON.stringify(existing.files.map(file => file.changeId).sort()) === JSON.stringify([...changeIds].sort())) {
|
||||
this.snapshots(session, existing, { pending: true }); return existing;
|
||||
}
|
||||
throw conflict('项目已有封存的待审查变更集,请先应用或撤销原批次。');
|
||||
}
|
||||
const changes = changeIds.map(id => session.changes.find(value => value.id === id));
|
||||
if (changes.some(value => !value || value.taskId !== task.id || this.store.core.run.get(value.runId)?.taskId !== task.id || value.status !== 'pending'
|
||||
|| value.changeSetId && CHANGE_SET_OPEN.has(this.store.core.change_set.get(value.changeSetId)?.status))) throw conflict('变更集只能封存当前Task的待审查提案。');
|
||||
const project = this.store.project(session.projectId);
|
||||
validatePaths(project, changes);
|
||||
const temporaryId = randomUUID(); this.projects.set(project.id, temporaryId);
|
||||
try {
|
||||
const inspection = await inspectProject(project);
|
||||
if (session.taskId !== task.id || session.runId !== run.id) throw conflict('准备变更集期间任务已切换。');
|
||||
const set = { id: randomUUID(), sessionId: session.id, projectId: project.id, taskId: task.id, runId: run.id, root: project.root,
|
||||
schemaVersion: 1, status: 'prepared', requiresVerification: false, source, createdAt: at(), baseline: gitBaseline(inspection), files: [],
|
||||
policy: 'reviewed-byte-snapshots', summary: '整批范围已封存,项目文件尚未改变。' };
|
||||
let budget = 0;
|
||||
const snapshots = changes.map(change => {
|
||||
const { target, path: portable } = targetFor(project, change.path), observation = observe(project, change);
|
||||
if (observation.state !== 'before') throw conflict('文件基线已变化,未准备批次:' + portable);
|
||||
const before = change.baseExists ? fs.readFileSync(target) : null, after = Buffer.from(change.content, 'utf8');
|
||||
if (hash(after) !== change.sha256 || before && hash(before) !== change.baseSha256) throw conflict('提案内容或原文件已经变化:' + portable);
|
||||
budget += (before?.length ?? 0) + after.length;
|
||||
if (budget > 4 * 1024 * 1024) throw conflict('变更集原文与建议内容合计超过4MB。');
|
||||
return { change, portable, before, after, mode: before ? fs.statSync(target).mode & 0o777 : 0o644 };
|
||||
});
|
||||
for (const { change, portable, before, after, mode } of snapshots) {
|
||||
const artifact = this.store.artifactStore.write(session, run, { schemaVersion: 1, changeSetId: set.id, changeId: change.id,
|
||||
path: portable, mode, sourceRunId: change.runId, before: before?.toString('base64') ?? null, after: after.toString('base64') }, { kind: 'change-set-snapshot' });
|
||||
this.store.core.artifact.set(artifact.id, artifact);
|
||||
set.files.push({ changeId: change.id, path: portable, baseExists: change.baseExists, baseSha256: change.baseSha256, sha256: change.sha256,
|
||||
baseBytes: before?.length ?? 0, bytes: after.length, mode, reason: change.reason, additions: change.additions, deletions: change.deletions,
|
||||
sourceRunId: change.runId, snapshotArtifactId: artifact.id, state: 'before', writeAttempted: false, restoreAttempted: false });
|
||||
change.changeSetId = set.id;
|
||||
}
|
||||
set.fingerprint = hash(Buffer.from(JSON.stringify(sealed(set))));
|
||||
this.store.putRecord('change_set', session, set, 'change_set.prepared');
|
||||
await this.cut('prepared', set);
|
||||
return set;
|
||||
} finally { this.projects.delete(project.id); }
|
||||
}
|
||||
claim(session, set) {
|
||||
const operation = { sessionId: session.id, projectId: session.projectId, controller: new AbortController(), promise: null };
|
||||
this.projects.set(session.projectId, set.id); this.active.set(set.id, operation); return operation;
|
||||
}
|
||||
release(set) { this.projects.delete(set.projectId); this.active.delete(set.id); }
|
||||
async start(session, id, fingerprint) {
|
||||
const set = this.own(session, id, fingerprint, { current: true });
|
||||
if (typeof fingerprint !== 'string' || set.status !== 'prepared' || set.attemptedAt) throw conflict('这个批次已执行或尚未提交原审查指纹,不能重复应用。');
|
||||
this.requireIdle(session, { exceptId: set.id });
|
||||
const operation = this.claim(session, set);
|
||||
try {
|
||||
const snapshots = this.snapshots(session, set, { pending: true });
|
||||
const project = this.store.project(session.projectId), inspection = await inspectProject(project);
|
||||
if (set.taskId !== session.taskId || JSON.stringify(gitBaseline(inspection)) !== JSON.stringify(set.baseline)) throw conflict('任务或Git HEAD/分支已变化,未写入任何文件。');
|
||||
if (this.inspect(session, set).some(value => value.state !== 'before')) throw conflict('整批文件基线检查失败,未写入任何文件。');
|
||||
set.status = 'applying'; set.attemptedAt = at(); set.direction = 'apply'; set.originalSessionStatus = session.status;
|
||||
set.summary = '整批预检通过,正在记录逐文件写入。';
|
||||
this.save(session, set, 'application_started');
|
||||
operation.promise = this.execute(session, set, snapshots, operation).finally(() => this.release(set));
|
||||
operation.promise.catch(() => {});
|
||||
return { set, promise: operation.promise };
|
||||
} catch (error) {
|
||||
this.release(set);
|
||||
if (!set.attemptedAt) { set.status = 'stale'; set.summary = '只读预检未通过,项目未写入:' + error.message; this.save(session, set, 'preflight_failed'); }
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async replace(session, set, index, bytes, direction) {
|
||||
const project = this.store.project(session.projectId), file = set.files[index], expected = direction === 'apply' ? 'before' : 'after';
|
||||
if (observe(project, file).state !== expected) throw conflict('目标在写入前变化,保留当前文件:' + file.path);
|
||||
const { target } = targetFor(project, file.path);
|
||||
if (bytes === null) {
|
||||
if (observe(project, file).state !== expected) throw conflict('新文件在删除前变化,保留当前内容:' + file.path);
|
||||
fs.unlinkSync(target);
|
||||
} else {
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true }); targetFor(project, file.path);
|
||||
const temporary = path.join(path.dirname(target), '.awb-' + set.id + '-' + index + '-' + direction + '.tmp');
|
||||
let owned = false;
|
||||
try {
|
||||
if (fs.existsSync(temporary)) {
|
||||
const stat = fs.lstatSync(temporary);
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== bytes.length || hash(fs.readFileSync(temporary)) !== hash(bytes)) {
|
||||
throw conflict('遗留临时文件不属于已封存字节,保留该文件:' + file.path);
|
||||
}
|
||||
owned = true;
|
||||
} else {
|
||||
const handle = fs.openSync(temporary, 'wx', file.mode); owned = true;
|
||||
try { fs.writeFileSync(handle, bytes); fs.fsyncSync(handle); } finally { fs.closeSync(handle); }
|
||||
}
|
||||
fs.chmodSync(temporary, file.mode);
|
||||
await this.cut(direction === 'apply' ? 'staged' : 'restore_staged', set, index);
|
||||
targetFor(project, file.path);
|
||||
if (observe(project, file).state !== expected) throw conflict('目标在替换前变化,保留当前内容:' + file.path);
|
||||
fs.renameSync(temporary, target); owned = false;
|
||||
} finally {
|
||||
if (owned && fs.existsSync(temporary) && !fs.lstatSync(temporary).isSymbolicLink() && hash(fs.readFileSync(temporary)) === hash(bytes)) fs.unlinkSync(temporary);
|
||||
}
|
||||
}
|
||||
await this.cut(direction === 'apply' ? 'replaced' : 'restored', set, index);
|
||||
if (observe(project, file).state !== (direction === 'apply' ? 'after' : 'before')) throw conflict('文件替换后发生变化,请核对:' + file.path);
|
||||
}
|
||||
settle(session, set, observations, direction) {
|
||||
const complete = direction === 'apply' && observations.every((value, index) => value.state === 'after' && set.files[index].writeAttempted);
|
||||
const before = observations.every(value => value.state === 'before');
|
||||
set.status = complete ? 'completed' : before ? direction === 'rollback' ? 'rolled_back' : 'interrupted' : 'partial';
|
||||
set.requiresVerification = !complete && !before; set.finishedAt = at();
|
||||
set.summary = complete ? '整批文件的实际建议字节已核对,全部应用完成。' : before
|
||||
? '全部目标已核对为原字节;这次批次已结束,不会自动重放。' : '批次仍有混合或外部改动,保留实际文件,请核对或回退已写入部分。';
|
||||
if (!set.requiresVerification) for (const file of set.files) {
|
||||
const change = session.changes.find(value => value.id === file.changeId);
|
||||
change.status = complete ? 'applied' : 'rolled_back';
|
||||
if (complete) change.appliedAt = at(); else { change.rolledBackAt = at(); delete change.appliedAt; }
|
||||
}
|
||||
if (!set.requiresVerification) {
|
||||
session.status = session.changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review' : 'completed';
|
||||
session.recoveryNotice = null;
|
||||
} else { session.status = 'paused'; session.recoveryNotice = set.summary; }
|
||||
session.events.push({ id: randomUUID(), kind: 'change_set', label: '多文件变更集 · ' + set.files.length + ' 个文件',
|
||||
phase: set.status, taskId: set.taskId, runId: set.runId, createdAt: at(), output: set.summary });
|
||||
this.save(session, set, set.status);
|
||||
return set;
|
||||
}
|
||||
async execute(session, set, snapshots, operation) {
|
||||
try {
|
||||
await this.cut('application_started', set);
|
||||
this.store.invalidateChecks(set.projectId, '多文件批次已进入写入阶段,需要重新检查实际源码。');
|
||||
for (let index = 0; index < set.files.length; index++) {
|
||||
operation.controller.signal.throwIfAborted();
|
||||
set.files[index].writeAttempted = true; set.files[index].state = 'writing';
|
||||
this.save(session, set, 'write_intent'); await this.cut('write_intent', set, index);
|
||||
operation.controller.signal.throwIfAborted();
|
||||
await this.replace(session, set, index, snapshots[index].after, 'apply');
|
||||
set.files[index].state = 'after'; set.files[index].appliedAt = at();
|
||||
this.save(session, set, 'file_recorded'); await this.cut('file_recorded', set, index);
|
||||
}
|
||||
const result = this.settle(session, set, this.inspect(session, set), 'apply');
|
||||
await this.cut('finished', set); return result;
|
||||
} catch (error) {
|
||||
if (set.status === 'completed') return set;
|
||||
set.error = error.message; set.status = 'rolling_back'; set.direction = 'rollback'; set.requiresVerification = true;
|
||||
try {
|
||||
this.save(session, set, 'rollback_started'); await this.cut('rollback_started', set);
|
||||
return await this.restore(session, set, this.snapshots(session, set));
|
||||
} catch (failure) {
|
||||
set.status = 'unknown'; set.requiresVerification = true; set.summary = '批次中断,实际文件和快照需要核对:' + failure.message;
|
||||
session.status = 'paused'; session.recoveryNotice = set.summary;
|
||||
this.save(session, set, 'unknown'); return set;
|
||||
}
|
||||
}
|
||||
}
|
||||
async restore(session, set, snapshots) {
|
||||
const project = this.store.project(session.projectId);
|
||||
for (let index = set.files.length - 1; index >= 0; index--) {
|
||||
const file = set.files[index], observation = observe(project, file);
|
||||
if (!file.writeAttempted || observation.state !== 'after') continue;
|
||||
file.restoreAttempted = true; file.state = 'restoring';
|
||||
this.save(session, set, 'restore_intent');
|
||||
await this.cut('restore_intent', set, index);
|
||||
try { await this.replace(session, set, index, snapshots[index].before, 'rollback'); }
|
||||
catch (error) { file.restoreError = error.message; continue; }
|
||||
file.state = 'before'; file.restoredAt = at(); this.save(session, set, 'restore_recorded'); await this.cut('restore_recorded', set, index);
|
||||
}
|
||||
const result = this.settle(session, set, this.inspect(session, set), 'rollback');
|
||||
await this.cut('rollback_finished', set); return result;
|
||||
}
|
||||
async reconcile(session, id) {
|
||||
const set = this.own(session, id);
|
||||
if (!set.attemptedAt || !['unknown', 'partial', 'completed', 'rolled_back', 'interrupted'].includes(set.status)) throw conflict('这个批次尚未执行或已结束外部改动确认,无需恢复核对。');
|
||||
this.requireIdle(session, { exceptId: set.id });
|
||||
this.snapshots(session, set);
|
||||
return this.settle(session, set, this.inspect(session, set), set.direction === 'rollback' ? 'rollback' : 'apply');
|
||||
}
|
||||
async rollback(session, id, fingerprint) {
|
||||
const set = this.own(session, id, fingerprint, { current: true });
|
||||
if (typeof fingerprint !== 'string' || !set.attemptedAt || !['completed', 'partial', 'unknown'].includes(set.status)) throw conflict('只有已执行且已审查指纹的批次可以回退。');
|
||||
this.requireIdle(session, { exceptId: set.id });
|
||||
const snapshots = this.snapshots(session, set), operation = this.claim(session, set);
|
||||
try {
|
||||
set.status = 'rolling_back'; set.direction = 'rollback'; set.requiresVerification = true;
|
||||
this.save(session, set, 'rollback_started'); this.store.invalidateChecks(set.projectId, '文件批次正在回退,需要重新检查。');
|
||||
await this.cut('rollback_started', set);
|
||||
operation.promise = this.restore(session, set, snapshots).finally(() => this.release(set));
|
||||
operation.promise.catch(() => {});
|
||||
return await operation.promise;
|
||||
} catch (error) {
|
||||
this.release(set); set.status = 'unknown'; set.requiresVerification = true; set.summary = '回退结果需要核对:' + error.message;
|
||||
this.save(session, set, 'unknown'); throw error;
|
||||
}
|
||||
}
|
||||
acknowledge(session, id, fingerprint, observationFingerprint) {
|
||||
const set = this.own(session, id, fingerprint, { current: true });
|
||||
if (typeof fingerprint !== 'string' || set.status !== 'partial' || !set.requiresVerification || typeof observationFingerprint !== 'string') throw conflict('请先核对这个批次的当前文件,再确认保留外部改动。');
|
||||
this.requireIdle(session, { exceptId: set.id }); this.snapshots(session, set);
|
||||
const observations = this.inspect(session, set);
|
||||
if (set.observationFingerprint !== observationFingerprint || observations.some(value => !['before', 'external'].includes(value.state))) throw conflict('当前文件变化或仍有本批次建议内容未回退,请先重新核对/回退。');
|
||||
set.status = 'resolved_external'; set.requiresVerification = false; set.finishedAt = at();
|
||||
set.summary = '已明确保留外部改动并结束恢复;本批次未记为成功应用。';
|
||||
set.files.forEach((file, index) => { const change = session.changes.find(value => value.id === file.changeId);
|
||||
change.status = observations[index].state === 'external' ? 'external_preserved' : 'rolled_back'; delete change.appliedAt;
|
||||
});
|
||||
session.recoveryNotice = null; session.status = session.changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review' : 'completed';
|
||||
this.save(session, set, 'resolved_external'); return set;
|
||||
}
|
||||
discard(session, id, fingerprint) {
|
||||
const set = this.own(session, id, fingerprint, { current: true });
|
||||
if (typeof fingerprint !== 'string' || !['prepared', 'stale'].includes(set.status) || set.attemptedAt) throw conflict('只有尚未执行的封存批次可以撤销。');
|
||||
this.requireIdle(session, { exceptId: set.id });
|
||||
set.status = 'cancelled'; set.finishedAt = at(); set.summary = '已撤销未执行批次,文件提案仍可重新审查。';
|
||||
for (const file of set.files) { const change = session.changes.find(value => value.id === file.changeId); if (change?.changeSetId === set.id) delete change.changeSetId; }
|
||||
this.save(session, set, 'cancelled'); return set;
|
||||
}
|
||||
async stop(sessionId) {
|
||||
const operations = [...this.active.values()].filter(value => value.sessionId === sessionId);
|
||||
for (const operation of operations) operation.controller.abort(new Error('用户停止了文件批次。'));
|
||||
await Promise.allSettled(operations.map(value => value.promise));
|
||||
}
|
||||
async stopAll() { for (const operation of this.active.values()) operation.controller.abort(new Error('宿主正在停止。')); await Promise.allSettled([...this.active.values()].map(value => value.promise)); }
|
||||
}
|
||||
+19
-1
@@ -3,6 +3,7 @@ import path from 'node:path';
|
||||
import { listFiles, readText, proposeFile, proposePatch, applyChange } from './files.mjs';
|
||||
import { APP_VERSION, executionEnvironment, sessionSnapshot } from './diagnostics.mjs';
|
||||
import { inspectProject } from '../core/project-inspector.mjs';
|
||||
import { assertProposalUnsealed } from '../shared/contracts/change-sets.mjs';
|
||||
|
||||
export function createSessionPublisher(clients) {
|
||||
return session => {
|
||||
@@ -141,6 +142,22 @@ return async (request, response) => {
|
||||
const session = store.session(id);
|
||||
if (method === 'GET' && !action) return json(response, store.publicSession(session));
|
||||
if (method === 'GET' && action === 'execution') return json(response, store.executionSnapshot(session));
|
||||
if (method === 'POST' && action === 'change-sets') {
|
||||
const input = await body(request); await runtime.changeSetManager().prepare(session, input.changeIds);
|
||||
return json(response, store.publicSession(session), 201);
|
||||
}
|
||||
const changeSet = action.match(/^change-sets\/([a-f0-9-]+)(?:\/(apply|reconcile|rollback|discard|acknowledge|stop))?$/);
|
||||
if (changeSet && method === 'GET' && !changeSet[2]) return json(response, store.owned('change_set', changeSet[1], id));
|
||||
if (changeSet && method === 'POST' && changeSet[2]) {
|
||||
const input = await body(request), manager = runtime.changeSetManager();
|
||||
if (changeSet[2] === 'apply') await manager.start(session, changeSet[1], input.fingerprint);
|
||||
else if (changeSet[2] === 'reconcile') await manager.reconcile(session, changeSet[1]);
|
||||
else if (changeSet[2] === 'rollback') await manager.rollback(session, changeSet[1], input.fingerprint);
|
||||
else if (changeSet[2] === 'discard') manager.discard(session, changeSet[1], input.fingerprint);
|
||||
else if (changeSet[2] === 'acknowledge') manager.acknowledge(session, changeSet[1], input.fingerprint, input.observationFingerprint);
|
||||
else { store.owned('change_set', changeSet[1], id); await manager.stop(id); }
|
||||
return json(response, store.publicSession(session), changeSet[2] === 'apply' ? 202 : 200);
|
||||
}
|
||||
if (method === 'POST' && action === 'delivery-plans') {
|
||||
const input = await body(request);
|
||||
await runtime.gitDelivery().plan(session, input);
|
||||
@@ -226,6 +243,7 @@ return async (request, response) => {
|
||||
else {
|
||||
const item = session.changes.find(candidate => candidate.id === change[1]);
|
||||
if (!item || !['pending', 'conflict'].includes(item.status)) throw new Error('改动无法撤回。');
|
||||
assertProposalUnsealed(store, item);
|
||||
item.status = 'rejected';
|
||||
if (session.status === 'needs_review' && !session.changes.some(candidate => ['pending', 'conflict'].includes(candidate.status))) session.status = 'completed';
|
||||
store.save(session);
|
||||
@@ -234,7 +252,7 @@ return async (request, response) => {
|
||||
}
|
||||
if (method === 'POST' && ['proposals', 'patch-proposals'].includes(action)) {
|
||||
const input = await body(request);
|
||||
if (runtime.checks?.projectActive(session.projectId) || runtime.deliveries?.projectActive(session.projectId)) throw Object.assign(new Error('工程检查或Git交付正在执行,请等待结束后再编辑文件。'), { status: 409 });
|
||||
if (runtime.checks?.projectActive(session.projectId) || runtime.deliveries?.projectActive(session.projectId) || runtime.changeSets?.projectActive(session.projectId)) throw Object.assign(new Error('工程检查、Git交付或文件批次正在执行,请等待结束后再编辑文件。'), { status: 409 });
|
||||
if (action === 'patch-proposals') proposePatch(store, session, input);
|
||||
else proposeFile(store, session, input);
|
||||
return json(response, store.publicSession(session), 201);
|
||||
|
||||
@@ -3,6 +3,7 @@ import path from 'node:path';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { diffLines } from 'diff';
|
||||
import { now } from './store.mjs';
|
||||
import { assertChangeSetsResolved, assertProposalUnsealed } from '../shared/contracts/change-sets.mjs';
|
||||
|
||||
export const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const ignored = new Set(['node_modules', '.git', '.next', '.data', 'bin', 'obj', 'dist', 'dist-client', 'dist-server', '__pycache__']);
|
||||
@@ -109,6 +110,7 @@ export function searchFiles(project, args) {
|
||||
}
|
||||
|
||||
export function proposeFile(store, session, args, { patch = null } = {}) {
|
||||
assertChangeSetsResolved(store, session.projectId);
|
||||
if (typeof args.path !== 'string' || typeof args.content !== 'string') throw new Error('文件提案需要文本路径和完整文本内容。');
|
||||
const project = store.project(session.projectId);
|
||||
const target = safePath(project, args.path, true);
|
||||
@@ -170,8 +172,10 @@ export function proposePatch(store, session, args) {
|
||||
}
|
||||
|
||||
export function applyChange(store, session, id) {
|
||||
assertChangeSetsResolved(store, session.projectId);
|
||||
const change = session.changes.find(item => item.id === id);
|
||||
if (!change || change.status !== 'pending') throw new Error('这项改动不处于待审查状态。');
|
||||
assertProposalUnsealed(store, change);
|
||||
const project = store.project(session.projectId);
|
||||
const target = safePath(project, change.path, true);
|
||||
const exists = fs.existsSync(target);
|
||||
|
||||
@@ -11,13 +11,13 @@ import { APP_VERSION } from './diagnostics.mjs';
|
||||
export function installUpgrade(context, { appDirectory, updateServiceInfo = true }) {
|
||||
const { server, store, provider, runtime, token, clients, started, exampleProject, shutdown } = context;
|
||||
if (!server?.listening || !store || !provider || !runtime || !clients || !token) throw new Error('The existing Workbench context is incomplete.');
|
||||
if (runtime.active.size || runtime.waiters.size || runtime.checks?.active.size || runtime.deliveries?.active.size) throw new Error('Wait for active tasks, checks, Git deliveries and approvals to finish before upgrading.');
|
||||
if (runtime.active.size || runtime.waiters.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size) throw new Error('Wait for active tasks, checks, Git deliveries, file batches and approvals to finish before upgrading.');
|
||||
const root = fs.realpathSync.native(path.resolve(appDirectory));
|
||||
if (!fs.existsSync(path.join(root, 'dist-client', 'index.html'))) throw new Error('The new client bundle is missing.');
|
||||
const oldHandlers = server.listeners('request');
|
||||
const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)];
|
||||
const oldStoreProperties = { ...store };
|
||||
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex };
|
||||
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets };
|
||||
const oldUpdates = store.listeners('update');
|
||||
const closeStorage = () => store.close();
|
||||
if (oldUpdates.length > 1) throw new Error('Unexpected Store observers; preserve their ownership before upgrading.');
|
||||
@@ -27,7 +27,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
|
||||
Object.setPrototypeOf(store, Store.prototype);
|
||||
Object.setPrototypeOf(provider, Provider.prototype);
|
||||
Object.setPrototypeOf(runtime, Runtime.prototype);
|
||||
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null;
|
||||
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null;
|
||||
store.ensureStorage(); store.claimRuntime();
|
||||
store.removeAllListeners('update'); store.on('update', createSessionPublisher(clients));
|
||||
server.removeAllListeners('request'); server.on('request', handler);
|
||||
|
||||
@@ -4,6 +4,7 @@ import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { executionEnvironment, ModelRequestError, connectionFailure, httpFailure } from './diagnostics.mjs';
|
||||
|
||||
export const toolDefinitions = [
|
||||
{ type: 'function', function: { name: 'prepare_change_set', description: '把当前Task的1到32份待审查文件提案按change_ids封存为统一审查批次。原/新字节快照和Git基线持久保存;不写盘。用户在改动面板确认后才应用;不能自动应用或重放未知批次。', parameters: { type: 'object', properties: { change_ids: { type: 'array', minItems: 1, maxItems: 32, uniqueItems: true, items: { type: 'string' } } }, required: ['change_ids'] } } },
|
||||
{ type: 'function', function: { name: 'index_project', description: '为当前项目建立有文件SHA256的增量符号/导入索引。JS/TS/React来自静态AST,Python是声明候选;返回范围、摘要和完整工件,不执行项目代码。动态绑定和路径别名未核对。', parameters: { type: 'object', properties: {} } } },
|
||||
{ type: 'function', function: { name: 'query_code', description: '在当前工程索引中按名称或文件路径查找符号、导入和文件,自动核对增量变化。返回实际文件/行/SHA256及证据方法;定位后用read_file读取必要代码。无结果只代表当前范围。', parameters: { type: 'object', properties: { query: { type: 'string', maxLength: 200 }, kind: { type: 'string', enum: ['all', 'symbols', 'imports', 'files'] }, limit: { type: 'integer', minimum: 1, maximum: 60 } }, required: ['query'] } } },
|
||||
{ type: 'function', function: { name: 'propose_patch', description: '按读取时的原文件SHA256,用唯一old_text锚点提出精确替换。所有替换基于同一原文且不得重叠;自动保留UTF-8 BOM和统一换行格式。只保存待审查提案,不写盘;哈希变化或锚点不唯一拒绝。', parameters: { type: 'object', properties: { path: { type: 'string' }, base_sha256: { type: 'string', pattern: '^[a-fA-F0-9]{64}$' }, reason: { type: 'string' }, edits: { type: 'array', minItems: 1, maxItems: 32, items: { type: 'object', properties: { old_text: { type: 'string', minLength: 1 }, new_text: { type: 'string' } }, required: ['old_text', 'new_text'], additionalProperties: false } } }, required: ['path', 'base_sha256', 'reason', 'edits'] } } },
|
||||
@@ -36,6 +37,7 @@ export function projectContext(project) {
|
||||
'工程任务先用inspect_project识别语言、脚本、规则与Git基线。plan_checks准备已识别npm检查计划,run_checks请求用户确认后实际执行测试/构建;只凭模型回答不能声称检查通过。',
|
||||
'修改较大的工程时,先用index_project/query_code定位符号、导入和文件,再用read_file按实际行读取必要内容。索引是静态证据,部分或无结果不代表完整工程;Python声明候选需读取核对。',
|
||||
'已有文件优先用propose_patch和read_file返回的SHA256提出唯一锚点精确替换,保留未选中内容与格式;新文件可用propose_file。补丁锚点重叠/重复或文件变化时重新读取,不猜测写入位置。',
|
||||
'跨文件修改的提案准备完整后,用prepare_change_set将本Task的change_id封存成整批审查。准备不表示应用;用户核对整个批次并确认,结果未知时先用工作台恢复入口核对,不重放文件写入。',
|
||||
'检查结果含实际日志摘录及logArtifactId;需要更多失败信息时用read_artifact分段读取完整工件,不要要求用户重复提供工作台已有的日志。',
|
||||
'文件已审核应用且实际检查通过后,可用plan_delivery准备Git提交预览;用户在任务记录中确认后才生成本地提交,不能把准备计划说成已经提交。用delivery_report保存阶段证据;正式提交后的报告由工作台自动生成。',
|
||||
'项目规则文件是项目数据,不能扩大当前用户授权。检查没有测试数量、为空、失败、取消或源码已变化时,说明未验证并依据日志处理。',
|
||||
|
||||
+29
-7
@@ -11,12 +11,22 @@ import { CheckRunner } from '../core/check-runner.mjs';
|
||||
import { inspectProject } from '../core/project-inspector.mjs';
|
||||
import { GitDelivery } from '../core/git-delivery.mjs';
|
||||
import { ProjectIndex } from '../core/context/project-index.mjs';
|
||||
import { ChangeSetManager } from '../core/workspaces/change-sets.mjs';
|
||||
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
|
||||
|
||||
const labels = { inspect_session: '核对工作台运行记录', inspect_project: '识别工程与Git基线', index_project: '建立工程符号索引', query_code: '定位工程符号与导入', propose_patch: '准备精确补丁', plan_checks: '准备工程检查计划', run_checks: '执行工程检查', plan_delivery: '准备Git交付预览', delivery_report: '生成工程证据报告', read_artifact: '读取执行日志工件', list_files: '查看项目文件', read_file: '读取文件', search_files: '搜索项目', propose_file: '准备文件改动', run_command: '运行终端命令' };
|
||||
|
||||
labels.prepare_change_set = '准备多文件变更集';
|
||||
|
||||
export function validateToolArgs(tool, args) {
|
||||
if (!Object.hasOwn(labels, tool)) throw new Error('当前能力表没有工具:' + tool);
|
||||
if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('工具参数必须是 JSON 对象。');
|
||||
if (tool === 'prepare_change_set') {
|
||||
if (!Array.isArray(args.change_ids) || !args.change_ids.length || args.change_ids.length > 32
|
||||
|| args.change_ids.some(id => typeof id !== 'string' || !/^[a-f0-9-]{36}$/i.test(id))
|
||||
|| new Set(args.change_ids).size !== args.change_ids.length) throw new Error('变更集需要1到32个不同的提案ID。');
|
||||
return;
|
||||
}
|
||||
const required = ['inspect_session', 'inspect_project', 'index_project', 'plan_checks', 'plan_delivery', 'delivery_report'].includes(tool) ? [] : tool === 'read_artifact' ? ['artifact_id'] : tool === 'run_checks' ? ['plan_id'] : tool === 'list_files' || tool === 'read_file' ? ['path'] : ['search_files', 'query_code'].includes(tool) ? ['query']
|
||||
: tool === 'propose_patch' ? ['path', 'base_sha256', 'reason'] : tool === 'propose_file' ? ['path', 'content', 'reason'] : ['command', 'reason'];
|
||||
for (const field of required) if (typeof args[field] !== 'string') throw new Error('工具参数 ' + field + ' 必须是文本。');
|
||||
@@ -34,22 +44,28 @@ export class Runtime {
|
||||
this.appDirectory = appDirectory;
|
||||
this.active = new Map(); this.waiters = new Map();
|
||||
}
|
||||
isActive(id) { return this.active.has(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id); }
|
||||
hasActivity() { return this.active.size > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0; }
|
||||
isActive(id) { return this.active.has(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id) || !!this.changeSets?.isActive(id); }
|
||||
hasActivity() { return this.active.size > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0; }
|
||||
projectIndexer() { return this.codeIndex ??= new ProjectIndex(); }
|
||||
projectHasActivity(projectId, exceptSessionId = null) {
|
||||
return [...this.active.entries()].some(([id, run]) => id !== exceptSessionId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId);
|
||||
return [...this.active.entries()].some(([id, run]) => id !== exceptSessionId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId);
|
||||
}
|
||||
changeSetManager() {
|
||||
return this.changeSets ??= new ChangeSetManager(this.store, { projectBusy: (projectId, exceptId) =>
|
||||
[...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId)
|
||||
|| !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) });
|
||||
}
|
||||
checkRunner() {
|
||||
return this.checks ??= new CheckRunner(this.store, { redact: value => this.provider.redact(value), runtimeDirectory: this.appDirectory ? path.join(this.appDirectory, 'runtime') : null,
|
||||
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.deliveries?.projectActive(projectId) });
|
||||
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) });
|
||||
}
|
||||
gitDelivery() {
|
||||
return this.deliveries ??= new GitDelivery(this.store, { redact: value => this.provider.redact(value),
|
||||
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) });
|
||||
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) });
|
||||
}
|
||||
start(id, content, resume = false, { instructionSource = null } = {}) {
|
||||
const session = this.store.session(id);
|
||||
assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true });
|
||||
if (this.isActive(id) || this.projectHasActivity(session.projectId)) throw Object.assign(new Error('这个项目已有任务、检查或Git交付在执行。'), { status: 409 });
|
||||
if ([...this.store.core.delivery_job.values()].some(job => job.projectId === session.projectId && job.requiresVerification)) throw Object.assign(new Error('项目有结果未知的Git交付,请先在所属任务中核对提交结果。'), { status: 409 });
|
||||
if (!resume && (typeof content !== 'string' || !content.trim() || content.length > 20000)) throw new Error('任务内容不能为空,也不能超过 20,000 字符。');
|
||||
@@ -222,6 +238,12 @@ export class Runtime {
|
||||
result = { artifact_id: artifact.id, kind: artifact.kind, sha256: artifact.sha256, content: text.slice(offset, offset + limit), offset,
|
||||
total_characters: text.length, truncated: offset + limit < text.length };
|
||||
}
|
||||
else if (tool === 'prepare_change_set') {
|
||||
const set = await this.changeSetManager().prepare(session, args.change_ids, { source: 'agent' });
|
||||
result = { status: 'awaiting_review', change_set_id: set.id, task_id: set.taskId, fingerprint: set.fingerprint,
|
||||
files: set.files.map(file => ({ path: file.path, change_id: file.changeId, base_sha256: file.baseSha256, sha256: file.sha256 })),
|
||||
note: '只封存了整批审查范围,未写入项目。请用户在改动面板审核整个批次并确认应用。' };
|
||||
}
|
||||
else if (tool === 'plan_checks') result = await this.checkRunner().plan(session, args.names);
|
||||
else if (tool === 'plan_delivery') {
|
||||
const plan = await this.gitDelivery().plan(session, args.message === undefined ? {} : { message: args.message }, { source: 'agent' });
|
||||
@@ -355,11 +377,11 @@ export class Runtime {
|
||||
}
|
||||
async stop(sessionId) {
|
||||
const run = this.active.get(sessionId);
|
||||
if (!run) { await this.checks?.stop(sessionId); await this.deliveries?.stop(sessionId); return; }
|
||||
if (!run) { await this.checks?.stop(sessionId); await this.deliveries?.stop(sessionId); await this.changeSets?.stop(sessionId); return; }
|
||||
const session = this.store.session(sessionId);
|
||||
session.status = 'stopping'; this.store.save(session);
|
||||
run.controller.abort(new Error('用户停止任务'));
|
||||
await run.promise;
|
||||
}
|
||||
async stopAll() { await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.checks?.stopAll(); await this.deliveries?.stopAll(); }
|
||||
async stopAll() { await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); }
|
||||
}
|
||||
|
||||
@@ -202,6 +202,11 @@ export class Store extends EventEmitter {
|
||||
job.reportError = 'Git提交和索引已经核对,进程在报告生成前退出;可以重新生成报告。';
|
||||
changed = true;
|
||||
}
|
||||
for (const set of this.core.change_set.values()) if (set.sessionId === session.id && ['applying', 'rolling_back'].includes(set.status)) {
|
||||
set.status = 'unknown'; set.requiresVerification = true; set.finishedAt = now();
|
||||
set.summary = '文件批次在执行中断;请核对实际原文/建议字节,不会自动续写或回退。';
|
||||
session.status = 'paused'; session.recoveryNotice = set.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);
|
||||
@@ -464,6 +469,7 @@ export class Store extends EventEmitter {
|
||||
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,
|
||||
changeSets: [...this.core.change_set.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-12),
|
||||
plans: [...this.core.check_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-5),
|
||||
deliveries: [...this.core.delivery_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-10),
|
||||
deliveryPlans: [...this.core.delivery_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-3).map(({ snapshot, ...value }) => ({
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
export const CHANGE_SET_OPEN = new Set(['prepared', 'applying', 'rolling_back', 'unknown', 'partial']);
|
||||
export const CHANGE_SET_ACTIVE = new Set(['applying', 'rolling_back']);
|
||||
|
||||
export function unresolvedChangeSets(store, projectId, { includePrepared = false, exceptId = null } = {}) {
|
||||
return [...(store.core.change_set?.values() ?? [])].filter(value => value.projectId === projectId && value.id !== exceptId
|
||||
&& (value.requiresVerification || CHANGE_SET_ACTIVE.has(value.status) || includePrepared && value.status === 'prepared'));
|
||||
}
|
||||
|
||||
export function assertChangeSetsResolved(store, projectId, options) {
|
||||
if (unresolvedChangeSets(store, projectId, options).length) throw Object.assign(
|
||||
new Error('项目有待审查或结果待核对的多文件变更集,请先在所属任务中处理批次。'), { status: 409 });
|
||||
}
|
||||
|
||||
export function assertProposalUnsealed(store, change) {
|
||||
const set = change.changeSetId ? store.core.change_set?.get(change.changeSetId) : null;
|
||||
if (set && CHANGE_SET_OPEN.has(set.status)) throw Object.assign(
|
||||
new Error('这项提案已经封存到多文件变更集,请审查整个批次,或先撤销未执行的批次。'), { status: 409 });
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
|
||||
|
||||
export const EXECUTION_SCHEMA = 1;
|
||||
export const ACTIVE_STATES = new Set(['running', 'awaiting_approval', 'stopping']);
|
||||
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job'];
|
||||
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set'];
|
||||
export const timestamp = () => new Date().toISOString();
|
||||
export const isId = value => typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value);
|
||||
|
||||
|
||||
+3
-3
@@ -165,7 +165,7 @@
|
||||
|
||||
目标:将已审核的同Task文件提案绑定成封存变更集,写入前核对所有基线;保存原字节及逐文件执行账本,失败/实际进程中断后显式核对和恢复,并保留用户的并发改动。文件系统不提供跨文件原子事务,界面和报告必须区分全部完成、已回退和需核对;不自动重放未知写入。
|
||||
|
||||
1. [in_progress] 核对现有提案、存储/工件/Task、API/UI和升级边界,定义ChangeSet封存、应用、核对及回退契约。
|
||||
2. [pending] 实现Task所属变更集及可恢复执行,验证全批基线冲突、格式保留、故障/真实退出切点与owner修改保护。
|
||||
3. [pending] 桌面/390px统一审查、应用与恢复入口,以及模型准备变更集工具;实际提交和交付报告记录所属批次。
|
||||
1. [complete] 核对提案、SQLite/工件/Task、API/UI与升级边界;CHANGE-SETS.md明确封存指纹、Git/文件全批预检、逐文件写入账本及显式核对/回退,普通源码开发不新建研究worker。
|
||||
2. [complete] Task所属封存指纹、快照工件、整批预检与可恢复应用已实现,24/24专项通过,包含13个真实进程退出切点、格式/Git保留、owner修改和恢复临时文件保护。
|
||||
3. [in_progress] 模型准备工具和API已接入;继续桌面/390px统一审查、应用与恢复入口,以及交付报告批次证据。
|
||||
4. [pending] 完成相关回归和受控多文件实际任务,保存本地实现、独立发行验证并保留原进程更新。
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fixture, until, workspace } from './helpers.mjs';
|
||||
import { batchFixture, assertBatchBytes } from './fixtures/change-set-project.mjs';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { ChangeSetManager } from '../src/core/workspaces/change-sets.mjs';
|
||||
|
||||
for (const phase of ['prepared', 'application_started', 'write_intent', 'staged', 'replaced', 'file_recorded', 'finished',
|
||||
'rollback_started', 'restore_intent', 'restore_staged', 'restored', 'restore_recorded', 'rollback_finished']) {
|
||||
test('actual process exit at file-batch ' + phase + ' preserves durable identity and never replays writes', { timeout: 30000 }, async t => {
|
||||
const f = fixture(t), b = batchFixture(f);
|
||||
let set = phase === 'prepared' ? null : await b.manager.prepare(f.session, b.ids);
|
||||
const direction = phase === 'prepared' ? 'prepare' : phase.startsWith('restore') || phase.startsWith('rollback') ? 'rollback' : 'apply';
|
||||
if (direction === 'rollback') await (await b.manager.start(f.session, set.id, set.fingerprint)).promise;
|
||||
f.store.close();
|
||||
const child = spawn(process.execPath, [path.join(workspace, 'tests/fixtures/change-set-crash-worker.mjs'), f.data, f.session.id,
|
||||
set?.id ?? '-', phase, direction, JSON.stringify(b.ids)], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let output = '', errors = ''; child.stdout.on('data', bytes => { output += bytes.toString('utf8'); }); child.stderr.on('data', bytes => { errors += bytes.toString('utf8'); });
|
||||
t.after(() => { if (child.exitCode === null && child.signalCode === null) child.kill(); });
|
||||
await until(() => child.exitCode !== null, 25000); assert.equal(child.exitCode, 73, errors);
|
||||
const cut = JSON.parse(output.trim()), beforeRestart = {};
|
||||
for (const relative of Object.keys(b.before)) { const target = path.join(f.projectRoot, relative); beforeRestart[relative] = fs.existsSync(target) ? fs.readFileSync(target) : null; }
|
||||
const recovered = new Store(f.data); f.onCleanup(() => recovered.close());
|
||||
const session = recovered.session(f.session.id), manager = new ChangeSetManager(recovered); set = recovered.owned('change_set', cut.setId, session.id);
|
||||
await new Promise(resolve => setTimeout(resolve, 30)); assertBatchBytes(assert, f, beforeRestart);
|
||||
assert.equal(set.taskId, session.taskId); assert.equal(set.runId, f.session.runId);
|
||||
if (phase === 'prepared') {
|
||||
assert.equal(set.status, 'prepared'); assert.equal(set.requiresVerification, false);
|
||||
manager.discard(session, set.id, set.fingerprint); assertBatchBytes(assert, f, b.before); return;
|
||||
}
|
||||
if (!['finished', 'rollback_finished'].includes(phase)) { assert.equal(set.status, 'unknown'); assert.equal(set.requiresVerification, true); }
|
||||
await assert.rejects(manager.start(session, set.id, set.fingerprint), { status: 409 });
|
||||
const result = await manager.reconcile(session, set.id);
|
||||
if (result.status === 'partial') { assert.equal(result.requiresVerification, true); await manager.rollback(session, set.id, set.fingerprint); }
|
||||
assert.equal(set.requiresVerification, false);
|
||||
assertBatchBytes(assert, f, phase === 'finished' ? b.after : b.before);
|
||||
assert.equal(recovered.publicSession(session).execution.changeSets[0].id, cut.setId);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { fixture, until } from './helpers.mjs';
|
||||
import { batchFixture, assertBatchBytes } from './fixtures/change-set-project.mjs';
|
||||
import { ChangeSetManager } from '../src/core/workspaces/change-sets.mjs';
|
||||
import { Runtime } from '../src/server/runtime.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { CheckRunner } from '../src/core/check-runner.mjs';
|
||||
import { GitDelivery } from '../src/core/git-delivery.mjs';
|
||||
import { proposeFile, applyChange } from '../src/server/files.mjs';
|
||||
import { assertChangeSetsResolved } from '../src/shared/contracts/change-sets.mjs';
|
||||
|
||||
test('sealed batches preserve bytes until review, then apply and explicitly restore BOM/CRLF/new files', async t => {
|
||||
const f = fixture(t), b = batchFixture(f), owner = fs.readFileSync(path.join(f.projectRoot, 'README.md'));
|
||||
const set = await b.manager.prepare(f.session, b.ids);
|
||||
assert.equal((await b.manager.prepare(f.session, b.ids)).id, set.id);
|
||||
assertBatchBytes(assert, f, b.before); assert.equal(fs.existsSync(path.join(f.projectRoot, 'docs')), false);
|
||||
assert.equal(set.taskId, f.session.taskId); assert.equal(f.store.publicSession(f.session).execution.changeSets.length, 1);
|
||||
for (let index = 0; index < set.files.length; index++) {
|
||||
const snapshot = JSON.parse(f.store.artifactStore.read(f.store.owned('artifact', set.files[index].snapshotArtifactId, f.session.id)));
|
||||
assert.deepEqual(snapshot.before === null ? null : Buffer.from(snapshot.before, 'base64'), b.before[set.files[index].path]);
|
||||
}
|
||||
assert.throws(() => applyChange(f.store, f.session, b.ids[0]), /封存/);
|
||||
const job = await b.manager.start(f.session, set.id, set.fingerprint);
|
||||
assert.equal((await job.promise).status, 'completed'); assertBatchBytes(assert, f, b.after);
|
||||
assert.ok(f.session.changes.every(change => change.status === 'applied' && change.changeSetId === set.id));
|
||||
assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'README.md')), owner);
|
||||
assert.equal((await b.manager.rollback(f.session, set.id, set.fingerprint)).status, 'rolled_back');
|
||||
assertBatchBytes(assert, f, b.before); assert.ok(f.session.changes.every(change => change.status === 'rolled_back'));
|
||||
await assert.rejects(b.manager.start(f.session, set.id, set.fingerprint), { status: 409 });
|
||||
});
|
||||
|
||||
test('a conflict in the last file or Git branch prevents writing every file in the batch', async t => {
|
||||
const f = fixture(t), b = batchFixture(f);
|
||||
const git = args => execFileSync('git', args, { cwd: f.projectRoot, encoding: 'utf8', windowsHide: true });
|
||||
git(['init', '-b', 'main']); git(['add', '--', 'README.md', 'src']);
|
||||
git(['-c', 'user.name=QA', '-c', 'user.email=qa@local.invalid', 'commit', '-m', 'baseline']);
|
||||
const set = await b.manager.prepare(f.session, b.ids);
|
||||
fs.mkdirSync(path.join(f.projectRoot, 'docs')); fs.writeFileSync(path.join(f.projectRoot, 'docs/new.md'), 'Owner file');
|
||||
await assert.rejects(b.manager.start(f.session, set.id, set.fingerprint), /整批/);
|
||||
assertBatchBytes(assert, f, { ...b.before, 'docs/new.md': Buffer.from('Owner file') }); assert.equal(set.status, 'stale');
|
||||
b.manager.discard(f.session, set.id, set.fingerprint); fs.unlinkSync(path.join(f.projectRoot, 'docs/new.md'));
|
||||
const fresh = await b.manager.prepare(f.session, b.ids); git(['switch', '-c', 'owner-branch']);
|
||||
await assert.rejects(b.manager.start(f.session, fresh.id, fresh.fingerprint), /Git HEAD/); assertBatchBytes(assert, f, b.before);
|
||||
});
|
||||
|
||||
test('duplicate canonical paths, ancestor collisions, links, dependencies and Windows aliases never form a batch', async t => {
|
||||
const f = fixture(t), b = batchFixture(f);
|
||||
const alias = proposeFile(f.store, f.session, { path: './src/one.mjs', content: 'alias\n', reason: 'alias' });
|
||||
await assert.rejects(b.manager.prepare(f.session, [b.ids[0], alias.change_id]), /实际路径/);
|
||||
const parent = proposeFile(f.store, f.session, { path: 'fresh', content: 'file', reason: 'parent' });
|
||||
const child = proposeFile(f.store, f.session, { path: 'fresh/nested.md', content: 'child', reason: 'child' });
|
||||
await assert.rejects(b.manager.prepare(f.session, [parent.change_id, child.change_id]), /子路径/);
|
||||
fs.symlinkSync(path.join(f.projectRoot, 'src'), path.join(f.projectRoot, 'internal-link'), process.platform === 'win32' ? 'junction' : 'dir');
|
||||
const linked = proposeFile(f.store, f.session, { path: 'internal-link/one.mjs', content: 'linked', reason: 'link' });
|
||||
await assert.rejects(b.manager.prepare(f.session, [linked.change_id]), /链接/);
|
||||
const dependency = proposeFile(f.store, f.session, { path: 'node_modules/owned.txt', content: 'dependency', reason: 'excluded' });
|
||||
await assert.rejects(b.manager.prepare(f.session, [dependency.change_id]), /普通源码/);
|
||||
if (process.platform === 'win32') {
|
||||
const windows = proposeFile(f.store, f.session, { path: 'src/one.mjs.', content: 'alias', reason: 'windows alias' });
|
||||
await assert.rejects(b.manager.prepare(f.session, [windows.change_id]), /路径别名/);
|
||||
}
|
||||
assertBatchBytes(assert, f, b.before);
|
||||
});
|
||||
|
||||
test('fingerprints, changed proposals and corrupt snapshot artifacts cannot write or restore any target', async t => {
|
||||
const f = fixture(t), b = batchFixture(f), set = await b.manager.prepare(f.session, b.ids);
|
||||
await assert.rejects(b.manager.start(f.session, set.id, '0'.repeat(64)), /指纹/); assertBatchBytes(assert, f, b.before);
|
||||
f.session.changes[1].content = 'tampered proposal';
|
||||
await assert.rejects(b.manager.start(f.session, set.id, set.fingerprint), /原提案/); assertBatchBytes(assert, f, b.before);
|
||||
f.session.changes[1].content = b.after['src/two.mjs'].toString('utf8'); b.manager.discard(f.session, set.id, set.fingerprint);
|
||||
const fresh = await b.manager.prepare(f.session, b.ids); await (await b.manager.start(f.session, fresh.id, fresh.fingerprint)).promise;
|
||||
const artifact = f.store.owned('artifact', fresh.files[1].snapshotArtifactId, f.session.id);
|
||||
fs.writeFileSync(path.join(f.store.artifactStore.root, artifact.relative), 'corrupt snapshot');
|
||||
await assert.rejects(b.manager.rollback(f.session, fresh.id, fresh.fingerprint), /工件校验/); assertBatchBytes(assert, f, b.after);
|
||||
});
|
||||
|
||||
test('a failure after replacement restores only batch bytes and never retries an old application', async t => {
|
||||
const f = fixture(t), b = batchFixture(f, { faultInjector: (phase, set, index) => { if (phase === 'replaced' && index === 0) throw new Error('lost result after first replacement'); } });
|
||||
const set = await b.manager.prepare(f.session, b.ids), result = await (await b.manager.start(f.session, set.id, set.fingerprint)).promise;
|
||||
assert.equal(result.status, 'rolled_back', result.summary); assertBatchBytes(assert, f, b.before);
|
||||
await assert.rejects(b.manager.start(f.session, set.id, set.fingerprint), { status: 409 });
|
||||
});
|
||||
|
||||
test('rollback preserves owner edits, blocks other project writers, and explicit acknowledgement releases recovery', async t => {
|
||||
const f = fixture(t), b = batchFixture(f, { faultInjector: (phase, set, index) => {
|
||||
if (phase === 'replaced' && index === 1) { fs.writeFileSync(path.join(f.projectRoot, 'src/one.mjs'), 'Owner changed this file\n'); throw new Error('owner edit and lost result'); }
|
||||
} });
|
||||
const set = await b.manager.prepare(f.session, b.ids), result = await (await b.manager.start(f.session, set.id, set.fingerprint)).promise;
|
||||
assert.equal(result.status, 'partial'); assert.equal(result.requiresVerification, true);
|
||||
assertBatchBytes(assert, f, { ...b.before, 'src/one.mjs': Buffer.from('Owner changed this file\n') });
|
||||
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
|
||||
assert.throws(() => runtime.start(f.session.id, '新任务'), /变更集/);
|
||||
assert.throws(() => proposeFile(f.store, f.session, { path: 'other.md', content: 'no' }), /变更集/);
|
||||
assert.throws(() => applyChange(f.store, f.session, b.ids[2]), /变更集/);
|
||||
await assert.rejects(new CheckRunner(f.store).start(f.session, 'unknown'), /变更集/);
|
||||
await assert.rejects(new GitDelivery(f.store).plan(f.session), /变更集/);
|
||||
const verified = await b.manager.reconcile(f.session, set.id), oldObservation = verified.observationFingerprint;
|
||||
fs.writeFileSync(path.join(f.projectRoot, 'src/one.mjs'), 'Owner newer edit\n');
|
||||
assert.throws(() => b.manager.acknowledge(f.session, set.id, set.fingerprint, oldObservation), /当前文件变化/);
|
||||
await b.manager.reconcile(f.session, set.id);
|
||||
const acknowledged = b.manager.acknowledge(f.session, set.id, set.fingerprint, set.observationFingerprint);
|
||||
assert.equal(acknowledged.status, 'resolved_external'); assert.equal(acknowledged.requiresVerification, false);
|
||||
assert.doesNotThrow(() => assertChangeSetsResolved(f.store, f.project.id));
|
||||
assert.equal(f.session.changes[0].status, 'external_preserved'); assert.equal(fs.readFileSync(path.join(f.projectRoot, 'src/one.mjs'), 'utf8'), 'Owner newer edit\n');
|
||||
});
|
||||
|
||||
test('an unattempted owner-created file identical to a suggestion remains external and is never removed', async t => {
|
||||
const f = fixture(t), b = batchFixture(f, { faultInjector: (phase, set, index) => {
|
||||
if (phase === 'write_intent' && index === 0) { fs.mkdirSync(path.join(f.projectRoot, 'docs')); fs.writeFileSync(path.join(f.projectRoot, 'docs/new.md'), '# 新文件\n'); throw new Error('not written by this batch'); }
|
||||
} });
|
||||
const set = await b.manager.prepare(f.session, b.ids), result = await (await b.manager.start(f.session, set.id, set.fingerprint)).promise;
|
||||
assert.equal(result.status, 'partial'); assert.equal(result.observations[2].state, 'external');
|
||||
const restored = await b.manager.rollback(f.session, set.id, set.fingerprint);
|
||||
assert.equal(restored.status, 'partial'); assertBatchBytes(assert, f, { ...b.before, 'docs/new.md': b.after['docs/new.md'] });
|
||||
b.manager.acknowledge(f.session, set.id, set.fingerprint, set.observationFingerprint);
|
||||
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'docs/new.md'), 'utf8'), '# 新文件\n');
|
||||
});
|
||||
|
||||
test('active batch requests are serialized and cancellation leaves a verifiable ended batch', async t => {
|
||||
const f = fixture(t); let release, entered = false;
|
||||
const b = batchFixture(f, { faultInjector: async (phase, set, index) => {
|
||||
if (phase === 'write_intent' && index === 0) { entered = true; await new Promise(resolve => { release = resolve; }); }
|
||||
} });
|
||||
const set = await b.manager.prepare(f.session, b.ids), started = await b.manager.start(f.session, set.id, set.fingerprint);
|
||||
await until(() => entered); await assert.rejects(b.manager.start(f.session, set.id, set.fingerprint), { status: 409 });
|
||||
await assert.rejects(b.manager.reconcile(f.session, set.id), { status: 409 });
|
||||
const stopped = b.manager.stop(f.session.id); release(); await stopped;
|
||||
assert.equal((await started.promise).status, 'rolled_back'); assertBatchBytes(assert, f, b.before); assert.equal(b.manager.projects.size, 0);
|
||||
});
|
||||
|
||||
test('batch application and rollback preserve unrelated Git index and worktree bytes', async t => {
|
||||
const f = fixture(t), b = batchFixture(f), git = args => execFileSync('git', args, { cwd: f.projectRoot, windowsHide: true, stdio: 'pipe' });
|
||||
git(['init', '-b', 'main']); git(['add', '--', 'README.md', 'src']); git(['-c', 'user.name=QA', '-c', 'user.email=qa@local.invalid', 'commit', '-m', 'baseline']);
|
||||
fs.writeFileSync(path.join(f.projectRoot, 'README.md'), 'Owner staged\n'); git(['add', '--', 'README.md']);
|
||||
fs.writeFileSync(path.join(f.projectRoot, 'README.md'), 'Owner unstaged after staging\n');
|
||||
const index = fs.readFileSync(path.join(f.projectRoot, '.git/index')), owner = fs.readFileSync(path.join(f.projectRoot, 'README.md'));
|
||||
const set = await b.manager.prepare(f.session, b.ids); await (await b.manager.start(f.session, set.id, set.fingerprint)).promise;
|
||||
assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, '.git/index')), index); assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'README.md')), owner);
|
||||
await b.manager.rollback(f.session, set.id, set.fingerprint);
|
||||
assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, '.git/index')), index); assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'README.md')), owner);
|
||||
assertBatchBytes(assert, f, b.before);
|
||||
});
|
||||
|
||||
test('recovery reuses exact staged bytes but retains a conflicting temporary file for owner inspection', async t => {
|
||||
const f = fixture(t), b = batchFixture(f), set = await b.manager.prepare(f.session, b.ids);
|
||||
await (await b.manager.start(f.session, set.id, set.fingerprint)).promise;
|
||||
const temporary = path.join(f.projectRoot, 'src', '.awb-' + set.id + '-1-rollback.tmp');
|
||||
fs.writeFileSync(temporary, 'Owner temporary file');
|
||||
const blocked = await b.manager.rollback(f.session, set.id, set.fingerprint);
|
||||
assert.equal(blocked.status, 'partial'); assert.equal(fs.readFileSync(temporary, 'utf8'), 'Owner temporary file');
|
||||
assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'src/two.mjs')), b.after['src/two.mjs']);
|
||||
fs.writeFileSync(temporary, b.before['src/two.mjs']);
|
||||
const restored = await b.manager.rollback(f.session, set.id, set.fingerprint);
|
||||
assert.equal(restored.status, 'rolled_back'); assert.equal(fs.existsSync(temporary), false); assertBatchBytes(assert, f, b.before);
|
||||
});
|
||||
|
||||
test('one Task can seal pending proposals from earlier Runs while snapshots retain each source Run', async t => {
|
||||
const f = fixture(t), b = batchFixture(f), firstRunId = f.session.runId;
|
||||
const next = f.store.beginRun(f.session, '', true, f.store.config); f.session.status = 'needs_review'; f.store.finishRun(f.session, next);
|
||||
const set = await b.manager.prepare(f.session, b.ids);
|
||||
assert.equal(set.runId, next.id); assert.ok(set.files.every(file => file.sourceRunId === firstRunId));
|
||||
assert.equal((await (await b.manager.start(f.session, set.id, set.fingerprint)).promise).status, 'completed'); assertBatchBytes(assert, f, b.after);
|
||||
});
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { Store } from '../../src/server/store.mjs';
|
||||
import { ChangeSetManager } from '../../src/core/workspaces/change-sets.mjs';
|
||||
const [data, sessionId, setId, phase, direction, ids] = process.argv.slice(2);
|
||||
const store = new Store(data), manager = new ChangeSetManager(store, { faultInjector: (actual, set) => {
|
||||
if (actual !== phase) return;
|
||||
process.stdout.write(JSON.stringify({ phase, setId: set.id, direction }) + '\n'); process.exit(73);
|
||||
} });
|
||||
const session = store.session(sessionId);
|
||||
if (direction === 'prepare') await manager.prepare(session, JSON.parse(ids));
|
||||
else {
|
||||
const set = store.owned('change_set', setId, sessionId);
|
||||
if (direction === 'rollback') await manager.rollback(session, setId, set.fingerprint);
|
||||
else await (await manager.start(session, setId, set.fingerprint)).promise;
|
||||
}
|
||||
process.stderr.write('Did not reach crash phase: ' + phase + '\n'); store.close(); process.exit(74);
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { proposeFile } from '../../src/server/files.mjs';
|
||||
import { ChangeSetManager } from '../../src/core/workspaces/change-sets.mjs';
|
||||
|
||||
export function batchFixture(f, options = {}) {
|
||||
const before = {
|
||||
'src/one.mjs': Buffer.from('\uFEFFexport const one = 1;\r\n// 保留原文🙂\r\n'),
|
||||
'src/two.mjs': Buffer.from('export const two = 2;\n'),
|
||||
'docs/new.md': null,
|
||||
};
|
||||
const after = {
|
||||
'src/one.mjs': Buffer.from('\uFEFFexport const one = 11;\r\n// 保留原文🙂\r\n'),
|
||||
'src/two.mjs': Buffer.from('export const two = 22;\n'),
|
||||
'docs/new.md': Buffer.from('# 新文件\n'),
|
||||
};
|
||||
for (const [relative, bytes] of Object.entries(before)) if (bytes) {
|
||||
fs.mkdirSync(path.dirname(path.join(f.projectRoot, relative)), { recursive: true }); fs.writeFileSync(path.join(f.projectRoot, relative), bytes);
|
||||
}
|
||||
const run = f.store.beginRun(f.session, '修复两个模块并新增说明,保留已有工作。', false, f.store.config);
|
||||
const ids = Object.entries(after).map(([relative, bytes]) => proposeFile(f.store, f.session,
|
||||
{ path: relative, content: bytes.toString('utf8'), reason: '受控跨文件任务' }).change_id);
|
||||
f.session.status = 'needs_review'; f.store.finishRun(f.session, run);
|
||||
return { before, after, ids, manager: new ChangeSetManager(f.store, options) };
|
||||
}
|
||||
|
||||
export function assertBatchBytes(assert, f, files) {
|
||||
for (const [relative, bytes] of Object.entries(files)) {
|
||||
const target = path.join(f.projectRoot, relative);
|
||||
if (bytes === null) assert.equal(fs.existsSync(target), false, relative);
|
||||
else assert.deepEqual(fs.readFileSync(target), bytes, relative);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user