feat: add durable isolated Git workspaces and source-bound delivery
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
# 独立开发工作区
|
||||
|
||||
本切片在开发中。实际发行、回归和模型验收完成后再登记为已交付。
|
||||
|
||||
从当前Git项目封存已提交的HEAD、来源目录、命名分支、索引字节、可读取源码、其他引用和Git配置的散列。审查后创建宿主拥有的独立目录及新分支,打开为独立项目和会话。来源的未提交文件不会自动复制;依赖安装另行审查。工作区的Task、Run、模型上下文和报告标明实际执行目录、分支、起始提交与来源身份。
|
||||
|
||||
创建记录先于Git执行保存,包含宿主PID和实际Git子进程PID。成功后核对工作区登记、共同Git目录、HEAD、分支、索引条目和标记、所有检出文件的Git内容散列及来源快照。在登记项目/会话前后再次核对。重复请求使用保存的身份;完成项目允许在原分支上继续修改和提交。
|
||||
|
||||
创建中断标为结果待核对。显式核对只读取实际状态,完整一致时补齐项目/会话登记;外部目录、分支或内容变化会保留并说明差异。原执行进程仍在运行时不能结束核对。确认保留外部状态不宣称创建成功,不自动删除、重试、reset或合并。读取验证不会补建丢失的控制文件。已归档的子会话保持归档。
|
||||
|
||||
支持已有提交的普通命名分支,最多1000份已提交文件、单文件1MB、总计16MB,拒绝提交的链接、子模块、凭据/依赖/内部目录、Windows设备名和大小写冲突。当前不支持稀疏检出、独立worktree配置或外部Git配置包含。Git以参数数组执行,使用受限环境及空hooks目录,关闭fsmonitor和配置中所有clean/smudge/process/required过滤器,保留内置换行转换。创建不会执行项目代码或安装依赖。
|
||||
|
||||
工作区创建参与Runtime、工程检查、Git交付、文件批次和升级的活动检查。同仓库正在创建或结果待核对的记录需要先在所属会话处理。直接文件读取/编辑也核对物理Git身份。来源状态只在创建及创建恢复时要求完全一致,之后正常开发允许来源和子分支各自推进;本轮没有自动合并和工作区归档能力。
|
||||
|
||||
验收要求包含真实进程退出切点、外部改动、保留原索引/已有修改、hooks和过滤器无执行、子工作区批次到真实检查和Git报告,以及桌面和390px界面的创建/切换/恢复/迟到响应。证据随实际完成逐项登记。
|
||||
@@ -159,3 +159,10 @@
|
||||
- 最终1.5.1发行20261029140959308的2216/381份归档、CRC/SHA、独立便携实际4项检查通过;97份核心/测试/全部脚本/构建输入及6份编译与独立163项验收源码一致。原PID23080/模型及8项目10会话保留再次升级。证据提交67e5cbd后继续开发下一切片,正式服务保持已验证不可变目录。
|
||||
|
||||
- 下一切片已实现Git预览后的确定性审查边界:当前助手消息中后续工具成对记为未执行,保存计划/暂停原因,不继续请求模型;确认已有预览后内核完成原Task及报告,预览可修改/撤回。34项交付/实际退出/Runtime相关回归及9组桌面/390px交付流程通过,0页面/请求异常;确认截图已目视核对,证据为git-review-ui-validation.json。功能仍在开发源码,正式1.5.1保持。
|
||||
|
||||
- 接续全量推进:修复工作区草稿与Store metadata不匹配,补齐提交树/大小/Windows名称核对、源配置散列、实际检出内容与索引检查、登记前后重复核对和只读打开验证。首批3项工作区行为通过,原索引字节及owner修改保留;开始接入Runtime/API/检查/交付/文件批次和桌面/390px界面。正式4318仍为冻结1.5.1/PID23080。
|
||||
- 上一轮大补丁因类结束锚点不匹配被整体拒绝,本轮已拆成精确小补丁。大批读取超出输出上限已改为按相关段落读取;尚未收到部分不视为核对完成。
|
||||
|
||||
- 工作区初批21/21通过,包含8个真实进程退出切点和外部登记改动,所有clean/smudge/process/required及hooks/fsmonitor探针均无执行;内置CRLF转换与中文空格路径通过。实际API首次2项失败为隐藏.git写入方式和报告异步保存等待条件,已针对校正,继续重新验收。
|
||||
|
||||
- 实际API2/2通过:子工作区同Task批次修复、真实3项测试/build、确定性Git审查与报告完成,确认后没有新增模型请求;原项目索引/HEAD/owner文件保留。原检查/批次/Git/Runtime相关76/76回归通过。首轮界面6组已通过,迟到失败测试错误地要求不存在的toast节点,改为核对匹配错误的节点数量为0,产品没有错误串会话。
|
||||
|
||||
@@ -6,6 +6,8 @@ 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';
|
||||
import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
|
||||
import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
|
||||
|
||||
const at = () => new Date().toISOString();
|
||||
const conflict = message => Object.assign(new Error(message), { status: 409 });
|
||||
@@ -54,6 +56,8 @@ export class CheckRunner {
|
||||
|
||||
async plan(session, names) {
|
||||
assertChangeSetsResolved(this.store, session.projectId);
|
||||
assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true });
|
||||
await verifyWorkspaceProject(this.store, this.store.project(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));
|
||||
@@ -81,6 +85,7 @@ export class CheckRunner {
|
||||
|
||||
async start(session, planId, { signal, source = 'user' } = {}) {
|
||||
assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true });
|
||||
assertWorkspacesResolved(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('先应用或撤回本任务的待审查改动,再检查实际工程。');
|
||||
@@ -104,6 +109,7 @@ export class CheckRunner {
|
||||
async execute(session, plan, job, run, signal) {
|
||||
const task = this.store.core.task.get(job.taskId);
|
||||
try {
|
||||
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
|
||||
const before = await inspectProject(this.store.project(session.projectId));
|
||||
signal.throwIfAborted();
|
||||
if (before.fingerprint !== plan.fingerprint) throw conflict('检查计划创建后工程或Git基线已变化,请重新识别再执行。');
|
||||
|
||||
@@ -2,6 +2,8 @@ import { inspectProject } from './project-inspector.mjs';
|
||||
import { ChangeSetManager } from './workspaces/change-sets.mjs';
|
||||
import { verifyPlanEvidence } from './context/request-plan.mjs';
|
||||
import { pendingDeliveryReview } from '../shared/contracts/delivery-review.mjs';
|
||||
import { projectWorkspaceIdentity, unresolvedWorkspaces } from '../shared/contracts/workspaces.mjs';
|
||||
import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
|
||||
|
||||
const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待改动或交付审查',
|
||||
needs_checks: '需要实际工程检查', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' };
|
||||
@@ -34,6 +36,7 @@ export class DeliveryReporter {
|
||||
const task = this.store.owned('task', taskId, session.id);
|
||||
const run = this.store.owned('run', runId, session.id);
|
||||
const project = this.store.project(session.projectId);
|
||||
await verifyWorkspaceProject(this.store, project);
|
||||
inspection ??= await inspectProject(project);
|
||||
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('生成报告期间任务已切换,请重新生成。'), { status: 409 });
|
||||
if (job && (job.sessionId !== session.id || job.taskId !== taskId)) throw new Error('提交记录不属于当前任务。');
|
||||
@@ -42,6 +45,7 @@ export class DeliveryReporter {
|
||||
const check = verifiedCheck(this.store, session, inspection);
|
||||
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 }));
|
||||
requiresVerification.push(...unresolvedWorkspaces(this.store, project.id).map(value => ({ id: value.id, tool: 'workspace', status: value.status })));
|
||||
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 => {
|
||||
@@ -74,12 +78,13 @@ export class DeliveryReporter {
|
||||
: !check ? 'needs_checks' : commits.length ? 'verified_committed' : 'verified_uncommitted';
|
||||
const report = {
|
||||
schemaVersion: 1, kind: 'engineering-delivery', generatedAt: new Date().toISOString(), status, statusLabel: labels[status],
|
||||
project: { id: project.id, name: project.name, root: project.root },
|
||||
project: { id: project.id, name: project.name, root: project.root }, workspace: projectWorkspaceIdentity(project),
|
||||
task: { id: task.id, goal: task.goal, status: task.status, instructions: task.instructions, acceptance: task.acceptance ?? [],
|
||||
requirementsAcceptance: 'not_recorded', note: '源码和检查证据不代替业务需求验收。' },
|
||||
workspaceIdentity: task.workspaceIdentity ?? null, requirementsAcceptance: 'not_recorded', note: '源码和检查证据不代替业务需求验收。' },
|
||||
source: { fingerprint: inspection.sourceFingerprint, scope: inspection.scope, gitHead: inspection.git.head, branch: inspection.git.branch },
|
||||
runs: [...this.store.core.run.values()].filter(value => value.taskId === taskId).map(value => ({ id: value.id, resumeOf: value.resumeOf,
|
||||
engine: value.engine, status: value.status, model: value.model, startedAt: value.startedAt, finishedAt: value.finishedAt, usage: value.usage, stopReason: value.stopReason })),
|
||||
engine: value.engine, status: value.status, model: value.model, startedAt: value.startedAt, finishedAt: value.finishedAt, usage: value.usage, stopReason: value.stopReason,
|
||||
...(value.workspaceIdentity ? { workspaceIdentity: value.workspaceIdentity } : {}) })),
|
||||
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, changeSetId: value.changeSetId ?? null, appliedAt: value.appliedAt ?? null, additions: value.additions, deletions: value.deletions })),
|
||||
@@ -117,6 +122,10 @@ 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.workspace?.kind === 'managed-worktree') lines.push('', '## 独立开发工作区', '', '工作区:' + report.workspace.workspaceId,
|
||||
'来源项目:' + report.workspace.sourceProjectId, '来源目录:' + report.workspace.sourceRoot,
|
||||
'起始提交:' + report.workspace.baseCommit, '独立分支:' + report.workspace.branch,
|
||||
'交付保存在此分支;合并回来源项目需要另行审查。');
|
||||
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(' | ') + ' |',
|
||||
|
||||
@@ -9,6 +9,8 @@ import { inspectProject } from './project-inspector.mjs';
|
||||
import { gitArguments, gitEnvironment, runGit } from './git-process.mjs';
|
||||
import { DeliveryReporter, verifiedCheck } from './delivery-report.mjs';
|
||||
import { pendingDeliveryReview, resolveDeliveryReview } from '../shared/contracts/delivery-review.mjs';
|
||||
import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
|
||||
import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
|
||||
|
||||
const at = () => new Date().toISOString();
|
||||
const sha = value => createHash('sha256').update(value).digest('hex');
|
||||
@@ -71,6 +73,7 @@ export class GitDelivery {
|
||||
}
|
||||
assertTask(session) {
|
||||
assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true });
|
||||
assertWorkspacesResolved(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归属不一致。');
|
||||
@@ -84,6 +87,7 @@ export class GitDelivery {
|
||||
}
|
||||
|
||||
async snapshot(project, { allowOwnLock = false } = {}) {
|
||||
await verifyWorkspaceProject(this.store, project);
|
||||
const root = safePath(project);
|
||||
let top;
|
||||
try { top = await this.needGit(project, ['rev-parse', '--show-toplevel']); }
|
||||
|
||||
@@ -13,12 +13,12 @@ export function gitArguments(root, args, hooksDirectory) {
|
||||
...(hooksDirectory ? ['-c', 'core.hooksPath=' + hooksDirectory] : []), ...args];
|
||||
}
|
||||
|
||||
export function runGit(root, args, { input, env = {}, signal, timeoutMs = 10000, hooksDirectory, maximumBytes = 2 * 1024 * 1024 } = {}) {
|
||||
export function runGit(root, args, { input, env = {}, signal, timeoutMs = 10000, hooksDirectory, maximumBytes = 2 * 1024 * 1024, onSpawn } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal?.aborted) return reject(signal.reason ?? new Error('Git操作已停止。'));
|
||||
const child = spawn('git', gitArguments(root, args, hooksDirectory), { env: gitEnvironment(env), windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
|
||||
const chunks = [], errors = [];
|
||||
let bytes = 0, exceeded = false, timedOut = false;
|
||||
let bytes = 0, exceeded = false, timedOut = false, spawnError = null;
|
||||
const capture = list => chunk => { bytes += chunk.length; if (bytes > maximumBytes) { exceeded = true; child.kill(); } else list.push(chunk); };
|
||||
child.stdout.on('data', capture(chunks)); child.stderr.on('data', capture(errors));
|
||||
child.stdin.on('error', () => {});
|
||||
@@ -28,10 +28,15 @@ export function runGit(root, args, { input, env = {}, signal, timeoutMs = 10000,
|
||||
child.once('error', error => { clearTimeout(timer); signal?.removeEventListener('abort', stop); reject(error); });
|
||||
child.once('close', code => {
|
||||
clearTimeout(timer); signal?.removeEventListener('abort', stop);
|
||||
if (spawnError) return reject(spawnError);
|
||||
const output = Buffer.concat(chunks), errorOutput = Buffer.concat(errors).toString('utf8');
|
||||
resolve({ ok: code === 0 && !exceeded && !timedOut && !signal?.aborted, code, output, text: output.toString('utf8'),
|
||||
error: errorOutput, exceeded, timedOut, aborted: !!signal?.aborted });
|
||||
});
|
||||
child.once('spawn', () => {
|
||||
try { onSpawn?.(child.pid); }
|
||||
catch (error) { spawnError = error; child.kill(); }
|
||||
});
|
||||
child.stdin.end(input);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
+33
-1
@@ -4,6 +4,8 @@ import { listFiles, readText, proposeFile, proposePatch, applyChange } from './f
|
||||
import { APP_VERSION, executionEnvironment, sessionSnapshot } from './diagnostics.mjs';
|
||||
import { inspectProject } from '../core/project-inspector.mjs';
|
||||
import { assertProposalUnsealed } from '../shared/contracts/change-sets.mjs';
|
||||
import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
|
||||
import { verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
|
||||
|
||||
export function createSessionPublisher(clients) {
|
||||
return session => {
|
||||
@@ -121,6 +123,7 @@ return async (request, response) => {
|
||||
const projectMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/(files|file|inspection|code-index|code-query)$/);
|
||||
if (method === 'GET' && projectMatch) {
|
||||
const project = store.project(projectMatch[1]);
|
||||
await verifyWorkspaceProject(store, project);
|
||||
if (projectMatch[2] === 'inspection') return json(response, await inspectProject(project));
|
||||
if (['code-index', 'code-query'].includes(projectMatch[2])) {
|
||||
const indexer = runtime.projectIndexer(), index = await indexer.refresh(project);
|
||||
@@ -134,6 +137,7 @@ return async (request, response) => {
|
||||
if (method === 'GET' && route === '/api/sessions') return json(response, store.listSessions());
|
||||
if (method === 'POST' && route === '/api/sessions') {
|
||||
const input = await body(request);
|
||||
await verifyWorkspaceProject(store, store.project(input.projectId));
|
||||
return json(response, store.publicSession(store.createSession(input.projectId)), 201);
|
||||
}
|
||||
const sessionMatch = route.match(/^\/api\/sessions\/([a-f0-9-]+)(?:\/(.*))?$/);
|
||||
@@ -142,6 +146,30 @@ 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 === 'GET' && action === 'workspaces') return json(response, store.executionSnapshot(session).workspaces);
|
||||
if (method === 'POST' && action === 'workspaces') {
|
||||
const input = await body(request);
|
||||
return json(response, await runtime.workspaceManager().prepare(session, input.label), 201);
|
||||
}
|
||||
const workspace = action.match(/^workspaces\/([a-f0-9-]+)(?:\/(create|reconcile|acknowledge|discard|open|stop))?$/);
|
||||
if (workspace && method === 'GET' && !workspace[2]) return json(response, store.owned('workspace', workspace[1], id));
|
||||
if (workspace && method === 'POST' && workspace[2]) {
|
||||
const input = await body(request), record = store.owned('workspace', workspace[1], id);
|
||||
if (workspace[2] === 'open') {
|
||||
if (record.status !== 'ready') throw Object.assign(new Error('工作区尚未完整确认,请先核对创建结果。'), { status: 409 });
|
||||
const project = store.project(record.childProjectId), child = store.session(record.childSessionId);
|
||||
await verifyWorkspaceProject(store, project);
|
||||
if (child.projectId !== project.id || child.archived) throw Object.assign(new Error('原工作区会话已归档或归属变化,请从项目栏打开该项目的当前会话。'), { status: 409 });
|
||||
return json(response, { workspace: record, project, session: store.publicSession(child) });
|
||||
}
|
||||
const manager = runtime.workspaceManager();
|
||||
if (workspace[2] === 'create') await manager.start(session, record.id, input.fingerprint);
|
||||
else if (workspace[2] === 'reconcile') await manager.reconcile(session, record.id, input.fingerprint);
|
||||
else if (workspace[2] === 'acknowledge') await manager.acknowledge(session, record.id, input.fingerprint, input.observationFingerprint);
|
||||
else if (workspace[2] === 'discard') manager.discard(session, record.id, input.fingerprint);
|
||||
else await manager.stop(id);
|
||||
return json(response, record, workspace[2] === 'create' ? 202 : 200);
|
||||
}
|
||||
if (method === 'GET' && action === 'context-plans') {
|
||||
const runId = url.searchParams.get('run'); if (runId) store.owned('run', runId, id);
|
||||
return json(response, [...store.core.context_plan.values()].filter(plan => plan.sessionId === id && (!runId || plan.runId === runId)).slice(-100));
|
||||
@@ -261,6 +289,8 @@ return async (request, response) => {
|
||||
if (method === 'POST' && change) {
|
||||
await body(request);
|
||||
if (runtime.projectHasActivity(session.projectId)) throw Object.assign(new Error('项目正在执行任务或检查,请等待结束或停止后再审查文件改动。'), { status: 409 });
|
||||
assertWorkspacesResolved(store, session.projectId, { includePrepared: true });
|
||||
await verifyWorkspaceProject(store, store.project(session.projectId));
|
||||
if (change[2] === 'apply') applyChange(store, session, change[1]);
|
||||
else {
|
||||
const item = session.changes.find(candidate => candidate.id === change[1]);
|
||||
@@ -274,7 +304,9 @@ 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) || runtime.changeSets?.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) || runtime.workspaces?.projectActive(session.projectId)) throw Object.assign(new Error('工程检查、Git交付、文件批次或工作区正在执行,请等待结束后再编辑文件。'), { status: 409 });
|
||||
assertWorkspacesResolved(store, session.projectId, { includePrepared: true });
|
||||
await verifyWorkspaceProject(store, store.project(session.projectId));
|
||||
if (action === 'patch-proposals') proposePatch(store, session, input);
|
||||
else proposeFile(store, session, input);
|
||||
return json(response, store.publicSession(session), 201);
|
||||
|
||||
@@ -4,6 +4,7 @@ import { createHash, randomUUID } from 'node:crypto';
|
||||
import { diffLines } from 'diff';
|
||||
import { now } from './store.mjs';
|
||||
import { assertChangeSetsResolved, assertProposalUnsealed } from '../shared/contracts/change-sets.mjs';
|
||||
import { assertWorkspacePath, assertWorkspacesResolved } from '../shared/contracts/workspaces.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__']);
|
||||
@@ -17,6 +18,7 @@ export function excludedFromInventory(relative) {
|
||||
}
|
||||
|
||||
export function safePath(project, relative = '', allowMissing = false) {
|
||||
assertWorkspacePath(project);
|
||||
if (typeof relative !== 'string' || relative.includes('\0') || relative.includes(':') || path.isAbsolute(relative) || path.win32.isAbsolute(relative)) throw new Error('路径必须相对于项目文件夹。');
|
||||
const portable = relative.replaceAll('\\', '/');
|
||||
if (portable.split('/').includes('..') || secretName.test(portable) || portable.split('/').some(part => part.toLowerCase() === '.git')) throw new Error('该路径不在可读取的项目范围内。');
|
||||
@@ -111,6 +113,7 @@ export function searchFiles(project, args) {
|
||||
|
||||
export function proposeFile(store, session, args, { patch = null } = {}) {
|
||||
assertChangeSetsResolved(store, session.projectId);
|
||||
assertWorkspacesResolved(store, session.projectId, { includePrepared: true });
|
||||
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);
|
||||
@@ -173,6 +176,7 @@ export function proposePatch(store, session, args) {
|
||||
|
||||
export function applyChange(store, session, id) {
|
||||
assertChangeSetsResolved(store, session.projectId);
|
||||
assertWorkspacesResolved(store, session.projectId, { includePrepared: true });
|
||||
const change = session.changes.find(item => item.id === id);
|
||||
if (!change || change.status !== 'pending') throw new Error('这项改动不处于待审查状态。');
|
||||
assertProposalUnsealed(store, change);
|
||||
|
||||
@@ -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 || runtime.changeSets?.projects.size) throw new Error('Wait for active tasks, checks, Git deliveries, file batches 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 || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size) throw new Error('Wait for active tasks, checks, Git deliveries, file batches, workspaces 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, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans };
|
||||
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces };
|
||||
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.changeSets = null; runtime.contextPlans = null;
|
||||
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null;
|
||||
store.ensureStorage(); store.claimRuntime();
|
||||
store.removeAllListeners('update'); store.on('update', createSessionPublisher(clients));
|
||||
server.removeAllListeners('request'); server.on('request', handler);
|
||||
|
||||
+20
-9
@@ -16,6 +16,8 @@ import { artifactPage, readMessageBudget, recordArtifactRead, clearReadStreak }
|
||||
import { ChangeSetManager } from '../core/workspaces/change-sets.mjs';
|
||||
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
|
||||
import { pendingDeliveryReview } from '../shared/contracts/delivery-review.mjs';
|
||||
import { WorkspaceManager, verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
|
||||
import { assertWorkspacesResolved, projectWorkspaceIdentity } from '../shared/contracts/workspaces.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: '运行终端命令' };
|
||||
|
||||
@@ -47,34 +49,42 @@ 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) || !!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; }
|
||||
isActive(id) { return this.active.has(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id) || !!this.changeSets?.isActive(id) || !!this.workspaces?.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 || (this.workspaces?.projects.size ?? 0) > 0 || (this.workspaces?.pending.size ?? 0) > 0; }
|
||||
projectIndexer() { return this.codeIndex ??= new ProjectIndex(); }
|
||||
requestPlanner() { return this.contextPlans ??= new RequestPlanner(this.store); }
|
||||
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) || !!this.changeSets?.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) || !!this.workspaces?.projectActive(projectId);
|
||||
}
|
||||
workspaceManager() {
|
||||
return this.workspaces ??= new WorkspaceManager(this.store, { initialize: this.store.core.workspace.size === 0,
|
||||
redact: value => this.provider.redact(value), projectBusy: projectId =>
|
||||
[...this.active.values()].some(run => 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) });
|
||||
|| !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.workspaces?.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) || !!this.changeSets?.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) || !!this.workspaces?.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) || !!this.changeSets?.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) || !!this.workspaces?.projectActive(projectId) });
|
||||
}
|
||||
start(id, content, resume = false, { instructionSource = null } = {}) {
|
||||
const session = this.store.session(id);
|
||||
if (pendingDeliveryReview(this.store, session)) throw Object.assign(new Error('当前任务已有待确认的Git交付预览。请在任务记录中审查并确认提交,或撤回预览后继续。'), { status: 409 });
|
||||
assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true });
|
||||
assertWorkspacesResolved(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 字符。');
|
||||
const project = this.store.project(session.projectId);
|
||||
safePath(project);
|
||||
const controller = new AbortController();
|
||||
const config = structuredClone(this.store.config);
|
||||
if (config.mode !== 'demo') this.provider.validate(config);
|
||||
@@ -120,6 +130,7 @@ export class Runtime {
|
||||
const signal = run.controller.signal;
|
||||
let projectionLogged = false;
|
||||
try {
|
||||
await verifyWorkspaceProject(this.store, run.project);
|
||||
for (let step = 0; step < config.maxSteps; step++) {
|
||||
signal.throwIfAborted();
|
||||
checkBudget(run.record, this.store.core.task.get(run.taskId));
|
||||
@@ -130,7 +141,7 @@ export class Runtime {
|
||||
const unknown = [...this.store.core.tool.values()].filter(tool => tool.taskId === task.id && tool.requiresVerification)
|
||||
.map(tool => ({ invocation_id: tool.id, call_id: tool.callId, tool: tool.tool, status: tool.state, requires_verification: true }));
|
||||
const context = this.provider.redact(projectContext(run.project) + '\n当前项目/会话/任务身份:' + JSON.stringify({
|
||||
project_id: run.project.id, session_id: session.id, task_id: task.id }) + '\n当前Task文件提案状态:' + JSON.stringify(state)
|
||||
project_id: run.project.id, session_id: session.id, task_id: task.id, workspace: projectWorkspaceIdentity(run.project) }) + '\n当前Task文件提案状态:' + JSON.stringify(state)
|
||||
+ '\n当前任务目标与全部追加要求(用户任务数据,完整保留):\n' + JSON.stringify({
|
||||
goal: task.goal, instructions: task.instructions, constraints: task.constraints ?? [], acceptance: task.acceptance ?? [],
|
||||
}) + '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
|
||||
@@ -420,11 +431,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); await this.changeSets?.stop(sessionId); return; }
|
||||
if (!run) { await this.checks?.stop(sessionId); await this.deliveries?.stop(sessionId); await this.changeSets?.stop(sessionId); await this.workspaces?.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(); await this.changeSets?.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(); await this.workspaces?.stopAll(); }
|
||||
}
|
||||
|
||||
+42
-6
@@ -7,6 +7,7 @@ import { StateDatabase, runtimeOwnerAlive } from '../core/storage/state-database
|
||||
import { ArtifactStore } from '../core/storage/artifact-store.mjs';
|
||||
import { collectLegacy, cleanConfig } from '../core/storage/legacy-import.mjs';
|
||||
import { ACTIVE_STATES, CORE_KINDS, createTask, createRun, ownedRecord, emptyUsage, accumulateUsage, accountedTokens, isId } from '../shared/contracts/execution.mjs';
|
||||
import { WORKSPACE_ACTIVE, projectWorkspaceIdentity, assertWorkspacePath } from '../shared/contracts/workspaces.mjs';
|
||||
|
||||
export const now = () => new Date().toISOString();
|
||||
|
||||
@@ -210,6 +211,11 @@ export class Store extends EventEmitter {
|
||||
set.summary = '文件批次在执行中断;请核对实际原文/建议字节,不会自动续写或回退。';
|
||||
session.status = 'paused'; session.recoveryNotice = set.summary; changed = true;
|
||||
}
|
||||
for (const workspace of this.core.workspace.values()) if (workspace.sessionId === session.id && WORKSPACE_ACTIVE.has(workspace.status)) {
|
||||
workspace.status = 'unknown'; workspace.requiresVerification = true; workspace.finishedAt = now();
|
||||
workspace.summary = '隔离工作区创建中断,请核对实际目录、分支和Git登记。不会重放创建、删除或重置。';
|
||||
session.status = 'paused'; session.recoveryNotice = workspace.summary; changed = true;
|
||||
}
|
||||
for (const event of session.events ?? []) {
|
||||
if (['running', 'waiting', 'retrying'].includes(event.phase)) {
|
||||
const invocation = [...this.core.tool.values()].find(item => item.sessionId === session.id && item.callId === event.toolCallId);
|
||||
@@ -291,13 +297,27 @@ export class Store extends EventEmitter {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
addProject(root) {
|
||||
addProject(root, { id = null, name = null, workspace = null } = {}) {
|
||||
if (id !== null && !isId(id) || name !== null && (typeof name !== 'string' || !name.trim() || name.length > 200 || /[\x00-\x1f]/.test(name))) throw new Error('内部项目身份或名称无效。');
|
||||
const resolved = fs.realpathSync.native(path.resolve(root));
|
||||
if (!fs.statSync(resolved).isDirectory()) throw new Error('请选择项目文件夹。');
|
||||
const key = process.platform === 'win32' ? resolved.toLowerCase() : resolved;
|
||||
const existing = this.projects.find(project => (process.platform === 'win32' ? project.root.toLowerCase() : project.root) === key);
|
||||
if (existing) return existing;
|
||||
const project = { id: randomUUID(), root: resolved, name: path.basename(resolved), addedAt: now() };
|
||||
if (existing) {
|
||||
if (id && existing.id !== id || workspace && JSON.stringify(existing.workspace) !== JSON.stringify(workspace)) throw Object.assign(new Error('目标目录已经属于另一个项目身份,不能替换。'), { status: 409 });
|
||||
return existing;
|
||||
}
|
||||
if (id && this.projects.some(project => project.id === id)) throw Object.assign(new Error('项目身份已经用于另一个目录。'), { status: 409 });
|
||||
if (workspace) {
|
||||
const record = this.core.workspace.get(workspace.id), source = record && this.project(record.projectId);
|
||||
const expected = record && { id: record.id, sourceProjectId: record.projectId, sourceSessionId: record.sessionId, sourceRoot: record.source.root,
|
||||
sourceWorkspaceId: source.workspace?.id ?? null, baseCommit: record.source.head, branch: record.branch,
|
||||
commonGitDir: record.source.commonDir, gitDir: record.observation?.gitDir, fingerprint: record.fingerprint };
|
||||
if (!record || record.status !== 'registering' || record.childProjectId !== id || record.root !== resolved
|
||||
|| JSON.stringify(workspace) !== JSON.stringify(expected)) throw Object.assign(new Error('工作区项目必须来自已验证的持久创建记录。'), { status: 409 });
|
||||
assertWorkspacePath({ root: resolved, workspace });
|
||||
}
|
||||
const project = { id: id ?? randomUUID(), root: resolved, name: name ?? path.basename(resolved), addedAt: now(), ...(workspace ? { workspace: structuredClone(workspace) } : {}) };
|
||||
const next = [project, ...this.projects];
|
||||
this.storage.transaction(() => this.storage.writeProjects(next));
|
||||
this.projects = next;
|
||||
@@ -310,10 +330,16 @@ export class Store extends EventEmitter {
|
||||
return project;
|
||||
}
|
||||
|
||||
createSession(projectId, title = '新任务') {
|
||||
createSession(projectId, title = '新任务', { id = null } = {}) {
|
||||
this.project(projectId);
|
||||
if (id !== null && !isId(id)) throw new Error('内部会话身份无效。');
|
||||
if (id && this.sessions.has(id)) {
|
||||
const existing = this.sessions.get(id);
|
||||
if (existing.projectId !== projectId) throw Object.assign(new Error('会话身份已经属于另一个项目。'), { status: 409 });
|
||||
return existing;
|
||||
}
|
||||
const session = {
|
||||
id: randomUUID(), projectId, title, status: 'idle', createdAt: now(), updatedAt: now(),
|
||||
id: id ?? randomUUID(), projectId, title, status: 'idle', createdAt: now(), updatedAt: now(),
|
||||
messages: [], providerMessages: [], events: [], changes: [], approvals: [],
|
||||
failure: null, lastFailure: null,
|
||||
compactions: 0, estimatedTokens: 0, usage: null, archived: false,
|
||||
@@ -340,7 +366,11 @@ export class Store extends EventEmitter {
|
||||
if (task.readProgress) {
|
||||
task.readProgress.repeated = 0; task.readProgress.changingIndexes = []; task.readProgress.warning = null; task.readProgress.pause = false;
|
||||
}
|
||||
const workspaceIdentity = projectWorkspaceIdentity(this.project(session.projectId));
|
||||
task.workspaceIdentity ??= structuredClone(workspaceIdentity);
|
||||
if (JSON.stringify(task.workspaceIdentity) !== JSON.stringify(workspaceIdentity)) throw Object.assign(new Error('任务的工作区身份已变化,不能将原任务移动到另一个工作区。'), { status: 409 });
|
||||
const run = createRun(session, task, config, resume ? previousRunId : null);
|
||||
run.workspaceIdentity = structuredClone(workspaceIdentity);
|
||||
this.core.run.set(run.id, run); task.activeRunId = run.id;
|
||||
session.taskId = task.id; session.runId = run.id; session.status = 'running';
|
||||
this.save(session, { type: 'run.started', detail: { resumeOf: run.resumeOf } });
|
||||
@@ -467,11 +497,17 @@ export class Store extends EventEmitter {
|
||||
const tools = [...this.core.tool.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id);
|
||||
const artifacts = [...this.core.artifact.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-30);
|
||||
const jobs = [...this.core.check_job.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-10);
|
||||
const projectWorkspaces = [...this.core.workspace.values()].filter(value => value.projectId === session.projectId);
|
||||
const recentWorkspaceIds = new Set(projectWorkspaces.slice(-12).map(value => value.id));
|
||||
return {
|
||||
schemaVersion: 1, task: task ?? null, run: run ?? null,
|
||||
workspaceIdentity: projectWorkspaceIdentity(this.project(session.projectId)),
|
||||
workspaces: projectWorkspaces.filter(value => recentWorkspaceIds.has(value.id) || value.requiresVerification
|
||||
|| ['prepared', 'creating', 'verifying', 'registering'].includes(value.status)),
|
||||
runs: [...this.core.run.values()].filter(value => value.sessionId === session.id).slice(-20).map(value => ({ id: value.id, taskId: value.taskId,
|
||||
status: value.status, startedAt: value.startedAt, finishedAt: value.finishedAt, steps: value.steps, toolCalls: value.toolCalls,
|
||||
usage: value.usage, stopReason: value.stopReason, model: value.model, budget: value.budget, resumeOf: value.resumeOf })),
|
||||
usage: value.usage, stopReason: value.stopReason, model: value.model, budget: value.budget, resumeOf: value.resumeOf,
|
||||
...(value.workspaceIdentity ? { workspaceIdentity: value.workspaceIdentity } : {}), ...(value.review ? { review: value.review } : {}) })),
|
||||
progress: { totalTools: tools.length, completedTools: tools.filter(value => value.state === 'completed').length,
|
||||
requiresVerification: tools.filter(value => value.requiresVerification).map(value => ({ id: value.id, tool: value.tool, callId: value.callId, state: value.state })) },
|
||||
artifacts, checks: jobs,
|
||||
|
||||
@@ -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', 'change_set', 'context_plan'];
|
||||
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set', 'context_plan', 'workspace'];
|
||||
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);
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
export const WORKSPACE_ACTIVE = new Set(['creating', 'verifying', 'registering']);
|
||||
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);
|
||||
|
||||
export function unresolvedWorkspaces(store, projectId, { exceptId = null, includePrepared = false } = {}) {
|
||||
const records = [...(store.core.workspace?.values() ?? [])], project = store.project(projectId);
|
||||
const commonDirs = new Set(records.filter(record => record.projectId === projectId || record.childProjectId === projectId)
|
||||
.map(record => key(record.source.commonDir)));
|
||||
if (project.workspace?.commonGitDir) commonDirs.add(key(project.workspace.commonGitDir));
|
||||
return records.filter(record => record.id !== exceptId
|
||||
&& (record.projectId === projectId || record.childProjectId === projectId || commonDirs.has(key(record.source.commonDir)))
|
||||
&& (record.requiresVerification || record.status === 'unknown' || WORKSPACE_ACTIVE.has(record.status)
|
||||
|| includePrepared && record.status === 'prepared'));
|
||||
}
|
||||
|
||||
export function assertWorkspacesResolved(store, projectId, options) {
|
||||
if (unresolvedWorkspaces(store, projectId, options).length) throw conflict(
|
||||
'这个项目的Git隔离工作区正在准备、创建或结果待核对,请先在所属会话处理工作区记录。');
|
||||
}
|
||||
|
||||
function controlFile(file) {
|
||||
const stat = fs.lstatSync(file);
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 4096) throw conflict('隔离工作区的Git身份文件已变化,请核对原工作区。');
|
||||
return fs.readFileSync(file, 'utf8').trim();
|
||||
}
|
||||
|
||||
// A linked checkout must still be the same Git administrative directory and
|
||||
// branch. This guard also applies to direct file APIs before any file mutation.
|
||||
export function assertWorkspacePath(project) {
|
||||
if (!project.workspace) return;
|
||||
const identity = project.workspace;
|
||||
if (!identity.gitDir || !identity.commonGitDir || !identity.branch) throw conflict('隔离工作区缺少已验证的Git身份。');
|
||||
const root = fs.lstatSync(project.root);
|
||||
if (!root.isDirectory() || root.isSymbolicLink() || !same(fs.realpathSync.native(project.root), project.root)) throw conflict('隔离工作区路径已变化,不能继续使用旧项目身份。');
|
||||
if (!key(identity.gitDir).startsWith(key(path.join(identity.commonGitDir, 'worktrees')) + path.sep)
|
||||
|| !same(fs.realpathSync.native(identity.gitDir), identity.gitDir)
|
||||
|| !same(fs.realpathSync.native(identity.commonGitDir), identity.commonGitDir)) throw conflict('隔离工作区Git管理目录与来源不匹配。');
|
||||
const gitFile = path.join(project.root, '.git'), match = controlFile(gitFile).match(/^gitdir: (.+)$/);
|
||||
if (!match || !same(path.resolve(project.root, match[1]), identity.gitDir)
|
||||
|| !same(controlFile(path.join(identity.gitDir, 'gitdir')), gitFile)
|
||||
|| !same(path.resolve(identity.gitDir, controlFile(path.join(identity.gitDir, 'commondir'))), identity.commonGitDir)
|
||||
|| controlFile(path.join(identity.gitDir, 'HEAD')) !== 'ref: refs/heads/' + identity.branch) throw conflict(
|
||||
'隔离工作区的目录、Git登记或分支已被外部修改,请保留现场并核对后重新打开。');
|
||||
}
|
||||
|
||||
export function projectWorkspaceIdentity(project) {
|
||||
if (!project.workspace) return { kind: 'local-project', projectId: project.id, root: project.root };
|
||||
const value = project.workspace;
|
||||
return { kind: 'managed-worktree', projectId: project.id, root: project.root, workspaceId: value.id,
|
||||
sourceProjectId: value.sourceProjectId, sourceSessionId: value.sourceSessionId, sourceRoot: value.sourceRoot,
|
||||
sourceWorkspaceId: value.sourceWorkspaceId ?? null, baseCommit: value.baseCommit, branch: value.branch,
|
||||
commonGitDir: value.commonGitDir, gitDir: value.gitDir, fingerprint: value.fingerprint };
|
||||
}
|
||||
+11
-1
@@ -176,7 +176,7 @@
|
||||
|
||||
1. [complete] 完整请求计划包含系统、项目/Task状态、工具定义和响应余量;固定任务目标,按完整assistant/tool组选择近期历史,将旧组封存到SHA256可核验工件,明确估算与服务实际用量区别。
|
||||
2. [complete] 单长Task、多语言/大结果、完整协议、续接/实际退出及归属验证通过,158项完整回归和62组桌面/手机界面通过;独立不可变1.5包、原PID升级完成。真实模型首轮失败证据已保留,进入下方1.5.1修复与同Task续接,未将失败算成工程交付通过。
|
||||
3. [pending] 封存已提交HEAD、独立命名分支/worktree、持久准备/核对记录和稳定项目身份;保留原HEAD/index/用户改动,不隐式执行hooks或内容过滤器。
|
||||
3. [in_progress] 封存已提交HEAD、独立命名分支/worktree、持久准备/核对记录和稳定项目身份;首批21项行为/退出/过滤器通过,继续实际API、界面和发行验收。
|
||||
4. [pending] 继续React/TypeScript与Python工程检查,以及证据绑定的REA/Codex/DeepSeek适配和有界Purge实验;只将实测通过的切片标已实现。
|
||||
|
||||
## 真实工件循环修复(1.5.1,当前优先)
|
||||
@@ -185,3 +185,13 @@
|
||||
2. [complete] 工件页按双层JSON预算/Unicode边界/next_offset返回,直接代码依据优先选择;Task持久已读区间及no_progress暂停,专项4项和1项优先选择回归通过。
|
||||
3. [complete] 完整163项回归、63组UI、独立源码/便携与原PID升级完成;原失败Task四补丁/批次/14项检查/build和工作台Git交付通过。模型仍paused/step_limit、321秒续接上限与新增453235已报告tokens分别保留,不宣称自主循环完整收尾或成本下降。
|
||||
4. [in_progress] 接续.qa中已保存的独立Git/worktree创建/核对草稿,先补齐Git预览后确定性等待确认,再完成原工作区保护、退出恢复与桌面/手机流程。
|
||||
|
||||
## 独立工作区与审查收尾(1.6.0开发)
|
||||
|
||||
1. [complete] Git预览后确定性停止模型请求并等待审查;34项相关回归/9组界面和本地提交7d60dc9保留。
|
||||
2. [in_progress] 工作区快照、普通检出、过滤器/hook关闭、稳定归属和实际进程恢复;21项初批行为通过,API和交付整合继续。
|
||||
3. [in_progress] 原项目/子工作区导航与桌面/390px界面,异步操作有完整归属保护;构建通过,真实浏览器待验收。
|
||||
4. [pending] 全部回归、不可变1.6.0包/独立源码验收、原PID/连接升级、真实模型工作区工程交付与证据本地提交。
|
||||
5. [pending] 继续React/TypeScript与Python工程检查、REA证据绑定的机制适配和Purge实验;Electron/移动配对及完整M2/M6另行验收。
|
||||
|
||||
本轮错误:首批API验证的2项失败均在测试阶段。Windows隐藏.git不能以创建标志覆盖,改为r+打开原控制文件;Git提交completed早于报告工件保存,改为同时等待报告身份再核对。没有修改正式服务或真实凭据。
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import { Store } from '../../src/server/store.mjs';
|
||||
import { WorkspaceManager } from '../../src/core/workspaces/git-workspaces.mjs';
|
||||
|
||||
const [data, sessionId, workspaceId, cut] = process.argv.slice(2), store = new Store(data);
|
||||
const manager = new WorkspaceManager(store, { initialize: false, faultInjector: (phase, record) => {
|
||||
if (phase !== cut) return;
|
||||
process.stdout.write(JSON.stringify({ phase, workspaceId: record.id, root: record.root, branch: record.branch, gitPid: record.gitPid }) + '\n');
|
||||
process.exit(73);
|
||||
} });
|
||||
const record = store.owned('workspace', workspaceId, sessionId);
|
||||
await (await manager.start(store.session(sessionId), record.id, record.fingerprint)).promise;
|
||||
process.stderr.write('Workspace did not reach crash cut: ' + cut + ' / ' + record.status + ' / ' + record.summary + '\n');
|
||||
await manager.stopAll(); store.close(); process.exit(74);
|
||||
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { deliveryGit } from './delivery-project.mjs';
|
||||
|
||||
export function captureWorkspaceSource(f) {
|
||||
const index = deliveryGit(f, ['rev-parse', '--path-format=absolute', '--git-path', 'index']).trim();
|
||||
return { head: deliveryGit(f, ['rev-parse', 'HEAD']), branch: deliveryGit(f, ['symbolic-ref', 'HEAD']),
|
||||
refs: deliveryGit(f, ['for-each-ref', '--format=%(refname) %(objectname)']).split('\n').filter(Boolean),
|
||||
index: fs.readFileSync(index), files: ['owner-staged.txt', 'owner-unstaged.txt', 'owner-untracked.txt', 'src/add.mjs']
|
||||
.map(relative => [relative, fs.existsSync(path.join(f.projectRoot, relative)) ? fs.readFileSync(path.join(f.projectRoot, relative)) : null]) };
|
||||
}
|
||||
export function assertWorkspaceSource(assert, f, original, branch) {
|
||||
const current = captureWorkspaceSource(f);
|
||||
assert.deepEqual({ ...current, refs: current.refs.filter(value => !value.startsWith('refs/heads/' + branch + ' ')) }, original);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fixture, launchWorkbench, until, compatibleFixture, call, completion, assertToolPairs } from './helpers.mjs';
|
||||
import { createDeliveryProject, deliveryGit } from './fixtures/delivery-project.mjs';
|
||||
import { captureWorkspaceSource, assertWorkspaceSource } from './fixtures/workspace-project.mjs';
|
||||
|
||||
function replaceControlFile(file, contents) {
|
||||
// Git marks .git as hidden on Windows. Open the existing ordinary file
|
||||
// without O_CREAT; writeFileSync(path) would fail for that hidden file.
|
||||
const descriptor = fs.openSync(file, 'r+'), bytes = Buffer.isBuffer(contents) ? contents : Buffer.from(contents);
|
||||
try { fs.writeSync(descriptor, bytes, 0, bytes.length, 0); fs.ftruncateSync(descriptor, bytes.length); }
|
||||
finally { fs.closeSync(descriptor); }
|
||||
}
|
||||
|
||||
test('workspace HTTP ownership, reviewed creation and reopen survive restart without changing source files', { timeout: 60000 }, async t => {
|
||||
const f = fixture(t); createDeliveryProject(f); const before = captureWorkspaceSource(f); f.store.close();
|
||||
const host = await launchWorkbench(t, f.data), parent = '/sessions/' + f.session.id;
|
||||
const plan = await host.api(parent + '/workspaces', { label: 'API隔离工作区' });
|
||||
assert.equal(plan.source.dirty, true); assert.equal(fs.existsSync(plan.root), false);
|
||||
await assert.rejects(host.api(parent + '/workspaces/' + plan.id + '/create', {}), /指纹/);
|
||||
await assert.rejects(host.api(parent + '/messages', { content: 'edit source during review' }), /工作区/);
|
||||
const other = await host.api('/sessions', { projectId: f.project.id });
|
||||
await assert.rejects(host.api('/sessions/' + other.id + '/workspaces/' + plan.id), /不属于/);
|
||||
await assert.rejects(host.api('/sessions/' + other.id + '/workspaces/' + plan.id + '/create', { fingerprint: plan.fingerprint }), /不属于/);
|
||||
await Promise.all([host.api(parent + '/workspaces/' + plan.id + '/create', { fingerprint: plan.fingerprint }), host.api(parent + '/workspaces/' + plan.id + '/create', { fingerprint: plan.fingerprint })]);
|
||||
let record; await until(async () => { record = await host.api(parent + '/workspaces/' + plan.id); return record.status === 'ready'; }, 25000);
|
||||
assertWorkspaceSource(assert, f, before, record.branch);
|
||||
const opened = await host.api(parent + '/workspaces/' + plan.id + '/open', {});
|
||||
assert.equal(opened.project.id, record.childProjectId); assert.equal(opened.session.id, record.childSessionId);
|
||||
assert.equal(opened.session.execution.workspaceIdentity.sourceProjectId, f.project.id);
|
||||
await host.close(); const restarted = await launchWorkbench(t, f.data);
|
||||
const reopened = await restarted.api(parent + '/workspaces/' + plan.id + '/open', {});
|
||||
assert.deepEqual(reopened.project, opened.project); assert.equal(reopened.session.id, opened.session.id);
|
||||
assert.equal((await restarted.api('/bootstrap')).projects.filter(value => value.workspace?.id === plan.id).length, 1);
|
||||
const gitFile = path.join(record.root, '.git'), actualPointer = fs.readFileSync(gitFile);
|
||||
replaceControlFile(gitFile, 'gitdir: ' + path.join(f.projectRoot, '.git') + '\n');
|
||||
await assert.rejects(restarted.api(parent + '/workspaces/' + plan.id + '/open', {}), /登记|外部修改/);
|
||||
await assert.rejects(restarted.api('/projects/' + record.childProjectId + '/file?path=src/add.mjs'), /登记|外部修改/);
|
||||
await assert.rejects(restarted.api('/sessions/' + record.childSessionId + '/proposals', { path: 'src/add.mjs', content: 'changed', reason: 'invalid identity' }), /登记|外部修改/);
|
||||
replaceControlFile(gitFile, actualPointer); assertWorkspaceSource(assert, f, before, record.branch);
|
||||
});
|
||||
|
||||
test('isolated model Task applies a batch, executes real checks and commits at the Git review boundary with a source-bound report', { timeout: 90000 }, async t => {
|
||||
const f = fixture(t); createDeliveryProject(f); const before = captureWorkspaceSource(f); f.store.close();
|
||||
let mode = 'repair';
|
||||
const model = await compatibleFixture(t, (url, input) => {
|
||||
if (!input?.messages) return { data: [{ id: 'workspace-http-fixture' }] };
|
||||
const lastUser = input.messages.findLastIndex(value => value.role === 'user'), results = input.messages.slice(lastUser + 1)
|
||||
.filter(value => value.role === 'tool').map(value => JSON.parse(value.content));
|
||||
if (!results.length) return completion([call('plan-' + mode, 'plan_checks', {})]);
|
||||
if (results.length === 1) return completion([call('check-' + mode, 'run_checks', { plan_id: results[0].id })]);
|
||||
if (results.length === 2 && mode === 'repair') return completion([
|
||||
call('isolate-add', 'propose_file', { path: 'src/add.mjs', content: "import { sum } from './math.mjs';\nexport const add = sum;\n", reason: 'Repair only the isolated module' }),
|
||||
call('isolate-math', 'propose_file', { path: 'src/math.mjs', content: 'export const sum = (a,b) => a+b;\n', reason: 'Add isolated arithmetic helper' }),
|
||||
]);
|
||||
if (results.length === 4 && mode === 'repair') return completion([call('isolate-batch', 'prepare_change_set', { change_ids: results.filter(value => value.change_id).map(value => value.change_id) })]);
|
||||
if (results.length === 2 && mode === 'delivery') return completion([
|
||||
call('isolated-delivery-plan', 'plan_delivery', { message: 'feat: repair isolated addition' }),
|
||||
call('after-review-must-not-run', 'run_command', { command: "Set-Content -LiteralPath 'AFTER-REVIEW.txt' -Value 'unexpected'", reason: 'This deferred call must be interrupted at review' }),
|
||||
]);
|
||||
return completion([], '已保存独立工作区的提案,等待审查。');
|
||||
});
|
||||
const host = await launchWorkbench(t, f.data), parent = '/sessions/' + f.session.id;
|
||||
await host.api('/config', { mode: 'compatible', baseUrl: model.baseUrl, model: 'workspace-http-fixture', apiKey: 'SYNTHETIC-WORKSPACE-QA-ONLY', maxSteps: 12 });
|
||||
const plan = await host.api(parent + '/workspaces', { label: '独立工程交付' });
|
||||
await host.api(parent + '/workspaces/' + plan.id + '/create', { fingerprint: plan.fingerprint });
|
||||
await until(async () => (await host.api(parent + '/workspaces/' + plan.id)).status === 'ready', 25000);
|
||||
const opened = await host.api(parent + '/workspaces/' + plan.id + '/open', {}), route = '/sessions/' + opened.session.id;
|
||||
await host.api(route + '/messages', { content: 'Repair addition in this isolated project, run the real tests and build, deliver a reviewed local Git commit.' });
|
||||
let session;
|
||||
await until(async () => { session = await host.api(route); return session.status === 'awaiting_approval'; }, 25000);
|
||||
assert.equal(session.approvals.at(-1).cwd, plan.root); await host.api(route + '/approvals/' + session.approvals.at(-1).id, { allow: true });
|
||||
await until(async () => { session = await host.api(route); return session.status === 'needs_review'; }, 30000);
|
||||
assert.equal(session.execution.checks[0].results[0].tests.failed, 3);
|
||||
const taskId = session.execution.task.id, batch = session.execution.changeSets.at(-1);
|
||||
await host.api(route + '/change-sets/' + batch.id + '/apply', { fingerprint: batch.fingerprint });
|
||||
await until(async () => { session = await host.api(route); return session.execution.changeSets.at(-1).status === 'completed'; });
|
||||
mode = 'delivery'; await host.api(route + '/continue-reviewed', {});
|
||||
await until(async () => { session = await host.api(route); return session.status === 'awaiting_approval'; });
|
||||
await host.api(route + '/approvals/' + session.approvals.at(-1).id, { allow: true });
|
||||
await until(async () => { session = await host.api(route); return session.execution.run.stopReason === 'git_review'; }, 30000);
|
||||
assert.equal(session.execution.task.id, taskId); assert.equal(session.execution.checks.at(-1).status, 'passed');
|
||||
assert.equal(session.execution.checks.at(-1).results[0].tests.passed, 3);
|
||||
assert.equal(session.approvals.length, 2); assert.equal(fs.existsSync(path.join(plan.root, 'AFTER-REVIEW.txt')), false);
|
||||
const requests = model.requests.length, deliveryPlan = session.execution.deliveryPlans.at(-1);
|
||||
await host.api(route + '/delivery-jobs', { planId: deliveryPlan.id });
|
||||
await until(async () => { session = await host.api(route); return session.execution.deliveries.at(-1).status === 'completed' && !!session.execution.deliveries.at(-1).reportArtifactId; }, 30000);
|
||||
assert.equal(model.requests.length, requests); assert.equal(session.status, 'completed'); assert.equal(session.execution.run.status, 'completed');
|
||||
const job = session.execution.deliveries.at(-1), report = JSON.parse((await host.api('/artifacts/' + job.reportArtifactId + '?session=' + session.id + '&limit=64000')).content);
|
||||
assert.equal(report.status, 'verified_committed'); assert.equal(report.workspace.workspaceId, plan.id);
|
||||
assert.equal(report.workspace.root, plan.root); assert.equal(report.workspace.sourceRoot, f.projectRoot);
|
||||
assert.equal(report.task.workspaceIdentity.workspaceId, plan.id); assert.ok(report.runs.every(value => value.workspaceIdentity.workspaceId === plan.id));
|
||||
assert.equal(deliveryGit({ projectRoot: plan.root }, ['rev-parse', 'HEAD']).trim(), job.commit);
|
||||
assertWorkspaceSource(assert, f, before, plan.branch);
|
||||
const exported = await host.api(route + '/export'); assertToolPairs(exported.session.providerMessages);
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fixture } from './helpers.mjs';
|
||||
import { createDeliveryProject, deliveryGit, writeDeliveryFile } from './fixtures/delivery-project.mjs';
|
||||
import { captureWorkspaceSource, assertWorkspaceSource } from './fixtures/workspace-project.mjs';
|
||||
import { WorkspaceManager } from '../src/core/workspaces/git-workspaces.mjs';
|
||||
import { Runtime } from '../src/server/runtime.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { CheckRunner } from '../src/core/check-runner.mjs';
|
||||
import { proposeFile } from '../src/server/files.mjs';
|
||||
|
||||
test('worktree checkout disables hooks, fsmonitor and all filter command variants while honoring built-in EOL conversion', { timeout: 60000 }, async t => {
|
||||
const f = fixture(t); createDeliveryProject(f, { ownerChanges: false });
|
||||
writeDeliveryFile(f, '.gitattributes', '*.mjs filter=full eol=crlf\n*.txt filter=cleanonly\n*.md filter=processonly\npackage.json filter=smudgeonly\n');
|
||||
writeDeliveryFile(f, 'src/空 格.mjs', 'export const value = 1;\n');
|
||||
deliveryGit(f, ['add', '--', '.gitattributes', 'src/空 格.mjs']); deliveryGit(f, ['commit', '-m', 'Attributes fixture before command configuration']);
|
||||
const marker = path.join(f.root, 'commands-executed.txt'), probe = path.join(f.root, 'probe.mjs');
|
||||
fs.writeFileSync(probe, `import fs from 'node:fs'; fs.appendFileSync(${JSON.stringify(marker)}, 'executed\\n'); process.exit(2);\n`);
|
||||
const command = 'node ' + "'" + probe.replaceAll('\\', '/').replaceAll("'", "'\\''") + "'";
|
||||
for (const [driver, variants] of [['full', ['clean', 'smudge', 'process']], ['cleanonly', ['clean']], ['smudgeonly', ['smudge']], ['processonly', ['process']]]) {
|
||||
for (const variant of variants) deliveryGit(f, ['config', 'filter.' + driver + '.' + variant, command]);
|
||||
deliveryGit(f, ['config', 'filter.' + driver + '.required', 'true']);
|
||||
}
|
||||
deliveryGit(f, ['config', 'core.fsmonitor', command]);
|
||||
const hooks = path.join(f.projectRoot, '.git', 'custom-hooks'); fs.mkdirSync(hooks);
|
||||
fs.writeFileSync(path.join(hooks, 'post-checkout'), '#!/bin/sh\n' + command + '\n', { mode: 0o755 });
|
||||
deliveryGit(f, ['config', 'core.hooksPath', hooks]);
|
||||
const before = captureWorkspaceSource(f), manager = new WorkspaceManager(f.store), record = await manager.prepare(f.session, 'filters');
|
||||
await (await manager.start(f.session, record.id, record.fingerprint)).promise;
|
||||
assert.equal(record.status, 'ready', record.summary); assert.equal(record.observation.contentsVerified, true);
|
||||
assert.equal(fs.existsSync(marker), false); assertWorkspaceSource(assert, f, before, record.branch);
|
||||
assert.equal(fs.readFileSync(path.join(record.root, 'src/空 格.mjs'), 'utf8'), 'export const value = 1;\r\n');
|
||||
});
|
||||
|
||||
test('an ignored external file at checkout is observed and never accepted as pristine creation', async t => {
|
||||
const f = fixture(t); createDeliveryProject(f, { ownerChanges: false });
|
||||
const manager = new WorkspaceManager(f.store, { faultInjector: (phase, record) => {
|
||||
if (phase === 'git_finished') { fs.mkdirSync(path.join(record.root, 'dist')); fs.writeFileSync(path.join(record.root, 'dist/owner.txt'), 'Owner ignored addition\n'); }
|
||||
} });
|
||||
const record = await manager.prepare(f.session, 'ignored'); await (await manager.start(f.session, record.id, record.fingerprint)).promise;
|
||||
assert.equal(record.status, 'unknown'); assert.equal(record.observation.clean, false); assert.equal(record.observation.contentsVerified, true);
|
||||
const verifier = new WorkspaceManager(f.store); await verifier.reconcile(f.session, record.id, record.fingerprint);
|
||||
assert.equal(record.status, 'unknown'); assert.equal(f.store.projects.length, 1);
|
||||
await verifier.acknowledge(f.session, record.id, record.fingerprint, record.observation.fingerprint);
|
||||
assert.equal(fs.readFileSync(path.join(record.root, 'dist/owner.txt'), 'utf8'), 'Owner ignored addition\n');
|
||||
});
|
||||
|
||||
test('outside content hidden by assume-unchanged cannot pass workspace verification and blocks further source execution', async t => {
|
||||
const f = fixture(t); createDeliveryProject(f);
|
||||
const manager = new WorkspaceManager(f.store, { faultInjector: (phase, record) => {
|
||||
if (phase === 'git_finished') {
|
||||
deliveryGit({ projectRoot: record.root }, ['update-index', '--assume-unchanged', '--', 'src/add.mjs']);
|
||||
fs.writeFileSync(path.join(record.root, 'src/add.mjs'), 'Owner hidden change\n');
|
||||
}
|
||||
} });
|
||||
const record = await manager.prepare(f.session, 'flags'); await (await manager.start(f.session, record.id, record.fingerprint)).promise;
|
||||
assert.equal(record.status, 'unknown'); assert.equal(record.observation.contentsVerified, false);
|
||||
assert.equal(f.store.projects.length, 1);
|
||||
const runtime = new Runtime(f.store, new Provider()), checks = new CheckRunner(f.store);
|
||||
assert.throws(() => runtime.start(f.session.id, 'new source task'), /工作区/);
|
||||
assert.throws(() => proposeFile(f.store, f.session, { path: 'another.txt', content: 'x', reason: 'x' }), /工作区/);
|
||||
await assert.rejects(checks.plan(f.session), /工作区/);
|
||||
record.ownerPid = process.pid; f.store.save(f.session);
|
||||
await assert.rejects(manager.reconcile(f.session, record.id, record.fingerprint), /进程仍在运行/);
|
||||
record.ownerPid = null; f.store.save(f.session);
|
||||
await manager.reconcile(f.session, record.id, record.fingerprint);
|
||||
assert.equal(record.status, 'unknown'); assert.equal(fs.readFileSync(path.join(record.root, 'src/add.mjs'), 'utf8'), 'Owner hidden change\n');
|
||||
});
|
||||
|
||||
test('workspace preparation refuses known shared-repository activity and preserves archived child sessions', async t => {
|
||||
const f = fixture(t); createDeliveryProject(f, { ownerChanges: false });
|
||||
let busyProject = null;
|
||||
const manager = new WorkspaceManager(f.store, { projectBusy: projectId => projectId === busyProject });
|
||||
const first = await manager.prepare(f.session, 'first'); await (await manager.start(f.session, first.id, first.fingerprint)).promise;
|
||||
assert.equal(first.status, 'ready', first.summary);
|
||||
const child = f.store.session(first.childSessionId); child.archived = true; f.store.save(child);
|
||||
await manager.reconcile(f.session, first.id, first.fingerprint); assert.equal(child.archived, true);
|
||||
busyProject = first.childProjectId; await assert.rejects(manager.prepare(f.session, 'while-child-busy'), /同仓库/);
|
||||
assert.equal(f.store.core.workspace.size, 1);
|
||||
});
|
||||
|
||||
for (const kind of ['excluded dependency', 'large committed blob', 'case collision', 'committed symbolic link', 'external config include']) {
|
||||
test('workspace review rejects ' + kind + ' before any checkout', async t => {
|
||||
const f = fixture(t); createDeliveryProject(f, { ownerChanges: false });
|
||||
if (kind === 'excluded dependency') { writeDeliveryFile(f, 'node_modules/probe.txt', 'dependency\n'); deliveryGit(f, ['add', '-f', '--', 'node_modules/probe.txt']); }
|
||||
if (kind === 'large committed blob') { writeDeliveryFile(f, 'large.txt', Buffer.alloc(1024 * 1024 + 1, 65)); deliveryGit(f, ['add', '--', 'large.txt']); }
|
||||
if (kind === 'case collision' || kind === 'committed symbolic link') {
|
||||
const blob = deliveryGit(f, ['hash-object', '-w', '--stdin'], 'README.md\n').trim();
|
||||
if (kind === 'case collision') for (const name of ['Case.txt', 'case.txt']) deliveryGit(f, ['update-index', '--add', '--cacheinfo', '100644', blob, name]);
|
||||
else deliveryGit(f, ['update-index', '--add', '--cacheinfo', '120000', blob, 'link.txt']);
|
||||
}
|
||||
if (kind !== 'external config include') deliveryGit(f, ['commit', '-m', 'Unsupported source shape fixture']);
|
||||
else { const include = path.join(f.root, 'external.gitconfig'); fs.writeFileSync(include, '[core]\n\tautocrlf = false\n'); deliveryGit(f, ['config', 'include.path', include]); }
|
||||
const before = captureWorkspaceSource(f), manager = new WorkspaceManager(f.store);
|
||||
await assert.rejects(manager.prepare(f.session, 'rejected'), /凭据|依赖|上限|大小写|链接|配置包含/);
|
||||
assert.equal(f.store.core.workspace.size, 0); assert.equal(fs.readdirSync(manager.outputRoot).length, 0);
|
||||
assertWorkspaceSource(assert, f, before, 'never-created');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
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 { createDeliveryProject, deliveryGit } from './fixtures/delivery-project.mjs';
|
||||
import { captureWorkspaceSource, assertWorkspaceSource } from './fixtures/workspace-project.mjs';
|
||||
import { WorkspaceManager, verifyWorkspaceProject } from '../src/core/workspaces/git-workspaces.mjs';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
|
||||
const alive = pid => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch { return false; } };
|
||||
for (const phase of ['intent', 'git_started', 'git_finished', 'verifying', 'registering', 'project_registered', 'session_registered', 'ready']) {
|
||||
test('actual process exit at workspace ' + phase + ' preserves source and reconciles without creation replay', { timeout: 60000 }, async t => {
|
||||
const f = fixture(t); createDeliveryProject(f);
|
||||
const original = captureWorkspaceSource(f), manager = new WorkspaceManager(f.store), planned = await manager.prepare(f.session, 'recovery-' + phase);
|
||||
f.store.close();
|
||||
const child = spawn(process.execPath, [path.join(workspace, 'tests/fixtures/workspace-crash-worker.mjs'), f.data, f.session.id, planned.id, phase],
|
||||
{ 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()), store = new Store(f.data); f.onCleanup(() => store.close());
|
||||
const session = store.session(f.session.id), record = store.owned('workspace', planned.id, session.id), adapter = new WorkspaceManager(store, { initialize: false });
|
||||
f.onCleanup(() => adapter.stopAll());
|
||||
assert.equal(record.status, phase === 'ready' ? 'ready' : 'unknown');
|
||||
if (alive(cut.gitPid)) await assert.rejects(adapter.reconcile(session, record.id, record.fingerprint), /进程仍在运行/);
|
||||
await until(() => !alive(cut.gitPid), 15000);
|
||||
const beforeRefs = deliveryGit(f, ['for-each-ref', '--format=%(refname) %(objectname)']);
|
||||
assertWorkspaceSource(assert, f, original, record.branch);
|
||||
if (phase !== 'ready') await assert.rejects(adapter.start(session, record.id, record.fingerprint), /不能再次执行/);
|
||||
const reconciled = await adapter.reconcile(session, record.id, record.fingerprint);
|
||||
if (phase === 'intent') {
|
||||
assert.equal(reconciled.status, 'unknown'); assert.equal(fs.existsSync(record.root), false);
|
||||
await adapter.acknowledge(session, record.id, record.fingerprint, record.observation.fingerprint);
|
||||
assert.equal(record.status, 'resolved_external'); assert.equal(store.projects.length, 1);
|
||||
} else if (record.observation?.ready || phase === 'ready') {
|
||||
assert.equal(reconciled.status, 'ready', reconciled.summary); assert.equal(store.projects.length, 2);
|
||||
await verifyWorkspaceProject(store, store.project(record.childProjectId));
|
||||
const again = await adapter.reconcile(session, record.id, record.fingerprint);
|
||||
assert.equal(again.childSessionId, record.childSessionId); assert.equal(store.sessions.size, 2);
|
||||
} else {
|
||||
assert.equal(phase, 'git_started', record.summary); assert.equal(record.status, 'unknown');
|
||||
await adapter.acknowledge(session, record.id, record.fingerprint, record.observation.fingerprint);
|
||||
assert.equal(record.status, 'resolved_external');
|
||||
}
|
||||
assert.equal(deliveryGit(f, ['for-each-ref', '--format=%(refname) %(objectname)']), beforeRefs);
|
||||
assertWorkspaceSource(assert, f, original, record.branch);
|
||||
});
|
||||
}
|
||||
|
||||
test('outside changes at project registration remain unknown and preserve the already registered child identity', async t => {
|
||||
const f = fixture(t); createDeliveryProject(f);
|
||||
const manager = new WorkspaceManager(f.store, { faultInjector: (phase, record) => {
|
||||
if (phase === 'project_registered') fs.writeFileSync(path.join(record.root, 'src/add.mjs'), 'Owner changed the child during registration\n');
|
||||
} });
|
||||
const record = await manager.prepare(f.session, 'registration-race');
|
||||
await (await manager.start(f.session, record.id, record.fingerprint)).promise;
|
||||
assert.equal(record.status, 'unknown'); assert.equal(f.store.project(record.childProjectId).workspace.id, record.id);
|
||||
const child = f.store.session(record.childSessionId); child.archived = true; f.store.save(child);
|
||||
const verifier = new WorkspaceManager(f.store);
|
||||
await verifier.reconcile(f.session, record.id, record.fingerprint);
|
||||
assert.equal(record.status, 'unknown'); assert.equal(child.archived, true);
|
||||
assert.equal(fs.readFileSync(path.join(record.root, 'src/add.mjs'), 'utf8'), 'Owner changed the child during registration\n');
|
||||
await assert.rejects(verifyWorkspaceProject(f.store, f.store.project(record.childProjectId)), /恢复证据/);
|
||||
await verifier.acknowledge(f.session, record.id, record.fingerprint, record.observation.fingerprint);
|
||||
assert.equal(record.status, 'resolved_external'); assert.equal(child.archived, true);
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { fixture } from './helpers.mjs';
|
||||
import { createDeliveryProject, deliveryGit, writeDeliveryFile } from './fixtures/delivery-project.mjs';
|
||||
import { WorkspaceManager, verifyWorkspaceProject } from '../src/core/workspaces/git-workspaces.mjs';
|
||||
import { assertWorkspacePath, projectWorkspaceIdentity } from '../src/shared/contracts/workspaces.mjs';
|
||||
import { captureWorkspaceSource as sourceState, assertWorkspaceSource as preserved } from './fixtures/workspace-project.mjs';
|
||||
|
||||
test('managed worktree preserves source index and dirty files, opens a distinct project and binds Run identity', async t => {
|
||||
const f = fixture(t); createDeliveryProject(f);
|
||||
const before = sourceState(f), manager = new WorkspaceManager(f.store); f.onCleanup(() => manager.stopAll());
|
||||
const record = await manager.prepare(f.session, '隔离修复');
|
||||
assert.equal(record.source.dirty, true); assert.equal(record.source.changedPathCount, 3);
|
||||
assert.equal(record.source.treeFiles.length, 8); assert.ok(record.source.committedBytes > 0);
|
||||
assert.equal(fs.existsSync(record.root), false);
|
||||
const { promise } = await manager.start(f.session, record.id, record.fingerprint);
|
||||
const ready = await promise; assert.equal(ready.status, 'ready', ready.summary);
|
||||
assert.equal(ready.observation.contentsVerified, true); preserved(assert, f, before, record.branch);
|
||||
const project = f.store.project(record.childProjectId), session = f.store.session(record.childSessionId);
|
||||
assert.notEqual(project.id, f.project.id); assert.notEqual(session.id, f.session.id);
|
||||
assert.equal(session.projectId, project.id); assert.equal(project.root, record.root);
|
||||
assert.equal(project.workspace.gitDir, ready.observation.gitDir); assert.equal(project.workspace.sourceSessionId, f.session.id);
|
||||
assert.equal(fs.existsSync(path.join(record.root, 'owner-untracked.txt')), false);
|
||||
assert.equal(fs.readFileSync(path.join(record.root, 'owner-staged.txt'), 'utf8'), 'Owner baseline staged file\n');
|
||||
assert.equal(fs.existsSync(path.join(record.root, 'node_modules')), false);
|
||||
await verifyWorkspaceProject(f.store, project);
|
||||
const run = f.store.beginRun(session, 'Repair the isolated project', false, f.store.config);
|
||||
assert.deepEqual(run.workspaceIdentity, projectWorkspaceIdentity(project));
|
||||
assert.deepEqual(f.store.core.task.get(run.taskId).workspaceIdentity, run.workspaceIdentity);
|
||||
session.status = 'completed'; f.store.finishRun(session, run);
|
||||
const again = await manager.start(f.session, record.id, record.fingerprint);
|
||||
assert.equal((await again.promise).childSessionId, session.id); assert.equal(f.store.projects.length, 2);
|
||||
});
|
||||
|
||||
test('stale review, branch/path collisions and forged ownership do not run worktree creation', async t => {
|
||||
const f = fixture(t); createDeliveryProject(f, { ownerChanges: false });
|
||||
const manager = new WorkspaceManager(f.store), plan = await manager.prepare(f.session, 'collision');
|
||||
await assert.rejects(manager.start(f.session, plan.id, '0'.repeat(64)), /指纹/);
|
||||
assert.equal(plan.creationAttempted, false);
|
||||
fs.mkdirSync(plan.root); await assert.rejects(manager.start(f.session, plan.id, plan.fingerprint), /目录已存在/);
|
||||
fs.rmdirSync(plan.root);
|
||||
deliveryGit(f, ['branch', plan.branch]);
|
||||
const failed = await (await manager.start(f.session, plan.id, plan.fingerprint)).promise;
|
||||
assert.equal(failed.status, 'prepared'); assert.equal(failed.creationAttempted, false); assert.equal(fs.existsSync(plan.root), false);
|
||||
manager.discard(f.session, plan.id, plan.fingerprint);
|
||||
const next = await manager.prepare(f.session, 'stale');
|
||||
writeDeliveryFile(f, 'src/add.mjs', 'export const add = () => 99;\n');
|
||||
const stale = await (await manager.start(f.session, next.id, next.fingerprint)).promise;
|
||||
assert.equal(stale.status, 'prepared'); assert.equal(stale.creationAttempted, false); assert.equal(fs.existsSync(next.root), false);
|
||||
assert.throws(() => f.store.addProject(f.projectRoot, { id: randomUUID() }), /另一个项目/);
|
||||
assert.throws(() => f.store.createSession(f.project.id, 'Collision', { id: f.store.createSession(f.project.id).id.replace(/.$/, 'z') }), /无效/);
|
||||
});
|
||||
|
||||
test('workspace project verification is read-only and rejects physical Git identity changes', async t => {
|
||||
const f = fixture(t); createDeliveryProject(f, { ownerChanges: false });
|
||||
const manager = new WorkspaceManager(f.store), record = await manager.prepare(f.session, 'verify');
|
||||
await (await manager.start(f.session, record.id, record.fingerprint)).promise;
|
||||
assert.equal(record.status, 'ready', record.summary);
|
||||
const project = f.store.project(record.childProjectId);
|
||||
fs.writeFileSync(path.join(project.root, 'src/add.mjs'), 'export const add = (a,b) => a+b;\n');
|
||||
await verifyWorkspaceProject(f.store, project);
|
||||
const headFile = path.join(project.workspace.gitDir, 'HEAD'), original = fs.readFileSync(headFile);
|
||||
fs.writeFileSync(headFile, record.source.head + '\n');
|
||||
assert.throws(() => assertWorkspacePath(project), /外部修改/);
|
||||
await assert.rejects(verifyWorkspaceProject(f.store, project), /外部修改/);
|
||||
fs.writeFileSync(headFile, original);
|
||||
fs.unlinkSync(manager.emptyConfig);
|
||||
await assert.rejects(verifyWorkspaceProject(f.store, project));
|
||||
assert.equal(fs.existsSync(manager.emptyConfig), false, 'verification must not recreate missing control files');
|
||||
});
|
||||
Reference in New Issue
Block a user