eust-w 6722319314 🔒 Weigh a release by everything its environment does not run yet
A release's risk only counted what the target branch gained when the
run integrated. Commits people pushed to the branch directly, and
integrations that were never deployed, went out with the next release
without being classified: an environment preauthorized for automatic
release took a migration or a Dockerfile change pushed straight to the
branch without approval. The POC chose what to rebuild from the same
narrow diff, so worker and coordinator kept running old code; on the
local POC, WishForge had in fact only ever rebuilt the api.

The control plane now gives the verifier the commit of the release the
environment runs, and the classification covers everything between it
and the release, as well as what the integration brought. On the POC,
each deployment records the commit and the image a release put there.
The build plans from that snapshot, the one the release is checked
against: worker and coordinator keep their images only while what they
run differs from the source in web files alone. A component of unknown
source (never deployed by a release, restored by a rollback, or set by
hand, which leaves the annotations stale) is rebuilt, and the release
is marked partial: it needs approval and does not roll back on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 16:44:13 +08:00

731 lines
31 KiB
TypeScript

import { isProduction, plainHttpAllowed } from '@wishforge/contracts';
import { createHash } from 'node:crypto';
import { appendFile, mkdir, mkdtemp, readFile, writeFile, rm, stat } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import { checkedCommand, type Command, type CommandExecutor, executeCommand } from './process.js';
import { RuntimeError, type PortableCheckpoint } from './types.js';
const shaPattern = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
export function requireCommit(value: string): string {
if (!shaPattern.test(value)) throw new RuntimeError('INVALID_COMMIT', 'A full immutable Git SHA is required');
return value;
}
export function safeIdentifier(value: string): string {
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,100}$/.test(value))
throw new RuntimeError('INVALID_IDENTIFIER', 'Unsafe resource identifier');
return value;
}
export function requireBranchName(value: string): string {
if (
!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,159}$/.test(value) ||
value === 'HEAD' ||
value.includes('..') ||
value.split('/').some(part => !part || part.startsWith('.') || part.endsWith('.') || part.endsWith('.lock'))
)
throw new RuntimeError('INVALID_REF', 'A safe branch name, not a revision expression, is required');
return value;
}
function requireTargetRef(value: string): string {
if (!value.startsWith('refs/heads/'))
throw new RuntimeError('INVALID_REF', 'A full refs/heads branch ref is required');
requireBranchName(value.slice('refs/heads/'.length));
return value;
}
export function validateRepositoryUrl(
repository: string,
options: { allowLocalHttp?: boolean; production?: boolean } = {},
): URL {
if (/[\u0000-\u0020\u007f]/.test(repository))
throw new RuntimeError('INVALID_REPOSITORY', 'Repository URL cannot contain whitespace or control characters');
if (/^ssh:/i.test(repository) || /^[^/@:]+@[^/:]+:/.test(repository))
throw new RuntimeError(
'REPOSITORY_TRANSPORT_UNSUPPORTED',
'SSH repository transport is not supported; use an HTTPS repository URL',
);
let url: URL;
try {
url = new URL(repository);
} catch {
throw new RuntimeError('INVALID_REPOSITORY', 'Use an HTTPS repository URL; local paths and SSH are not supported');
}
const localHttp =
options.allowLocalHttp && !(options.production ?? isProduction(process.env)) && plainHttpAllowed(process.env, url);
if ((url.protocol !== 'https:' && !localHttp) || url.username || url.password || url.search || url.hash)
throw new RuntimeError(
'REPOSITORY_POLICY',
'Repository must use HTTPS without inline credentials, query or fragment (explicit loopback development HTTP is supported)',
);
return url;
}
/** Merging a verified change into the target branch conflicted; a repair round has to resolve it. */
export class MergeConflictError extends RuntimeError {
constructor(
readonly paths: string[],
readonly targetCommit: string,
) {
super(
'MERGE_CONFLICT',
`Merging into the target branch conflicts in ${paths.length} file(s): ${paths.slice(0, 20).join(', ')}`,
);
}
}
export interface GitOptions {
credential?: { token: string; repositoryUrl: string; username?: 'x-access-token' };
/** Operator configuration only: a single HTTPS repository may use the host's SSH login in development. */
localSshTransport?: LocalSshTransport;
allowLocalHttp?: boolean;
/** Clone, fetch and push of large repositories can take minutes; local commands finish far sooner. */
timeoutMs?: number;
}
export interface LocalSshTransport {
repositoryUrl: string;
/** Canonical ssh://git@host/owner/repository.git, using the standard SSH port. */
sshUrl: string;
home: string;
}
function validateLocalSshTransport(transport: LocalSshTransport): void {
if (process.env.WF_DEPLOYMENT_MODE !== 'development' || process.env.NODE_ENV === 'production')
throw new RuntimeError(
'LOCAL_SSH_POLICY',
'Local SSH authentication is only available in explicit development mode',
);
const repository = validateRepositoryUrl(transport.repositoryUrl);
let ssh: URL;
try {
ssh = new URL(transport.sshUrl);
} catch {
throw new RuntimeError('LOCAL_SSH_POLICY', 'The operator SSH transport requires a canonical ssh://git@host URL');
}
if (
repository.protocol !== 'https:' ||
repository.port ||
repository.href !== transport.repositoryUrl ||
!/^\/[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9][A-Za-z0-9_.-]*\.git$/.test(repository.pathname) ||
ssh.protocol !== 'ssh:' ||
ssh.username !== 'git' ||
ssh.password ||
(ssh.port && ssh.port !== '22') ||
ssh.hostname !== repository.hostname ||
ssh.pathname !== repository.pathname ||
ssh.search ||
ssh.hash ||
/[\u0000-\u0020\u007f]/.test(transport.sshUrl) ||
!path.isAbsolute(transport.home) ||
/[\u0000-\u001f\u007f]/.test(transport.home)
)
throw new RuntimeError(
'LOCAL_SSH_POLICY',
'Local SSH must use git on port 22 for the exact configured HTTPS host and repository, with an absolute HOME',
);
}
/** Inline checkpoint transport limits (raw bytes); larger changes need durable artifact storage first. */
export const CHECKPOINT_BUNDLE_LIMIT = 4 * 1024 * 1024;
export const CHECKPOINT_PATCH_LIMIT = 4 * 1024 * 1024;
export class GitWorkspace {
constructor(
private readonly execute: CommandExecutor = executeCommand,
private readonly options: GitOptions = {},
) {
if (options.localSshTransport) validateLocalSshTransport(options.localSshTransport);
}
setCredential(credential: GitOptions['credential']) {
this.options.credential = credential;
}
private validateRepository(repository: string) {
const url = validateRepositoryUrl(repository, { allowLocalHttp: this.options.allowLocalHttp });
if (this.options.localSshTransport && repository !== this.options.localSshTransport.repositoryUrl)
throw new RuntimeError('LOCAL_SSH_SCOPE', 'The repository differs from the operator-pinned local SSH transport');
return url;
}
private command(cwd: string, args: string[]): Command {
const authEnv: Record<string, string> = {
GIT_CONFIG_COUNT: '1',
GIT_CONFIG_KEY_0: 'http.followRedirects',
GIT_CONFIG_VALUE_0: 'false',
};
if (this.options.credential) {
this.validateRepository(this.options.credential.repositoryUrl);
authEnv.GIT_CONFIG_COUNT = '2';
authEnv.GIT_CONFIG_KEY_1 = `http.${this.options.credential.repositoryUrl}.extraHeader`;
authEnv.GIT_CONFIG_VALUE_1 =
this.options.credential.username === 'x-access-token'
? `Authorization: Basic ${Buffer.from(`x-access-token:${this.options.credential.token}`).toString('base64')}`
: `Authorization: Bearer ${this.options.credential.token}`;
}
const transport = this.options.localSshTransport;
if (transport) {
validateLocalSshTransport(transport);
const count = Number(authEnv.GIT_CONFIG_COUNT);
authEnv[`GIT_CONFIG_KEY_${count}`] = `url.${transport.sshUrl}.insteadOf`;
authEnv[`GIT_CONFIG_VALUE_${count}`] = transport.repositoryUrl;
authEnv.GIT_CONFIG_COUNT = String(count + 1);
// Use the pinned URL directly: remote.origin.url/pushurl are multi-valued and cannot be
// safely overridden by adding another config value. Workspace config is never authority.
if (['fetch', 'push', 'ls-remote'].includes(args[0] ?? ''))
args = args.map(arg => (arg === 'origin' ? transport.repositoryUrl : arg));
}
return {
executable: 'git',
args: [
'-c',
'core.hooksPath=/dev/null',
'-c',
'core.fsmonitor=false',
'-c',
'commit.gpgsign=false',
'-c',
'user.name=WishForge Agent',
'-c',
'user.email=agent@wishforge.invalid',
...args,
],
cwd,
timeoutMs: this.options.timeoutMs ?? 10 * 60_000,
env: {
PATH: process.env.PATH,
LANG: 'C.UTF-8',
GIT_TERMINAL_PROMPT: '0',
GIT_CONFIG_NOSYSTEM: '1',
GIT_CONFIG_GLOBAL: '/dev/null',
...(transport
? { HOME: transport.home, GIT_SSH_COMMAND: 'ssh -oBatchMode=yes -oStrictHostKeyChecking=yes' }
: {}),
...authEnv,
},
};
}
private git(cwd: string, args: string[]) {
return checkedCommand(this.command(cwd, args), this.execute);
}
/**
* Rewrites an agent workspace's `.git/config` down to a safe allowlist before any trusted git
* command runs in it. The agent has file tools confined to the workspace, so it can plant
* `.git/config` there; git honours repo-local config for every command and no environment
* variable disables it. Left in place, a `filter.*.clean`/`smudge`, `diff.*.command`/`textconv`,
* `merge.*.driver`, `core.sshCommand`/`fsmonitor`/`pager`, `[include]`, or a `url.*.insteadOf`
* transport redirect would run as the worker (the operator, in host mode) during `add`, `diff`,
* `merge` or `bundle`. Command names are the agent's to choose, so `-c` cannot override them;
* the config itself is the lever. Only `core` basics, `remote`, `branch` and `extensions` are
* kept — exactly what a clone needs to fetch, merge and bundle. Applied each time, since a
* paused run's agent can plant again before it resumes.
*/
private async hardenWorkspaceConfig(workspace: string): Promise<void> {
const file = path.join(workspace, '.git', 'config');
const original = await readFile(file, 'utf8').catch(error => {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
throw error;
});
if (original === undefined) return; // A fresh non-repo workspace has no config to abuse.
const keep: Record<string, Set<string> | true> = {
core: new Set([
'repositoryformatversion',
'filemode',
'bare',
'logallrefupdates',
'ignorecase',
'precomposeunicode',
'symlinks',
'quotepath',
]),
remote: new Set(['url', 'fetch', 'pushurl', 'mirror']),
branch: new Set(['remote', 'merge']),
extensions: true,
};
const lines = original.split('\n');
const kept: string[] = [];
let section: string | undefined; // The base section name, lower-cased; undefined drops the key.
for (const raw of lines) {
const line = raw.trim();
const header = /^\[\s*([A-Za-z0-9.-]+)(?:\s+"(?:[^"\\]|\\.)*")?\s*\]$/.exec(line);
if (header) {
const name = header[1]!.toLowerCase();
const allowed = keep[name];
if (allowed) {
section = name;
kept.push(raw);
} else {
section = undefined; // Drop the whole section, its keys included.
}
continue;
}
if (line === '' || line.startsWith('#') || line.startsWith(';')) {
if (section) kept.push(raw);
continue;
}
const key = /^([A-Za-z0-9][A-Za-z0-9-]*)\s*=/.exec(line)?.[1]?.toLowerCase();
const allowed = section ? keep[section] : undefined;
// A continued value (trailing backslash) or a key the section does not allow is dropped.
if (section && allowed && key && (allowed === true || allowed.has(key))) kept.push(raw);
}
const next = `${kept.join('\n').replace(/\n+$/, '')}\n`;
if (next !== original) await writeFile(file, next);
}
private async isAncestor(repository: string, ancestor: string, descendant: string) {
const result = await this.execute(this.command(repository, ['merge-base', '--is-ancestor', ancestor, descendant]));
if (result.exitCode > 1)
throw new RuntimeError(
'COMMAND_FAILED',
`git merge-base exited ${result.exitCode}: ${result.stderr.slice(0, 2000)}`,
);
return result.exitCode === 0;
}
private async conflicts(workspace: string) {
return (await this.git(workspace, ['diff', '--name-only', '--diff-filter=U', '-z'])).split('\0').filter(Boolean);
}
async head(repository: string, ref = 'HEAD'): Promise<string> {
if (ref !== 'HEAD') requireTargetRef(ref);
return requireCommit(await this.git(repository, ['rev-parse', '--verify', `${ref}^{commit}`]));
}
async hasCommit(repository: string, commit: string): Promise<boolean> {
requireCommit(commit);
const result = await this.execute(this.command(repository, ['cat-file', '-e', `${commit}^{commit}`]));
return result.exitCode === 0;
}
async changedPaths(workspace: string, baseCommit: string, sourceCommit: string): Promise<string[]> {
requireCommit(baseCommit);
requireCommit(sourceCommit);
const output = await this.git(workspace, ['diff', '--name-only', '-z', baseCommit, sourceCommit, '--']);
return output.split('\0').filter(Boolean);
}
async initializeIntegration(input: {
repository: string;
originalRepository?: string;
workspace: string;
sourceCommit: string;
baseCommit: string;
targetRef: string;
allowLocalRepository?: boolean;
}): Promise<void> {
requireCommit(input.sourceCommit);
requireCommit(input.baseCommit);
requireTargetRef(input.targetRef);
const { stat } = await import('node:fs/promises');
const exists = await stat(input.repository).then(
() => true,
error => {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
throw error;
},
);
if (!exists) {
await mkdir(path.dirname(input.repository), { recursive: true });
if (input.originalRepository) {
if (!input.allowLocalRepository) this.validateRepository(input.originalRepository);
await this.git(path.dirname(input.repository), [
'clone',
'--bare',
'--',
input.originalRepository,
input.repository,
]);
} else {
await this.git(path.dirname(input.repository), ['init', '--bare', input.repository]);
}
}
if ((await this.git(input.repository, ['rev-parse', '--is-bare-repository'])) !== 'true')
throw new RuntimeError('UNSAFE_PROMOTION', 'Integration repository must be a dedicated bare repository');
if (input.originalRepository) {
// A mirror remote refuses explicit refspecs on push; repositories created by older versions used --mirror.
await this.git(input.repository, ['config', '--bool', 'remote.origin.mirror', 'false']);
// This repository is a cache of the remote: always adopt the remote's current target, even after a force push.
await this.git(input.repository, ['fetch', '--no-tags', 'origin', `+${input.targetRef}:${input.targetRef}`]);
}
await this.git(input.repository, [
'-c',
'protocol.file.allow=always',
'fetch',
'--no-tags',
'--',
input.workspace,
input.sourceCommit,
]);
if (!input.originalRepository && !exists)
await this.git(input.repository, [
'update-ref',
input.targetRef,
input.baseCommit,
'0'.repeat(input.baseCommit.length),
]);
}
async create(input: {
repository?: string;
targetBranch?: string;
/** Start from this branch's head instead of the target branch's. */
sourceBranch?: string;
baseCommit?: string;
root: string;
runId: string;
allowLocalRepository?: boolean;
}): Promise<{ workspace: string; baseCommit: string }> {
safeIdentifier(input.runId);
const targetBranch = requireBranchName(input.targetBranch ?? 'main');
const startBranch = input.sourceBranch === undefined ? targetBranch : requireBranchName(input.sourceBranch);
if (input.baseCommit !== undefined) requireCommit(input.baseCommit);
if (input.repository) {
if (input.allowLocalRepository) {
if (!path.isAbsolute(input.repository) || /[\u0000-\u001f\u007f]/.test(input.repository))
throw new RuntimeError(
'INVALID_REPOSITORY',
'An explicitly owned absolute local repository path is required',
);
} else this.validateRepository(input.repository);
}
await mkdir(input.root, { recursive: true });
const workspace = path.join(input.root, input.runId);
if (input.repository) {
await this.git(input.root, ['clone', '--no-local', '--no-checkout', '--', input.repository, workspace]);
// Explicit recovery SHAs remain immutable. A new run resolves only the
// configured branch's remote-tracking ref, never the remote default HEAD.
const ref = input.baseCommit ?? `refs/remotes/origin/${startBranch}`;
let baseCommit: string;
try {
baseCommit = requireCommit(await this.git(workspace, ['rev-parse', '--verify', `${ref}^{commit}`]));
if (input.baseCommit && baseCommit !== input.baseCommit) throw new Error('Expected the exact commit object');
} catch {
if (input.baseCommit)
throw new RuntimeError(
'CHECKPOINT_COMMIT_UNAVAILABLE',
'The immutable checkpoint commit is absent from the repository; restore its source bundle',
);
if (input.sourceBranch !== undefined)
throw new RuntimeError(
'SOURCE_BRANCH_UNAVAILABLE',
`Branch '${startBranch}' is not in the repository; push it, then continue the run`,
);
throw new RuntimeError(
'TARGET_BRANCH_UNAVAILABLE',
`Configured target branch '${targetBranch}' is absent; no fallback to remote HEAD was used`,
);
}
await this.git(workspace, ['checkout', '-b', `wishforge/${input.runId}`, baseCommit]);
return { workspace, baseCommit };
}
await mkdir(workspace, { recursive: false });
await this.git(workspace, ['init', `--initial-branch=${targetBranch}`]);
await this.git(workspace, ['commit', '--allow-empty', '-m', 'Initialize isolated WishForge workspace']);
return { workspace, baseCommit: requireCommit(await this.git(workspace, ['rev-parse', 'HEAD'])) };
}
async checkpoint(
workspace: string,
baseCommit: string,
runId: string,
provider: string,
sessionId?: string,
): Promise<PortableCheckpoint> {
requireCommit(baseCommit);
// The agent may have planted executable Git config; reduce it to a safe allowlist first.
await this.hardenWorkspaceConfig(workspace);
// Only invoked inside an owned isolated workspace. Never stage the human's checkout.
await this.git(workspace, ['add', '--all']);
const changed = await this.git(workspace, ['diff', '--cached', '--name-only']);
// The agent leaves its work uncommitted; a merge it resolved is recorded even if nothing changed.
const merging =
(await this.execute(this.command(workspace, ['rev-parse', '-q', '--verify', 'MERGE_HEAD']))).exitCode === 0;
if (changed || merging)
await this.git(workspace, ['commit', '-m', `✨ WishForge checkpoint ${safeIdentifier(runId)}`]);
const sourceCommit = requireCommit(await this.git(workspace, ['rev-parse', 'HEAD']));
const diff = await this.execute({
executable: 'git',
args: ['-c', 'core.hooksPath=/dev/null', 'diff', '--binary', '--full-index', baseCommit, sourceCommit, '--'],
cwd: workspace,
env: { PATH: process.env.PATH, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' },
});
if (diff.exitCode !== 0)
throw new RuntimeError('CHECKPOINT_DIFF_FAILED', 'Cannot export portable checkpoint patch');
const patch = diff.stdout;
if (Buffer.byteLength(patch) > CHECKPOINT_PATCH_LIMIT)
throw new RuntimeError('CHECKPOINT_TOO_LARGE', 'The change exceeds the 4 MiB checkpoint patch limit');
// Only the commits after the base travel in the bundle; the verifier fetches the base from the repository.
let bundle: Buffer | undefined;
if (sourceCommit !== baseCommit) {
const temporary = await mkdtemp(path.join(os.tmpdir(), 'wishforge-checkpoint-'));
try {
const file = path.join(temporary, 'checkpoint.bundle');
await this.git(workspace, ['bundle', 'create', file, `${baseCommit}..HEAD`]);
if ((await stat(file)).size > CHECKPOINT_BUNDLE_LIMIT)
throw new RuntimeError('CHECKPOINT_TOO_LARGE', 'The change exceeds the 4 MiB checkpoint bundle limit');
bundle = await readFile(file);
} finally {
await rm(temporary, { recursive: true, force: true });
}
}
return {
schemaVersion: 1,
runId,
provider,
sourceCommit,
baseCommit,
patch,
patchSha256: createHash('sha256').update(patch).digest('hex'),
...(bundle
? {
gitBundleBase64: bundle.toString('base64'),
gitBundleSha256: createHash('sha256').update(bundle).digest('hex'),
}
: {}),
createdAt: new Date().toISOString(),
...(sessionId ? { sessionId } : {}),
};
}
/**
* Rebuilds a checkpoint on the caller's own volume and never trusts executor paths:
* clone the project repository for the base, apply the incremental bundle, then
* check that the resulting tree reproduces the recorded patch exactly.
*/
async restore(input: {
checkpoint: PortableCheckpoint;
root: string;
runId: string;
repository?: string;
allowLocalRepository?: boolean;
}): Promise<{ workspace: string; baseCommit: string }> {
const cp = input.checkpoint;
safeIdentifier(input.runId);
requireCommit(cp.sourceCommit);
requireCommit(cp.baseCommit);
if (cp.schemaVersion !== 1 || createHash('sha256').update(cp.patch).digest('hex') !== cp.patchSha256)
throw new RuntimeError('CHECKPOINT_INVALID', 'Portable patch digest does not match');
if (!input.repository)
throw new RuntimeError(
'CHECKPOINT_UNRESTORABLE',
'Restoring a checkpoint requires the project repository that contains its base commit',
);
const bundle = cp.gitBundleBase64 ? this.decodeBundle(cp) : undefined;
const prepared = await this.create({
repository: input.repository,
baseCommit: bundle ? cp.baseCommit : cp.sourceCommit,
root: input.root,
runId: input.runId,
allowLocalRepository: input.allowLocalRepository,
}).catch(error => {
if (error instanceof RuntimeError && error.code === 'CHECKPOINT_COMMIT_UNAVAILABLE')
throw new RuntimeError(
'CHECKPOINT_BASE_UNAVAILABLE',
'The checkpoint base commit is no longer in the project repository (was the branch force-pushed?)',
);
throw error;
});
const workspace = prepared.workspace;
const temporary = await mkdtemp(path.join(os.tmpdir(), 'wishforge-restore-'));
try {
if (bundle) {
const file = path.join(temporary, 'checkpoint.bundle');
await writeFile(file, bundle, { mode: 0o600 });
await this.git(workspace, ['bundle', 'verify', file]);
await this.git(workspace, ['-c', 'protocol.file.allow=always', 'fetch', '--no-tags', '--', file, 'HEAD']);
await this.git(workspace, ['checkout', '-B', `wishforge/${input.runId}`, cp.sourceCommit]);
}
if ((await this.head(workspace)) !== cp.sourceCommit)
throw new RuntimeError('CHECKPOINT_INVALID', 'Restored source SHA does not match');
const patch = await this.execute({
executable: 'git',
args: [
'-c',
'core.hooksPath=/dev/null',
'diff',
'--binary',
'--full-index',
cp.baseCommit,
cp.sourceCommit,
'--',
],
cwd: workspace,
env: { PATH: process.env.PATH, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' },
});
if (patch.exitCode !== 0 || createHash('sha256').update(patch.stdout).digest('hex') !== cp.patchSha256)
throw new RuntimeError('CHECKPOINT_INVALID', 'Restored Git tree differs from the portable patch');
return { workspace, baseCommit: cp.baseCommit };
} catch (error) {
await rm(workspace, { recursive: true, force: true });
throw error;
} finally {
await rm(temporary, { recursive: true, force: true });
}
}
private decodeBundle(cp: PortableCheckpoint): Buffer {
const encoded = cp.gitBundleBase64!;
if (encoded.length > Math.ceil(CHECKPOINT_BUNDLE_LIMIT / 3) * 4 || !/^[A-Za-z0-9+/]*={0,2}$/.test(encoded))
throw new RuntimeError('CHECKPOINT_INVALID', 'Git bundle is too large or invalid');
const bundle = Buffer.from(encoded, 'base64');
if (createHash('sha256').update(bundle).digest('hex') !== cp.gitBundleSha256)
throw new RuntimeError('CHECKPOINT_INVALID', 'Git bundle digest does not match');
return bundle;
}
/**
* Prepares the commit that will become the target branch. When the target has not moved
* since the verified change was based on it, the candidate is that exact commit and needs
* no second verification; otherwise the change is merged onto the current target.
*/
async createCandidate(input: {
repository: string;
path: string;
targetRef: string;
expectedTargetCommit: string;
sourceCommit: string;
}): Promise<{ commit: string; baseCommit: string; fastForward: boolean }> {
requireCommit(input.expectedTargetCommit);
requireCommit(input.sourceCommit);
requireTargetRef(input.targetRef);
const actual = await this.git(input.repository, ['rev-parse', input.targetRef]);
if (actual !== input.expectedTargetCommit)
throw new RuntimeError('STALE_TARGET', 'Integration target changed; regenerate and revalidate the candidate');
if (await this.isAncestor(input.repository, actual, input.sourceCommit))
return { commit: input.sourceCommit, baseCommit: actual, fastForward: true };
await this.git(input.repository, ['worktree', 'add', '--detach', input.path, actual]);
const merge = await this.execute(
this.command(input.path, [
'merge',
'--no-ff',
...(this.options.localSshTransport
? ['-m', `✨ Integrate verified WishForge commit ${input.sourceCommit.slice(0, 12)}`]
: ['--no-edit']),
input.sourceCommit,
]),
);
if (merge.exitCode !== 0) {
const conflicts = await this.conflicts(input.path).catch(() => []);
await this.removeWorktree(input.repository, input.path);
if (conflicts.length) throw new MergeConflictError(conflicts, actual);
throw new RuntimeError('MERGE_FAILED', `git merge exited ${merge.exitCode}: ${merge.stderr.slice(0, 2000)}`);
}
return {
commit: requireCommit(await this.git(input.path, ['rev-parse', 'HEAD'])),
baseCommit: actual,
fastForward: false,
};
}
async removeWorktree(repository: string, worktree: string) {
await this.git(repository, ['worktree', 'remove', '--force', worktree]).catch(() => undefined);
await rm(worktree, { recursive: true, force: true });
}
/**
* Starts merging the current target branch into a restored workspace, for a repair round
* after an integration conflict. Conflicts stay in the working tree for the agent to resolve;
* the next checkpoint commits the merge.
*/
async mergeTarget(workspace: string, targetBranch: string): Promise<{ targetCommit: string; conflicts: string[] }> {
requireBranchName(targetBranch);
// The merge, and its attribute-selected merge drivers, must not run config the agent planted.
await this.hardenWorkspaceConfig(workspace);
const targetCommit = requireCommit(
await this.git(workspace, ['rev-parse', '--verify', `refs/remotes/origin/${targetBranch}^{commit}`]),
);
const merge = await this.execute(this.command(workspace, ['merge', '--no-ff', '--no-edit', targetCommit]));
if (merge.exitCode === 0) return { targetCommit, conflicts: [] };
const conflicts = await this.conflicts(workspace);
if (!conflicts.length)
throw new RuntimeError('MERGE_FAILED', `git merge exited ${merge.exitCode}: ${merge.stderr.slice(0, 2000)}`);
return { targetCommit, conflicts };
}
/** Keeps what dependency installation created (node_modules, virtualenvs) out of checkpoints. */
async excludeUntracked(workspace: string): Promise<string[]> {
const entries = (
await this.git(workspace, [
'ls-files',
'--others',
'--exclude-standard',
'--directory',
'--no-empty-directory',
'-z',
])
)
.split('\0')
.filter(Boolean);
if (entries.length) {
const file = path.join(workspace, '.git', 'info', 'exclude');
await mkdir(path.dirname(file), { recursive: true });
// Anchored, with glob characters escaped, so each line matches exactly the installed path.
await appendFile(file, `${entries.map(entry => `/${entry.replace(/[\\*?[\]!#]/g, '\\$&')}`).join('\n')}\n`);
}
return entries;
}
async promoteVerifiedCandidate(input: {
repository: string;
targetRef: string;
expectedTargetCommit: string;
candidateCommit: string;
verifiedCommit: string;
}): Promise<void> {
requireCommit(input.expectedTargetCommit);
requireCommit(input.candidateCommit);
if (input.candidateCommit !== input.verifiedCommit)
throw new RuntimeError('UNVERIFIED_CANDIDATE', 'Validation must refer to the exact candidate SHA');
requireTargetRef(input.targetRef);
const bare = await this.git(input.repository, ['rev-parse', '--is-bare-repository']);
if (bare !== 'true')
throw new RuntimeError('UNSAFE_PROMOTION', 'Atomic promotion requires a dedicated bare integration repository');
await this.git(input.repository, [
'update-ref',
input.targetRef,
input.candidateCommit,
input.expectedTargetCommit,
]);
}
async pushVerifiedCandidate(input: {
repository: string;
targetRef: string;
expectedTargetCommit: string;
candidateCommit: string;
verifiedCommit: string;
}): Promise<void> {
requireCommit(input.expectedTargetCommit);
requireCommit(input.candidateCommit);
if (input.candidateCommit !== input.verifiedCommit)
throw new RuntimeError('UNVERIFIED_CANDIDATE', 'Only the exact verified candidate can be pushed');
requireTargetRef(input.targetRef);
await this.git(input.repository, [
'merge-base',
'--is-ancestor',
input.expectedTargetCommit,
input.candidateCommit,
]);
const push = await this.execute(
this.command(input.repository, [
'push',
'--porcelain',
`--force-with-lease=${input.targetRef}:${input.expectedTargetCommit}`,
'origin',
`${input.candidateCommit}:${input.targetRef}`,
]),
);
if (push.exitCode === 0) return;
// The remote branch moved after the candidate was prepared: integrate onto the new tip.
if (/stale info|\[rejected\]|non-fast-forward|fetch first/i.test(`${push.stdout}\n${push.stderr}`))
throw new RuntimeError('STALE_TARGET', 'The target branch moved during integration');
throw new RuntimeError('COMMAND_FAILED', `git push exited ${push.exitCode}: ${push.stderr.slice(0, 2000)}`);
}
/** GitHub review path can only create/reconcile an immutable run-owned branch. */
async pushReviewBranch(input: {
repository: string;
runId: string;
candidateCommit: string;
verifiedCommit: string;
}): Promise<string> {
safeIdentifier(input.runId);
requireCommit(input.candidateCommit);
if (input.candidateCommit !== input.verifiedCommit)
throw new RuntimeError('UNVERIFIED_CANDIDATE', 'Review branch must contain the independently verified candidate');
const branch = requireBranchName(`wishforge/${input.runId}/${input.candidateCommit}`),
ref = `refs/heads/${branch}`;
const existing = await this.git(input.repository, ['ls-remote', '--refs', 'origin', ref]);
if (existing) {
if (existing !== `${input.candidateCommit}\t${ref}`)
throw new RuntimeError(
'REVIEW_BRANCH_CONFLICT',
'Existing review branch has different content; it was not overwritten',
);
return branch;
}
await this.git(input.repository, [
'push',
`--force-with-lease=${ref}:`,
'origin',
`${input.candidateCommit}:${ref}`,
]);
return branch;
}
}