Files
Agent-Workbench/src/core/git-delivery.mjs
T

465 lines
36 KiB
JavaScript

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';
import { safePath } from '../server/files.mjs';
import { inspectProject } from './project-inspector.mjs';
import { gitArguments, gitEnvironment, runGit } from './git-process.mjs';
import { DeliveryReporter, verifiedCheck } from './delivery-report.mjs';
const at = () => new Date().toISOString();
const sha = value => createHash('sha256').update(value).digest('hex');
const conflict = message => Object.assign(new Error(message), { status: 409 });
const oid = value => /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(value);
const activeStates = new Set(['queued', 'preparing', 'prepared', 'publishing', 'committed', 'reporting']);
export const DELIVERY_ACTIVE_STATES = [...activeStates];
const normalize = value => process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);
const digestFile = file => fs.existsSync(file) && fs.lstatSync(file).isFile() && !fs.lstatSync(file).isSymbolicLink() ? sha(fs.readFileSync(file)) : null;
const pidAlive = pid => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
function entries(text) {
return text.split('\0').filter(Boolean).map(line => {
const match = line.match(/^([0-7]{6}) ([a-f0-9]{40}(?:[a-f0-9]{24})?) ([0-3])\t(.+)$/s);
if (!match) throw conflict('Git索引格式未被当前交付器支持。');
return { mode: match[1], blob: match[2], stage: Number(match[3]), path: match[4], line };
});
}
function protectedIndex(stageText, flagText, paths) {
const chosen = new Set(paths);
return sha(JSON.stringify({
entries: entries(stageText).filter(item => !chosen.has(item.path)).map(item => item.line).sort(),
flags: flagText.split('\0').filter(line => line && !chosen.has(line.slice(2))).sort(),
}));
}
function validMessage(value) {
if (typeof value !== 'string' || !value.trim() || value.length > 1600 || value.includes('\0')
|| /^Workbench-(?:Delivery|Task|Session):/im.test(value)) throw new Error('提交说明需要1到1600个字符,不能包含工作台保留的trailer。');
return value.replaceAll('\r\n', '\n').trim();
}
function validAuthor(name, email) {
if (typeof name !== 'string' || !name.trim() || name.length > 120 || /[<>\r\n\0]/.test(name)
|| typeof email !== 'string' || email.length > 180 || !/^[^\s<>@\0]+@[^\s<>@\0]+$/.test(email)) throw new Error('Git署名需要有效的姓名和邮箱。');
return { name: name.trim(), email: email.trim() };
}
export class GitDelivery {
constructor(store, { redact = String, projectBusy = () => false, faultInjector = null } = {}) {
this.store = store; this.redact = redact; this.projectBusy = projectBusy; this.faultInjector = faultInjector;
this.active = new Map(); this.projects = new Map();
this.directory = path.join(store.directory, 'delivery');
this.hooksDirectory = path.join(this.directory, 'empty-hooks');
fs.mkdirSync(this.hooksDirectory, { recursive: true });
if (fs.lstatSync(this.directory).isSymbolicLink() || fs.lstatSync(this.hooksDirectory).isSymbolicLink()
|| fs.readdirSync(this.hooksDirectory).length) throw new Error('工作台Git执行目录需要普通空hooks目录。');
this.reporter = new DeliveryReporter(store, { redact });
}
isActive(sessionId) { return [...this.active.values()].some(value => value.sessionId === sessionId); }
projectActive(projectId) { return this.projects.has(projectId); }
git(project, args, options = {}) { return runGit(safePath(project), args, { hooksDirectory: this.hooksDirectory, ...options }); }
async needGit(project, args, options) {
let result;
try { result = await this.git(project, args, options); }
catch (error) {
if (error.code === 'ENOENT') throw conflict('本机未发现Git。请安装Git for Windows并重新打开工作台,再准备本地提交。');
throw error;
}
if (!result.ok) throw Object.assign(new Error(this.redact(result.error.trim() || 'Git操作未完成。')), { status: result.aborted ? 409 : 400, gitResult: result });
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归属不一致。');
if (session.changes.some(change => ['pending', 'conflict'].includes(change.status))) throw conflict('先应用或撤回待审查改动,再准备提交。');
if ([...this.store.core.tool.values()].some(value => value.taskId === task.id && value.requiresVerification)) throw conflict('先核对本任务结果未知的工具,再准备提交。');
if ([...this.store.core.delivery_job.values()].some(value => value.projectId === session.projectId && (value.requiresVerification || value.status === 'unknown'))) throw conflict('这个项目有结果未知的提交,先核对该结果;不会重放提交。');
return { task, run };
}
assertIdle(session, { exceptSessionId = null } = {}) {
if (this.projectActive(session.projectId) || this.projectBusy(session.projectId, exceptSessionId)) throw conflict('项目正在执行任务、检查或Git交付,请等待结束。');
}
async snapshot(project, { allowOwnLock = false } = {}) {
const root = safePath(project);
let top;
try { top = await this.needGit(project, ['rev-parse', '--show-toplevel']); }
catch (error) {
if (/not a git repository/i.test(error.message)) throw conflict('这个工程尚未启用独立Git,请先在工程目录建立Git基线,再准备交付。');
throw error;
}
if (normalize(top.text.trim()) !== normalize(root)) throw conflict('当前项目需要独立Git仓库,上级仓库不能作为交付基线。');
const configNames = ['core.autocrlf', 'core.eol', 'core.filemode', 'core.sparsecheckout', 'extensions.refstorage', 'user.name', 'user.email'];
const [head, ref, gitDirectory, index, stage, flags, inventory, ...configs] = await Promise.all([
this.needGit(project, ['rev-parse', '--verify', 'HEAD']),
this.git(project, ['symbolic-ref', '--quiet', 'HEAD']),
this.needGit(project, ['rev-parse', '--absolute-git-dir']),
this.needGit(project, ['rev-parse', '--path-format=absolute', '--git-path', 'index']),
this.needGit(project, ['ls-files', '--stage', '-z']),
this.needGit(project, ['ls-files', '-v', '-z']),
this.needGit(project, ['ls-files', '--cached', '--others', '--exclude-standard', '-z']),
...configNames.map(name => this.git(project, ['config', '--get', name])),
]);
const headId = head.text.trim(), reference = ref.text.trim();
if (!oid(headId) || !ref.ok || !/^refs\/heads\/[^\s\0]+$/.test(reference)) throw conflict('当前交付切片需要已有提交的命名分支;请先用Git建立基线分支。');
const gitDir = fs.realpathSync.native(gitDirectory.text.trim()), indexPath = path.resolve(index.text.trim());
if (normalize(path.dirname(indexPath)) !== normalize(gitDir) || !fs.existsSync(indexPath) || fs.lstatSync(indexPath).isSymbolicLink()
|| fs.statSync(indexPath).size > 16 * 1024 * 1024) throw conflict('当前Git索引位置、类型或大小未被交付器支持。');
for (const name of ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'REBASE_HEAD', 'rebase-apply', 'rebase-merge', 'sequencer', 'BISECT_START']) {
if (fs.existsSync(path.join(gitDir, name))) throw conflict('Git正在合并、变基或定位问题;先完成该操作再交付。');
}
if (!allowOwnLock && fs.existsSync(indexPath + '.lock')) throw conflict('Git索引正在被其他操作锁定,请先核对该操作。');
const paths = [...new Set(inventory.text.split('\0').filter(Boolean))];
if (paths.length > 1000) throw conflict('工程超过当前1000文件快照上限,请缩小工程范围后交付。');
const attributes = await this.needGit(project, ['check-attr', '-z', 'filter', 'working-tree-encoding', '--stdin'], { input: paths.join('\0') + (paths.length ? '\0' : '') });
const attributeParts = attributes.text.split('\0').filter(Boolean);
for (let i = 0; i < attributeParts.length; i += 3) if (!['unspecified', 'unset'].includes(attributeParts[i + 2])) {
throw conflict('工程使用自定义Git内容过滤或工作树编码,当前交付器不执行这些转换:' + attributeParts[i]);
}
const config = Object.fromEntries(configNames.map((name, i) => [name, configs[i].ok ? configs[i].text.trim() : null]));
if (config['core.sparsecheckout'] === 'true') throw conflict('当前交付器不支持稀疏检出工程。');
const indexSha256 = digestFile(indexPath);
const digest = sha(JSON.stringify({ root, head: headId, reference, gitDir, indexPath, indexSha256,
stage: stage.text, flags: flags.text, config, attributes: attributes.text }));
return { head: headId, reference, branch: reference.slice(11), gitDir, indexPath, indexSha256,
stage: stage.text, flags: flags.text, config, attributesSha256: sha(attributes.text), digest };
}
async blob(project, relative, bytes, { write = false, signal } = {}) {
const result = await this.needGit(project, ['hash-object', ...(write ? ['-w'] : []), '--path=' + relative, '--stdin'], { input: bytes, signal });
const id = result.text.trim(); if (!oid(id)) throw new Error('Git没有返回有效的文件blob身份。'); return id;
}
baseBytes(session, change) {
const backup = path.join(this.store.directory, 'backups', session.id, change.id + '.txt');
const bytes = fs.existsSync(backup) ? fs.readFileSync(backup) : Buffer.from(change.baseContent, 'utf8');
if (sha(bytes) !== change.baseSha256) throw conflict('原始文件字节备份与提案基线不一致:' + change.path);
return bytes;
}
async selectedFiles(session, project, snapshot) {
const selected = new Map();
for (const change of session.changes.filter(value => value.taskId === session.taskId && value.status === 'applied')) {
const target = safePath(project, change.path);
let ancestor = project.root;
for (const segment of change.path.replaceAll('\\', '/').split('/').filter(Boolean)) {
ancestor = path.join(ancestor, segment);
if (fs.lstatSync(ancestor).isSymbolicLink()) throw conflict('交付路径经过链接,需要使用实际普通文件路径重新审查:' + change.path);
}
if (!fs.lstatSync(target).isFile() || fs.lstatSync(target).isSymbolicLink()) throw conflict('交付路径需要普通文件:' + change.path);
const relative = path.relative(project.root, fs.realpathSync.native(target)).replaceAll('\\', '/');
if (/[\r\n\t\0]/.test(relative)) throw conflict('交付文件名不能包含换行或控制分隔符。');
if (!selected.has(relative)) selected.set(relative, []);
selected.get(relative).push(change);
}
if (!selected.size || selected.size > 32) throw conflict('当前任务需要1到32个已应用且归属明确的文件;旧版未记录Task归属的提案需要重新审查。');
const stageEntries = entries(snapshot.stage), result = [];
for (const [relative, chain] of selected) {
const latest = chain.at(-1), bytes = fs.readFileSync(safePath(project, relative));
if (sha(bytes) !== latest.sha256) throw conflict('文件在应用后已经变化,需要重新审查:' + relative);
for (let i = 1; i < chain.length; i++) if (chain[i].baseSha256 !== chain[i - 1].sha256 || !chain[i].baseExists) throw conflict('连续提案中混入其他修改,需要单独核对:' + relative);
const headRecord = (await this.needGit(project, ['ls-tree', '-z', snapshot.head, '--', relative])).text.split('\0').filter(Boolean);
if (headRecord.length > 1) throw conflict('交付路径没有唯一Git文件身份:' + relative);
const match = headRecord[0]?.match(/^([0-7]{6}) blob ([a-f0-9]{40}(?:[a-f0-9]{24})?)\t(.+)$/s);
if (headRecord.length && (!match || !['100644', '100755'].includes(match[1]) || match[3] !== relative)) throw conflict('链接、子模块或特殊文件不能直接交付:' + relative);
const mode = match?.[1] ?? '100644', beforeBlob = match?.[2] ?? null;
const indexed = stageEntries.filter(item => item.path === relative);
if (indexed.length && (indexed.length !== 1 || indexed[0].stage !== 0 || indexed[0].mode !== mode || indexed[0].blob !== beforeBlob)) throw conflict('选中文件已有暂存修改或冲突,提交会混入其他工作:' + relative);
const flag = snapshot.flags.split('\0').find(line => line.slice(2) === relative);
if (flag && flag[0] !== 'H') throw conflict('选中文件具有特殊Git索引标记,请先核对:' + relative);
const afterBlob = await this.blob(project, relative, bytes);
if (afterBlob === beforeBlob) continue;
let baseIndex = -1;
if (beforeBlob) {
for (let i = 0; i < chain.length; i++) {
if (chain[i].baseExists && await this.blob(project, relative, this.baseBytes(session, chain[i])) === beforeBlob) { baseIndex = i; break; }
}
if (baseIndex < 0) throw conflict('选中文件在本任务之前已有其他工作区修改,需要单独审查:' + relative);
} else if (chain[0].baseExists) throw conflict('这个未跟踪文件在任务之前已经存在,不能混入本任务提交:' + relative);
else baseIndex = 0;
const base = chain[baseIndex];
const diff = createTwoFilesPatch('a/' + relative, 'b/' + relative, base.baseContent, latest.content, '', '', { context: 3 });
const parts = diffLines(base.baseContent, latest.content);
result.push({ path: relative, changeIds: chain.slice(baseIndex).map(value => value.id), mode, beforeBlob, afterBlob,
baseSha256: base.baseSha256, sha256: latest.sha256, reason: latest.reason,
additions: parts.filter(part => part.added).reduce((sum, part) => sum + part.count, 0),
deletions: parts.filter(part => part.removed).reduce((sum, part) => sum + part.count, 0), diff: this.redact(diff) });
}
if (!result.length) throw conflict('当前任务的文件内容已在Git HEAD中,没有新的交付改动。');
if (Buffer.byteLength(result.map(file => file.diff).join('\n'), 'utf8') > 1024 * 1024) throw conflict('提交差异超过1MB预览上限,请缩小本次任务。');
return result.sort((a, b) => a.path.localeCompare(b.path));
}
async plan(session, options = {}, { source = 'user' } = {}) {
const idleOptions = { exceptSessionId: source === 'agent' ? session.id : null };
this.assertIdle(session, idleOptions); const { task, run } = this.assertTask(session);
const identity = { taskId: task.id, runId: run.id }, project = this.store.project(session.projectId);
const snapshot = await this.snapshot(project), inspection = await inspectProject(project);
const check = verifiedCheck(this.store, session, inspection);
if (!check) {
const previous = this.store.core.check_job.get(task.verification.checkJobId);
if (previous?.status === 'passed' && task.verification.status === 'passed') {
previous.stale = true; previous.staleReason = 'Git交付核对发现源码或检查日志证据失效。';
task.verification = { ...task.verification, status: 'stale', reason: previous.staleReason };
this.store.save(session, { type: 'check.evidence_stale', detail: { jobId: previous.id } });
}
throw conflict('提交需要与当前源码一致、日志完整且测试数量明确的通过记录;请先执行工程检查。');
}
if (!check.sourceFingerprint) {
check.sourceFingerprint = inspection.sourceFingerprint;
task.verification = { ...task.verification, sourceFingerprint: inspection.sourceFingerprint };
}
const files = await this.selectedFiles(session, project, snapshot);
const name = options.authorName ?? snapshot.config['user.name'] ?? 'Agent Workbench';
const email = options.authorEmail ?? snapshot.config['user.email'] ?? 'local@agent-workbench.invalid';
const author = { ...validAuthor(name, email), source: options.authorName || options.authorEmail ? 'explicit' : snapshot.config['user.name'] && snapshot.config['user.email'] ? 'git-config' : 'workbench-local' };
const message = validMessage(options.message ?? '完成:' + task.goal.replace(/\s+/g, ' ').slice(0, 90));
const second = await this.snapshot(project);
if (snapshot.digest !== second.digest || identity.taskId !== session.taskId || identity.runId !== session.runId) throw conflict('准备提交期间工程或任务已变化,请重新预览。');
this.assertIdle(session, idleOptions); this.assertTask(session);
const diffArtifact = this.store.artifactStore.write(session, run, files.map(file => file.diff).join('\n'), { kind: 'delivery-diff', mediaType: 'text/plain' });
this.store.core.artifact.set(diffArtifact.id, diffArtifact);
const plan = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id, status: 'planned', createdAt: at(),
message, author, files, paths: files.map(file => file.path), snapshot, preparedBy: source, fingerprint: inspection.fingerprint, sourceFingerprint: inspection.sourceFingerprint,
checkJobId: check.id, checkSummary: check.results.map(value => ({ name: value.name, command: value.command, exitCode: value.exitCode, tests: value.tests, logArtifactId: value.logArtifactId })),
protectedIndexSha256: protectedIndex(snapshot.stage, snapshot.flags, files.map(file => file.path)), diffArtifactId: diffArtifact.id,
policy: { name: 'local-reviewed-snapshot', hooks: 'disabled', signing: 'unsigned', remote: 'none',
note: '工作台生成本地普通提交,保留其他暂存与工作区改动;本次不执行仓库hooks和GPG签名。' } };
return this.store.putRecord('delivery_plan', session, plan, 'delivery.plan');
}
async start(session, planId) {
this.assertIdle(session); this.assertTask(session);
const plan = this.store.owned('delivery_plan', planId, session.id);
if (plan.taskId !== session.taskId || plan.runId !== session.runId || plan.status !== 'planned') throw conflict('提交计划已使用或不属于当前Task/Run,请重新预览。');
const controller = new AbortController();
const job = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: plan.taskId, runId: plan.runId, planId: plan.id,
status: 'queued', startedAt: at(), finishedAt: null, parent: plan.snapshot.head, branch: plan.snapshot.branch, paths: plan.paths,
sourceFingerprint: plan.sourceFingerprint, checkJobId: plan.checkJobId, message: plan.message, author: plan.author,
expectedCommit: null, commit: null, requiresVerification: false, originalSessionStatus: session.status, ownerPid: process.pid };
const active = { controller, sessionId: session.id, projectId: session.projectId, promise: null };
this.active.set(job.id, active); this.projects.set(session.projectId, job.id);
try {
plan.status = 'accepted'; plan.jobId = job.id;
this.store.putRecord('delivery_job', session, job, 'delivery.queued');
active.promise = this.execute(session, plan, job, controller.signal).finally(() => { this.active.delete(job.id); this.projects.delete(session.projectId); });
active.promise.catch(() => {});
return { job, promise: active.promise };
} catch (error) { this.active.delete(job.id); this.projects.delete(session.projectId); throw error; }
}
async checkpoint(session, job, phase) {
this.store.save(session, { type: 'delivery.' + phase, detail: { jobId: job.id, status: job.status } });
await this.faultInjector?.(phase, job);
}
async execute(session, plan, job, signal) {
const project = this.store.project(session.projectId);
let lockOwned = false, keepLock = false;
try {
await this.faultInjector?.('queued', job);
const snapshot = await this.snapshot(project), inspection = await inspectProject(project);
signal.throwIfAborted();
if (session.taskId !== plan.taskId || session.runId !== plan.runId || snapshot.digest !== plan.snapshot.digest || inspection.fingerprint !== plan.fingerprint) throw conflict('提交预览后工程、Git索引或Task/Run已变化,没有执行提交。');
if (!verifiedCheck(this.store, session, inspection)) throw conflict('提交前检查证据已失效,请重新运行工程检查。');
const selected = await this.selectedFiles(session, project, snapshot);
if (JSON.stringify(selected) !== JSON.stringify(plan.files)) throw conflict('当前文件与已审核提交清单不一致。');
signal.throwIfAborted();
job.status = 'preparing'; session.status = 'running';
job.indexPath = snapshot.indexPath; job.indexBeforeSha256 = snapshot.indexSha256;
job.lockPath = snapshot.indexPath + '.lock'; job.lockMarkerSha256 = sha('Agent Workbench index lock ' + job.id + '\n');
await this.checkpoint(session, job, 'preparing');
fs.writeFileSync(job.lockPath, 'Agent Workbench index lock ' + job.id + '\n', { flag: 'wx', mode: 0o600 }); lockOwned = true;
await this.checkpoint(session, job, 'index_locked');
if (digestFile(job.indexPath) !== snapshot.indexSha256) throw conflict('锁定索引前Git暂存区已经变化。');
const directory = path.join(this.directory, job.id); fs.mkdirSync(directory);
const deliveryIndex = path.join(directory, 'commit.index'), nextIndex = path.join(directory, 'next.index');
fs.copyFileSync(job.indexPath, nextIndex);
await this.needGit(project, ['read-tree', snapshot.head], { env: { GIT_INDEX_FILE: deliveryIndex }, signal });
for (const file of plan.files) {
const bytes = fs.readFileSync(safePath(project, file.path));
if (sha(bytes) !== file.sha256 || await this.blob(project, file.path, bytes, { write: true, signal }) !== file.afterBlob) throw conflict('准备提交对象时文件内容变化:' + file.path);
}
const indexInfo = plan.files.map(file => file.mode + ' ' + file.afterBlob + '\t' + file.path + '\0').join('');
for (const indexFile of [deliveryIndex, nextIndex]) await this.needGit(project, ['update-index', '-z', '--index-info'], { input: indexInfo, env: { GIT_INDEX_FILE: indexFile }, signal });
const nextBytes = fs.readFileSync(nextIndex); job.indexAfterSha256 = sha(nextBytes);
fs.writeFileSync(job.lockPath, nextBytes);
const handle = fs.openSync(job.lockPath, 'r+'); try { fs.fsyncSync(handle); } finally { fs.closeSync(handle); }
job.tree = (await this.needGit(project, ['write-tree'], { env: { GIT_INDEX_FILE: deliveryIndex }, signal })).text.trim();
if (!oid(job.tree)) throw new Error('Git交付树没有有效身份。');
const message = plan.message + '\n\nWorkbench-Delivery: ' + job.id + '\nWorkbench-Task: ' + job.taskId + '\nWorkbench-Session: ' + job.sessionId + '\n';
const date = at();
job.expectedCommit = (await this.needGit(project, ['commit-tree', job.tree, '-p', snapshot.head], { input: message, signal,
env: { GIT_AUTHOR_NAME: plan.author.name, GIT_AUTHOR_EMAIL: plan.author.email, GIT_COMMITTER_NAME: plan.author.name,
GIT_COMMITTER_EMAIL: plan.author.email, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date } })).text.trim();
if (!oid(job.expectedCommit)) throw new Error('Git提交对象没有有效身份。');
job.status = 'prepared'; await this.checkpoint(session, job, 'prepared');
signal.throwIfAborted();
await this.publishReference(project, session, plan, job, signal);
job.status = 'committed'; job.commit = job.expectedCommit; await this.checkpoint(session, job, 'committed');
await this.finishPublished(project, session, plan, job);
lockOwned = false; job.status = 'reporting'; job.requiresVerification = false;
job.summary = '已生成并核对本地提交;任务文件、实际检查和其他工作区/暂存改动均已保留。';
} catch (error) {
keepLock = !!job.referenceAttempted;
job.status = keepLock ? 'unknown' : signal.aborted ? 'cancelled' : error.status === 409 ? 'stale' : 'failed';
job.requiresVerification = keepLock;
job.summary = this.redact(keepLock ? 'Git引用可能已更新,需要核对实际结果;不会再次提交。' + ' ' + error.message : error.message);
} finally {
if (lockOwned && !keepLock) this.releaseOwnedLock(job);
job.stopRequested = signal.aborted; job.finishedAt = at(); session.status = job.originalSessionStatus;
await this.checkpoint(session, job, 'finished');
}
if (job.status === 'reporting') {
try {
const inspection = await inspectProject(project);
job.status = 'completed';
await this.reporter.create(session, { job, inspection });
} catch (error) {
job.status = 'completed'; job.reportError = this.redact(error.message);
this.store.save(session, { type: 'delivery.report_failed', detail: { jobId: job.id } });
}
}
return job;
}
async publishReference(project, session, plan, job, signal) {
const child = spawn('git', gitArguments(safePath(project), ['update-ref', '-m', 'Agent Workbench delivery ' + job.id, '--stdin'], this.hooksDirectory),
{ env: gitEnvironment(), windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
job.refProcessPid = child.pid ?? null;
let output = '', errors = '', commitSent = false, preparedResolve;
const prepared = new Promise(resolve => { preparedResolve = resolve; });
child.stdin.on('error', () => {});
child.stdout.on('data', bytes => { output += bytes.toString('utf8'); if (output.includes('prepare: ok')) preparedResolve(true); });
child.stderr.on('data', bytes => { errors = (errors + bytes.toString('utf8')).slice(-8000); });
const done = new Promise((resolve, reject) => { child.once('error', reject); child.once('close', code => resolve(code)); });
done.catch(() => {});
const timer = setTimeout(() => child.kill(), 15000);
const stop = () => { if (!commitSent && !child.stdin.writableEnded) child.stdin.end('abort\n'); };
signal.addEventListener('abort', stop, { once: true });
try {
await this.checkpoint(session, job, 'ref_started');
child.stdin.write('start\nupdate HEAD ' + job.expectedCommit + ' ' + plan.snapshot.head + '\nprepare\n');
const ready = await Promise.race([prepared, done.then(() => false)]);
if (!ready) throw conflict(errors.trim() || 'Git没有锁定原HEAD,未发布提交。');
const actualRef = (await this.needGit(project, ['symbolic-ref', '--quiet', 'HEAD'])).text.trim();
if (actualRef !== plan.snapshot.reference || digestFile(job.indexPath) !== job.indexBeforeSha256) throw conflict('Git锁定后当前分支或索引与提交计划不同,未发布提交。');
const inspection = await inspectProject(project);
if (inspection.sourceFingerprint !== plan.sourceFingerprint || !verifiedCheck(this.store, session, inspection)) throw conflict('Git锁定后源码或实际检查已经变化,未发布提交。');
await this.checkpoint(session, job, 'ref_prepared');
signal.throwIfAborted();
job.status = 'publishing'; job.referenceAttempted = true;
await this.checkpoint(session, job, 'publishing');
commitSent = true; child.stdin.end('commit\n');
const code = await done;
if (code !== 0 || !output.includes('commit: ok')) throw new Error(this.redact(errors.trim() || 'Git发布未返回确认结果。'));
} finally {
if (!commitSent && !child.stdin.writableEnded) child.stdin.end('abort\n');
await done.catch(() => {});
job.refProcessPid = null;
clearTimeout(timer); signal.removeEventListener('abort', stop);
}
}
async verifyPublished(project, plan, job) {
if (!oid(job.expectedCommit ?? '') || !oid(job.tree ?? '')) throw conflict('提交缺少持久对象身份,不能猜测或重放。');
const [head, ref, tree, parents, commit, changed] = await Promise.all([
this.needGit(project, ['rev-parse', 'HEAD']), this.git(project, ['symbolic-ref', '--quiet', 'HEAD']),
this.needGit(project, ['rev-parse', job.expectedCommit + '^{tree}']),
this.needGit(project, ['rev-list', '--parents', '-n', '1', job.expectedCommit]),
this.needGit(project, ['cat-file', 'commit', job.expectedCommit]),
this.needGit(project, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', plan.snapshot.head, job.expectedCommit]),
]);
if (head.text.trim() !== job.expectedCommit || ref.text.trim() !== plan.snapshot.reference) throw conflict('当前HEAD或分支与本次预期提交不同,需要人工核对引用变化。');
if (tree.text.trim() !== job.tree || parents.text.trim() !== job.expectedCommit + ' ' + plan.snapshot.head
|| !commit.text.endsWith('Workbench-Delivery: ' + job.id + '\nWorkbench-Task: ' + job.taskId + '\nWorkbench-Session: ' + job.sessionId + '\n')) throw conflict('实际提交对象、父节点或任务身份与本次计划不同。');
if (JSON.stringify(changed.text.split('\0').filter(Boolean).sort()) !== JSON.stringify(plan.paths.slice().sort())) throw conflict('实际Git提交路径超出本次审核范围。');
for (const file of plan.files) {
const actual = (await this.needGit(project, ['ls-tree', '-z', job.expectedCommit, '--', file.path])).text;
if (actual !== file.mode + ' blob ' + file.afterBlob + '\t' + file.path + '\0') throw conflict('实际提交文件与已审核快照不同:' + file.path);
}
return true;
}
async finishPublished(project, session, plan, job) {
// Inspect our exact index/lock bytes before Git reads an externally damaged
// index. Recheck after verifying the commit before publishing the index.
const beforeIndex = digestFile(job.indexPath), beforeLock = digestFile(job.lockPath);
if (beforeIndex === job.indexAfterSha256) {
if (fs.existsSync(job.lockPath)) throw conflict('索引已发布但仍有其他锁,请核对该操作。');
} else if (beforeIndex !== job.indexBeforeSha256 || beforeLock !== job.indexAfterSha256) {
throw conflict('提交已存在,但索引或遗留锁已被其他操作修改,保留现场。');
}
await this.verifyPublished(project, plan, job);
if (normalize(fs.realpathSync.native(path.dirname(job.indexPath))) !== normalize(plan.snapshot.gitDir)) throw conflict('Git索引目录的实际位置已变化,保留本次现场。');
if (digestFile(job.indexPath) === job.indexAfterSha256) {
// An exit after the atomic index rename is recoverable without rewriting.
if (fs.existsSync(job.lockPath)) throw conflict('索引已发布但仍有其他锁,请核对该操作。');
} else {
if (digestFile(job.indexPath) !== job.indexBeforeSha256 || digestFile(job.lockPath) !== job.indexAfterSha256) throw conflict('提交已存在,但索引或遗留锁已被其他操作修改,保留现场。');
fs.renameSync(job.lockPath, job.indexPath);
}
await this.checkpoint(session, job, 'index_published');
const [stage, flags, inspection] = await Promise.all([this.needGit(project, ['ls-files', '--stage', '-z']), this.needGit(project, ['ls-files', '-v', '-z']), inspectProject(project)]);
job.indexPreserved = protectedIndex(stage.text, flags.text, plan.paths) === plan.protectedIndexSha256;
job.workspacePreserved = inspection.sourceFingerprint === plan.sourceFingerprint;
if (!job.indexPreserved || !job.workspacePreserved) throw conflict('提交已经存在,但工作区或无关索引条目发生变化,需要核对实际结果。');
job.commit = job.expectedCommit;
}
releaseOwnedLock(job) {
if (!job.lockPath || !fs.existsSync(job.lockPath)) return;
const actual = digestFile(job.lockPath);
if (actual === job.lockMarkerSha256 || actual === job.indexAfterSha256) fs.unlinkSync(job.lockPath);
}
async reconcile(session, jobId) {
this.assertIdle(session);
const job = this.store.owned('delivery_job', jobId, session.id), plan = this.store.owned('delivery_plan', job.planId, session.id);
if (job.status === 'completed') return job;
if (!['unknown', 'interrupted', 'failed', 'stale', 'cancelled'].includes(job.status)) throw conflict('提交仍在执行,请等待结束后核对。');
if (job.ownerPid !== process.pid && pidAlive(job.ownerPid) || pidAlive(job.refProcessPid)) throw conflict('原提交进程可能仍在运行,先等待实际进程结束。');
const project = this.store.project(session.projectId);
const reservation = { sessionId: session.id, projectId: session.projectId, controller: new AbortController(), promise: Promise.resolve() };
this.active.set(job.id, reservation); this.projects.set(session.projectId, job.id);
reservation.promise = this.reconcileOwned(session, job, plan, project).finally(() => { this.active.delete(job.id); this.projects.delete(session.projectId); });
reservation.promise.catch(() => {});
return reservation.promise;
}
async reconcileOwned(session, job, plan, project) {
const currentIndex = (await this.needGit(project, ['rev-parse', '--path-format=absolute', '--git-path', 'index'])).text.trim();
if (normalize(currentIndex) !== normalize(plan.snapshot.indexPath) || job.indexPath && normalize(job.indexPath) !== normalize(currentIndex)) throw conflict('项目Git索引位置已变化,不能修复旧索引。');
const head = (await this.needGit(project, ['rev-parse', 'HEAD'])).text.trim();
if (head === job.expectedCommit) {
await this.finishPublished(project, session, plan, job); job.status = 'completed'; job.requiresVerification = false;
job.summary = '已核对中断前的实际提交并修复本次索引发布;没有重新执行提交。';
} else if (head === plan.snapshot.head && (await this.needGit(project, ['symbolic-ref', '--quiet', 'HEAD'])).text.trim() === plan.snapshot.reference) {
if (job.lockPath && fs.existsSync(job.lockPath)) {
if (digestFile(job.indexPath) !== job.indexBeforeSha256 || ![job.lockMarkerSha256, job.indexAfterSha256].includes(digestFile(job.lockPath))) throw conflict('遗留索引锁与原基线不同,不能删除其他操作的锁。');
this.releaseOwnedLock(job);
}
job.status = 'interrupted'; job.requiresVerification = false; job.summary = '已核对原HEAD,本次预期提交未挂到当前分支;本次遗留锁已清理,没有重放。需要新预览才能提交。';
} else throw conflict('Git引用与保存的结果不一致,无法确认提交;保留需核对状态,不会重放。');
job.reconciledAt = at(); this.store.save(session, { type: 'delivery.reconciled', detail: { jobId: job.id, status: job.status } });
if (job.status === 'completed' && session.taskId === job.taskId) await this.reporter.create(session, { job });
return job;
}
async report(session, { source = 'user' } = {}) {
this.assertIdle(session, { exceptSessionId: source === 'agent' ? session.id : null });
const id = randomUUID(), reservation = { sessionId: session.id, projectId: session.projectId, controller: new AbortController(), promise: null };
this.active.set(id, reservation); this.projects.set(session.projectId, id);
reservation.promise = (async () => {
const inspection = await inspectProject(this.store.project(session.projectId));
reservation.controller.signal.throwIfAborted();
return this.reporter.create(session, { inspection });
})().finally(() => { this.active.delete(id); this.projects.delete(session.projectId); });
reservation.promise.catch(() => {});
return reservation.promise;
}
async stop(sessionId, jobId) {
if (jobId) this.store.owned('delivery_job', jobId, sessionId);
const values = [...this.active.entries()].filter(([id, value]) => value.sessionId === sessionId && (!jobId || id === jobId));
for (const [, value] of values) value.controller.abort(new Error('用户停止Git交付'));
await Promise.all(values.map(([, value]) => value.promise));
}
async stopAll() { await Promise.all([...new Set([...this.active.values()].map(value => value.sessionId))].map(id => this.stop(id))); }
}