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

This commit is contained in:
Agent Workbench Dev
2026-10-29 23:22:30 +08:00
parent 7d60dc9c55
commit 7d9bfb85da
22 changed files with 1038 additions and 26 deletions
+13
View File
@@ -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);
+15
View File
@@ -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);
}
+98
View File
@@ -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);
});
+101
View File
@@ -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');
});
}
+68
View File
@@ -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);
});
+73
View File
@@ -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');
});