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>
This commit is contained in:
eust-w 2026-10-19 19:17:14 +08:00
parent 6d2dcebe65
commit 0bcfbc13dd
32 changed files with 547 additions and 70 deletions

View File

@ -304,6 +304,15 @@ export class ControlPlane {
this.validateKey(key);
return this.store.transaction(actor.tenantId, async tx => {
const project = await projectAccess(tx, actor, projectId);
if (
data.sourceBranch &&
(data.sourceBranch === project.targetBranch || data.sourceBranch.startsWith('wishforge/'))
)
throw new DomainError(
'INVALID_SOURCE_BRANCH',
'Start from another branch than the target branch, for example one pushed from the IDE',
400,
);
return idempotent(tx, `wish:${actor.userId}:${projectId}:${key ?? ''}`, { projectId, ...data }, async () => {
const tenant = await tx.tenant();
const runs = await tx.list<Run>('run');

View File

@ -1,5 +1,8 @@
import { DomainError, type Actor, type Project, type Run, isProduction } from '@wishforge/contracts';
/** IDE workspaces push here; a wish starting from such a branch verifies and merges it. */
export const IDE_BRANCH_PREFIX = 'ide/';
/** Only the trusted control plane can provision repositories or mint repository-scoped access. */
export class GitStorage {
constructor(
@ -45,8 +48,8 @@ export class GitStorage {
});
}
/**
* Write access for people editing in the project's IDE workspace, like any Git client of the
* repository: pushes are fast-forward only and land on the branch the next wish starts from.
* Write access for people editing in the project's IDE workspace. The Git service lets it
* update `ide/` branches only: the target branch changes through verified wishes alone.
*/
workspaceCredential(project: Project) {
if (project.repositoryStorage !== 'platform' || !project.repositoryUrl)
@ -60,8 +63,19 @@ export class GitStorage {
projectId: project.id,
permission: 'write',
ttlSeconds: 900,
refPrefix: `refs/heads/${IDE_BRANCH_PREFIX}`,
});
}
/** The branches people pushed from the IDE, most recent first. */
async ideBranches(project: Project) {
if (project.repositoryStorage !== 'platform' || !project.repositoryUrl || !this.configured()) return [];
const listed = await this.request<{ branches: { name: string; commit: string; updatedAt: string }[] }>('/refs', {
tenantId: project.tenantId,
projectId: project.id,
prefix: `refs/heads/${IDE_BRANCH_PREFIX}`,
});
return listed.branches;
}
async credential(actor: Actor, project: Project, run: Run) {
if (
project.repositoryStorage !== 'platform' ||

View File

@ -512,6 +512,10 @@ export class ApiController {
res.type('text/csv').setHeader('Content-Disposition', `attachment; filename="${exported.filename}"`);
res.send(exported.content);
}
@Get('projects/:id/branches') async branches(@Req() r: AuthRequest, @Param('id') id: string) {
const project = await this.s.control.store.read(r.actor.tenantId, tx => projectAccess(tx, r.actor, id));
return ok(await new GitStorage(this.s.control.env).ideBranches(project));
}
@Get('projects/:id/workspaces') async workspaces(@Req() r: AuthRequest, @Param('id') id: string) {
return ok(
await this.s.control.store.read(r.actor.tenantId, async tx => {

View File

@ -1,7 +1,7 @@
import { isProduction } from '@wishforge/contracts';
import { createHmac, timingSafeEqual } from 'node:crypto';
import { spawn } from 'node:child_process';
import { mkdir, open, realpath, stat, unlink } from 'node:fs/promises';
import { mkdir, open, realpath, rename, stat, unlink, writeFile } from 'node:fs/promises';
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import path from 'node:path';
import { checkedCommand, RuntimeError, safeIdentifier, requireBranchName } from '@wishforge/runtime';
@ -22,6 +22,74 @@ export interface GitClaims {
iat: number;
exp: number;
runId?: string;
/** Pushes may only update refs under this prefix: an IDE workspace pushes `refs/heads/ide/*`. */
refPrefix?: string;
}
const REF_PREFIX = /^refs\/heads\/[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/$/;
const gitEnv = () => ({
PATH: process.env.PATH,
LANG: 'C.UTF-8',
GIT_CONFIG_GLOBAL: '/dev/null',
GIT_CONFIG_NOSYSTEM: '1',
GIT_AUTHOR_NAME: 'WishForge',
GIT_AUTHOR_EMAIL: 'platform@wishforge.invalid',
GIT_COMMITTER_NAME: 'WishForge',
GIT_COMMITTER_EMAIL: 'platform@wishforge.invalid',
});
/**
* Every push runs this hook. A credential scoped to a ref prefix cannot update anything else,
* so people's pushes from the IDE reach the target branch only through a verified wish.
*/
export const PRE_RECEIVE_HOOK = [
'#!/bin/sh',
'[ -z "$WISHFORGE_REF_PREFIX" ] && exit 0',
'while read -r old new ref; do',
' case "$ref" in',
' "$WISHFORGE_REF_PREFIX"*) ;;',
' *)',
' branch="${WISHFORGE_REF_PREFIX#refs/heads/}"',
' echo "WishForge:这个凭据只能推送 $branch 开头的分支,已拒绝 $ref。" >&2',
' echo "WishForge:请推送到 $branch 开头的分支,再提交一个从该分支开始的愿望,由它验证并合入。" >&2',
' exit 1',
' ;;',
' esac',
'done',
'',
].join('\n');
/** Writes the platform hook; returns the directory pushes use as core.hooksPath. */
export async function installHooks(root: string) {
const directory = path.join(root, '.hooks');
await mkdir(directory, { recursive: true, mode: 0o700 });
const hook = path.join(directory, 'pre-receive');
await writeFile(`${hook}.tmp`, PRE_RECEIVE_HOOK, { mode: 0o700 });
await rename(`${hook}.tmp`, hook);
return directory;
}
/** The branches under a prefix, most recently committed first. */
export async function branchesIn(repository: string, prefix: string) {
if (!REF_PREFIX.test(prefix)) throw new RuntimeError('INVALID_REF', 'Use a branch prefix like refs/heads/ide/');
const output = await checkedCommand({
executable: 'git',
args: [
'-c',
'core.hooksPath=/dev/null',
'for-each-ref',
'--sort=-committerdate',
'--count=200',
'--format=%(refname)%09%(objectname)%09%(committerdate:iso-strict)',
prefix,
],
cwd: repository,
env: gitEnv(),
});
return output
.split('\n')
.filter(Boolean)
.map(line => {
const [ref, commit, updatedAt] = line.split('\t');
return { name: ref!.slice('refs/heads/'.length), commit: commit!, updatedAt: updatedAt! };
});
}
function sameSecret(a: string, b: string) {
const x = Buffer.from(a),
@ -60,6 +128,7 @@ export function verifyGitToken(
!['read', 'write'].includes(claims.permission) ||
!Number.isInteger(claims.exp) ||
!Number.isInteger(claims.iat) ||
(claims.refPrefix !== undefined && (typeof claims.refPrefix !== 'string' || !REF_PREFIX.test(claims.refPrefix))) ||
claims.exp <= now ||
claims.iat > now + 30 ||
claims.exp - claims.iat > 900
@ -103,18 +172,9 @@ export async function createGitService(config: GitServiceConfig) {
);
await mkdir(config.root, { recursive: true, mode: 0o700 });
const root = await realpath(config.root);
const gitEnv = {
PATH: process.env.PATH,
LANG: 'C.UTF-8',
GIT_CONFIG_GLOBAL: '/dev/null',
GIT_CONFIG_NOSYSTEM: '1',
GIT_AUTHOR_NAME: 'WishForge',
GIT_AUTHOR_EMAIL: 'platform@wishforge.invalid',
GIT_COMMITTER_NAME: 'WishForge',
GIT_COMMITTER_EMAIL: 'platform@wishforge.invalid',
};
const hooks = await installHooks(root);
const git = (cwd: string, args: string[], input?: string) =>
checkedCommand({ executable: 'git', args: ['-c', 'core.hooksPath=/dev/null', ...args], cwd, input, env: gitEnv });
checkedCommand({ executable: 'git', args: ['-c', 'core.hooksPath=/dev/null', ...args], cwd, input, env: gitEnv() });
const location = async (tenantId: string, projectId: string) => {
safeIdentifier(tenantId);
safeIdentifier(projectId);
@ -137,7 +197,7 @@ export async function createGitService(config: GitServiceConfig) {
json(response, 200, { status: 'ok', service: 'git-storage' });
return;
}
if (['/repos', '/tokens'].includes(url.pathname) && request.method === 'POST') {
if (['/repos', '/tokens', '/refs'].includes(url.pathname) && request.method === 'POST') {
const auth = request.headers.authorization ?? '';
if (!auth.startsWith('Bearer ') || !sameSecret(auth.slice(7), config.adminToken)) {
json(response, 401, { error: 'UNAUTHORIZED' });
@ -195,8 +255,13 @@ export async function createGitService(config: GitServiceConfig) {
await lock.close();
await unlink(lockPath);
}
} else if (url.pathname === '/refs') {
await stat(repository);
json(response, 200, { branches: await branchesIn(repository, String(body.prefix ?? '')) });
} else {
await stat(repository);
if (body.refPrefix !== undefined && (typeof body.refPrefix !== 'string' || !REF_PREFIX.test(body.refPrefix)))
throw new RuntimeError('INVALID_REF', 'refPrefix must look like refs/heads/<name>/');
if (body.permission !== 'read' && body.permission !== 'write')
throw new RuntimeError('INVALID_PERMISSION', 'Git permission must be read or write');
const ttl = Number(body.ttlSeconds ?? 300);
@ -211,6 +276,7 @@ export async function createGitService(config: GitServiceConfig) {
iat: issued,
exp: issued + ttl,
...(typeof body.runId === 'string' ? { runId: safeIdentifier(body.runId) } : {}),
...(typeof body.refPrefix === 'string' ? { refPrefix: body.refPrefix } : {}),
};
json(response, 200, {
token: issueGitToken(claims, config.tokenSecret),
@ -253,7 +319,12 @@ export async function createGitService(config: GitServiceConfig) {
await stat(repository);
const child = spawn('git', ['http-backend'], {
env: {
...gitEnv,
...gitEnv(),
// Pushes run the platform hook (and nothing a repository could carry itself).
GIT_CONFIG_COUNT: '1',
GIT_CONFIG_KEY_0: 'core.hooksPath',
GIT_CONFIG_VALUE_0: hooks,
...(claims.refPrefix ? { WISHFORGE_REF_PREFIX: claims.refPrefix } : {}),
GIT_PROJECT_ROOT: root,
GIT_HTTP_EXPORT_ALL: '1',
PATH_INFO: `/${tenantId}/${projectId}.git/${operation}`,

View File

@ -0,0 +1,61 @@
import { it, expect } from 'vitest';
import { execFile } from 'node:child_process';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { promisify } from 'node:util';
import { branchesIn, installHooks, issueGitToken, verifyGitToken } from '../src/service.js';
// Runs without opening a port: the push goes over Git's local transport, which runs the same hook.
const run = promisify(execFile);
const git = (cwd: string, args: string[], env: Record<string, string> = {}) =>
run('git', ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', ...args], {
cwd,
env: { ...process.env, ...env },
}).then(result => result.stdout.trim());
it('lets a credential scoped to ide/ push only ide/ branches, and lists them', async () => {
const root = await mkdtemp(path.join(os.tmpdir(), 'wishforge-git-hooks-'));
try {
const hooks = await installHooks(root);
const repository = path.join(root, 'project.git');
await git(root, ['init', '--quiet', '--bare', '--initial-branch=main', repository]);
// Over HTTP the service sets core.hooksPath for each request; a local push reads it from the repository.
await git(repository, ['config', 'core.hooksPath', hooks]);
const clone = path.join(root, 'clone');
await git(root, ['clone', '--quiet', repository, clone]);
await writeFile(path.join(clone, 'a.txt'), 'a\n');
await git(clone, ['add', 'a.txt']);
await git(clone, ['commit', '--quiet', '-m', 'A']);
// Without a scope (the platform's own integration pushes) any branch may be updated.
await git(clone, ['push', '--quiet', 'origin', 'HEAD:refs/heads/main']);
const integrated = await git(repository, ['rev-parse', 'main']);
await writeFile(path.join(clone, 'b.txt'), 'b\n');
await git(clone, ['add', 'b.txt']);
await git(clone, ['commit', '--quiet', '-m', 'B']);
const ide = { WISHFORGE_REF_PREFIX: 'refs/heads/ide/' };
await expect(git(clone, ['push', 'origin', 'HEAD:refs/heads/main'], ide)).rejects.toThrow(
/只能推送 ide\/ 开头的分支/,
);
expect(await git(repository, ['rev-parse', 'main'])).toBe(integrated);
await git(clone, ['push', '--quiet', 'origin', 'HEAD:refs/heads/ide/work'], ide);
expect(await branchesIn(repository, 'refs/heads/ide/')).toEqual([
{ name: 'ide/work', commit: await git(clone, ['rev-parse', 'HEAD']), updatedAt: expect.any(String) },
]);
await expect(branchesIn(repository, 'refs/heads/')).rejects.toMatchObject({ code: 'INVALID_REF' });
} finally {
await rm(root, { recursive: true, force: true });
}
});
it('carries the push scope in the signed token and refuses a malformed one', () => {
const secret = 's'.repeat(32);
const claims = { aud: 'wishforge-git' as const, tenantId: 't', projectId: 'p', permission: 'write' as const };
const scoped = issueGitToken({ ...claims, iat: 100, exp: 400, refPrefix: 'refs/heads/ide/' }, secret);
expect(verifyGitToken(scoped, secret, { tenantId: 't', projectId: 'p', write: true }, 200).refPrefix).toBe(
'refs/heads/ide/',
);
const broad = issueGitToken({ ...claims, iat: 100, exp: 400, refPrefix: 'refs/heads/' }, secret);
expect(() => verifyGitToken(broad, secret, { tenantId: 't', projectId: 'p', write: true }, 200)).toThrow();
});

View File

@ -1,4 +1,6 @@
import { it, expect, vi } from 'vitest';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { mkdtemp, rm, writeFile, symlink, mkdir } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
@ -107,6 +109,40 @@ it('provisions a real bare repository and serves authenticated clone/CAS push ov
const afterPush = await post('/repos', { tenantId: 'tenant', projectId: 'project', defaultBranch: 'other' });
expect(afterPush.defaultBranch).toBe('release/v1');
expect(afterPush.initialCommit).toBe(checkpoint.sourceCommit);
// An IDE credential pushes ide/ branches only; a wish verifies and merges them.
const ide = await post('/tokens', {
tenantId: 'tenant',
projectId: 'project',
permission: 'write',
refPrefix: 'refs/heads/ide/',
});
const run = promisify(execFile);
const inClone = (...args: string[]) =>
run(
'git',
[
'-c',
`http.${repositoryUrl}.extraHeader=Authorization: Bearer ${ide.token!}`,
'-c',
'user.name=Fixture',
'-c',
'user.email=fixture@example.invalid',
...args,
],
{ cwd: second.workspace },
);
await writeFile(path.join(second.workspace, 'ide.txt'), 'from the IDE\n');
await inClone('add', 'ide.txt');
await inClone('commit', '-m', 'Edit in the IDE');
await expect(inClone('push', repositoryUrl, 'HEAD:refs/heads/release/v1')).rejects.toThrow(/ide\//);
await inClone('push', repositoryUrl, 'HEAD:refs/heads/ide/work');
const branches = await post('/refs', { tenantId: 'tenant', projectId: 'project', prefix: 'refs/heads/ide/' });
expect(branches.branches).toEqual([
{ name: 'ide/work', commit: (await inClone('rev-parse', 'HEAD')).stdout.trim(), updatedAt: expect.any(String) },
]);
expect((await post('/repos', { tenantId: 'tenant', projectId: 'project' })).initialCommit).toBe(
checkpoint.sourceCommit,
);
const unsafe = await fetch(`${base}/repos`, {
method: 'POST',
headers: { authorization: `Bearer ${admin}`, 'content-type': 'application/json' },

View File

@ -25,12 +25,14 @@ npm run ide:build
npm run dev:ide
```
`dev:ide` 启动 Theia(`http://127.0.0.1:4300`,只能经网关访问)与网关(`http://127.0.0.1:4400`),所有工作区共用 `.wishforge/ide-workspace` 目录,每个项目克隆到其中以项目命名的文件夹,仓库令牌放在 `.wishforge/ide-credentials`。原生模块的编译需要 Python、make/C++ 与系统开发库(Linux 依赖见 `Dockerfile`)。
`dev:ide` 启动 Theia(`http://127.0.0.1:4300`,只能经网关访问)与网关(`http://127.0.0.1:4400`),所有工作区共用 `.wishforge/ide-workspace` 目录,每个项目克隆到其中以项目命名的文件夹(工作分支 `ide/work`),仓库令牌放在 `.wishforge/ide-credentials`。原生模块的编译需要 Python、make/C++ 与系统开发库(Linux 依赖见 `Dockerfile`)。
在项目页创建开发环境后点击「打开 IDE」。
- **克隆**:平台托管仓库的项目第一次打开时,目标分支会被克隆到以项目命名的文件夹,通常几秒内出现在资源管理器中。外部仓库(如 GitHub)不克隆,那里的改动应走 PR。
- **推送**:在 IDE 中提交并推送到目标分支,之后提交的愿望从这个 commit 开始。平台 Git 只接受快进推送;Agent 先合入了,就先拉取再推送。
- **克隆**:平台托管仓库的项目第一次打开时会被克隆到以项目命名的文件夹,通常几秒内出现在资源管理器中,并处在 `ide/work` 分支上。外部仓库(如 GitHub)不克隆,那里的改动应走 PR。
- **推送**:提交后直接 `git push`(或 Git 面板的「发布分支」),推送到 `ide/work`。也可以建其他 `ide/` 开头的分支;推送目标分支或其他分支会被平台 Git 拒绝。
- **合入**:在项目页的 IDE 分支列表点「提交愿望合入」,或提交愿望时把「起点」选成这个分支。运行从分支的最新提交开始,Agent 在上面继续实现,验证通过后一并合入目标分支;验证失败时照常进入修复轮。
- **同步**:Agent 合入了新的改动后,用 `git pull origin <目标分支>` 把它们拉进 `ide/work`。
- **凭据**:会话期间网关持续送来 15 分钟的仓库令牌,存放在仓库之外(见 [policy/README.md](policy/README.md))。没有人打开 IDE 时令牌会过期,`git push` 也随之失败。
- **提交身份**:取最近打开会话的用户,用 `git config user.name`、`git config user.email` 可以改成自己的。

View File

@ -30,7 +30,7 @@
## 仓库凭据
- **申请**:会话建立时,以及打开的 WebSocket 复核时令牌快到期(剩 5 分钟),网关以会话用户的身份调用 API `POST /internal/workspaces/:id/git-credential`,取得 15 分钟的仓库写令牌。
- **申请**:会话建立时,以及打开的 WebSocket 复核时令牌快到期(剩 5 分钟),网关以会话用户的身份调用 API `POST /internal/workspaces/:id/git-credential`,取得 15 分钟的仓库令牌。这个令牌只能推送 `ide/` 开头的分支,由平台 Git 执行这条限制。
- **投递**:网关把令牌交给工作区的 `POST /wishforge-internal/git-credential`,并附带 Theia 的连接令牌(没有就先请求一次 Theia 首页取得;Theia 重启后会自动重新取得)。投递内容还包括项目、仓库地址、目标分支和提交身份。
- **提交身份**:取最近建立的会话用户,来自 API 首次授权时按 OIDC name/email 给出的 `author`。
- **失败与例外**:失败时 30 秒后重试。外部仓库的项目 API 返回 409;工作区没有配置仓库时 Theia 返回 404。这两种情况在 30 分钟内不再申请,重新打开 IDE 会立即再试。

View File

@ -8,7 +8,8 @@
- **访问控制**:要求 Theia 的连接令牌,这个令牌只有网关持有。
- **校验**:请求必须严格符合格式,仓库地址必须与工作区配置一致。provisioner 设置 `WISHFORGE_GIT_REMOTE` 时只接受这一个仓库;本地共享的 Theia 设置 `WISHFORGE_GIT_ORIGIN`,接受这个 Git 服务上属于所投递项目的仓库。
- **令牌存放**:写入 `WISHFORGE_GIT_CREDENTIAL_DIR` 下的 `<项目>.gitconfig`(权限 0600,内容是 `http.<仓库>.extraHeader` 与提交身份),克隆通过 `include.path` 引用它。令牌不进入命令行、仓库文件或 `.git/config`;Kubernetes 中这个目录是内存卷。
- **克隆**:工作区中还没有该仓库的克隆时,把目标分支克隆到以项目命名的文件夹。同名文件夹已被占用时在名称后加上项目 ID 的前 8 位,两者都被占用时不克隆,从不覆盖已有文件。之后的投递只刷新令牌,项目改名后仍沿用原来的克隆。
- **克隆**:工作区中还没有该仓库的克隆时,把项目克隆到以项目命名的文件夹。同名文件夹已被占用时在名称后加上项目 ID 的前 8 位,两者都被占用时不克隆,从不覆盖已有文件。之后的投递只刷新令牌,项目改名后仍沿用原来的克隆。
- **工作分支**:克隆后切换到 `ide/work`(远端已有这个分支时跟踪它,否则从目标分支创建),并设置 `push.default=current` 与 `push.autoSetupRemote=true`,这样不带参数的 `git push` 就会发布这个分支。令牌只能推送 `ide/` 开头的分支。
- **身份覆盖**:用户自己设置的 `git config user.name` / `user.email` 优先于平台给的身份。
IDE 与 Agent 之间只通过 Git commit 交接,扩展不提供保存屏障、草稿恢复或调试控制租约。
@ -19,7 +20,7 @@ IDE 与 Agent 之间只通过 Git commit 交接,扩展不提供保存屏障、
node --test apps/ide/policy/test/*.test.cjs
```
测试覆盖插件安装接口被拒绝、白名单内容摘要校验与符号链接拒绝,以及用真实 Git 验证仓库的克隆、令牌刷新、提交身份、推送到目标分支、不覆盖已有文件夹和拒绝其他仓库。需要先安装 IDE 依赖(`npm run ide:install`);`npm run test:ide` 会一并运行。
测试覆盖插件安装接口被拒绝、白名单内容摘要校验与符号链接拒绝,以及用真实 Git 验证仓库的克隆、令牌刷新、提交身份、工作分支的发布与继续、不覆盖已有文件夹和拒绝其他仓库。需要先安装 IDE 依赖(`npm run ide:install`);`npm run test:ide` 会一并运行。
## 边界

View File

@ -1,14 +1,16 @@
'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 `git pull` and
// `git push` work like with any Git server and nothing secret lands in the repository or its
// .git/config. The first delivery clones the target branch into a folder named after the project.
// 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$/;
@ -186,6 +188,20 @@ function createGitWorkspace(config, { git = runGit } = {}) {
}
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))
@ -212,6 +228,7 @@ function createGitWorkspace(config, { git = runGit } = {}) {
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.
@ -221,4 +238,4 @@ function createGitWorkspace(config, { git = runGit } = {}) {
};
}
module.exports = { CREDENTIAL_PATH, GitWorkspaceError, readGitWorkspaceConfig, createGitWorkspace };
module.exports = { CREDENTIAL_PATH, WORK_BRANCH, GitWorkspaceError, readGitWorkspaceConfig, createGitWorkspace };

View File

@ -81,20 +81,29 @@ test('later deliveries only refresh the token, even after the project was rename
assert.equal(git(result.directory, 'config', '--get-all', 'include.path').split('\n').length, 1);
});
test('commits made in the workspace push to the target branch, and people can set their own identity', async t => {
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', 'origin', 'main');
git(directory, 'push', '--quiet');
assert.equal(
git(f.source, 'log', '-1', '--format=%an <%ae> %s', 'main'),
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 => {

View File

@ -1002,6 +1002,23 @@ button {
.workspace-list {
padding: 0 22px 20px;
}
.branch-list {
list-style: none;
margin: 0;
padding: 0 22px 16px;
}
.branch-list li {
display: flex;
align-items: center;
gap: 10px;
font-size: 12px;
padding: 8px 0;
border-bottom: 1px solid #edf1f5;
}
.branch-list li > span {
color: var(--muted);
flex: 1;
}
.workspace-row {
display: flex;
align-items: center;

View File

@ -4,7 +4,7 @@ import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { ArrowRight, ArrowUpRight, FolderGit2, GitBranch, Laptop, Plus, Search, Settings2 } from 'lucide-react';
import { formatTime, messageOf, mutateApi, safeUrl, useResource } from '@/lib/api';
import type { Project, Run, Workspace } from '@/lib/types';
import type { IdeBranch, Project, Run, Workspace } from '@/lib/types';
import {
Button,
ButtonLink,
@ -168,6 +168,7 @@ export function ProjectView({ id }: { id: string }) {
const projects = useResource<Project[]>('/projects');
const runs = useResource<Run[]>(`/runs?project=${id}`, 10000);
const workspaces = useResource<Workspace[]>(`/projects/${id}/workspaces`, 10000);
const branches = useResource<IdeBranch[]>(`/projects/${id}/branches`, 30000);
const projectResource = useResource<Project>(`/projects/${id}`);
const project = projectResource.data ?? projects.data?.find(item => item.id === id);
const [showSettings, setShowSettings] = useState(false);
@ -288,8 +289,25 @@ export function ProjectView({ id }: { id: string }) {
</Panel>
<Panel title="云 IDE" aside={<Laptop size={19} />}>
<p className="panel-intro">
在 IDE 中修改后提交并推送到 {project.targetBranch};之后提交的愿望从最新的代码开始。
在 IDE 中提交并推送到 <code>ide/</code> 开头的分支(默认 <code>ide/work</code>),再从该分支提交愿望:
验证通过后连同 Agent 的改动一起合入 {project.targetBranch}。
</p>
{branches.data?.length ? (
<ul className="branch-list">
{branches.data.map(branch => (
<li key={branch.name}>
<GitBranch size={15} />
<code>{branch.name}</code>
<span>
{branch.commit.slice(0, 7)} · {formatTime(branch.updatedAt)}
</span>
<ButtonLink secondary href={`/runs/new?project=${id}&branch=${encodeURIComponent(branch.name)}`}>
提交愿望合入
</ButtonLink>
</li>
))}
</ul>
) : null}
{workspaces.data?.length ? (
<div className="workspace-list">
{workspaces.data.map(workspace => (

View File

@ -21,6 +21,7 @@ import { formatTime, messageOf, mutateApi, safeUrl, shortId, useResource } from
import type {
CommandEvidence,
Evidence,
IdeBranch,
RunArtifacts,
RunDelivery,
Project,
@ -130,15 +131,21 @@ export function NewWishView() {
const [maxTokens, setMaxTokens] = useState(50000);
const [maxMinutes, setMaxMinutes] = useState(30);
const [maxRepairRounds, setMaxRepairRounds] = useState(3);
const [sourceBranch, setSourceBranch] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [idempotencyKey] = useState(() => crypto.randomUUID());
const router = useRouter();
useEffect(() => {
const selected = new URLSearchParams(window.location.search).get('project');
const query = new URLSearchParams(window.location.search);
const selected = query.get('project');
if (selected) setProjectId(selected);
const branch = query.get('branch');
if (branch) setSourceBranch(branch);
}, []);
const effectiveProject = projectId || projects.data?.[0]?.id || '';
const branches = useResource<IdeBranch[]>(effectiveProject ? `/projects/${effectiveProject}/branches` : null);
const targetBranch = projects.data?.find(project => project.id === effectiveProject)?.targetBranch ?? 'main';
const selectedProvider = providers.data?.find(item => item.id === provider);
async function submit(event: React.FormEvent) {
event.preventDefault();
@ -155,6 +162,7 @@ export function NewWishView() {
.filter(Boolean),
provider,
budget: { maxTokens, maxMinutes, maxRepairRounds },
...(sourceBranch ? { sourceBranch } : {}),
},
'POST',
idempotencyKey,
@ -179,7 +187,14 @@ export function NewWishView() {
<div className="form-section">
<h2>定义这次交付</h2>
<Field label="项目空间">
<select required value={effectiveProject} onChange={event => setProjectId(event.target.value)}>
<select
required
value={effectiveProject}
onChange={event => {
setProjectId(event.target.value);
setSourceBranch('');
}}
>
<option value="" disabled>
选择项目
</option>
@ -202,6 +217,22 @@ export function NewWishView() {
onChange={event => setGoal(event.target.value)}
/>
</Field>
<Field
label="起点"
hint={`从 IDE 推送的分支开始时,Agent 在这些改动的基础上工作,验证通过后一并合入 ${targetBranch}。`}
>
<select value={sourceBranch} onChange={event => setSourceBranch(event.target.value)}>
<option value="">{targetBranch} 的最新代码</option>
{sourceBranch && !branches.data?.some(branch => branch.name === sourceBranch) ? (
<option value={sourceBranch}>{sourceBranch}</option>
) : null}
{branches.data?.map(branch => (
<option value={branch.name} key={branch.name}>
{branch.name} · {branch.commit.slice(0, 7)} · {formatTime(branch.updatedAt)}
</option>
))}
</select>
</Field>
<Field label="验收标准" hint="每行一条。后端会用这些标准生成验证计划与证据。">
<textarea
required
@ -491,6 +522,11 @@ export function RunDetailView({ id }: { id: string }) {
<ArrowRight size={14} />
</Link>
</KeyValue>
{run.sourceBranch ? (
<KeyValue label="起点分支">
<code>{run.sourceBranch}</code>
</KeyValue>
) : null}
<KeyValue label="创建时间">{formatTime(run.createdAt)}</KeyValue>
<KeyValue label="更新时间">{formatTime(run.updatedAt)}</KeyValue>
<KeyValue label="修复轮次">

View File

@ -27,6 +27,8 @@ export type Project = {
};
};
export type ProviderId = 'codex' | 'codebuddy';
/** A branch people pushed from the IDE; a wish starting from it verifies and merges it. */
export type IdeBranch = { name: string; commit: string; updatedAt: string };
export type Run = {
id: string;
projectId: string;
@ -46,6 +48,8 @@ export type Run = {
lastFailure?: { kind: string; argv?: string[]; exitCode?: number; outputTail: string };
integratedCommit?: string;
error?: string | { message?: string; code?: string };
/** The run started from this branch instead of the target branch. */
sourceBranch?: string;
};
export type RunEvent = {
seq: number;

View File

@ -21,7 +21,8 @@ export const waitingGuides: Record<WaitingReason, WaitingGuide> = {
},
git_storage: {
title: '项目仓库未就绪',
action: '在项目页重试仓库创建或改用可访问的 HTTPS 仓库,然后点击「继续」。',
action:
'在项目页重试仓库创建或改用可访问的 HTTPS 仓库;起点分支不存在时,先在 IDE 中推送这个分支。然后点击「继续」。',
link: project,
resumable: true,
},

View File

@ -134,6 +134,7 @@ const GIT_STORAGE = new Set([
'REPOSITORY_TRANSPORT_UNSUPPORTED',
'REPOSITORY_POLICY',
'TARGET_BRANCH_UNAVAILABLE',
'SOURCE_BRANCH_UNAVAILABLE',
'INVALID_REF',
'CHECKPOINT_BASE_UNAVAILABLE',
]);

View File

@ -209,6 +209,7 @@ export async function executeRun(config: WorkerConfig, input: RunInput): Promise
: await git.create({
repository: context.project.repositoryUrl,
targetBranch: context.project.targetBranch,
sourceBranch: run.sourceBranch,
baseCommit: run.sourceCommit,
root: tenantRoot(config, input),
runId: attempt,
@ -252,6 +253,7 @@ export async function executeRun(config: WorkerConfig, input: RunInput): Promise
repairCount: run.repairCount,
lastFailure,
lessons: context.lessons,
sourceBranch: run.sourceBranch,
});
await provider.start({
runId: input.runId,

View File

@ -356,7 +356,9 @@ async function integrateDirectly(session: Session, repository: string, verified:
sourceCommit: candidate.commit,
targetRef: session.targetRef,
});
return deliver(session, candidate);
// Release risk covers everything the target branch gains, including commits of a source
// branch the run started from, not only what the agent changed.
return deliver(session, { ...candidate, baseCommit: expected });
}
}

View File

@ -4,7 +4,7 @@ WorkBuddy、Codex 等客户端通过 MCP(Streamable HTTP)接入,以登录
- 地址:本地为 `http://127.0.0.1:4000/mcp`,生产为 API 的 HTTPS 地址加 `/mcp`(不是 `/api/mcp`)。
- 认证:OAuth(授权码 + PKCE)。未认证请求返回 401,`WWW-Authenticate` 中给出受保护资源元数据地址 `/.well-known/oauth-protected-resource`,其中列出授权服务器。本地授权服务器是 Keycloak:`http://127.0.0.1:4100/realms/wishforge`(发现文档在 `/realms/wishforge/.well-known/openid-configuration`)。令牌的 issuer、有效期与 `wishforge-api` audience 都会校验,租户成员资格与工具权限在服务端检查。
- 工具:`list_projects`、`submit_wish`、`get_run`、`get_run_events`、`answer_question`、`control_run`、`get_delivery`、`request_release`。工具与 Web 共用同一套领域逻辑;通过工具做出的修改在审计中记为真实用户。
- 工具:`list_projects`、`submit_wish`、`get_run`、`get_run_events`、`answer_question`、`control_run`、`get_delivery`、`request_release`。工具与 Web 共用同一套领域逻辑;通过工具做出的修改在审计中记为真实用户。`submit_wish` 可以带 `sourceBranch`(例如在 IDE 中推送的 `ide/work`),运行从这个分支开始,验证后合入目标分支。
## Codex

View File

@ -244,7 +244,11 @@ sequenceDiagram
3. 用户点击「打开 IDE」:Web 调用 API `/v1/workspaces/:id/launch`,API 向网关申请一次性启动码,浏览器跳转网关 `/session?code=`。
4. 网关为每个 HTTP 请求与 WebSocket 连接向 API 校验成员资格与角色,并定期复核已打开的连接;撤销后立即断开。
5. 会话建立后,网关以该用户的身份向 API 申请 15 分钟的仓库写令牌(`/internal/workspaces/:id/git-credential`,每次都复核成员资格与角色),交给工作区后端(Theia 策略扩展的 `/wishforge-internal/git-credential`,需要只有网关持有的 Theia 连接令牌,浏览器无法经网关访问该路径)。后端把令牌写进仓库之外的 Git 配置片段(Kubernetes 中是内存卷),由克隆通过 `include.path` 引用;首次收到时把目标分支克隆到以项目命名的文件夹。会话期间网关在令牌到期前 5 分钟续期,没有人打开 IDE 时令牌自然过期。
6. IDE 与 Agent 之间只通过 Git commit 交接:在 IDE 中提交并推送到目标分支(平台 Git 只接受快进推送),之后提交的愿望以该 commit 为基线;与 Agent 的合入同时发生时,由合入的 CAS 推送与合并重验处理。提交身份取最近打开会话的用户(OIDC 的 name/email),可以用 `git config` 覆盖。外部仓库(如 GitHub)不克隆,那里的改动应走 PR。
6. IDE 与 Agent 之间只通过 Git commit 交接,人的改动也要经过验证才进入目标分支:
- **推送范围**:IDE 的令牌只能推送 `ide/` 开头的分支。平台 Git 用 pre-receive 钩子执行这条限制,克隆默认在 `ide/work` 分支上工作。
- **合入**:愿望可以指定起点分支(`sourceBranch`),运行从该分支的最新提交开始,Agent 在这些改动上继续工作。之后的验证、修复与合入照常进行:目标分支是起点的祖先时快进,否则合并后重新验证,冲突按修复轮处理。发布风险按目标分支合入前后的全部差异计算,包括起点分支带来的提交。
- **提交身份**:取最近打开会话的用户(OIDC 的 name/email),可以用 `git config` 覆盖。
- **外部仓库**:如 GitHub 的仓库不克隆,那里的改动应走 PR。
### 4.6 经验沉淀与 Agent 配置
@ -351,7 +355,7 @@ MCP 工具:`list_projects`、`submit_wish`、`get_run`、`get_run_events`、`a
| ADR-5 | Agent 客户端通过 MCP 接入 | WorkBuddy、Codex 等原生支持 MCP 与 OAuth,权限沿用用户身份,无需为每个客户端写适配。 |
| ADR-6 | RSI 限定在任务、项目与租户范围,晋升由人决定 | 自动的平台级元进化需要基准集、评估器与大量真实运行才有统计意义,在当前阶段不可验证,且有跨租户数据风险。 |
| ADR-7 | IDE 与 Agent 只通过 Git commit 交接 | Git 已经提供精确、可审计的版本身份;IDE 快照、保存屏障等机制复杂且依赖 Theia 内部实现。 |
| ADR-8 | IDE 中的提交直接推送目标分支,令牌由网关按会话投递 | 有编辑权限的人本来就能改代码;直接推送最简单,Agent 的合入用 CAS 与合并重验处理目标分支的前进,下一次运行的验证覆盖整个仓库。代价是人工提交在下一次运行前未经验证。工作区自己不能签发凭据,令牌只在有人打开 IDE 时存在,最长 15 分钟。 |
| ADR-8 | IDE 只推送 `ide/` 分支,由从该分支开始的愿望验证并合入;令牌由网关按会话投递 | 目标分支只经由验证器的合入改变,人工改动与 Agent 改动走同一条验证与发布风险评估路径,也能借助修复轮修好。代价是人工改动要多提交一次愿望才能进入目标分支。工作区自己不能签发凭据,令牌只在有人打开 IDE 时存在,最长 15 分钟。 |
## 11. 已知限制

View File

@ -89,7 +89,7 @@ npm run ide:build
npm run dev:ide
```
在项目页点击「创建开发环境」,本地 provisioner 会把工作区指向本机的 Theia(Theia 未启动时工作区显示为准备中);就绪后点击「打开 IDE」。本地模式下所有工作区共用同一个 Theia 实例和 `.wishforge/ide-workspace` 目录:第一次打开某个项目的工作区时,它的目标分支被克隆到其中以项目命名的文件夹。在 IDE 中提交并 `git push` 到目标分支后,再提交的愿望就从这个 commit 开始;令牌只在 IDE 打开期间有效。
在项目页点击「创建开发环境」,本地 provisioner 会把工作区指向本机的 Theia(Theia 未启动时工作区显示为准备中);就绪后点击「打开 IDE」。本地模式下所有工作区共用同一个 Theia 实例和 `.wishforge/ide-workspace` 目录:第一次打开某个项目的工作区时,项目被克隆到其中以项目命名的文件夹,并处在 `ide/work` 分支上。在 IDE 中提交并 `git push` 后,在项目页的 IDE 分支列表点「提交愿望合入」,运行会从这个分支开始,验证通过后合入目标分支。令牌只在 IDE 打开期间有效,只能推送 `ide/` 开头的分支。
多人协作需要额外启动 OCT 服务,见 [apps/ide/collaboration/README.md](../apps/ide/collaboration/README.md)。

View File

@ -132,7 +132,7 @@ node --import tsx scripts/tenant-admin.ts member <租户ID> <成员 subject> <
provisioner 用 `WF_THEIA_IMAGE`(digest)创建工作区;配置 `WF_OCT_WORKSPACE_IMAGE` 与 `WF_IDE_PUBLIC_URL` 后每个工作区带一个协作 sidecar。
平台托管仓库的工作区在第一次打开时克隆目标分支。网关在会话期间不断为它申请 15 分钟的仓库写令牌,人们可以在 IDE 中直接推送目标分支(只允许快进)。为此需要:
平台托管仓库的工作区在第一次打开时克隆项目,并切换到 `ide/work` 分支。网关在会话期间不断为它申请 15 分钟的仓库令牌,这个令牌只能推送 `ide/` 开头的分支,由平台 Git 的 pre-receive 钩子执行。人们推送后,从该分支提交愿望,由它验证并合入目标分支。为此需要:
- 工作区 Pod 能访问平台 Git:provisioner 会为每个工作区放行,控制面一侧见 [infra/k8s](../infra/k8s/README.md) 的 `workspaces-to-git`;
- 项目的 `repositoryUrl`(`WF_GIT_PUBLIC_BASE_URL`)对工作区可达;
@ -211,6 +211,6 @@ node scripts/backup-restore.mjs --restore-verify --manifest .wishforge/backups/<
- **Temporal 授权**:当前 worker 与 Temporal 之间没有 mTLS 与按队列授权。执行沙箱可以连接 Temporal,理论上可以轮询其他队列。生产必须为 Temporal 开启 mTLS 并配置授权插件,或在网络层只允许沙箱连接专用的 Temporal 前端;在此之前不要在同一 Temporal 命名空间中混合不同信任级别的租户。
- **IDE 同 UID**:Theia 后端与用户终端以同一用户运行,同一工作区内的协作者之间没有隔离。
- **IDE 推送不经验证**:项目的 owner/admin/developer 可以在 IDE 中直接推送目标分支(只允许快进),这些提交不经过验证器,平台也不记录推送者(提交身份可以自行修改)。需要每次改动都经过验证时,只把编辑权限给可信成员,或改用外部仓库并在那里用 PR 与分支保护约束。
- **IDE 推送者不留痕**:平台不记录是谁推送了 `ide/` 分支,提交身份可以自行修改。这些改动进入目标分支前一定经过验证,但作者归属只能参考提交信息。
- **OCT 房间不持久**:协作服务重启后需要重新创建房间。
- **TypeScript 运行时转译**:镜像通过 `tsx` 加载 TypeScript 源码运行(不在运行时做类型检查),尚未改为预编译产物。

View File

@ -8,7 +8,7 @@
## 基线与检查点
- 新运行克隆仓库后,以 `refs/remotes/origin/<targetBranch>` 指向的 commit 为基线;远端默认 HEAD 与同名标签不会被选中。目标分支不存在时明确报错(`TARGET_BRANCH_UNAVAILABLE`)。分支名与引用表达式在创建项目与运行时都会校验。
- 新运行克隆仓库后,以 `refs/remotes/origin/<targetBranch>` 指向的 commit 为基线;愿望指定了起点分支(`sourceBranch`)时改用 `refs/remotes/origin/<sourceBranch>`。远端默认 HEAD 与同名标签不会被选中。目标分支不存在时明确报错(`TARGET_BRANCH_UNAVAILABLE`);起点分支不存在时运行进入 `git_storage` 等待(`SOURCE_BRANCH_UNAVAILABLE`),推送该分支后继续即可。起点分支不能是目标分支,也不能是平台自己的 `wishforge/` 分支。分支名与引用表达式在创建项目与运行时都会校验。
- 检查点是相对基线的增量 Git bundle(`<base>..HEAD`)加上二进制补丁及其摘要。bundle 与补丁各不超过 4 MiB;配置了对象存储时 bundle 存入对象存储(见 [artifact-storage.md](artifact-storage.md))。工作区没有变化时检查点不含 bundle。
- 恢复检查点时,从项目仓库克隆基线 commit,再应用 bundle 并核对补丁摘要;恢复出的 commit 与检查点不一致时拒绝。基线已不在仓库中(例如目标分支被强制推送)时报 `CHECKPOINT_BASE_UNAVAILABLE`,运行进入等待。
- 执行器安装依赖后,安装产生的未跟踪文件(如 `node_modules/`)写入 `.git/info/exclude`,不会进入检查点。
@ -18,7 +18,8 @@
- verifier 在独立的裸仓库(远端的缓存)中准备候选 commit:目标分支没有移动时直接使用已验证的 commit;否则把它合并到目标分支的最新提交上,并对合并结果重新验证。
- 推送使用 `--force-with-lease` 并先做祖先检查;推送时目标分支又前进了,就基于新的提交重新准备候选,最多三次。
- 合并冲突时提交失败的集成证据(冲突文件与目标 commit),按一轮修复处理:修复轮先把最新目标分支合并进工作区,执行器解决冲突标记,检查点以该目标 commit 为基线。修复轮数用尽时运行进入 `integration_conflict` 等待。
- IDE 工作区(FR-H2):有编辑会话时得到 15 分钟的仓库写令牌,可以直接推送目标分支。平台 Git 拒绝非快进推送与删除分支,人工推送不会改写历史;之后的新运行以它为基线,正在进行的运行合入时按上面的规则合并并重新验证。
- IDE 工作区(FR-H2):有编辑会话时得到 15 分钟的仓库令牌,令牌里写明只能更新 `refs/heads/ide/`。平台 Git 对每次推送运行 pre-receive 钩子,越界的引用被拒绝;平台自己的合入不受这个限制。所有推送都只接受快进,也不能删除分支。IDE 分支经由从它开始的愿望进入目标分支,过程与 Agent 的改动相同。
- 平台 Git 的管理接口 `POST /refs`(`{tenantId, projectId, prefix}`)按最近提交时间列出某个前缀下的分支,工作台据此列出 IDE 分支。
- GitHub 仓库走评审路径:只推送不可变的 `wishforge/<运行>/<commit>` 分支,控制面创建或对账对应的 PR 并等待合并(`github_review`);合并后在 GitHub 实际产生的合并 commit 上重新验证,再提交集成证据。未配置 GitHub App 的 GitHub 仓库不会退回直接推送(`github_unconfigured`)。安装令牌按仓库授权而不是按分支授权,目标分支仍需要分支保护。
## wishforge.yaml V1

View File

@ -17,8 +17,8 @@
|---|---|---|
| 工作概览 `/` | 进行中与待处理的运行数、最近运行、项目准备入口 | `GET /v1/dashboard` |
| 项目空间 `/projects` | 项目列表、创建项目 | `GET/POST /v1/projects` |
| 项目详情 `/projects/:id` | 仓库状态(平台仓库失败可重试)、IDE 工作区、项目运行、项目经验(查看、添加约定、停用、删除)、设置(目标分支、验证命令、安装命令、交付配置、验收配置) | `GET/PATCH /v1/projects/:id`、`POST /repository`、`/workspaces`、`/lessons`、`/v1/lessons/:id` |
| 运行记录 `/runs` | 运行列表与筛选;提交愿望(不可用的执行器不可选并显示原因) | `GET /v1/runs`、`POST /v1/projects/:id/wishes` |
| 项目详情 `/projects/:id` | 仓库状态(平台仓库失败可重试)、IDE 工作区与从 IDE 推送的 `ide/` 分支(每个分支可以直接「提交愿望合入」)、项目运行、项目经验(查看、添加约定、停用、删除)、设置(目标分支、验证命令、安装命令、交付配置、验收配置) | `GET/PATCH /v1/projects/:id`、`POST /repository`、`/workspaces`、`/branches`、`/lessons`、`/v1/lessons/:id` |
| 运行记录 `/runs` | 运行列表与筛选;提交愿望(不可用的执行器不可选并显示原因;「起点」可以选一个 IDE 分支,运行从它开始,验证后合入) | `GET /v1/runs`、`POST /v1/projects/:id/wishes`、`GET /v1/projects/:id/branches` |
| 运行详情 `/runs/:id` | 阶段进度、等待原因与对应操作、最近一次失败(修复轮的输入);标签页:概览、代码变更(检查点按文件的 diff)、阶段事件(Agent 消息、命令、文件变更、计划)、验证证据(命令、退出码、耗时、输出尾部,合入与冲突);交付结果(合入的 commit 或应用地址) | `GET /v1/runs/:id`、`/events/stream`、`/artifacts`、`/delivery`、`POST /commands` |
| 发布与审批 `/releases` | 发布列表(失败原因);审批对话框展示需求目标与验收标准、项目、环境(是否生产)、验证命令、commit、镜像、审批期限与请求人 | `GET /v1/releases`、`GET /v1/releases/:id/review`、`POST /v1/approvals/:id/decision` |
| 环境 `/environments` | 环境列表与创建、应用地址、Runner 注册、部署密钥引用、部署结果未知时「核对后解锁」 | `/v1/environments*`、`POST /v1/environments/:id/unlock` |

View File

@ -75,7 +75,7 @@ RSI(Recursive Self-Improvement,递归自我改进)在 WishForge 中指**
**J3 在云 IDE 中协作**
1. 从项目页打开工作区,在浏览器中编辑、使用终端和调试器。
2. 改动通过 Git 提交并推送到平台仓库;之后提交的愿望基于最新代码。
2. 改动提交并推送到 `ide/` 开头的分支;从该分支提交一个愿望,验证通过后合入目标分支。
3. 可以邀请有编辑权限的成员实时协作。
**J4 失败与修复**
@ -168,7 +168,7 @@ RSI(Recursive Self-Improvement,递归自我改进)在 WishForge 中指**
| ID | 优先级 | 需求 | 验收标准 |
|---|---|---|---|
| FR-H1 | P0 | 从工作台打开项目的 Theia 工作区;网关对每个 HTTP/WebSocket 请求校验租户、项目与角色;viewer 不能进入编辑会话。 | 撤销成员资格后,现有连接会被关闭。 |
| FR-H2 | P1 | 工作区首次打开时克隆项目仓库(平台托管仓库),有人使用期间持续注入仓库范围的短期凭据;IDE 中的改动通过 Git 提交、推送交还平台。外部仓库的改动走 PR,不克隆。 | 新工作区打开后即有项目代码,推送后新愿望基于该 commit。 |
| FR-H2 | P1 | 工作区首次打开时克隆项目仓库(平台托管仓库),有人使用期间持续注入仓库范围的短期凭据;IDE 只能推送 `ide/` 开头的分支,愿望可以指定从这样的分支开始,验证通过后连同 Agent 的改动一起合入目标分支。外部仓库的改动走 PR,不克隆。 | 新工作区打开后即有项目代码;IDE 直接推送目标分支被拒绝;从 IDE 分支开始的愿望验证并合入这些改动。 |
| FR-H3 | P1 | 多人实时协作(OCT),房间按工作区隔离,仅有编辑权限的成员可以加入。 | 其他工作区的邀请无法加入。 |
| FR-H4 | P1 | 工作区手动暂停/恢复与空闲自动暂停。 | 暂停后不占用计算资源,恢复后数据仍在。 |
| FR-H5 | P1 | 扩展白名单:只能使用平台预置并校验过摘要的扩展。 | 安装未经审核扩展的请求被拒绝。 |

View File

@ -14,6 +14,8 @@ export interface PromptInput {
lastFailure?: FailureSummary;
/** Active project lessons, most recent first. */
lessons?: string[];
/** The branch the workspace started from instead of the target branch. */
sourceBranch?: string;
}
/** Keeps the most recent lessons that fit the count and size limits. */
@ -70,6 +72,9 @@ export function bundlePrompt(config: AgentBundleConfig, input: PromptInput) {
lessons.length
? `Lessons from earlier work on this project (apply them when relevant):\n${lessons.map(lesson => `- ${lesson}`).join('\n')}`
: '',
input.sourceBranch
? `The workspace starts from branch ${input.sourceBranch}, which holds changes people made themselves (for example in the IDE). Keep those changes and build on them; this run verifies and merges them into the target branch together with your work.`
: '',
input.repairCount ? repairSection(input.repairCount, input.lastFailure) : '',
'Implement this requirement in the current isolated branch. Do not deploy, and do not change protected verification commands, credentials or deployment policies. Commit your work; a separate verifier will check the acceptance criteria. Finish with a short summary of what you changed and why.',
]

View File

@ -41,6 +41,19 @@ describe('agent prompt', () => {
expect(repair).toContain('````\nPASS');
});
it('tells the agent to keep and build on the changes of the branch it starts from', () => {
const plain = bundlePrompt(BASELINE_BUNDLE, { goal: 'Merge', acceptanceCriteria: ['Checks pass'], repairCount: 0 });
expect(plain).not.toContain('starts from branch');
const fromBranch = bundlePrompt(BASELINE_BUNDLE, {
goal: 'Merge the notes work',
acceptanceCriteria: ['Checks pass'],
repairCount: 0,
sourceBranch: 'ide/work',
});
expect(fromBranch).toContain('starts from branch ide/work');
expect(fromBranch).toContain('Keep those changes');
});
it('asks the agent to resolve a merge conflict against the target commit', () => {
const prompt = bundlePrompt(BASELINE_BUNDLE, {
goal: 'Goal',

View File

@ -138,6 +138,8 @@ export interface Run extends Entity {
implementationSummary?: string;
/** Commit pushed to the target branch by the independent verifier. */
integratedCommit?: string;
/** The run started from this branch's head instead of the target branch; the run merges it. */
sourceBranch?: string;
executionGeneration?: string;
/** Outbox item that will start the current generation. */
pendingStartId?: string;
@ -338,6 +340,10 @@ export const wishInput = z
acceptanceCriteria: z.array(text.max(2000)).min(1).max(30),
provider: z.enum(providers).default('codex'),
budget: budgetSchema.default({}),
/** Start from this branch instead of the target branch, e.g. one pushed from the IDE. */
sourceBranch: gitBranchName
.optional()
.describe('Start from this branch (for example ide/work, pushed from the IDE) instead of the target branch'),
})
.strict();
export const commandInput = z

View File

@ -224,6 +224,8 @@ export class GitWorkspace {
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;
@ -231,6 +233,7 @@ export class GitWorkspace {
}): 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) {
@ -247,17 +250,25 @@ export class GitWorkspace {
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/${targetBranch}`;
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(
input.baseCommit ? 'CHECKPOINT_COMMIT_UNAVAILABLE' : 'TARGET_BRANCH_UNAVAILABLE',
input.baseCommit
? 'The immutable checkpoint commit is absent from the repository; restore its source bundle'
: `Configured target branch '${targetBranch}' is absent; no fallback to remote HEAD was used`,
'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]);

View File

@ -8,17 +8,18 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { execFile } from 'node:child_process';
import { existsSync } from 'node:fs';
import { createRequire } from 'node:module';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { promisify } from 'node:util';
import type { Actor, Evidence, Lesson, Run } from '@wishforge/contracts';
import type { Actor, CheckpointRecord, Evidence, Lesson, Project, Run } from '@wishforge/contracts';
import { executeCommand, type CommandExecutor, type ProviderStart } from '@wishforge/runtime';
import { ManagedProvider } from '../packages/runtime/src/providers/base.js';
import { ControlPlane } from '../apps/api/src/domain/control-plane.js';
import { Services } from '../apps/api/src/http.js';
import { ServiceTokens } from '../apps/api/src/service-tokens.js';
import { recordAllocation, reserveExecutionGrant } from '../apps/api/src/domain/entitlements.js';
import { installHooks } from '../apps/git-service/src/service.js';
import { createActivities, type ActivityOutcome, type RunInput } from '../apps/worker/src/activities.js';
import { MemoryStore } from './helpers/memory-store.js';
import { internalFetch } from './helpers/internal-fetch.js';
@ -116,13 +117,22 @@ afterEach(async () => {
await rm(root, { recursive: true, force: true });
});
/** git clones of the loopback URL are served from the bare repository in the temporary directory. */
const execute: CommandExecutor = command =>
executeCommand(
/**
* git clones of the loopback URL are served from the bare repository in the temporary directory;
* image builds are answered like a registry push, so no Docker is needed.
*/
const execute: CommandExecutor = async command => {
if (command.executable === 'docker') {
const metadata = command.args[command.args.indexOf('--metadata-file') + 1]!;
await writeFile(metadata, JSON.stringify({ 'containerimage.digest': `sha256:${'c'.repeat(64)}` }));
return { exitCode: 0, stdout: '', stderr: '', durationMs: 1 };
}
return executeCommand(
command.executable === 'git'
? { ...command, args: command.args.map(arg => (arg === REMOTE_URL ? remote : arg)) }
: command,
);
};
async function createProject() {
const project = await services.control.createProject(owner, {
@ -143,11 +153,11 @@ async function createProject() {
);
return project;
}
async function submit(projectId: string, goal: string, key: string) {
async function submit(projectId: string, goal: string, key: string, extra: Record<string, unknown> = {}) {
const { run_id } = await services.control.submit(
owner,
projectId,
{ goal, acceptanceCriteria: ['check.mjs passes'], provider: 'codex', budget: { maxRepairRounds: 2 } },
{ goal, acceptanceCriteria: ['check.mjs passes'], provider: 'codex', budget: { maxRepairRounds: 2 }, ...extra },
key,
);
return run_id;
@ -349,9 +359,10 @@ describe('local main loop', () => {
expect(lessons[0]?.summary).toContain('Merging into the target branch conflicted in greeting.txt');
});
it('starts the next wish from a commit pushed in the IDE workspace', async () => {
it('verifies and merges a branch pushed from the IDE through a wish that starts from it', async () => {
const project = await createProject();
// The IDE workspace clones the repository and pushes a person's commit to the target branch.
// The Git service's push hook: an IDE credential may update ide/ branches only.
await git(remote, 'config', 'core.hooksPath', await installHooks(path.join(root, 'git-service')));
const remoteUrl = `file://${remote}`;
const ide = createGitWorkspace({
root: path.join(root, 'ide'),
@ -368,14 +379,24 @@ describe('local main loop', () => {
author: { name: 'Ada Lovelace', email: 'ada@example.com' },
});
await cloning;
const inIde = (...args: string[]) =>
run('git', args, { cwd: directory, env: { ...process.env, WISHFORGE_REF_PREFIX: 'refs/heads/ide/' } });
await writeFile(path.join(directory, 'notes.md'), 'written in the IDE\n');
await run('git', ['add', 'notes.md'], { cwd: directory });
await run('git', ['commit', '-m', 'Notes from the IDE'], { cwd: directory });
await run('git', ['push', 'origin', 'main'], { cwd: directory });
const pushed = await git(remote, 'rev-parse', 'main');
expect(await git(remote, 'log', '-1', '--format=%an', 'main')).toBe('Ada Lovelace');
await inIde('add', 'notes.md');
await inIde('commit', '-m', 'Notes from the IDE');
const target = await git(remote, 'rev-parse', 'main');
await expect(inIde('push', 'origin', 'HEAD:main')).rejects.toThrow(/ide\//);
await inIde('push');
const pushed = await git(remote, 'rev-parse', 'ide/work');
expect(await git(remote, 'rev-parse', 'main')).toBe(target);
expect(await git(remote, 'log', '-1', '--format=%an', 'ide/work')).toBe('Ada Lovelace');
const runId = await submit(project.id, 'Make the greeting say hello world', 'wish-ide-0001');
await expect(submit(project.id, 'Merge', 'wish-ide-0000', { sourceBranch: 'main' })).rejects.toMatchObject({
code: 'INVALID_SOURCE_BRANCH',
});
const runId = await submit(project.id, 'Make the greeting say hello world', 'wish-ide-0001', {
sourceBranch: 'ide/work',
});
let sawNotes = false;
const session = await provision(runId, async start => {
sawNotes = existsSync(path.join(start.workspace, 'notes.md'));
@ -383,10 +404,69 @@ describe('local main loop', () => {
});
expect(await drive(session)).toEqual({ status: 'complete' });
expect(sawNotes).toBe(true);
// The run started from the pushed commit, so its change lands directly on top of it.
expect(prompts.at(-1)).toContain('starts from branch ide/work');
// The run started from the branch and was verified, so it lands on the target branch whole.
expect(await git(remote, 'rev-parse', 'main^')).toBe(pushed);
expect(await git(remote, 'show', 'main:notes.md')).toBe('written in the IDE');
expect(await git(remote, 'show', 'main:greeting.txt')).toBe('hello world');
expect(await services.control.run(owner, runId)).toMatchObject({ status: 'succeeded', sourceBranch: 'ide/work' });
});
it('weighs the release risk of everything the branch brings, not only the agent’s change', async () => {
const project = await createProject();
await store.transaction(TENANT, async tx => {
const current = (await tx.get<Project>('project', project.id))!;
await tx.put('project', {
...current,
deliveryConfig: {
imageRepository: 'registry.local/greeting',
architecture: 'linux/amd64',
environmentId: 'environment-1',
dockerfile: 'Dockerfile',
containerPort: 3000,
healthPath: '/health',
smokeChecks: [],
},
});
});
// A person adds a migration in the IDE; the agent then only touches the greeting.
const seed = path.join(root, 'person');
await git(root, 'clone', remote, seed);
await git(seed, 'switch', '--create', 'ide/work');
await mkdir(path.join(seed, 'migrations'));
await writeFile(path.join(seed, 'migrations', '001-notes.sql'), 'create table notes (body text);\n');
await writeFile(path.join(seed, 'Dockerfile'), 'FROM scratch\n');
await git(seed, 'add', '.');
await git(seed, 'commit', '-m', 'Add a notes table');
await git(seed, 'push', 'origin', 'ide/work');
const runId = await submit(project.id, 'Make the greeting say hello world', 'wish-ide-0003', {
sourceBranch: 'ide/work',
});
const session = await provision(runId, writeGreeting('hello world', 'Updated the greeting.'));
expect(await drive(session)).toMatchObject({ status: 'release' });
const checkpoint = await store.transaction(TENANT, async tx =>
tx.get<CheckpointRecord>('checkpoint', (await tx.get<Run>('run', runId))!.checkpointId!),
);
expect(checkpoint?.trustedClassification).toMatchObject({ migration: true });
expect(checkpoint?.trustedClassification?.changedPaths).toEqual(
expect.arrayContaining(['Dockerfile', 'greeting.txt', 'migrations/001-notes.sql']),
);
});
it('waits for a source branch that was not pushed, and starts once it exists', async () => {
const project = await createProject();
const runId = await submit(project.id, 'Make the greeting say hello world', 'wish-ide-0002', {
sourceBranch: 'ide/missing',
});
const session = await provision(runId, writeGreeting('hello world', 'Updated the greeting.'));
expect(await drive(session)).toMatchObject({ status: 'waiting', reason: 'git_storage' });
expect((await services.control.run(owner, runId)).waitingDetail).toContain('SOURCE_BRANCH_UNAVAILABLE');
// Once the branch is pushed, continuing the run starts from it.
const seed = path.join(root, 'person');
await git(root, 'clone', remote, seed);
await git(seed, 'push', 'origin', 'HEAD:refs/heads/ide/missing');
await services.control.command(owner, runId, { action: 'resume' }, 'resume-branch-0001');
await release(runId, session.generation);
const resumed = await provision(runId, writeGreeting('hello world', 'Updated the greeting.'));
expect(await drive(resumed)).toEqual({ status: 'complete' });
});
it('keeps executors inside their own run and lets nothing but integration complete a run', async () => {
const project = await createProject();

View File

@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { Actor, Project } from '@wishforge/contracts';
import { ControlPlane } from '../apps/api/src/domain/control-plane.js';
import { Services } from '../apps/api/src/http.js';
import { GitStorage } from '../apps/api/src/domain/git-storage.js';
import { MemoryStore } from './helpers/memory-store.js';
import { internalFetch } from './helpers/internal-fetch.js';
@ -85,7 +86,7 @@ describe('IDE workspace repository access', () => {
const later = await call('/workspaces/workspace-1/authorize', { userId: devUser, operation: 'edit' });
expect((await later.json()).data.author).toBeUndefined();
});
it('mints a write credential for the project’s platform repository', async () => {
it('mints a credential that may push ide/ branches of the project’s platform repository', async () => {
gitCalls = [];
const response = await call('/workspaces/workspace-1/git-credential', { userId: devUser });
expect(response.status).toBe(200);
@ -100,7 +101,13 @@ describe('IDE workspace repository access', () => {
expect(gitCalls).toEqual([
{
path: '/tokens',
body: { tenantId: 'demo', projectId: project.id, permission: 'write', ttlSeconds: 900 },
body: {
tenantId: 'demo',
projectId: project.id,
permission: 'write',
ttlSeconds: 900,
refPrefix: 'refs/heads/ide/',
},
authorization: `Bearer ${env.WF_GIT_ADMIN_TOKEN}`,
},
]);
@ -131,3 +138,48 @@ describe('IDE workspace repository access', () => {
expect(await response.json()).toMatchObject({ error: { code: 'WORKSPACE_REPOSITORY_UNSUPPORTED' } });
});
});
describe('wishes that start from an IDE branch', () => {
it('lists the ide/ branches people pushed, for platform repositories only', async () => {
vi.stubGlobal('fetch', async (input: string | URL, init: RequestInit) => {
gitCalls.push({
path: new URL(String(input)).pathname,
body: JSON.parse(String(init.body)),
authorization: (init.headers as Record<string, string>).Authorization,
});
return Response.json({
branches: [{ name: 'ide/work', commit: 'b'.repeat(40), updatedAt: '2026-10-19T12:00:00+08:00' }],
});
});
gitCalls = [];
const git = new GitStorage(env);
expect(await git.ideBranches(project)).toEqual([
{ name: 'ide/work', commit: 'b'.repeat(40), updatedAt: '2026-10-19T12:00:00+08:00' },
]);
expect(gitCalls).toEqual([
{
path: '/refs',
body: { tenantId: 'demo', projectId: project.id, prefix: 'refs/heads/ide/' },
authorization: `Bearer ${env.WF_GIT_ADMIN_TOKEN}`,
},
]);
expect(await git.ideBranches({ ...project, repositoryStorage: 'external' })).toEqual([]);
});
it('records the branch on the run and refuses the target branch or the platform’s own branches', async () => {
const control = new Services(new ControlPlane(store, env)).control;
const submit = (sourceBranch: string, key: string) =>
control.submit(
owner,
project.id,
{ goal: 'Merge the IDE work', acceptanceCriteria: ['Checks pass'], sourceBranch },
key,
);
await expect(submit('main', 'source-branch-0001')).rejects.toMatchObject({ code: 'INVALID_SOURCE_BRANCH' });
await expect(submit('wishforge/run/abc', 'source-branch-0002')).rejects.toMatchObject({
code: 'INVALID_SOURCE_BRANCH',
});
await expect(submit('../main', 'source-branch-0003')).rejects.toThrow('A safe Git branch name is required');
const { run_id } = await submit('ide/work', 'source-branch-0004');
expect(await control.run(owner, run_id)).toMatchObject({ sourceBranch: 'ide/work' });
});
});