wishforge-ide/apps/ide/policy/test/git-workspace.test.cjs
eust-w 0bcfbc13dd feat(ide): push IDE work to ide/ branches and merge it through a verified wish
People's changes now reach the target branch the same way the agent's do. The
IDE credential carries a ref prefix and the Git service runs a pre-receive hook
on every push that refuses updates outside it, so the IDE can push only
`ide/` branches; the platform's own integration is unaffected.

- A wish may name a source branch. The run starts from that branch's head, the
  agent builds on it, and verification, repair rounds, merging onto a moved
  target and conflict repair work as before. A missing branch makes the run
  wait (git_storage) until it is pushed.
- Release risk is now computed from the target branch before integration, not
  from where the run started: a migration committed on the source branch would
  otherwise have been missed and could have skipped approval.
- Clones work on `ide/work`; a plain `git push` publishes it.
- The console lists a project's IDE branches with a button to submit a wish
  that merges one, and the new-wish form has a starting-point field; MCP
  `submit_wish` accepts `sourceBranch`. The Git service lists branches under
  a prefix for this (`POST /refs`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 19:17:14 +08:00

192 lines
8.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
require('reflect-metadata');
const test = require('node:test');
const assert = require('node:assert/strict');
const { execFileSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { createGitWorkspace, readGitWorkspaceConfig } = require('../git-workspace.cjs');
const git = (cwd, ...args) =>
execFileSync('git', args, {
cwd,
encoding: 'utf8',
env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' },
}).trim();
function fixture(t) {
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'wishforge-git-workspace-'));
t.after(() => fs.rmSync(base, { recursive: true, force: true }));
const source = path.join(base, 'p1.git');
git(base, 'init', '--quiet', '--bare', '--initial-branch=main', source);
const seed = path.join(base, 'seed');
git(base, 'clone', '--quiet', source, seed);
fs.writeFileSync(path.join(seed, 'README.md'), '# Todo\n');
git(seed, 'add', 'README.md');
git(seed, '-c', 'user.name=Seed', '-c', 'user.email=seed@example.com', 'commit', '--quiet', '-m', 'Initial');
git(seed, 'push', '--quiet', 'origin', 'HEAD:main');
const root = path.join(base, 'workspace');
fs.mkdirSync(root);
const config = { root, credentialDir: path.join(base, 'credentials'), remote: `file://${source}` };
const delivery = (overrides = {}) => ({
projectId: 'p1',
projectName: 'Todo App',
repositoryUrl: config.remote,
branch: 'main',
token: 'payload.signature-1',
expiresAt: new Date(Date.now() + 900_000).toISOString(),
author: { name: 'Ada Lovelace', email: 'ada@example.com' },
...overrides,
});
return { base, source, root, config, delivery };
}
test('the first delivery clones the target branch and keeps the token out of the repository', async t => {
const f = fixture(t);
const workspace = createGitWorkspace(f.config);
const result = await workspace.apply(f.delivery());
assert.equal(result.status, 'cloning');
await result.cloning;
const clone = path.join(f.root, 'todo-app');
assert.equal(result.directory, clone);
assert.equal(fs.readFileSync(path.join(clone, 'README.md'), 'utf8'), '# Todo\n');
const credential = path.join(f.config.credentialDir, 'p1.gitconfig');
assert.equal(fs.statSync(credential).mode & 0o777, 0o600);
assert.doesNotMatch(fs.readFileSync(path.join(clone, '.git/config'), 'utf8'), /payload\.signature/);
assert.equal(
git(clone, 'config', `http.${f.config.remote}.extraHeader`),
'Authorization: Bearer payload.signature-1',
);
assert.equal(git(clone, 'config', 'user.name'), 'Ada Lovelace');
assert.equal(git(clone, 'config', 'user.email'), 'ada@example.com');
});
test('later deliveries only refresh the token, even after the project was renamed', async t => {
const f = fixture(t);
const workspace = createGitWorkspace(f.config);
await (
await workspace.apply(f.delivery())
).cloning;
const result = await workspace.apply(
f.delivery({ projectName: 'Renamed', token: 'payload.signature-2', author: undefined }),
);
assert.deepEqual(result, { status: 'ready', directory: path.join(f.root, 'todo-app') });
assert.equal(
git(result.directory, 'config', `http.${f.config.remote}.extraHeader`),
'Authorization: Bearer payload.signature-2',
);
// A delivery without an author keeps the last one.
assert.equal(git(result.directory, 'config', 'user.name'), 'Ada Lovelace');
assert.equal(git(result.directory, 'config', '--get-all', 'include.path').split('\n').length, 1);
});
test('people commit on ide/work, and a plain push publishes it without touching the target branch', async t => {
const f = fixture(t);
const workspace = createGitWorkspace(f.config);
const { directory, cloning } = await workspace.apply(f.delivery());
await cloning;
assert.equal(git(directory, 'branch', '--show-current'), 'ide/work');
const target = git(f.source, 'rev-parse', 'main');
git(directory, 'config', 'user.name', 'Grace Hopper');
fs.writeFileSync(path.join(directory, 'notes.md'), 'edited in the IDE\n');
git(directory, 'add', 'notes.md');
git(directory, 'commit', '--quiet', '-m', 'Edit in the IDE');
git(directory, 'push', '--quiet');
assert.equal(
git(f.source, 'log', '-1', '--format=%an <%ae> %s', 'ide/work'),
'Grace Hopper <ada@example.com> Edit in the IDE',
);
assert.equal(git(f.source, 'rev-parse', 'main'), target);
// A later clone, for example of a recreated workspace, continues the published branch.
fs.rmSync(directory, { recursive: true });
const again = await workspace.apply(f.delivery());
await again.cloning;
assert.equal(git(again.directory, 'rev-parse', 'HEAD'), git(f.source, 'rev-parse', 'ide/work'));
assert.equal(git(again.directory, 'rev-parse', '--abbrev-ref', '@{upstream}'), 'origin/ide/work');
});
test('an existing folder with the project’s name is never overwritten', async t => {
const f = fixture(t);
fs.mkdirSync(path.join(f.root, 'todo-app'));
fs.writeFileSync(path.join(f.root, 'todo-app', 'mine.txt'), 'keep\n');
const workspace = createGitWorkspace(f.config);
const result = await workspace.apply(f.delivery());
await result.cloning;
assert.equal(result.directory, path.join(f.root, 'todo-app-p1'));
assert.equal(fs.readFileSync(path.join(f.root, 'todo-app', 'mine.txt'), 'utf8'), 'keep\n');
fs.mkdirSync(path.join(f.root, 'other'));
fs.rmSync(result.directory, { recursive: true });
fs.mkdirSync(result.directory);
assert.deepEqual(await workspace.apply(f.delivery()), { status: 'conflict' });
});
test('deliveries for another repository or with unexpected content are refused', async t => {
const f = fixture(t);
const workspace = createGitWorkspace(f.config);
for (const payload of [
f.delivery({ repositoryUrl: 'https://git.example/git/tenant/other.git' }),
f.delivery({ branch: '../main' }),
f.delivery({ token: 'not a token' }),
f.delivery({ author: { name: 'Eve <eve@example.com>', email: 'eve@example.com' } }),
{ ...f.delivery(), command: 'rm -rf /' },
])
await assert.rejects(workspace.apply(payload), { code: 'INVALID_GIT_CREDENTIAL' });
assert.deepEqual(fs.readdirSync(f.root), []);
const shared = createGitWorkspace({ ...f.config, remote: undefined, origin: 'http://127.0.0.1:4504' });
await assert.rejects(
shared.apply(f.delivery({ repositoryUrl: 'http://127.0.0.1:4504/git/demo/p2.git' })),
{ code: 'INVALID_GIT_CREDENTIAL' },
'the repository must belong to the delivered project',
);
await assert.rejects(shared.apply(f.delivery({ repositoryUrl: 'http://127.0.0.1:9999/git/demo/p1.git' })), {
code: 'INVALID_GIT_CREDENTIAL',
});
});
test('the endpoint is only configured for a workspace with Git settings', () => {
assert.equal(readGitWorkspaceConfig({ WISHFORGE_WORKSPACE_PATH: '/w' }), undefined);
assert.deepEqual(
readGitWorkspaceConfig({
WISHFORGE_WORKSPACE_PATH: '/w',
WISHFORGE_GIT_CREDENTIAL_DIR: '/run/wishforge/git',
WISHFORGE_GIT_REMOTE: 'https://git.example/git/t/p1.git',
}),
{ root: '/w', credentialDir: '/run/wishforge/git', remote: 'https://git.example/git/t/p1.git' },
);
const { GitCredentialEndpoint } = require('../git-credential-endpoint.cjs');
const routes = [];
const app = { post: (...args) => routes.push(args) };
const keys = [
'WISHFORGE_WORKSPACE_PATH',
'WISHFORGE_GIT_CREDENTIAL_DIR',
'WISHFORGE_GIT_REMOTE',
'WISHFORGE_GIT_ORIGIN',
];
const previous = Object.fromEntries(keys.map(key => [key, process.env[key]]));
try {
delete process.env.WISHFORGE_GIT_REMOTE;
delete process.env.WISHFORGE_GIT_ORIGIN;
new GitCredentialEndpoint().configure(app);
assert.equal(routes.length, 0);
Object.assign(process.env, {
WISHFORGE_WORKSPACE_PATH: '/w',
WISHFORGE_GIT_CREDENTIAL_DIR: '/run/wishforge/git',
WISHFORGE_GIT_ORIGIN: 'http://127.0.0.1:4504',
});
const endpoint = new GitCredentialEndpoint();
let validated = false;
endpoint.connectionValidator = { validateRequest: () => (validated = true) };
endpoint.configure(app);
assert.equal(routes.length, 1);
assert.equal(routes[0][0], '/wishforge-internal/git-credential');
routes[0][1]({}, {}, () => {});
assert.equal(validated, true, 'Theia’s connection token is checked first');
} finally {
for (const key of keys)
if (previous[key] === undefined) delete process.env[key];
else process.env[key] = previous[key];
}
});