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>
242 lines
10 KiB
JavaScript
242 lines
10 KiB
JavaScript
'use strict';
|
||
// Brings the project's repository into the IDE workspace. While someone has the workspace open,
|
||
// the gateway delivers a short-lived repository token (see gateway/git-credentials.mjs); it is
|
||
// written to a Git config file outside the repository that the clone includes, so nothing secret
|
||
// lands in the repository or its .git/config. The first delivery clones the project into a folder
|
||
// named after it and switches to the ide/work branch: the token may push ide/ branches only, and
|
||
// a wish starting from such a branch verifies and merges it into the target branch.
|
||
const { spawn } = require('node:child_process');
|
||
const fs = require('node:fs/promises');
|
||
const path = require('node:path');
|
||
|
||
const CREDENTIAL_PATH = '/wishforge-internal/git-credential';
|
||
const WORK_BRANCH = 'ide/work';
|
||
const ID = /^[A-Za-z0-9_-]{1,128}$/;
|
||
const TOKEN = /^[A-Za-z0-9_-]{1,4096}\.[A-Za-z0-9_-]{1,512}$/;
|
||
const PLATFORM_REPOSITORY = /^\/git\/[A-Za-z0-9][A-Za-z0-9_-]{0,100}\/([A-Za-z0-9][A-Za-z0-9_-]{0,100})\.git$/;
|
||
|
||
class GitWorkspaceError extends Error {
|
||
constructor(code, message) {
|
||
super(message);
|
||
this.code = code;
|
||
}
|
||
}
|
||
const invalid = message => new GitWorkspaceError('INVALID_GIT_CREDENTIAL', message);
|
||
|
||
function branchName(value) {
|
||
if (
|
||
typeof value !== 'string' ||
|
||
!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/.test(value) ||
|
||
/\.\.|\/\/|\/\.|@\{/.test(value) ||
|
||
/(?:\/|\.|\.lock)$/.test(value)
|
||
)
|
||
throw invalid('Invalid branch');
|
||
return value;
|
||
}
|
||
function personText(value) {
|
||
return typeof value === 'string' && value.length > 0 && value.length <= 200 && !/[\u0000-\u001f\u007f<>]/.test(value);
|
||
}
|
||
|
||
/** The workspace's Git settings; without them the credential endpoint stays off. */
|
||
function readGitWorkspaceConfig(env) {
|
||
const root = env.WISHFORGE_WORKSPACE_PATH;
|
||
const credentialDir = env.WISHFORGE_GIT_CREDENTIAL_DIR;
|
||
if (!root || !credentialDir) return undefined;
|
||
// A workspace of its own accepts exactly its project's repository; the one local Theia
|
||
// shared by every project accepts any repository of the platform Git service it is given.
|
||
if (env.WISHFORGE_GIT_REMOTE) return { root, credentialDir, remote: new URL(env.WISHFORGE_GIT_REMOTE).href };
|
||
if (env.WISHFORGE_GIT_ORIGIN) return { root, credentialDir, origin: new URL(env.WISHFORGE_GIT_ORIGIN).origin };
|
||
return undefined;
|
||
}
|
||
|
||
function validate(payload, config) {
|
||
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw invalid('Expected an object');
|
||
const fields = ['projectId', 'projectName', 'repositoryUrl', 'branch', 'token', 'expiresAt', 'author'];
|
||
if (Object.keys(payload).some(key => !fields.includes(key))) throw invalid('Unexpected field');
|
||
if (!ID.test(payload.projectId ?? '')) throw invalid('Invalid project');
|
||
if (
|
||
payload.projectName !== undefined &&
|
||
(typeof payload.projectName !== 'string' || payload.projectName.length > 200)
|
||
)
|
||
throw invalid('Invalid project name');
|
||
let repository;
|
||
try {
|
||
repository = new URL(payload.repositoryUrl);
|
||
} catch {
|
||
throw invalid('Invalid repository');
|
||
}
|
||
if (config.remote) {
|
||
if (repository.href !== config.remote) throw invalid('This workspace belongs to another repository');
|
||
} else if (
|
||
repository.origin !== config.origin ||
|
||
repository.username ||
|
||
repository.password ||
|
||
repository.search ||
|
||
repository.hash ||
|
||
PLATFORM_REPOSITORY.exec(repository.pathname)?.[1] !== payload.projectId
|
||
)
|
||
throw invalid('Repository is not the project’s platform repository');
|
||
if (!TOKEN.test(payload.token ?? '')) throw invalid('Invalid token');
|
||
if (!Number.isFinite(Date.parse(payload.expiresAt))) throw invalid('Invalid expiry');
|
||
const author = payload.author;
|
||
if (
|
||
author !== undefined &&
|
||
(!author ||
|
||
typeof author !== 'object' ||
|
||
Object.keys(author).some(key => !['name', 'email'].includes(key)) ||
|
||
!personText(author.name) ||
|
||
!personText(author.email) ||
|
||
!/^[^\s@]+@[^\s@]+$/.test(author.email))
|
||
)
|
||
throw invalid('Invalid author');
|
||
return {
|
||
projectId: payload.projectId,
|
||
projectName: payload.projectName,
|
||
repositoryUrl: repository.href,
|
||
branch: branchName(payload.branch),
|
||
token: payload.token,
|
||
author: author && { name: author.name, email: author.email },
|
||
};
|
||
}
|
||
|
||
/** Quotes a value or subsection name for a Git config file. */
|
||
const quote = value => `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
||
|
||
function runGit(args, { cwd, include } = {}) {
|
||
return new Promise((resolve, reject) => {
|
||
const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never' };
|
||
// Passing the credential file by path keeps the token out of the command line.
|
||
if (include)
|
||
Object.assign(env, { GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'include.path', GIT_CONFIG_VALUE_0: include });
|
||
const child = spawn('git', args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
let stdout = '';
|
||
let stderr = '';
|
||
child.stdout.on('data', chunk => {
|
||
stdout = (stdout + chunk).slice(-65536);
|
||
});
|
||
child.stderr.on('data', chunk => {
|
||
stderr = (stderr + chunk).slice(-2048);
|
||
});
|
||
const timer = setTimeout(() => child.kill('SIGKILL'), 10 * 60_000);
|
||
child.on('error', () => {
|
||
clearTimeout(timer);
|
||
reject(new GitWorkspaceError('GIT_UNAVAILABLE', 'Git is not installed in this workspace'));
|
||
});
|
||
child.on('close', code => {
|
||
clearTimeout(timer);
|
||
if (code === 0) resolve(stdout.trim());
|
||
else reject(new GitWorkspaceError('GIT_FAILED', `git ${args[0]} exited ${code}: ${stderr.trim()}`));
|
||
});
|
||
});
|
||
}
|
||
|
||
async function exists(file) {
|
||
return fs.lstat(file).then(
|
||
() => true,
|
||
error => {
|
||
if (error.code === 'ENOENT') return false;
|
||
throw error;
|
||
},
|
||
);
|
||
}
|
||
|
||
function createGitWorkspace(config, { git = runGit } = {}) {
|
||
const clones = new Map();
|
||
const authors = new Map();
|
||
|
||
async function writeCredential(file, input) {
|
||
// A delivery without an author (for example after the gateway restarted) keeps the last one.
|
||
const author = input.author ?? authors.get(input.projectId);
|
||
if (author) authors.set(input.projectId, author);
|
||
const lines = [
|
||
'# Written by WishForge while the IDE is open; the token expires on its own.',
|
||
`[http ${quote(input.repositoryUrl)}]`,
|
||
`\textraHeader = ${quote(`Authorization: Bearer ${input.token}`)}`,
|
||
...(author ? ['[user]', `\tname = ${quote(author.name)}`, `\temail = ${quote(author.email)}`] : []),
|
||
];
|
||
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
||
const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
|
||
await fs.writeFile(temporary, `${lines.join('\n')}\n`, { mode: 0o600 });
|
||
await fs.rename(temporary, file);
|
||
}
|
||
async function origin(directory) {
|
||
if (!(await exists(path.join(directory, '.git')))) return undefined;
|
||
return git(['config', '--get', 'remote.origin.url'], { cwd: directory }).catch(() => undefined);
|
||
}
|
||
/** An earlier clone keeps working even after the project was renamed or the folder moved. */
|
||
async function findClone(repositoryUrl) {
|
||
if ((await origin(config.root)) === repositoryUrl) return config.root;
|
||
const entries = await fs.readdir(config.root, { withFileTypes: true }).catch(() => []);
|
||
for (const entry of entries.slice(0, 200))
|
||
if (entry.isDirectory() && !entry.name.startsWith('.')) {
|
||
const directory = path.join(config.root, entry.name);
|
||
if ((await origin(directory)) === repositoryUrl) return directory;
|
||
}
|
||
return undefined;
|
||
}
|
||
async function freeDirectory(input) {
|
||
const name =
|
||
(input.projectName ?? '')
|
||
.normalize('NFKC')
|
||
.toLowerCase()
|
||
.replace(/[^\p{L}\p{N}._-]+/gu, '-')
|
||
.replace(/^[-.]+|[-.]+$/g, '')
|
||
.slice(0, 60) || 'project';
|
||
for (const candidate of [name, `${name}-${input.projectId.slice(0, 8)}`]) {
|
||
const directory = path.join(config.root, candidate);
|
||
if (!(await exists(directory))) return directory;
|
||
}
|
||
return undefined;
|
||
}
|
||
/** People commit on ide/work; a plain `git push` publishes it, `git pull origin <target>` updates it. */
|
||
async function startWorkBranch(directory) {
|
||
const published = await git(['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${WORK_BRANCH}`], {
|
||
cwd: directory,
|
||
}).catch(() => '');
|
||
await git(
|
||
published
|
||
? ['switch', '--create', WORK_BRANCH, '--track', `origin/${WORK_BRANCH}`]
|
||
: ['switch', '--create', WORK_BRANCH],
|
||
{ cwd: directory },
|
||
);
|
||
await git(['config', '--local', 'push.default', 'current'], { cwd: directory });
|
||
await git(['config', '--local', 'push.autoSetupRemote', 'true'], { cwd: directory });
|
||
}
|
||
async function includeCredential(directory, file) {
|
||
const included = await git(['config', '--local', '--get-all', 'include.path'], { cwd: directory }).catch(() => '');
|
||
if (!included.split('\n').includes(file))
|
||
await git(['config', '--local', '--add', 'include.path', file], { cwd: directory });
|
||
}
|
||
|
||
return {
|
||
/** Stores the delivered credential and clones the repository when the workspace lacks it. */
|
||
async apply(payload) {
|
||
const input = validate(payload, config);
|
||
const file = path.join(config.credentialDir, `${input.projectId}.gitconfig`);
|
||
await writeCredential(file, input);
|
||
const pending = clones.get(input.repositoryUrl);
|
||
if (pending) return { status: 'cloning', directory: pending.directory, cloning: pending.done };
|
||
const existing = await findClone(input.repositoryUrl);
|
||
if (existing) {
|
||
await includeCredential(existing, file);
|
||
return { status: 'ready', directory: existing };
|
||
}
|
||
const directory = await freeDirectory(input);
|
||
if (!directory) return { status: 'conflict' };
|
||
const done = (async () => {
|
||
await git(['clone', '--origin', 'origin', '--branch', input.branch, '--', input.repositoryUrl, directory], {
|
||
include: file,
|
||
});
|
||
await includeCredential(directory, file);
|
||
await startWorkBranch(directory);
|
||
})().finally(() => clones.delete(input.repositoryUrl));
|
||
clones.set(input.repositoryUrl, { directory, done });
|
||
// A failed clone is retried with the next delivery.
|
||
done.catch(error => console.error(`WishForge could not clone the project: ${error.message}`));
|
||
return { status: 'cloning', directory, cloning: done };
|
||
},
|
||
};
|
||
}
|
||
|
||
module.exports = { CREDENTIAL_PATH, WORK_BRANCH, GitWorkspaceError, readGitWorkspaceConfig, createGitWorkspace };
|