Skip to content

Commit cea420e

Browse files
authored
feat(sop): configure repository work branch naming (#1342)
* feat(sop): configure repository work branch naming * fix(web): simplify SOP work branch prefix choices * test(web): update repository drawer branch naming fixture * fix(sop): retry AI branch names that already exist remotely
1 parent 058a530 commit cea420e

37 files changed

Lines changed: 1115 additions & 112 deletions

‎cmd/agentflow/main.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ func main() {
218218
readyStatus := "serving"
219219
switch role {
220220
case "worker":
221-
httpapi.ConfigureWorkerSOPSandboxSelection(s, e)
221+
httpapi.ConfigureWorkerSOPHelpers(s, e)
222222
e.ConfigureControl(engine.ControlConfig{Role: role, URL: endpoints.ControlURL, Token: endpoints.ControlToken, APIURL: endpoints.APIBase})
223223
e.StartInstanceHeartbeat(claimCtx)
224224
srv = &http.Server{Addr: endpoints.ListenAddr, Handler: workerHandler(e), ReadHeaderTimeout: 10 * time.Second}

‎docs/api/collaboration.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" -X POST \
6666
"$AGENTFLOW_URL/api/repositories"
6767
```
6868

69+
可用 `workBranchNaming` 设置 SOP 自动新建工作分支的命名方式。更新时省略该字段会保留已保存的配置,新仓库缺省使用 `feature/`。
70+
71+
- `{"mode":"prefix","prefix":"feat/"}` 为原有分支名主体加上指定前缀。`prefix` 留空时直接使用分支名主体。
72+
- `{"mode":"ai","executorId":"codebuddy","model":"hy4std","prompt":"用小写英文概括改动,带上需求编号"}` 使用指定的 CLI 和模型生成完整分支名。`executorId` 和 `model` 必填,`prompt` 可留空。调用使用 SOP 责任人的凭据或已授权执行机器的登录。平台能访问远端仓库时,会在遇到同名分支后按原命名要求重新生成。节点重试沿用已保存的分支名。
73+
6974
### `DELETE /api/repositories?id={id}`
7075

7176
`id` 必填。成功删除仓库,并清除引用它的项目默认仓库设置,返回 `200 {"status":"deleted"}`;缺少 `id` 或存储错误为 `400`。

‎docs/api/openapi.yaml‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5073,6 +5073,8 @@ components:
50735073
type: string
50745074
integrateBranch:
50755075
type: string
5076+
workBranchNaming:
5077+
$ref: "#/components/schemas/WorkBranchNaming"
50765078
createdAt:
50775079
type: string
50785080
format: date-time
@@ -5081,6 +5083,30 @@ components:
50815083
type: string
50825084
format: date-time
50835085
readOnly: true
5086+
WorkBranchNaming:
5087+
type: object
5088+
description: Naming settings for newly created SOP work branches. Repositories without settings use the feature/ prefix.
5089+
required: [mode]
5090+
properties:
5091+
mode:
5092+
type: string
5093+
enum: [prefix, ai]
5094+
prefix:
5095+
type: string
5096+
description: Literal prefix in prefix mode. An empty or omitted prefix within this mode produces a name without a prefix.
5097+
example: feat/
5098+
executorId:
5099+
type: string
5100+
description: Built-in CLI executor ID. Required in AI mode.
5101+
example: codebuddy
5102+
model:
5103+
type: string
5104+
description: Concrete model ID. Required in AI mode.
5105+
example: hy4std
5106+
prompt:
5107+
type: string
5108+
maxLength: 2000
5109+
description: Optional repository naming instructions for AI mode.
50845110
IssueListPage:
50855111
type: object
50865112
required: [items, total, offset, limit, hasMore]

‎e2e/api/20-issues.test.mjs‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import { test, before, after } from 'node:test';
55
import assert from 'node:assert/strict';
66
import { api, get, post, put, list, track, cleanup, ensureProject, waitFor, waitRun } from '../lib/api.mjs';
7-
import { cfg } from '../lib/env.mjs';
7+
import { cfg, requireToken } from '../lib/env.mjs';
88
import { createWorkflow, script, approval, trackRun } from '../lib/fixtures.mjs';
99

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

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

55+
test('creates a Markdown requirement and serves its attached image to authenticated users', async () => {
56+
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGPQc/8PAAIbAXVXkdKiAAAAAElFTkSuQmCC', 'base64');
57+
const description = '## Reproduction\n\nSee the **attached image**.';
58+
const form = new FormData();
59+
form.set('issue', JSON.stringify({ projectId: P, kind: 'requirement', title: `E2E requirement image ${cfg.runTag}`, description }));
60+
form.append('images', new Blob([png], { type: 'image/png' }), 'reproduction.png');
61+
62+
const created = await post('/api/issues', form);
63+
removeLater(created.id);
64+
const detail = await detailOf(created.id);
65+
assert.equal(detail.issue.description, description);
66+
assert.equal(detail.images.length, 1);
67+
const [image] = detail.images;
68+
assert.ok(image.id);
69+
assert.equal(image.name, 'reproduction.png');
70+
71+
const path = `/api/issues/${created.id}/images/${image.id}`;
72+
await get(path, { auth: false, expect: 401 });
73+
const response = await fetch(cfg.base + path, {
74+
headers: { Authorization: `Bearer ${requireToken()}` },
75+
signal: AbortSignal.timeout(15_000),
76+
});
77+
assert.equal(response.status, 200);
78+
assert.equal(response.headers.get('content-type'), 'image/png');
79+
assert.deepEqual(Buffer.from(await response.arrayBuffer()), png);
80+
});
81+
5582
test('edit keeps identity and records an operation', async () => {
5683
const { issue: current } = await detailOf(issue.id);
5784
const saved = await put('/api/issues', { ...current, title: `${current.title}(已编辑)`, priority: 'high' });

‎internal/domain/assistant_preferences.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package domain
22

33
import (
4+
"fmt"
45
"strings"
56
"time"
67
)
@@ -13,6 +14,23 @@ type AssistantDefaults struct {
1314
Approval string `json:"approval,omitempty"`
1415
}
1516

17+
// ValidateCLIModelID checks the literal model identifier accepted by CLI settings.
18+
func ValidateCLIModelID(id string) error {
19+
const maxCLIModelIDLen = 128
20+
if id == "" {
21+
return fmt.Errorf("模型 ID 不能为空")
22+
}
23+
if len(id) > maxCLIModelIDLen {
24+
return fmt.Errorf("模型 ID 长度不能超过 %d 个字符", maxCLIModelIDLen)
25+
}
26+
for _, r := range id {
27+
if r <= ' ' || r == 0x7f || r == '"' || r == '\'' || r == '`' || r == '\\' {
28+
return fmt.Errorf("模型 ID %q 不能包含空格、引号、反斜杠或控制字符", id)
29+
}
30+
}
31+
return nil
32+
}
33+
1634
// AssistantPreferencesInstructionsMax caps the user's own rules for Main Bot.
1735
const AssistantPreferencesInstructionsMax = 4000
1836

‎internal/domain/project.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,8 @@ type Repository struct {
133133
IntegrateBranch string `json:"integrateBranch,omitempty"`
134134
CreatedAt time.Time `json:"createdAt"`
135135
UpdatedAt time.Time `json:"updatedAt"`
136+
137+
WorkBranchNaming *WorkBranchNaming `json:"workBranchNaming,omitempty"`
136138
}
137139

138140
// PublicRepository strips the git token for API responses. Clone/push still

‎internal/domain/work_branch.go‎

Lines changed: 81 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,83 @@ import (
44
"fmt"
55
"strings"
66
"time"
7+
"unicode/utf8"
78
)
89

10+
const (
11+
DefaultWorkBranchPrefix = "feature/"
12+
WorkBranchNamingPrefix = "prefix"
13+
WorkBranchNamingAI = "ai"
14+
)
15+
16+
// WorkBranchNaming controls how a repository names newly generated work
17+
// branches. An absent setting uses the legacy prefix. In prefix mode an empty
18+
// Prefix deliberately produces a branch with no prefix.
19+
type WorkBranchNaming struct {
20+
Mode string `json:"mode"`
21+
Prefix string `json:"prefix,omitempty"`
22+
ExecutorID string `json:"executorId,omitempty"`
23+
Model string `json:"model,omitempty"`
24+
Prompt string `json:"prompt,omitempty"`
25+
}
26+
27+
func (n WorkBranchNaming) Normalize() (WorkBranchNaming, error) {
28+
switch n.Mode {
29+
case WorkBranchNamingPrefix:
30+
n.Prefix = strings.TrimSpace(n.Prefix)
31+
n.ExecutorID, n.Model, n.Prompt = "", "", ""
32+
if !ValidNewWorkBranchName(n.Prefix + "work-branch") {
33+
return WorkBranchNaming{}, fmt.Errorf("工作分支前缀不能生成合法的 Git 分支名")
34+
}
35+
case WorkBranchNamingAI:
36+
n.ExecutorID = strings.TrimSpace(n.ExecutorID)
37+
n.Model = strings.TrimSpace(n.Model)
38+
n.Prompt = strings.TrimSpace(n.Prompt)
39+
n.Prefix = ""
40+
if n.ExecutorID == "" || n.Model == "" || n.Model == "default" || n.Model == "default-model" {
41+
return WorkBranchNaming{}, fmt.Errorf("请在仓库设置中为 AI 分支命名选择 CLI 和具体模型")
42+
}
43+
if strings.HasPrefix(n.Model, "-") {
44+
return WorkBranchNaming{}, fmt.Errorf("模型 ID 不能以 - 开头")
45+
}
46+
if err := ValidateCLIModelID(n.Model); err != nil {
47+
return WorkBranchNaming{}, err
48+
}
49+
if utf8.RuneCountInString(n.Prompt) > 2000 {
50+
return WorkBranchNaming{}, fmt.Errorf("分支命名要求最多 2000 个字符")
51+
}
52+
default:
53+
return WorkBranchNaming{}, fmt.Errorf("工作分支命名方式必须是 prefix 或 ai")
54+
}
55+
return n, nil
56+
}
57+
58+
// ValidGitBranchName accepts literal branch names, excluding revisions and
59+
// values that could be interpreted as command options.
60+
func ValidGitBranchName(branch string) bool {
61+
if branch == "" || branch == "HEAD" || strings.HasPrefix(branch, "-") ||
62+
strings.HasSuffix(branch, ".") || strings.Contains(branch, "..") ||
63+
strings.Contains(branch, "@{") || strings.ContainsAny(branch, "~^:?*[\\") {
64+
return false
65+
}
66+
for _, r := range branch {
67+
if r <= ' ' || r == 127 {
68+
return false
69+
}
70+
}
71+
for _, component := range strings.Split(branch, "/") {
72+
if component == "" || strings.HasPrefix(component, ".") || strings.HasSuffix(component, ".lock") {
73+
return false
74+
}
75+
}
76+
return true
77+
}
78+
79+
// ValidNewWorkBranchName expects a short name suitable for a checkout.
80+
func ValidNewWorkBranchName(branch string) bool {
81+
return ValidGitBranchName(branch) && branch != "@" && !strings.HasPrefix(branch, "refs/heads/")
82+
}
83+
984
// DefaultWorkBranch names the git work branch for an issue run. Gongfeng issues
1085
// use fix-issue-{iid}; TAPD stories use story-{tapdId}; platform requirements use
1186
// requirement-{number}. The suffix is a local timestamp that keeps branch names
@@ -17,26 +92,26 @@ func DefaultWorkBranch(issue Issue, now time.Time) string {
1792

1893
if source == "tapd" || strings.HasPrefix(strings.TrimSpace(issue.ID), "tapd-") {
1994
if id := tapdStoryID(issue); id != "" {
20-
return "feature/story-" + SafeGitRefSegment(id) + "-" + suffix
95+
return DefaultWorkBranchPrefix + "story-" + SafeGitRefSegment(id) + "-" + suffix
2196
}
2297
}
2398
if source == "gongfeng" || kind == "issue" {
2499
if n := gongfengIssueNumber(issue); n > 0 {
25-
return fmt.Sprintf("feature/fix-issue-%d-%s", n, suffix)
100+
return fmt.Sprintf("%sfix-issue-%d-%s", DefaultWorkBranchPrefix, n, suffix)
26101
}
27102
}
28103
if kind == "requirement" || source == "" || source == "local" {
29104
if issue.Number > 0 {
30-
return fmt.Sprintf("feature/requirement-%d-%s", issue.Number, suffix)
105+
return fmt.Sprintf("%srequirement-%d-%s", DefaultWorkBranchPrefix, issue.Number, suffix)
31106
}
32107
}
33108
if issue.Number > 0 {
34-
return fmt.Sprintf("feature/fix-issue-%d-%s", issue.Number, suffix)
109+
return fmt.Sprintf("%sfix-issue-%d-%s", DefaultWorkBranchPrefix, issue.Number, suffix)
35110
}
36111
if issue.ID != "" {
37-
return "feature/" + SafeGitRefSegment(issue.ID) + "-" + suffix
112+
return DefaultWorkBranchPrefix + SafeGitRefSegment(issue.ID) + "-" + suffix
38113
}
39-
return "feature/fix-" + suffix
114+
return DefaultWorkBranchPrefix + "fix-" + suffix
40115
}
41116

42117
func gongfengIssueNumber(issue Issue) int {

‎internal/engine/engine.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ type Engine struct {
9595
WorkspaceActive func(domain.Run) bool
9696
WorkspaceCheckpointTransport func(context.Context, domain.Run, domain.RunnerWorkspaceRequest) (domain.RunnerWorkspaceResponse, error)
9797
SelectSOPSandbox func(context.Context, SOPSandboxSelection) string
98+
GenerateSOPWorkBranch func(context.Context, SOPWorkBranchRequest) (string, error)
9899
maintenanceOnce sync.Once
99100
}
100101

‎internal/engine/node_execute.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -561,7 +561,7 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl
561561
}
562562
return nil
563563
}); err != nil {
564-
if ctx.Err() != nil || !firstRepositoryAgent(wf, node) {
564+
if ctx.Err() != nil || errors.Is(err, gitwork.ErrWorkBranchExists) || !firstRepositoryAgent(wf, node) {
565565
failNode(err, nodeRejects(node))
566566
return
567567
}

‎internal/engine/prompt.go‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,23 @@ func applyPromptPlaceholders(st *repo.Store, wf domain.WorkflowDefinition, node
3333
}
3434
prompt = strings.ReplaceAll(prompt, "{{input}}", run.Input)
3535
prompt = strings.ReplaceAll(prompt, "{{repository}}", promptRepositoryLine(run))
36+
repositories := run.RepositoryContexts()
3637
if run.UsesConversationWorkspace() {
3738
prompt += "\n\n## 对话工作区\n\n在交接的工作区内继续,保留已有文件和本地改动。"
38-
for _, repository := range run.RepositoryContexts() {
39+
for _, repository := range repositories {
3940
dir := repository.WorkspaceDir
4041
if dir == "" {
4142
dir = "."
4243
}
4344
prompt += fmt.Sprintf("\n- %s 在 `%s`,工作分支 `%s`,PR/MR 目标分支 `%s`。", repository.Name, dir, repository.WorkBranch, repositoryBaseBranch(repository))
4445
}
46+
} else if len(repositories) > 1 || run.Repository.CreateNewWorkBranch {
47+
prompt += "\n\n## 仓库工作分支\n\n使用各仓库已分配的工作分支作为 PR/MR 的源分支。"
48+
for _, repository := range repositories {
49+
if !repository.ReadOnly && repository.WorkBranch != "" {
50+
prompt += fmt.Sprintf("\n- %s 在 %q,工作分支 %q,PR/MR 目标分支 %q。", repository.Name, repository.WorkspaceDir, repository.WorkBranch, repositoryBaseBranch(repository))
51+
}
52+
}
4553
}
4654
pipelineURL := "未配置 Pipeline"
4755
if run.Repository.PipelineURLPattern != "" {

0 commit comments

Comments
 (0)