Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/agentflow/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ func main() {
readyStatus := "serving"
switch role {
case "worker":
httpapi.ConfigureWorkerSOPSandboxSelection(s, e)
httpapi.ConfigureWorkerSOPHelpers(s, e)
e.ConfigureControl(engine.ControlConfig{Role: role, URL: endpoints.ControlURL, Token: endpoints.ControlToken, APIURL: endpoints.APIBase})
e.StartInstanceHeartbeat(claimCtx)
srv = &http.Server{Addr: endpoints.ListenAddr, Handler: workerHandler(e), ReadHeaderTimeout: 10 * time.Second}
Expand Down
5 changes: 5 additions & 0 deletions docs/api/collaboration.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" -X POST \
"$AGENTFLOW_URL/api/repositories"
```

可用 `workBranchNaming` 设置 SOP 自动新建工作分支的命名方式。更新时省略该字段会保留已保存的配置,新仓库缺省使用 `feature/`。

- `{"mode":"prefix","prefix":"feat/"}` 为原有分支名主体加上指定前缀。`prefix` 留空时直接使用分支名主体。
- `{"mode":"ai","executorId":"codebuddy","model":"hy4std","prompt":"用小写英文概括改动,带上需求编号"}` 使用指定的 CLI 和模型生成完整分支名。`executorId` 和 `model` 必填,`prompt` 可留空。调用使用 SOP 责任人的凭据或已授权执行机器的登录。平台能访问远端仓库时,会在遇到同名分支后按原命名要求重新生成。节点重试沿用已保存的分支名。

### `DELETE /api/repositories?id={id}`

`id` 必填。成功删除仓库,并清除引用它的项目默认仓库设置,返回 `200 {"status":"deleted"}`;缺少 `id` 或存储错误为 `400`。
Expand Down
26 changes: 26 additions & 0 deletions docs/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5073,6 +5073,8 @@ components:
type: string
integrateBranch:
type: string
workBranchNaming:
$ref: "#/components/schemas/WorkBranchNaming"
createdAt:
type: string
format: date-time
Expand All @@ -5081,6 +5083,30 @@ components:
type: string
format: date-time
readOnly: true
WorkBranchNaming:
type: object
description: Naming settings for newly created SOP work branches. Repositories without settings use the feature/ prefix.
required: [mode]
properties:
mode:
type: string
enum: [prefix, ai]
prefix:
type: string
description: Literal prefix in prefix mode. An empty or omitted prefix within this mode produces a name without a prefix.
example: feat/
executorId:
type: string
description: Built-in CLI executor ID. Required in AI mode.
example: codebuddy
model:
type: string
description: Concrete model ID. Required in AI mode.
example: hy4std
prompt:
type: string
maxLength: 2000
description: Optional repository naming instructions for AI mode.
IssueListPage:
type: object
required: [items, total, offset, limit, hasMore]
Expand Down
29 changes: 28 additions & 1 deletion e2e/api/20-issues.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { api, get, post, put, list, track, cleanup, ensureProject, waitFor, waitRun } from '../lib/api.mjs';
import { cfg } from '../lib/env.mjs';
import { cfg, requireToken } from '../lib/env.mjs';
import { createWorkflow, script, approval, trackRun } from '../lib/fixtures.mjs';

const P = cfg.projectId;
Expand Down Expand Up @@ -52,6 +52,33 @@ test('list supports project filter, search and pagination', async () => {

const detailOf = async id => get(`/api/issues/${id}`);

test('creates a Markdown requirement and serves its attached image to authenticated users', async () => {
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGPQc/8PAAIbAXVXkdKiAAAAAElFTkSuQmCC', 'base64');
const description = '## Reproduction\n\nSee the **attached image**.';
const form = new FormData();
form.set('issue', JSON.stringify({ projectId: P, kind: 'requirement', title: `E2E requirement image ${cfg.runTag}`, description }));
form.append('images', new Blob([png], { type: 'image/png' }), 'reproduction.png');

const created = await post('/api/issues', form);
removeLater(created.id);
const detail = await detailOf(created.id);
assert.equal(detail.issue.description, description);
assert.equal(detail.images.length, 1);
const [image] = detail.images;
assert.ok(image.id);
assert.equal(image.name, 'reproduction.png');

const path = `/api/issues/${created.id}/images/${image.id}`;
await get(path, { auth: false, expect: 401 });
const response = await fetch(cfg.base + path, {
headers: { Authorization: `Bearer ${requireToken()}` },
signal: AbortSignal.timeout(15_000),
});
assert.equal(response.status, 200);
assert.equal(response.headers.get('content-type'), 'image/png');
assert.deepEqual(Buffer.from(await response.arrayBuffer()), png);
});

test('edit keeps identity and records an operation', async () => {
const { issue: current } = await detailOf(issue.id);
const saved = await put('/api/issues', { ...current, title: `${current.title}(已编辑)`, priority: 'high' });
Expand Down
18 changes: 18 additions & 0 deletions internal/domain/assistant_preferences.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package domain

import (
"fmt"
"strings"
"time"
)
Expand All @@ -13,6 +14,23 @@ type AssistantDefaults struct {
Approval string `json:"approval,omitempty"`
}

// ValidateCLIModelID checks the literal model identifier accepted by CLI settings.
func ValidateCLIModelID(id string) error {
const maxCLIModelIDLen = 128
if id == "" {
return fmt.Errorf("模型 ID 不能为空")
}
if len(id) > maxCLIModelIDLen {
return fmt.Errorf("模型 ID 长度不能超过 %d 个字符", maxCLIModelIDLen)
}
for _, r := range id {
if r <= ' ' || r == 0x7f || r == '"' || r == '\'' || r == '`' || r == '\\' {
return fmt.Errorf("模型 ID %q 不能包含空格、引号、反斜杠或控制字符", id)
}
}
return nil
}

// AssistantPreferencesInstructionsMax caps the user's own rules for Main Bot.
const AssistantPreferencesInstructionsMax = 4000

Expand Down
2 changes: 2 additions & 0 deletions internal/domain/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ type Repository struct {
IntegrateBranch string `json:"integrateBranch,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`

WorkBranchNaming *WorkBranchNaming `json:"workBranchNaming,omitempty"`
}

// PublicRepository strips the git token for API responses. Clone/push still
Expand Down
87 changes: 81 additions & 6 deletions internal/domain/work_branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,83 @@ import (
"fmt"
"strings"
"time"
"unicode/utf8"
)

const (
DefaultWorkBranchPrefix = "feature/"
WorkBranchNamingPrefix = "prefix"
WorkBranchNamingAI = "ai"
)

// WorkBranchNaming controls how a repository names newly generated work
// branches. An absent setting uses the legacy prefix. In prefix mode an empty
// Prefix deliberately produces a branch with no prefix.
type WorkBranchNaming struct {
Mode string `json:"mode"`
Prefix string `json:"prefix,omitempty"`
ExecutorID string `json:"executorId,omitempty"`
Model string `json:"model,omitempty"`
Prompt string `json:"prompt,omitempty"`
}

func (n WorkBranchNaming) Normalize() (WorkBranchNaming, error) {
switch n.Mode {
case WorkBranchNamingPrefix:
n.Prefix = strings.TrimSpace(n.Prefix)
n.ExecutorID, n.Model, n.Prompt = "", "", ""
if !ValidNewWorkBranchName(n.Prefix + "work-branch") {
return WorkBranchNaming{}, fmt.Errorf("工作分支前缀不能生成合法的 Git 分支名")
}
case WorkBranchNamingAI:
n.ExecutorID = strings.TrimSpace(n.ExecutorID)
n.Model = strings.TrimSpace(n.Model)
n.Prompt = strings.TrimSpace(n.Prompt)
n.Prefix = ""
if n.ExecutorID == "" || n.Model == "" || n.Model == "default" || n.Model == "default-model" {
return WorkBranchNaming{}, fmt.Errorf("请在仓库设置中为 AI 分支命名选择 CLI 和具体模型")
}
if strings.HasPrefix(n.Model, "-") {
return WorkBranchNaming{}, fmt.Errorf("模型 ID 不能以 - 开头")
}
if err := ValidateCLIModelID(n.Model); err != nil {
return WorkBranchNaming{}, err
}
if utf8.RuneCountInString(n.Prompt) > 2000 {
return WorkBranchNaming{}, fmt.Errorf("分支命名要求最多 2000 个字符")
}
default:
return WorkBranchNaming{}, fmt.Errorf("工作分支命名方式必须是 prefix 或 ai")
}
return n, nil
}

// ValidGitBranchName accepts literal branch names, excluding revisions and
// values that could be interpreted as command options.
func ValidGitBranchName(branch string) bool {
if branch == "" || branch == "HEAD" || strings.HasPrefix(branch, "-") ||
strings.HasSuffix(branch, ".") || strings.Contains(branch, "..") ||
strings.Contains(branch, "@{") || strings.ContainsAny(branch, "~^:?*[\\") {
return false
}
for _, r := range branch {
if r <= ' ' || r == 127 {
return false
}
}
for _, component := range strings.Split(branch, "/") {
if component == "" || strings.HasPrefix(component, ".") || strings.HasSuffix(component, ".lock") {
return false
}
}
return true
}

// ValidNewWorkBranchName expects a short name suitable for a checkout.
func ValidNewWorkBranchName(branch string) bool {
return ValidGitBranchName(branch) && branch != "@" && !strings.HasPrefix(branch, "refs/heads/")
}

// DefaultWorkBranch names the git work branch for an issue run. Gongfeng issues
// use fix-issue-{iid}; TAPD stories use story-{tapdId}; platform requirements use
// requirement-{number}. The suffix is a local timestamp that keeps branch names
Expand All @@ -17,26 +92,26 @@ func DefaultWorkBranch(issue Issue, now time.Time) string {

if source == "tapd" || strings.HasPrefix(strings.TrimSpace(issue.ID), "tapd-") {
if id := tapdStoryID(issue); id != "" {
return "feature/story-" + SafeGitRefSegment(id) + "-" + suffix
return DefaultWorkBranchPrefix + "story-" + SafeGitRefSegment(id) + "-" + suffix
}
}
if source == "gongfeng" || kind == "issue" {
if n := gongfengIssueNumber(issue); n > 0 {
return fmt.Sprintf("feature/fix-issue-%d-%s", n, suffix)
return fmt.Sprintf("%sfix-issue-%d-%s", DefaultWorkBranchPrefix, n, suffix)
}
}
if kind == "requirement" || source == "" || source == "local" {
if issue.Number > 0 {
return fmt.Sprintf("feature/requirement-%d-%s", issue.Number, suffix)
return fmt.Sprintf("%srequirement-%d-%s", DefaultWorkBranchPrefix, issue.Number, suffix)
}
}
if issue.Number > 0 {
return fmt.Sprintf("feature/fix-issue-%d-%s", issue.Number, suffix)
return fmt.Sprintf("%sfix-issue-%d-%s", DefaultWorkBranchPrefix, issue.Number, suffix)
}
if issue.ID != "" {
return "feature/" + SafeGitRefSegment(issue.ID) + "-" + suffix
return DefaultWorkBranchPrefix + SafeGitRefSegment(issue.ID) + "-" + suffix
}
return "feature/fix-" + suffix
return DefaultWorkBranchPrefix + "fix-" + suffix
}

func gongfengIssueNumber(issue Issue) int {
Expand Down
1 change: 1 addition & 0 deletions internal/engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ type Engine struct {
WorkspaceActive func(domain.Run) bool
WorkspaceCheckpointTransport func(context.Context, domain.Run, domain.RunnerWorkspaceRequest) (domain.RunnerWorkspaceResponse, error)
SelectSOPSandbox func(context.Context, SOPSandboxSelection) string
GenerateSOPWorkBranch func(context.Context, SOPWorkBranchRequest) (string, error)
maintenanceOnce sync.Once
}

Expand Down
2 changes: 1 addition & 1 deletion internal/engine/node_execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,7 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl
}
return nil
}); err != nil {
if ctx.Err() != nil || !firstRepositoryAgent(wf, node) {
if ctx.Err() != nil || errors.Is(err, gitwork.ErrWorkBranchExists) || !firstRepositoryAgent(wf, node) {
failNode(err, nodeRejects(node))
return
}
Expand Down
10 changes: 9 additions & 1 deletion internal/engine/prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,23 @@ func applyPromptPlaceholders(st *repo.Store, wf domain.WorkflowDefinition, node
}
prompt = strings.ReplaceAll(prompt, "{{input}}", run.Input)
prompt = strings.ReplaceAll(prompt, "{{repository}}", promptRepositoryLine(run))
repositories := run.RepositoryContexts()
if run.UsesConversationWorkspace() {
prompt += "\n\n## 对话工作区\n\n在交接的工作区内继续,保留已有文件和本地改动。"
for _, repository := range run.RepositoryContexts() {
for _, repository := range repositories {
dir := repository.WorkspaceDir
if dir == "" {
dir = "."
}
prompt += fmt.Sprintf("\n- %s 在 `%s`,工作分支 `%s`,PR/MR 目标分支 `%s`。", repository.Name, dir, repository.WorkBranch, repositoryBaseBranch(repository))
}
} else if len(repositories) > 1 || run.Repository.CreateNewWorkBranch {
prompt += "\n\n## 仓库工作分支\n\n使用各仓库已分配的工作分支作为 PR/MR 的源分支。"
for _, repository := range repositories {
if !repository.ReadOnly && repository.WorkBranch != "" {
prompt += fmt.Sprintf("\n- %s 在 %q,工作分支 %q,PR/MR 目标分支 %q。", repository.Name, repository.WorkspaceDir, repository.WorkBranch, repositoryBaseBranch(repository))
}
}
}
pipelineURL := "未配置 Pipeline"
if run.Repository.PipelineURLPattern != "" {
Expand Down
32 changes: 20 additions & 12 deletions internal/engine/repository_workspace.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func prepareSharedRepository(ctx context.Context, dir string, repository domain.
return err
}
}
if !existing || repository.RequireExistingWorkBranch || repository.CreateNewWorkBranch {
if !existing || repository.RequireExistingWorkBranch {
return prepareRepository(ctx, dir, repository)
}
ctx = withRepositoryGit(ctx, repository)
Expand All @@ -104,6 +104,13 @@ func prepareSharedRepository(ctx context.Context, dir string, repository domain.
if err := applyWorkspaceGitIdentity(ctx, dir); err != nil {
return err
}
if repository.CreateNewWorkBranch {
if _, created := gitRevParse(ctx, dir, "refs/heads/"+repository.WorkBranch); !created {
if err := gitwork.RequireNewRemoteWorkBranch(ctx, dir, repository.WorkBranch); err != nil {
return err
}
}
}
if err := gitwork.ContinueSOPCheckout(ctx, dir, repository.WorkBranch); err != nil {
return err
}
Expand Down Expand Up @@ -468,7 +475,12 @@ func resumeRepository(ctx context.Context, workspace string, repository domain.R
// (and may have pushed), so it is resumed. Without it the branch is
// still to be created here, and a same-named remote branch belongs to
// someone else: refuse it exactly as a fresh clone does.
if _, created := gitRevParse(ctx, workspace, "refs/heads/"+strings.TrimSpace(repository.WorkBranch)); !created {
if _, created := gitRevParse(ctx, workspace, "refs/heads/"+strings.TrimSpace(repository.WorkBranch)); created {
checkout = func() error {
_, err := gitC(ctx, workspace, "checkout", "--quiet", repository.WorkBranch)
return err
}
} else {
checkout = func() error { return checkoutNewWorkBranch(ctx, workspace, repository.WorkBranch) }
}
}
Expand Down Expand Up @@ -521,20 +533,16 @@ func checkoutNewWorkBranch(ctx context.Context, workspace, workBranch string) er
if _, ok := gitRevParse(ctx, workspace, "refs/heads/"+workBranch); ok {
return fmt.Errorf("本地已存在分支 %s,不能按新建分支处理", workBranch)
}
out, err := gitC(ctx, workspace, "ls-remote", "--heads", "origin", "refs/heads/"+workBranch)
if err != nil {
return fmt.Errorf("无法确认远端分支 %s 是否存在:%w", workBranch, err)
}
for _, line := range strings.Split(out, "\n") {
_, ref, ok := strings.Cut(strings.TrimSpace(line), "\t")
if ok && ref == "refs/heads/"+workBranch {
return fmt.Errorf("远端已存在分支 %s,不能按新建分支处理;继续该分支请用 branchMode=continue", workBranch)
}
if err := gitwork.RequireNewRemoteWorkBranch(ctx, workspace, workBranch); err != nil {
return err
}
return createWorkBranchFromBase(ctx, workspace, workBranch)
}

func fetchRepositoryWorkBranch(ctx context.Context, workspace string, repository domain.RepositoryContext) error {
if repository.CreateNewWorkBranch {
return nil
}
err := fetchRemoteWorkBranch(ctx, workspace, repository.WorkBranch)
if err != nil && repository.RequireExistingWorkBranch {
return fmt.Errorf("继续开发的分支 %q 不存在或无法读取,请确认已有分支名称和权限:%w", repository.WorkBranch, err)
Expand Down Expand Up @@ -677,7 +685,7 @@ func defaultWorkBranch(issueNumber int, issueID string, now time.Time) string {
} else if issueID != "" {
branchOwner = "fix-" + domain.SafeGitRefSegment(issueID)
}
branch := "feature/" + branchOwner + "-" + now.In(time.Local).Format("20060102-1504")
branch := domain.DefaultWorkBranchPrefix + branchOwner + "-" + now.In(time.Local).Format("20060102-1504")
if issueNumber <= 0 && issueID == "" {
// Nothing ties these runs together (chat workspaces, free
// collaboration), so two started in the same minute must not share
Expand Down
Loading
Loading