wishforge-ide/apps/worker/test/github-delivery.test.ts
eust-w cce214f8fb feat: close the main loop from wish to integrated commit
Verification ran git inside the tree under test, kept no command output and
treated every infrastructure fault as a test failure; repairs went through an
executor lease the coordinator should not hold; and a project without delivery
could never succeed. This reworks the worker execution path and the control-plane
contracts it depends on.

- Verification exports the exact commit to a directory without .git, installs
  dependencies (network allowed) and runs the protected commands under
  bubblewrap in kata mode or directly in host mode; evidence records exit code,
  duration, digest, a redacted output tail and the isolation used. Production
  rejects host evidence. A failed installation waits as infrastructure.
- Waiting reasons are an enum with a redacted detail; dispatcher, GitHub and
  model-proxy states map onto it, and the console explains each one with a way out.
- Repairs are requested by the coordinator through /internal/runs/:id/repair;
  the control plane derives the failure summary from the verifier's evidence and
  enforces the repair budget. Continuing after the budget is spent grants one more
  round; a new requirement revision starts a fresh budget.
- Execution identities may only move a run within their own stages and only to
  running or waiting; success comes from integration evidence (no delivery
  configured) or deployment acceptance. The unused preview stage is gone.
- Integration fast-forwards when the target has not moved, merges and re-verifies
  otherwise, retries when a push finds the target moved, and turns merge conflicts
  into a repair round that merges the current target for the agent to resolve.
- Successful runs that needed a repair leave a project lesson; active lessons are
  injected into later prompts, and admins can list, add, disable and delete them.
- Executor progress (messages, commands, file changes, plan updates) is stored as
  normalized events; previously agent messages were recorded as the literal word
  "output". Provider failures keep the work as a checkpoint and wait as
  provider_error instead of failing the run.
- Workers declare WF_SANDBOX_MODE=host|kata (host refused in production),
  heartbeat with retries until the lease could have expired, and retry safe
  control-plane reads with backoff.
- tests/local-loop.test.ts runs the loop end to end with real Git, the in-process
  control plane behind its internal routes and a scripted agent.

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

145 lines
5.5 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest';
import type { GitHubDeliveryState, GitHubDeliveryOperation } from '@wishforge/contracts';
import type { PortableCheckpoint } from '@wishforge/runtime';
import { advanceGitHubDelivery, restoreMergedGitHubSource } from '../src/github-delivery.js';
const candidate = 'a'.repeat(40),
base = 'b'.repeat(40),
merged = 'c'.repeat(40);
const operation: GitHubDeliveryOperation = {
id: 'gh-operation',
revision: 1,
status: 'open',
headBranch: `wishforge/run/${candidate}`,
baseBranch: 'main',
expectedHeadSha: candidate,
expectedBaseSha: base,
mergeApproved: false,
mergeAttempted: false,
pullRequestUrl: 'https://github.com/fixture/repo/pull/1',
};
function input(state: GitHubDeliveryState, request = vi.fn()) {
return {
state,
api: { request },
git: { pushReviewBranch: vi.fn(async () => operation.headBranch) },
runId: 'run',
revision: 1,
leaseToken: 1,
repository: '/owned/integration.git',
candidateCommit: candidate,
verifiedCommit: candidate,
expectedBaseCommit: base,
assertIntegrationGate: vi.fn(async () => {}),
refreshGitCredential: vi.fn(async () => {}),
};
}
describe('independent GitHub worker delivery path', () => {
it('never falls back to target-branch push when GitHub is unconfigured', async () => {
const f = input({ required: true, enabled: false, reason: 'GITHUB_UNCONFIGURED' });
expect(await advanceGitHubDelivery(f)).toMatchObject({
kind: 'waiting',
reason: 'github_unconfigured',
detail: 'GITHUB_UNCONFIGURED',
});
expect(f.git.pushReviewBranch).not.toHaveBeenCalled();
expect(f.api.request).not.toHaveBeenCalled();
expect(await advanceGitHubDelivery(input({ required: false, enabled: false }))).toEqual({ kind: 'standard_git' });
});
it('pushes only an immutable run review branch behind the integration gate then waits for approval', async () => {
const events: string[] = [];
const state = { required: true, enabled: true };
const request = vi.fn(async (route: string) => {
events.push(route.endsWith('/create') ? 'create' : 'advance');
return { ...state, operation, reason: 'github_merge_approval' };
});
const f = input(state, request);
f.assertIntegrationGate = vi.fn(async () => {
events.push('gate');
});
f.refreshGitCredential = vi.fn(async () => {
events.push('credential');
});
f.git.pushReviewBranch = vi.fn(async () => {
events.push('review-branch');
return operation.headBranch;
});
expect(await advanceGitHubDelivery(f)).toMatchObject({
kind: 'waiting',
operationId: operation.id,
reason: 'github_review',
detail: expect.stringContaining('github_merge_approval'),
});
expect(events).toEqual(['gate', 'credential', 'review-branch', 'gate', 'create', 'gate', 'advance']);
expect(f.git.pushReviewBranch).toHaveBeenCalledWith({
repository: '/owned/integration.git',
runId: 'run',
candidateCommit: candidate,
verifiedCommit: candidate,
});
});
it('reconciles an existing operation without recreating a review branch or PR', async () => {
const f = input(
{ required: true, enabled: true, operation },
vi.fn(async () => ({
required: true,
enabled: true,
operation: { ...operation, status: 'reverification_required', mergedCommitSha: merged },
})),
);
expect(await advanceGitHubDelivery(f)).toMatchObject({
kind: 'merged',
sourceCommit: merged,
baseCommit: base,
operationId: operation.id,
});
expect(f.git.pushReviewBranch).not.toHaveBeenCalled();
expect(f.api.request).toHaveBeenCalledTimes(1);
expect(f.api.request.mock.calls[0][0]).toMatch(/github\/advance$/);
});
it('requires a fresh human workspace gate before any remote write', async () => {
const f = input({ required: true, enabled: true });
f.assertIntegrationGate = vi.fn(async () => {
throw new Error('human workspace input is stale');
});
await expect(advanceGitHubDelivery(f)).rejects.toThrow('stale');
expect(f.git.pushReviewBranch).not.toHaveBeenCalled();
expect(f.api.request).not.toHaveBeenCalled();
});
it('restores the actual merged SHA into a fresh workspace while preserving the original review base', async () => {
const checkpoint: PortableCheckpoint = {
schemaVersion: 1,
runId: 'run',
provider: 'codex',
sourceCommit: merged,
baseCommit: base,
patch: '',
patchSha256: 'd'.repeat(64),
createdAt: new Date().toISOString(),
};
const git = {
create: vi.fn(async () => ({ workspace: '/owned/merged-fixture', baseCommit: merged })),
checkpoint: vi.fn(async () => checkpoint),
};
const result = await restoreMergedGitHubSource({
git,
repositoryUrl: 'https://github.com/fixture/repo.git',
targetBranch: 'main',
root: '/owned/verifier',
runId: 'run',
provider: 'codex',
merged: { kind: 'merged', sourceCommit: merged, baseCommit: base, operationId: operation.id },
assertIntegrationGate: async () => {},
refreshGitCredential: async () => {},
});
expect(git.create).toHaveBeenCalledWith(
expect.objectContaining({
baseCommit: merged,
targetBranch: 'main',
runId: expect.stringMatching(/^run-merged-/),
}),
);
expect(result).toEqual({ workspace: '/owned/merged-fixture', checkpoint });
expect(git.checkpoint).toHaveBeenCalledWith('/owned/merged-fixture', base, 'run', 'codex');
});
});