diff --git a/apps/api/src/domain/control-plane.ts b/apps/api/src/domain/control-plane.ts index c02bded..45eefb3 100644 --- a/apps/api/src/domain/control-plane.ts +++ b/apps/api/src/domain/control-plane.ts @@ -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'); diff --git a/apps/api/src/domain/git-storage.ts b/apps/api/src/domain/git-storage.ts index 9b30bd7..bed4615 100644 --- a/apps/api/src/domain/git-storage.ts +++ b/apps/api/src/domain/git-storage.ts @@ -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' || diff --git a/apps/api/src/http.ts b/apps/api/src/http.ts index 6236f03..a15dc1f 100644 --- a/apps/api/src/http.ts +++ b/apps/api/src/http.ts @@ -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 => { diff --git a/apps/git-service/src/service.ts b/apps/git-service/src/service.ts index f892a43..35c481c 100644 --- a/apps/git-service/src/service.ts +++ b/apps/git-service/src/service.ts @@ -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//'); 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}`, diff --git a/apps/git-service/test/hooks.test.ts b/apps/git-service/test/hooks.test.ts new file mode 100644 index 0000000..d4dc4fd --- /dev/null +++ b/apps/git-service/test/hooks.test.ts @@ -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 = {}) => + 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(); +}); diff --git a/apps/git-service/test/service.test.ts b/apps/git-service/test/service.test.ts index 161ba34..5e1c00a 100644 --- a/apps/git-service/test/service.test.ts +++ b/apps/git-service/test/service.test.ts @@ -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' }, diff --git a/apps/ide/README.md b/apps/ide/README.md index b861108..aa53504 100644 --- a/apps/ide/README.md +++ b/apps/ide/README.md @@ -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` 可以改成自己的。 diff --git a/apps/ide/gateway/README.md b/apps/ide/gateway/README.md index d495a59..266cfa0 100644 --- a/apps/ide/gateway/README.md +++ b/apps/ide/gateway/README.md @@ -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 会立即再试。 diff --git a/apps/ide/policy/README.md b/apps/ide/policy/README.md index bb4803b..2e31a57 100644 --- a/apps/ide/policy/README.md +++ b/apps/ide/policy/README.md @@ -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` 会一并运行。 ## 边界 diff --git a/apps/ide/policy/git-workspace.cjs b/apps/ide/policy/git-workspace.cjs index c0def9c..7349682 100644 --- a/apps/ide/policy/git-workspace.cjs +++ b/apps/ide/policy/git-workspace.cjs @@ -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 ` 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 }; diff --git a/apps/ide/policy/test/git-workspace.test.cjs b/apps/ide/policy/test/git-workspace.test.cjs index 92f7066..23c29e6 100644 --- a/apps/ide/policy/test/git-workspace.test.cjs +++ b/apps/ide/policy/test/git-workspace.test.cjs @@ -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 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 => { diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 6e82bd2..acf165d 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -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; diff --git a/apps/web/src/features/projects.tsx b/apps/web/src/features/projects.tsx index e4b97da..26da8be 100644 --- a/apps/web/src/features/projects.tsx +++ b/apps/web/src/features/projects.tsx @@ -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('/projects'); const runs = useResource(`/runs?project=${id}`, 10000); const workspaces = useResource(`/projects/${id}/workspaces`, 10000); + const branches = useResource(`/projects/${id}/branches`, 30000); const projectResource = useResource(`/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 }) { }>

- 在 IDE 中修改后提交并推送到 {project.targetBranch};之后提交的愿望从最新的代码开始。 + 在 IDE 中提交并推送到 ide/ 开头的分支(默认 ide/work),再从该分支提交愿望: + 验证通过后连同 Agent 的改动一起合入 {project.targetBranch}。

+ {branches.data?.length ? ( +
    + {branches.data.map(branch => ( +
  • + + {branch.name} + + {branch.commit.slice(0, 7)} · {formatTime(branch.updatedAt)} + + + 提交愿望合入 + +
  • + ))} +
+ ) : null} {workspaces.data?.length ? (
{workspaces.data.map(workspace => ( diff --git a/apps/web/src/features/runs.tsx b/apps/web/src/features/runs.tsx index 6e4cbe2..9396bc9 100644 --- a/apps/web/src/features/runs.tsx +++ b/apps/web/src/features/runs.tsx @@ -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(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() {

定义这次交付

- { + setProjectId(event.target.value); + setSourceBranch(''); + }} + > @@ -202,6 +217,22 @@ export function NewWishView() { onChange={event => setGoal(event.target.value)} /> + + +