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

This commit is contained in:
Agent Workbench Dev
2026-10-29 23:22:30 +08:00
parent 7d60dc9c55
commit 7d9bfb85da
22 changed files with 1038 additions and 26 deletions
+7
View File
@@ -4,6 +4,8 @@ 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';
import { assertWorkspacesResolved } from '../../shared/contracts/workspaces.mjs';
import { verifyWorkspaceProject } from './git-workspaces.mjs';
const at = () => new Date().toISOString();
const conflict = message => Object.assign(new Error(message), { status: 409 });
@@ -82,6 +84,7 @@ export class ChangeSetManager {
throw conflict('同一项目正在执行任务、检查、提交或文件批次,请等待结束后再操作。');
}
assertChangeSetsResolved(this.store, session.projectId, { exceptId, includePrepared });
assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true });
}
own(session, id, fingerprint = null, { current = false } = {}) {
const set = this.store.owned('change_set', id, session.id);
@@ -139,6 +142,7 @@ export class ChangeSetManager {
validatePaths(project, changes);
const temporaryId = randomUUID(); this.projects.set(project.id, temporaryId);
try {
await verifyWorkspaceProject(this.store, project);
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,
@@ -180,6 +184,7 @@ export class ChangeSetManager {
this.requireIdle(session, { exceptId: set.id });
const operation = this.claim(session, set);
try {
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
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/分支已变化,未写入任何文件。');
@@ -298,6 +303,7 @@ export class ChangeSetManager {
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 });
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
this.snapshots(session, set);
return this.settle(session, set, this.inspect(session, set), set.direction === 'rollback' ? 'rollback' : 'apply');
}
@@ -307,6 +313,7 @@ export class ChangeSetManager {
this.requireIdle(session, { exceptId: set.id });
const snapshots = this.snapshots(session, set), operation = this.claim(session, set);
try {
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
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);
+441
View File
@@ -0,0 +1,441 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
import { runGit } from '../git-process.mjs';
import { inspectProject } from '../project-inspector.mjs';
import { safePath, excludedFromInventory } from '../../server/files.mjs';
import { assertChangeSetsResolved } from '../../shared/contracts/change-sets.mjs';
import { assertWorkspacesResolved, assertWorkspacePath, WORKSPACE_ACTIVE } from '../../shared/contracts/workspaces.mjs';
const at = () => new Date().toISOString();
const hash = value => createHash('sha256').update(typeof value === 'string' || Buffer.isBuffer(value) ? value : JSON.stringify(value)).digest('hex');
const conflict = message => Object.assign(new Error(message), { status: 409 });
const key = value => process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);
const same = (a, b) => key(a) === key(b);
const inside = (parent, child) => key(child).startsWith(key(parent) + path.sep);
const alive = pid => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
const oid = value => /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(value);
const sealed = record => ({ id: record.id, projectId: record.projectId, sessionId: record.sessionId, taskId: record.taskId,
runId: record.runId, label: record.label, root: record.root, branch: record.branch, source: record.source,
childProjectId: record.childProjectId, childSessionId: record.childSessionId });
export function worktreeEntries(text) {
const records = []; let current;
for (const part of text.split('\0')) {
if (!part) { if (current) records.push(current); current = null; continue; }
const space = part.indexOf(' '), name = space < 0 ? part : part.slice(0, space), value = space < 0 ? true : part.slice(space + 1);
if (name === 'worktree') { if (current) records.push(current); current = { root: value }; }
else if (current) current[name] = value;
}
if (current) records.push(current); return records;
}
function ordinaryDirectory(directory) {
const stat = fs.lstatSync(directory);
if (!stat.isDirectory() || stat.isSymbolicLink() || !same(fs.realpathSync.native(directory), directory)) throw conflict('隔离工作区需要实际的普通目录,不能经过链接或路径别名。');
}
function sourceChanges(text) {
const parts = text.split('\0'), changes = [];
for (let index = 0; index < parts.length; index++) {
const part = parts[index]; if (!part) continue;
if (part.length < 4 || part[2] !== ' ') throw conflict('Git工作区状态格式无法识别。');
const status = part.slice(0, 2), item = { status, path: part.slice(3) };
if (/[RC]/.test(status)) item.originalPath = parts[++index]; changes.push(item);
}
return changes;
}
function configurationHash(file, optional = false) {
if (optional && !fs.existsSync(file)) return null;
const stat = fs.lstatSync(file);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 256 * 1024) throw conflict('Git配置不是有界普通文件,请先核对。');
return hash(fs.readFileSync(file));
}
function checkoutFile(project, relative) {
const target = safePath(project, relative); let current = project.root;
for (const part of path.relative(project.root, target).split(path.sep)) {
current = path.join(current, part);
const stat = fs.lstatSync(current);
if (stat.isSymbolicLink() || !same(fs.realpathSync.native(current), current)) throw conflict('实际检出路径不能经过链接或路径别名。');
}
return fs.lstatSync(target);
}
function committedTree(text) {
const entries = text.split('\0').filter(Boolean), files = [], names = new Map(); let bytes = 0;
if (entries.length > 1000) throw conflict('已提交版本超过当前1000文件工作区上限。');
for (const entry of entries) {
const match = entry.match(/^(100644|100755) blob ([a-f0-9]+)\s+(\d+)\t(.+)$/s);
if (!match || !oid(match[2])) throw conflict('已提交版本包含链接、子模块或未支持的Git文件类型。');
const [, mode, blob, size, relative] = match, count = Number(size), parts = relative.split('/');
if (parts.some(part => !part || /[\\<>:"|?*\x00-\x1f\x7f]/.test(part) || /[. ]$/.test(part) || part === '..'
|| /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i.test(part))) throw conflict('已提交路径含不唯一的Windows名称或控制字符。');
for (let i = 1; i <= parts.length; i++) {
const name = parts.slice(0, i).join('/'), normalized = name.toLowerCase();
if (names.has(normalized) && names.get(normalized) !== name) throw conflict('已提交路径在Windows上有大小写冲突。');
names.set(normalized, name);
}
if (excludedFromInventory(relative)) throw conflict('已提交版本包含凭据、依赖或内部目录,请先整理可交付的源码版本。');
if (!Number.isSafeInteger(count) || count > 1024 * 1024 || bytes + count > 16 * 1024 * 1024) throw conflict('已提交内容超过单文件1MB或总计16MB工作区上限。');
files.push({ mode, blob, bytes: count, path: relative }); bytes += count;
}
return { files, bytes };
}
export class WorkspaceManager {
constructor(store, { projectBusy = () => false, redact = String, faultInjector = null, initialize = true } = {}) {
this.store = store; this.projectBusy = projectBusy; this.redact = redact; this.faultInjector = faultInjector;
this.active = new Map(); this.pending = new Map(); this.projects = new Map(); this.repositories = new Map();
const dataRoot = fs.realpathSync.native(store.directory);
this.directory = path.join(dataRoot, 'workspaces'); this.outputRoot = path.join(this.directory, 'checkouts');
this.hooksDirectory = path.join(this.directory, 'empty-hooks'); this.emptyConfig = path.join(this.directory, 'empty-gitconfig');
ordinaryDirectory(dataRoot);
for (const directory of [this.directory, this.outputRoot, this.hooksDirectory]) {
if (initialize && !fs.existsSync(directory)) fs.mkdirSync(directory); ordinaryDirectory(directory);
}
if (fs.readdirSync(this.hooksDirectory).length) throw conflict('工作区创建器的hooks目录必须为空。');
if (initialize && !fs.existsSync(this.emptyConfig)) fs.writeFileSync(this.emptyConfig, '', { flag: 'wx' });
const config = fs.lstatSync(this.emptyConfig);
if (!config.isFile() || config.isSymbolicLink() || config.nlink !== 1 || config.size !== 0) throw conflict('工作区创建器的Git配置文件需要普通空文件。');
}
isActive(sessionId) { return [...this.active.values(), ...this.pending.values()].some(value => value.sessionId === sessionId); }
track(session, operation) {
const id = randomUUID(), pending = { sessionId: session.id, promise: null };
this.pending.set(id, pending);
pending.promise = operation().finally(() => this.pending.delete(id)); pending.promise.catch(() => {});
return pending.promise;
}
projectActive(projectId) {
return this.projects.has(projectId) || [...this.projects.keys()].some(sourceId => this.repositoryProjects(sourceId).some(project => project.id === projectId));
}
repositoryProjects(projectId) {
const project = this.store.project(projectId), common = project.workspace?.commonGitDir;
const roots = new Set([key(project.root)]);
for (const record of this.store.core.workspace.values()) if (record.projectId === projectId || record.childProjectId === projectId
|| common && same(record.source.commonDir, common)) roots.add(key(record.source.root));
return this.store.projects.filter(value => roots.has(key(value.root)) || value.workspace
&& (roots.has(key(value.workspace.sourceRoot)) || common && same(value.workspace.commonGitDir, common)));
}
assertIdle(session, exceptId = null) {
for (const project of this.repositoryProjects(session.projectId)) {
if (this.projectBusy(project.id) || this.projectActive(project.id)) throw conflict('来源或同仓库工作区正在执行任务、检查、提交或工作区操作,请等待结束。');
assertChangeSetsResolved(this.store, project.id, { includePrepared: true });
assertWorkspacesResolved(this.store, project.id, { exceptId });
if ([...this.store.core.delivery_job.values()].some(value => value.projectId === project.id && value.requiresVerification)
|| [...this.store.core.tool.values()].some(value => value.projectId === project.id && value.requiresVerification)) throw conflict('来源或同仓库项目有结果未知的操作,请先核对该结果。');
}
}
target(record, { absent = false, checkExisting = true } = {}) {
ordinaryDirectory(this.directory); ordinaryDirectory(this.outputRoot); ordinaryDirectory(this.hooksDirectory);
const config = fs.lstatSync(this.emptyConfig);
if (fs.readdirSync(this.hooksDirectory).length || !config.isFile() || config.isSymbolicLink() || config.nlink !== 1 || config.size !== 0) throw conflict('工作区执行配置已被外部修改。');
if (!inside(this.outputRoot, record.root) || !same(path.dirname(record.root), this.outputRoot)) throw conflict('工作区目标超出当前执行宿主拥有的目录。');
if (same(record.root, record.source.root) || inside(record.source.root, record.root) || inside(record.root, record.source.root)) throw conflict('隔离工作区与来源目录不能互相嵌套。');
if (fs.existsSync(record.root)) {
if (absent) throw conflict('目标工作区目录已存在,不能覆盖或复用外部目录。'); if (checkExisting) ordinaryDirectory(record.root);
}
}
own(session, id, fingerprint) {
const record = this.store.owned('workspace', id, session.id);
if (typeof fingerprint !== 'string' || fingerprint !== record.fingerprint || hash(sealed(record)) !== record.fingerprint) throw conflict('工作区审查指纹已变化,请重新打开原记录。');
if (!same(this.store.project(session.projectId).root, record.source.root)) throw conflict('工作区来源项目身份已变化。');
this.target(record, { checkExisting: false }); return record;
}
git(root, args, options = {}) {
return runGit(root, ['-c', 'core.longpaths=true', ...args], { timeoutMs: 30000, maximumBytes: 4 * 1024 * 1024, hooksDirectory: this.hooksDirectory,
...options, env: { GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: this.emptyConfig, ...(options.env ?? {}) } });
}
async need(root, args, options) {
let result;
try { result = await this.git(root, args, options); }
catch (error) { throw conflict(error.code === 'ENOENT' ? '本机未发现Git,请安装Git后再创建隔离工作区。' : this.redact(error.message)); }
if (!result.ok) throw conflict(this.redact(result.error.trim() || 'Git读取或工作区操作未完成。').slice(0, 2000)); return result;
}
async policy(root) {
const names = await this.git(root, ['config', '--null', '--name-only', '--get-regexp', '^filter\\..*\\.(clean|smudge|process|required)$']);
if (!names.ok && names.code !== 1) throw conflict('无法核对Git内容过滤器,暂不创建工作区。');
const conditional = await this.git(root, ['config', '--null', '--name-only', '--get-regexp', '^(include\\.path|include[Ii]f\\..*\\.path)$']);
if (conditional.ok && conditional.text || !conditional.ok && conditional.code !== 1) throw conflict('当前工作区创建器尚不支持Git外部配置包含。');
const drivers = [...new Set(names.text.split('\0').filter(Boolean).map(value => value.replace(/\.(clean|smudge|process|required)$/i, '')))];
return { drivers, args: drivers.flatMap(driver => ['-c', driver + '.clean=', '-c', driver + '.smudge=', '-c', driver + '.process=', '-c', driver + '.required=false']) };
}
async snapshot(project, { exceptBranch = null } = {}) {
await verifyWorkspaceProject(this.store, project);
const root = safePath(project), policy = await this.policy(root);
const args = command => [...policy.args, ...command];
const [top, head, ref, directory, common, index, status, inventory, sparse, worktreeConfig, refs] = await Promise.all([
this.need(root, ['rev-parse', '--show-toplevel']), this.need(root, ['rev-parse', '--verify', 'HEAD']),
this.need(root, ['symbolic-ref', '--quiet', 'HEAD']), this.need(root, ['rev-parse', '--absolute-git-dir']),
this.need(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']),
this.need(root, ['rev-parse', '--path-format=absolute', '--git-path', 'index']),
this.need(root, args(['status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=all'])),
this.need(root, ['ls-tree', '-l', '-r', '-z', '--full-tree', 'HEAD']),
this.git(root, ['config', '--bool', '--get', 'core.sparseCheckout']),
this.git(root, ['config', '--bool', '--get', 'extensions.worktreeConfig']),
this.need(root, ['for-each-ref', '--format=%(refname) %(objectname)']),
]);
if (!same(top.text.trim(), root) || !oid(head.text.trim()) || !/^refs\/heads\/[^\s\0]+$/.test(ref.text.trim())) throw conflict('来源需要独立Git仓库、已有提交和命名分支。');
if (sparse.text.trim() === 'true' || worktreeConfig.text.trim() === 'true'
|| !sparse.ok && sparse.code !== 1 || !worktreeConfig.ok && worktreeConfig.code !== 1) throw conflict('当前工作区创建器尚不支持稀疏检出或独立worktree配置。');
const gitDir = fs.realpathSync.native(directory.text.trim()), commonDir = fs.realpathSync.native(common.text.trim()), indexPath = path.resolve(index.text.trim());
ordinaryDirectory(gitDir); ordinaryDirectory(commonDir);
if (!same(path.dirname(indexPath), gitDir)) throw conflict('来源Git索引位置无法核对。');
const indexStat = fs.lstatSync(indexPath);
if (!indexStat.isFile() || indexStat.isSymbolicLink() || indexStat.nlink !== 1 || indexStat.size > 16 * 1024 * 1024 || fs.existsSync(indexPath + '.lock')) 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正在合并、变基或定位问题,请先完成该操作。');
const tree = committedTree(inventory.text);
const configuration = { common: configurationHash(path.join(commonDir, 'config')),
worktree: configurationHash(path.join(gitDir, 'config.worktree'), true) };
const inspection = await inspectProject(project);
if (!inspection.scope.complete) throw conflict('来源工程超出当前完整快照范围,请先缩小工程再创建隔离工作区。');
const changes = sourceChanges(status.text);
const snapshot = { root, head: head.text.trim(), reference: ref.text.trim(), branch: ref.text.trim().slice(11), gitDir,
commonDir, indexPath, indexSha256: hash(fs.readFileSync(indexPath)), statusSha256: hash(status.text),
sourceFingerprint: inspection.sourceFingerprint, treeSha256: hash(inventory.text), treeFiles: tree.files, committedBytes: tree.bytes,
filterDrivers: policy.drivers, configuration,
referencesSha256: hash(refs.text.split('\n').filter(line => line && !line.startsWith('refs/heads/' + exceptBranch + ' ')).sort()),
dirty: changes.length > 0, changedPaths: changes.slice(0, 32), changedPathCount: changes.length, scope: inspection.scope };
return { ...snapshot, fingerprint: hash(snapshot) };
}
prepare(session, label) { return this.track(session, () => this.prepareOwned(session, label)); }
async prepareOwned(session, label) {
if (typeof label !== 'string' || !label.trim() || label.length > 64 || /[\x00-\x1f]/.test(label)) throw new Error('工作区名称需要1到64个普通字符。');
this.assertIdle(session);
if ([...this.store.core.workspace.values()].some(value => value.projectId === session.projectId && value.status === 'prepared')) throw conflict('这个项目已有待确认的工作区计划,请先处理该记录。');
this.projects.set(session.projectId, 'preparing');
try {
const source = await this.snapshot(this.store.project(session.projectId)), id = randomUUID();
const slug = label.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32) || 'task';
const record = { schemaVersion: 1, id, projectId: session.projectId, sessionId: session.id,
taskId: session.taskId ?? null, runId: session.runId ?? null, label: label.trim(), source,
root: path.join(this.outputRoot, slug + '-' + id), branch: 'workbench/' + slug + '-' + id.slice(0, 12),
childProjectId: randomUUID(), childSessionId: randomUUID(), createdAt: at(), updatedAt: at(), finishedAt: null,
status: 'prepared', phase: 'prepared', creationAttempted: false, requiresVerification: false, ownerPid: null, gitPid: null,
sourcePreserved: null, observation: null, summary: '已封存来源提交和原工作区状态,确认后创建独立Git工作区。' };
this.target(record, { absent: true });
await this.need(source.root, ['check-ref-format', 'refs/heads/' + record.branch]);
record.fingerprint = hash(sealed(record));
this.store.putRecord('workspace', session, record, 'workspace.prepared'); this.faultInjector?.('prepared', record);
return record;
} finally { this.projects.delete(session.projectId); }
}
async start(session, id, fingerprint) {
const record = this.own(session, id, fingerprint);
if (this.active.has(record.id)) return { record, promise: this.active.get(record.id).promise };
if (record.status === 'ready') { await verifyWorkspaceProject(this.store, this.store.project(record.childProjectId)); return { record, promise: Promise.resolve(record) }; }
if (record.status !== 'prepared' || record.creationAttempted) throw conflict('工作区创建已进入执行或结果待核对,不能再次执行Git创建。');
this.assertIdle(session, record.id); this.target(record, { absent: true });
if (this.repositories.has(key(record.source.commonDir))) throw conflict('同一个Git仓库正在创建另一个隔离工作区。');
this.projects.set(session.projectId, record.id); this.repositories.set(key(record.source.commonDir), record.id);
const controller = new AbortController(), active = { sessionId: session.id, controller, promise: null };
this.active.set(record.id, active);
active.promise = this.create(session, record, controller.signal).finally(() => {
this.active.delete(record.id); this.projects.delete(session.projectId); this.repositories.delete(key(record.source.commonDir));
});
// Storage failures are still visible to awaited callers, without becoming
// an unhandled rejection when HTTP has already returned the saved intent.
active.promise.catch(() => {});
return { record, promise: active.promise };
}
save(session, record, phase) {
record.phase = phase; record.updatedAt = at(); this.store.putRecord('workspace', session, record, 'workspace.' + phase);
this.faultInjector?.(phase, record);
}
async create(session, record, signal) {
try {
const current = await this.snapshot(this.store.project(session.projectId));
if (current.fingerprint !== record.source.fingerprint) throw conflict('来源HEAD、索引或文件在审查后变化,请撤销旧计划并重新准备。');
this.target(record, { absent: true }); signal.throwIfAborted();
const branch = await this.git(record.source.root, ['show-ref', '--verify', '--quiet', 'refs/heads/' + record.branch]);
if (branch.ok || branch.code !== 1) throw conflict('隔离分支已经存在或引用无法核对,不能覆盖现有分支。');
const policy = await this.policy(record.source.root);
record.status = 'creating'; record.creationAttempted = true; record.ownerPid = process.pid; record.requiresVerification = true;
this.save(session, record, 'intent');
const result = await this.git(record.source.root, [...policy.args, 'worktree', 'add', '--no-track', '-b', record.branch, record.root, record.source.head],
{ signal, onSpawn: pid => { record.gitPid = pid; this.save(session, record, 'git_started'); } });
record.gitResult = { code: result.code, ok: result.ok, timedOut: result.timedOut, aborted: result.aborted,
message: this.redact(result.error).slice(0, 2000) }; record.gitPid = null;
this.save(session, record, 'git_finished');
if (!result.ok) throw conflict('Git创建没有完整确认结果,请核对实际分支和工作区。');
record.status = 'verifying'; this.save(session, record, 'verifying');
const observation = await this.observe(record);
record.observation = observation;
if (!observation.ready) throw conflict('Git返回后实际工作区或来源状态需要核对。');
await this.register(session, record);
} catch (error) {
record.status = record.creationAttempted ? 'unknown' : 'prepared'; record.requiresVerification = record.creationAttempted;
record.ownerPid = null; record.finishedAt = at(); record.summary = this.redact(error.message).slice(0, 2000);
this.save(session, record, record.creationAttempted ? 'unknown' : 'rejected');
}
return record;
}
async observe(record) {
this.target(record, { checkExisting: false });
const sourceProject = this.store.project(record.projectId), problems = [];
let source = null;
try { source = await this.snapshot(sourceProject, { exceptBranch: record.branch }); }
catch (error) { problems.push('来源:' + this.redact(error.message)); }
const entries = worktreeEntries((await this.need(record.source.root, ['worktree', 'list', '--porcelain', '-z'])).text);
const entry = entries.find(value => same(value.root, record.root));
const ref = await this.git(record.source.root, ['rev-parse', '--verify', 'refs/heads/' + record.branch]);
const branchHead = ref.ok ? ref.text.trim() : null;
const sourcePreserved = !!source && source.fingerprint === record.source.fingerprint;
if (!sourcePreserved) problems.push('来源HEAD、索引、文件或其他引用发生变化。');
let rootState = 'missing', gitDir = null, commonDir = null, workspaceHead = null, workspaceBranch = null, clean = false, contentsVerified = false;
try {
const stat = fs.lstatSync(record.root);
rootState = stat.isSymbolicLink() ? 'link' : stat.isDirectory() ? 'directory' : 'other';
if (rootState !== 'directory') throw conflict('目标已经不是普通目录。');
ordinaryDirectory(record.root);
const gitFile = path.join(record.root, '.git'), gitStat = fs.lstatSync(gitFile);
if (!gitStat.isFile() || gitStat.isSymbolicLink() || gitStat.nlink !== 1 || gitStat.size > 4096) throw conflict('工作区.git身份文件无法核对。');
const policy = await this.policy(record.root);
const [top, head, branch, directory, common, status, index, flags] = await Promise.all([
this.need(record.root, ['rev-parse', '--show-toplevel']), this.need(record.root, ['rev-parse', '--verify', 'HEAD']),
this.need(record.root, ['symbolic-ref', '--quiet', 'HEAD']), this.need(record.root, ['rev-parse', '--absolute-git-dir']),
this.need(record.root, ['rev-parse', '--path-format=absolute', '--git-common-dir']),
this.need(record.root, [...policy.args, 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignored=matching', '--ignore-submodules=all']),
this.need(record.root, ['ls-files', '--stage', '-z']), this.need(record.root, ['ls-files', '-v', '-z']),
]);
if (!same(top.text.trim(), record.root)) throw conflict('目标Git根目录与封存路径不匹配。');
gitDir = fs.realpathSync.native(directory.text.trim()); commonDir = fs.realpathSync.native(common.text.trim());
workspaceHead = head.text.trim(); workspaceBranch = branch.text.trim(); clean = status.text === '';
if (!same(commonDir, record.source.commonDir) || !inside(path.join(commonDir, 'worktrees'), gitDir)) throw conflict('工作区与来源Git共同目录不匹配。');
assertWorkspacePath({ root: record.root, workspace: { gitDir, commonGitDir: commonDir, branch: record.branch } });
const expected = record.source.treeFiles, staged = index.text.split('\0').filter(Boolean), tagged = flags.text.split('\0').filter(Boolean);
if (!Array.isArray(expected) || staged.length !== expected.length || tagged.length !== expected.length) throw conflict('工作区索引文件数量与封存提交不一致。');
const byPath = new Map(expected.map(file => [file.path, file]));
for (const entry of staged) {
const match = entry.match(/^(100644|100755) ([a-f0-9]+) 0\t(.+)$/s), file = match && byPath.get(match[3]);
if (!file || match[1] !== file.mode || match[2] !== file.blob) throw conflict('工作区索引含外部版本或未合并条目。');
}
if (tagged.some(entry => !entry.startsWith('H ') || !byPath.has(entry.slice(2)))) throw conflict('工作区索引存在跳过检查或假定未变化标记。');
const indexFile = path.join(gitDir, 'index'), indexStat = fs.lstatSync(indexFile);
if (!indexStat.isFile() || indexStat.isSymbolicLink() || indexStat.nlink !== 1 || indexStat.size > 16 * 1024 * 1024
|| fs.existsSync(indexFile + '.lock')) throw conflict('工作区索引或外部锁需要先核对。');
let actualBytes = 0;
const candidate = { root: record.root, workspace: { gitDir, commonGitDir: commonDir, branch: record.branch } };
for (const file of expected) {
const stat = checkoutFile(candidate, file.path);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 2 * 1024 * 1024
|| (actualBytes += stat.size) > 32 * 1024 * 1024) throw conflict('实际检出文件不是有界普通源码文件。');
}
// Git's C-quoted stdin paths are data, never shell command text. Hashing
// honors built-in EOL conversion while every configured filter is off.
const blobs = expected.length ? (await this.need(record.root, [...policy.args, 'hash-object', '--stdin-paths'],
{ input: expected.map(file => JSON.stringify(file.path)).join('\n') + '\n' })).text.trim().split('\n') : [];
contentsVerified = blobs.length === expected.length && expected.every((file, i) => blobs[i] === file.blob);
if (!contentsVerified) throw conflict('实际工作区内容与封存提交不一致。');
} catch (error) { if (error.code !== 'ENOENT') problems.push('目标:' + this.redact(error.message)); }
const registered = !!entry && entry.branch === 'refs/heads/' + record.branch && entry.HEAD === record.source.head && !entry.detached && !entry.prunable;
const valid = rootState === 'directory' && same(commonDir ?? '', record.source.commonDir) && workspaceHead === record.source.head
&& workspaceBranch === 'refs/heads/' + record.branch && branchHead === record.source.head && clean && registered && contentsVerified;
if (!valid) problems.push('分支、初始提交、Git登记或工作区文件尚未全部一致。');
const observation = { rootState, branchHead, workspaceHead, workspaceBranch, gitDir, commonDir, registered, clean, contentsVerified,
sourcePreserved, sourceFingerprint: source?.fingerprint ?? null, ready: valid && sourcePreserved && problems.length === 0,
problems, observedAt: at() };
return { ...observation, fingerprint: hash({ ...observation, observedAt: undefined }) };
}
async register(session, record) {
record.status = 'registering'; this.save(session, record, 'registering');
record.observation = await this.observe(record);
if (!record.observation.ready) throw conflict('登记前实际工作区或来源发生变化,请核对后保留现场。');
const metadata = { id: record.id, sourceProjectId: record.projectId, sourceSessionId: record.sessionId, sourceRoot: record.source.root,
sourceWorkspaceId: this.store.project(record.projectId).workspace?.id ?? null, baseCommit: record.source.head, branch: record.branch,
commonGitDir: record.source.commonDir, gitDir: record.observation.gitDir, fingerprint: record.fingerprint };
const project = this.store.addProject(record.root, { id: record.childProjectId,
name: this.store.project(record.projectId).name + ' · ' + record.label, workspace: metadata });
if (project.id !== record.childProjectId || project.workspace?.id !== record.id) throw conflict('目标目录已经属于其他项目,不能替换其归属。');
this.faultInjector?.('project_registered', record);
const child = this.store.createSession(project.id, '隔离开发 · ' + record.label, { id: record.childSessionId });
if (child.id !== record.childSessionId) throw conflict('隔离工作区会话身份不匹配。');
this.faultInjector?.('session_registered', record);
record.observation = await this.observe(record);
if (!record.observation.ready) throw conflict('登记期间实际工作区或来源发生变化,请核对已保存的项目身份。');
record.status = 'ready'; record.requiresVerification = false; record.sourcePreserved = true; record.ownerPid = null;
record.gitPid = null; record.finishedAt = at(); record.summary = '独立Git工作区已创建;原HEAD、索引和已有改动保留。';
this.save(session, record, 'ready'); return record;
}
reconcile(session, id, fingerprint) { return this.track(session, () => this.reconcileOwned(session, id, fingerprint)); }
async reconcileOwned(session, id, fingerprint) {
const record = this.own(session, id, fingerprint);
if (record.status === 'ready') { await verifyWorkspaceProject(this.store, this.store.project(record.childProjectId)); return record; }
if (record.status !== 'unknown') throw conflict('只有结果待核对的工作区需要此操作。');
if (alive(record.ownerPid) || alive(record.gitPid)) throw conflict('原工作区执行进程仍在运行,请等待其结束再核对。');
this.assertIdle(session, record.id); this.projects.set(session.projectId, record.id);
try {
record.observation = await this.observe(record);
this.save(session, record, 'observed');
if (record.observation.ready) await this.register(session, record);
else { record.summary = '已读取实际工作区状态;需要保留外部状态或完成本地Git核对,不会自动重放创建。'; this.save(session, record, 'observed'); }
return record;
} catch (error) {
record.status = 'unknown'; record.requiresVerification = true; record.summary = this.redact(error.message).slice(0, 2000);
this.save(session, record, 'unknown'); return record;
} finally { this.projects.delete(session.projectId); }
}
acknowledge(session, id, fingerprint, observationFingerprint) { return this.track(session, () => this.acknowledgeOwned(session, id, fingerprint, observationFingerprint)); }
async acknowledgeOwned(session, id, fingerprint, observationFingerprint) {
const record = this.own(session, id, fingerprint);
if (record.status !== 'unknown' || !record.observation || observationFingerprint !== record.observation.fingerprint) throw conflict('先核对实际工作区,再确认保留当前外部状态。');
if (alive(record.ownerPid) || alive(record.gitPid)) throw conflict('原工作区执行进程仍在运行,不能结束核对。');
this.assertIdle(session, record.id); this.projects.set(session.projectId, record.id);
try {
const current = await this.observe(record);
if (current.fingerprint !== observationFingerprint) throw conflict('当前工作区或来源状态已变化,请重新核对。');
record.status = 'resolved_external'; record.requiresVerification = false; record.finishedAt = at();
record.summary = '已保留当前目录、分支及外部状态,结束核对;未声明创建成功,不自动删除、重试或合并。';
this.save(session, record, 'resolved_external'); return record;
} finally { this.projects.delete(session.projectId); }
}
discard(session, id, fingerprint) {
const record = this.own(session, id, fingerprint);
if (record.status !== 'prepared' || record.creationAttempted) throw conflict('只有尚未执行的工作区计划可以撤销。');
this.assertIdle(session, record.id); record.status = 'discarded'; record.finishedAt = at(); record.summary = '工作区计划已撤销,未执行Git创建。';
this.save(session, record, 'discarded'); return record;
}
async stop(sessionId) {
const running = [...this.active.values(), ...this.pending.values()].filter(value => value.sessionId === sessionId);
for (const value of running) value.controller?.abort(); await Promise.allSettled(running.map(value => value.promise));
}
async stopAll() { await Promise.all([...new Set([...this.active.values(), ...this.pending.values()].map(value => value.sessionId))].map(id => this.stop(id))); }
}
// Opening an owned checkout is read-only. Normal source edits and subsequent
// commits are allowed; only creation recovery requires the original snapshot.
export async function verifyWorkspaceProject(store, project) {
if (!project.workspace) return;
const identity = project.workspace, record = store.core.workspace.get(identity.id);
if (!record || record.status !== 'ready' || record.requiresVerification || hash(sealed(record)) !== record.fingerprint
|| record.childProjectId !== project.id || !same(record.root, project.root) || identity.fingerprint !== record.fingerprint
|| identity.sourceProjectId !== record.projectId || identity.sourceSessionId !== record.sessionId
|| identity.baseCommit !== record.source.head || identity.branch !== record.branch
|| !same(identity.sourceRoot, record.source.root) || !same(identity.commonGitDir, record.source.commonDir)
|| !same(identity.gitDir ?? '', record.observation?.gitDir ?? '')) throw conflict('这个工作区缺少完整的创建或恢复证据,请返回来源会话核对。');
const source = store.project(record.projectId);
if (!same(source.root, record.source.root) || (source.workspace?.id ?? null) !== identity.sourceWorkspaceId) throw conflict('工作区来源项目身份已经变化。');
assertWorkspacePath(project);
const manager = new WorkspaceManager(store, { initialize: false }), root = safePath(project);
manager.target(record);
const [top, head, directory, common, entries, ancestor] = await Promise.all([
manager.need(root, ['rev-parse', '--show-toplevel']), manager.need(root, ['rev-parse', '--verify', 'HEAD']),
manager.need(root, ['rev-parse', '--absolute-git-dir']), manager.need(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']),
manager.need(root, ['worktree', 'list', '--porcelain', '-z']), manager.git(root, ['merge-base', '--is-ancestor', record.source.head, 'HEAD']),
]);
const entry = worktreeEntries(entries.text).find(value => same(value.root, root));
if (!same(top.text.trim(), root) || !same(directory.text.trim(), identity.gitDir) || !same(common.text.trim(), identity.commonGitDir)
|| !oid(head.text.trim()) || !ancestor.ok || !entry || entry.HEAD !== head.text.trim() || entry.branch !== 'refs/heads/' + record.branch
|| entry.detached || entry.prunable) throw conflict('工作区Git根目录、分支或实际登记已经变化,请先核对现场。');
assertWorkspacePath(project);
}