Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
feat(sop): add an MR node to the built-in code delivery SOPs (#967)
Robert062269e4bf093cf2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5513299a..ba99076f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,7 @@ Platform releases use `vX.Y.Z` tags and publish `ghcr.io/tencent/loopforge`. Loo## Unreleased+- The built-in backend, frontend and defect-fix SOPs gain a 「发起 MR」 node between 人工验收 and 交付汇总 (#717). It commits the work branch, pushes it and opens an MR/PR against the run's target branch, then records the link, branches and commit SHA in `mr-body.md`. Its command gate checks every writable repository of the run: one with commits beyond the target branch fails while it has uncommitted changes, while its checkout is off the run's work branch, or until `git ls-remote origin` shows that work branch at HEAD. A repository the run left unchanged is skipped. A second gate of the new mode `mr` has the engine look the MR up on the host with the same lookup delivery tracking uses (GitHub and Gongfeng): every writable repository whose work branch on origin carries commits beyond the target branch needs an MR from that work branch into that target branch that carries the pushed tip: an open one whose head is the tip (or whose host reports no head), or a merged one whose head is the tip. An agent that reports pass without opening an MR, opens it against the wrong branch, or leaves only an earlier merged MR on a reused work branch does not reach 交付汇总. The lookup runs as the run: on GitHub with the Git token the run pushed with (its responsible user's), falling back to the Owner of the run's own project; on Gongfeng through the run project's MCP as the responsible user. A repository bound to several projects is no longer checked as whichever project bound it first, and a failed lookup names the identity it used. A host the platform cannot query (an SSH repository, a failed lookup) goes straight to a person. `mr` gates take no commands, and the role editor keeps them when a role is saved. The gates retry once with their feedback and then wait for a person, so a run no longer succeeds with every source change left in a workspace that is reclaimed right after success. Run-scoped commands now get `AGENTFLOW_WORK_BRANCHES` (one `dir<TAB>work branch<TAB>target branch` line per writable repository) and repository-scoped commands get `AGENTFLOW_WORK_BRANCH` and `AGENTFLOW_BASE_BRANCH`; the target branch is the one frozen into the run, including a requirement's release branch and a scheduled SOP's integration branch. 交付汇总 no longer pushes or opens a PR itself. Runs without a bound repository still deliver from the task workspace. New installs get the new templates from the seed. Existing installs keep their templates until an operator runs `migrations/033_generic_sop_mr_node.sql` by hand (see docs/deployment.md); it rewrites a template only while its node graph and 交付汇总 position are the shipped original and its 交付汇总 prompt only while unedited. SOPs already adopted into a project are copies and keep their old graph. The product SOP delivers documents only and is unchanged.- A conversation reply that is still running keeps running through a slow heartbeat. A poll, the conversation list, a follow-up message or a steer used to record it as interrupted after 45 seconds without a stored heartbeat; the process then cancelled the CLI and the next message failed with 「工作区正在使用或保存,请稍后重试」 for up to 15 minutes. Reads of a turn this process executes no longer reap it, and an unchanged heartbeat on MySQL no longer counts as a lost turn. On MySQL a heartbeat's age is measured on the database clock that stamped it, so skew between an API host and MySQL neither reaps a live turn nor keeps a dead one; whether a lease holder stopped renewing is likewise judged from `run_workspace_checkpoints.lease_renewed_at`, stamped on the database clock, not from another replica's `lease_until`. When a turn whose process died is reaped, the workspace lease it recorded is released if nothing renewed it for 45 seconds, so the next message starts at once; a lease another turn took, one still renewed on another replica, and a background save are kept. `migrations/032_assistant_generation_workspace_lease.sql` adds the three columns by hand; startup AutoMigrate adds them too.- The platform image bundles DeepSeek Harness `@deepseek-ai/[email protected]` next to Codex and CodeBuddy, so a DeepSeek key works in conversations and SOP roles without an install step. 0.3.8 had no `dsh` and answered a DeepSeek Harness chat with “AI 助手生成失败,请稍后重试”. The image download grows by about 180 MB. An installation without the image installs the same pinned version from the conversation: every dsh release is a prerelease requiring Node 24.9, and npm on Node 22 found no version for the bare package name.diff --git a/docs/deployment.md b/docs/deployment.mdindex eb3ff8fb..15a9c4a0 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -161,6 +161,14 @@ docker compose exec -T mysql sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" mysql -u loopforThis repeatable SQL changes only instruction fields that still match the original public seed. It preserves operator edits and project copies. New installations already receive these instructions from the public catalog seed; application startup does not migrate data.+To add the 「发起 MR」 node to the built-in backend, frontend and defect-fix SOPs of an existing installation, apply `033_generic_sop_mr_node.sql` the same way:++```bash+docker compose exec -T mysql sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" mysql -u loopforge loopforge' < migrations/033_generic_sop_mr_node.sql+```++After it, a run of these SOPs commits and pushes its work branch and opens an MR/PR before 交付汇总, so the Git credentials of the run's responsible user need push access. The installer and `./start.sh pull` do not run it. It rewrites a template only while its node graph and 交付汇总 position are the shipped original, and the 交付汇总 prompt only while unedited; it is safe to repeat. Project SOPs adopted from these templates are copies and are not changed.+## GitHub credentialsUsers can choose **Connect GitHub** in personal credentials or while adding a repository, copy the displayed PIN, and approve it on GitHub. The platform saves the grant to that signed-in user's existing Git credential slot. The repository picker lists repositories owned by the account, shared with it, or accessible through its organizations, supports pagination and search over loaded repositories, and copies the selected repository's real default branch into the form. PAT entry remains available.diff --git a/internal/domain/delivery_mr.go b/internal/domain/delivery_mr.goindex 6537401e..889169e5 100644--- a/internal/domain/delivery_mr.go+++ b/internal/domain/delivery_mr.go@@ -20,6 +20,23 @@ type DeliveryMR struct {// GongfengState is the raw Gongfeng state from a live lookup; empty when// the MR was only recovered from artifact text.GongfengState string `json:"-"`+ // HeadSHA is the source commit a live lookup reports; empty when the host+ // response carries none.+ HeadSHA string `json:"-"`+}++// BranchMRQuery asks the host for the MRs from one work branch into one target+// branch, in a run's execution context: ProjectID is the run's project and+// GitToken the credential the run pushed with.+type BranchMRQuery struct {+ ProjectID string+ RemoteProject string+ SourceBranch string+ TargetBranch string+ GitToken string+ // ResponsibleUserID is the run's responsible user, the identity GitToken+ // belongs to.+ ResponsibleUserID int64}// GongfengMRURL is the canonical web URL of a Gongfeng merge request.diff --git a/internal/domain/verification.go b/internal/domain/verification.goindex d7e3e4ac..b42cbce5 100644--- a/internal/domain/verification.go+++ b/internal/domain/verification.go@@ -70,12 +70,18 @@ func uniqueGateID(base string, used map[string]bool) string {}}+// VerificationModeMR gates pass only when, for every repository whose pushed+// work branch carries new commits, the hosting platform has an MR from that+// work branch into the run's target branch that carries the pushed tip. The+// engine runs the check; the gate has no commands.+const VerificationModeMR = "mr"+// ValidateVerificationGate requires command gates to declare run or repositories.-// Manual gates and empty command lists may omit the field.+// Manual and MR gates and empty command lists may omit the field.func ValidateVerificationGate(gate VerificationGate) error {mode := gateMode(gate)switch mode {- case "", "command", "manual":+ case "", "command", "manual", VerificationModeMR:default:return fmt.Errorf("verification gate %s has invalid mode %q", gate.ID, gate.Mode)}@@ -83,6 +89,9 @@ func ValidateVerificationGate(gate VerificationGate) error {if scope != "" && scope != ExecutionScopeRun && scope != ExecutionScopeRepositories {return fmt.Errorf("verification gate %s has invalid executionScope %q", gate.ID, gate.ExecutionScope)}+ if mode == VerificationModeMR && commandHasContent(gate) {+ return fmt.Errorf("verification gate %s: mode %q takes no commands", gate.ID, VerificationModeMR)+ }if mode == "manual" || !commandHasContent(gate) {return nil}diff --git a/internal/domain/verification_test.go b/internal/domain/verification_test.goindex 914126aa..8c23425b 100644--- a/internal/domain/verification_test.go+++ b/internal/domain/verification_test.go@@ -19,6 +19,12 @@ func TestValidateVerificationGateRequiresScopeForCommands(t *testing.T) {if err := ValidateVerificationGate(VerificationGate{ID: "verdict", Mode: "submit", Required: true}); err == nil {t.Fatal("submit is an engine-owned terminal protocol, not a configurable gate")}+ if err := ValidateVerificationGate(VerificationGate{ID: "mr-opened", Mode: VerificationModeMR, Required: true}); err != nil {+ t.Fatalf("mr gate without scope or commands: %v", err)+ }+ if err := ValidateVerificationGate(VerificationGate{ID: "mr-opened", Mode: VerificationModeMR, Commands: []string{"true"}, ExecutionScope: ExecutionScopeRun}); err == nil {+ t.Fatal("an mr gate is checked by the engine and takes no commands")+ }}func TestSplitVerificationGatesSeparatesGitFromDeliverables(t *testing.T) {diff --git a/internal/domain/workflow.go b/internal/domain/workflow.goindex 69f1b6f3..57607475 100644--- a/internal/domain/workflow.go+++ b/internal/domain/workflow.go@@ -10,7 +10,7 @@ import (type VerificationGate struct {ID string `json:"id"`Name string `json:"name"`- Mode string `json:"mode"` // command, manual+ Mode string `json:"mode"` // command, manual, mrStage string `json:"stage,omitempty"` // after_execution, before_publishCommands []string `json:"commands,omitempty"`Required bool `json:"required"`diff --git a/internal/engine/core_cases_test.go b/internal/engine/core_cases_test.goindex d0ba8996..aea7f1a5 100644--- a/internal/engine/core_cases_test.go+++ b/internal/engine/core_cases_test.go@@ -172,6 +172,29 @@ func TestExecutionTargetsAndTelemetryHelpers(t *testing.T) {if !strings.Contains(command, "AGENTFLOW_REPOSITORY_ID='one'") || !strings.Contains(command, "cd -- 'repos/one'") {t.Fatal(command)}+ branched := domain.Run{Repositories: []domain.RepositoryContext{+ {RepositoryID: "one", WorkspaceDir: "one", WorkBranch: "feat", BaseBranch: "release/1.2", DefaultBranch: "main"},+ {RepositoryID: "two", WorkspaceDir: "two", WorkBranch: "feat", ReadOnly: true},+ {RepositoryID: "three", WorkspaceDir: "three"},+ {RepositoryID: "legacy", WorkBranch: "feat", DefaultBranch: "trunk"},+ }}+ runTargets, err := executionTargets(branched, domain.ExecutionScopeRun)+ if err != nil || len(runTargets) != 1 {+ t.Fatalf("run targets = %+v %v", runTargets, err)+ }+ if command := bindExecutionTarget("true", runTargets[0]); !strings.Contains(command, "export AGENTFLOW_WORK_BRANCHES='one\tfeat\trelease/1.2\n.\tfeat\ttrunk'\n") {+ t.Fatal(command)+ }+ repoTargets, err := executionTargets(branched, domain.ExecutionScopeRepositories)+ if err != nil {+ t.Fatal(err)+ }+ if command := bindExecutionTarget("true", repoTargets[0]); !strings.Contains(command, "AGENTFLOW_WORK_BRANCH='feat'") || !strings.Contains(command, "AGENTFLOW_BASE_BRANCH='release/1.2'") {+ t.Fatal(command)+ }+ if command := bindExecutionTarget("true", repoTargets[1]); !strings.Contains(command, "AGENTFLOW_WORK_BRANCH=''") {+ t.Fatal(command)+ }got, err := executeForTargets(run, domain.ExecutionScopeRepositories, func(target executionTarget) (string, error) {return target.label(), nil})diff --git a/internal/engine/engine.go b/internal/engine/engine.goindex f1c7ebf3..9e7ec051 100644--- a/internal/engine/engine.go+++ b/internal/engine/engine.go@@ -57,6 +57,10 @@ type Engine struct {// work branch. Nil (local/dev) falls back to MR links in run artifacts.FindBranchMR func(projectID, sourceBranch string) (domain.DeliveryMR, bool, error)+ // FindBranchMRsInto lists the MRs from a work branch into one target+ // branch with their head commits, for mode=mr gates. Nil cannot verify.+ FindBranchMRsInto func(domain.BranchMRQuery) ([]domain.DeliveryMR, error)+// runnerDispatchNotify wakes long-polling CLI runners when the engine// queues a runner task. Wired via SetRunnerDispatchNotify (httpapi.New);// nil falls back to the runner claim retry interval.diff --git a/internal/engine/execution_scope.go b/internal/engine/execution_scope.goindex a6f998e0..c4eccbc8 100644--- a/internal/engine/execution_scope.go+++ b/internal/engine/execution_scope.go@@ -12,6 +12,9 @@ import (type executionTarget struct {Scope stringRepository *domain.RepositoryContext+ // Repositories lists every run repository for a Run-scoped target, whose+ // command reaches them through AGENTFLOW_WORK_BRANCHES.+ Repositories []domain.RepositoryContext}func executionTargetSink(sink runtime.EventSink, target executionTarget) runtime.EventSink {@@ -40,10 +43,10 @@ func normalizeExecutionScope(scope string) string {func executionTargets(run domain.Run, scope string) ([]executionTarget, error) {scope = normalizeExecutionScope(scope)+ repositories := run.RepositoryContexts()if scope == domain.ExecutionScopeRun {- return []executionTarget{{Scope: scope}}, nil+ return []executionTarget{{Scope: scope, Repositories: repositories}}, nil}- repositories := run.RepositoryContexts()if len(repositories) == 0 {return nil, errors.New("逐仓库执行需要 Run 至少绑定一个代码仓库")}@@ -81,6 +84,8 @@ func (t executionTarget) label() string {// bindExecutionTarget makes script-like commands independent from the// physical single/multi-repository layout. Repository-scoped commands start// in the selected checkout; Run-scoped commands start at the workspace root.+// Branches are the ones frozen into the run, so a gate can check what was+// actually pushed instead of trusting whatever the checkout is on.func bindExecutionTarget(command string, target executionTarget) string {var b strings.Builderb.WriteString(`export AGENTFLOW_WORKSPACE="$PWD"`)@@ -89,14 +94,44 @@ func bindExecutionTarget(command string, target executionTarget) string {b.WriteString("\nexport AGENTFLOW_REPOSITORY_ID=" + shellSingleQuote(target.Repository.RepositoryID))b.WriteString("\nexport AGENTFLOW_REPOSITORY_NAME=" + shellSingleQuote(target.Repository.Name))b.WriteString("\nexport AGENTFLOW_REPOSITORY_DIR=" + shellSingleQuote(target.directory()))+ b.WriteString("\nexport AGENTFLOW_WORK_BRANCH=" + shellSingleQuote(writableWorkBranch(*target.Repository)))+ b.WriteString("\nexport AGENTFLOW_BASE_BRANCH=" + shellSingleQuote(repositoryBaseBranch(*target.Repository)))if dir := target.directory(); dir != "" {b.WriteString("\ncd -- " + shellSingleQuote(dir))}+ } else {+ b.WriteString("\nexport AGENTFLOW_WORK_BRANCHES=" + shellSingleQuote(workBranchManifest(target.Repositories)))}b.WriteString("\n" + command)return b.String()}+func writableWorkBranch(repository domain.RepositoryContext) string {+ if repository.ReadOnly {+ return ""+ }+ return strings.TrimSpace(repository.WorkBranch)+}++// workBranchManifest lists one "dir<TAB>work branch<TAB>target branch" line+// per repository the run may push. A legacy checkout at the workspace root+// is listed as ".".+func workBranchManifest(repositories []domain.RepositoryContext) string {+ var lines []string+ for _, repository := range repositories {+ work := writableWorkBranch(repository)+ if work == "" {+ continue+ }+ dir := strings.TrimSpace(repository.WorkspaceDir)+ if dir == "" {+ dir = "."+ }+ lines = append(lines, dir+"\t"+work+"\t"+repositoryBaseBranch(repository))+ }+ return strings.Join(lines, "\n")+}+func executeForTargets(run domain.Run, scope string, execute func(executionTarget) (string, error)) (string, error) {targets, err := executionTargets(run, scope)if err != nil {diff --git a/internal/engine/gate_mr.go b/internal/engine/gate_mr.gonew file mode 100644index 00000000..e86be9bf--- /dev/null+++ b/internal/engine/gate_mr.go@@ -0,0 +1,143 @@+package engine++import (+ "errors"+ "fmt"+ "strconv"+ "strings"++ "agentflow/internal/domain"+)++// mrPendingCommand prints the work branch tip on origin and how many commits+// it carries beyond the run's target branch; "- 0" when it was never pushed.+const mrPendingCommand = `refs="$(git ls-remote origin "refs/heads/$AGENTFLOW_WORK_BRANCH")" || exit 2+tip="$(printf '%s\n' "$refs" | cut -f1)"+if [ -z "$tip" ]; then echo "- 0"; exit 0; fi+git cat-file -e "$tip^{commit}" 2>/dev/null || git fetch -q origin "refs/heads/$AGENTFLOW_WORK_BRANCH" || exit 2+printf '%s %s\n' "$tip" "$(git rev-list --count "$tip" --not "refs/remotes/origin/$AGENTFLOW_BASE_BRANCH")"`++// errMRUnverifiable marks MR problems another agent iteration cannot fix: the+// host cannot be queried, so a person has to confirm the MR.+var errMRUnverifiable = errors.New("MR cannot be verified on the hosting platform")++// pushedWork is a repository's work branch tip on origin and how many commits+// it carries beyond the run's target branch.+type pushedWork struct {+ Tip string+ Ahead int+}++// verifyRunMRs implements mode=mr gates. Every writable repository whose work+// branch on origin carries commits beyond the run's target branch needs an MR+// from that work branch into that target branch that carries the pushed tip:+// an open MR whose head is the tip (or whose host reports no head), or a+// merged MR whose head is the tip. An earlier MR merged before this run's+// pushes does not count.+//+// The lookup runs in the run's execution context: its project and gitToken,+// the credential the run pushed with.+func (e *Engine) verifyRunMRs(run domain.Run, gitToken string, pending func(domain.RepositoryContext) (pushedWork, error)) error {+ var problems []string+ unverifiable := false+ for _, rc := range run.RepositoryContexts() {+ work := writableWorkBranch(rc)+ if work == "" {+ continue+ }+ label := strings.TrimSpace(rc.Name)+ if label == "" {+ label = rc.RepositoryID+ }+ base := repositoryBaseBranch(rc)+ pushed, err := pending(rc)+ if err != nil {+ problems = append(problems, fmt.Sprintf("%s:无法读取远端工作分支 %s:%v", label, work, err))+ continue+ }+ if pushed.Ahead == 0 {+ continue+ }+ project := strings.TrimSpace(rc.GongfengProjectID)+ if e.FindBranchMRsInto == nil || project == "" {+ problems = append(problems, fmt.Sprintf("%s:托管平台不支持自动核验 MR,请人工确认已创建 %s → %s 的 MR", label, work, base))+ unverifiable = true+ continue+ }+ mrs, err := e.FindBranchMRsInto(domain.BranchMRQuery{ProjectID: run.ExecutionContext.ProjectID, RemoteProject: project, SourceBranch: work, TargetBranch: base, GitToken: gitToken, ResponsibleUserID: run.ExecutionContext.ResponsibleUserID})+ if err != nil {+ problems = append(problems, fmt.Sprintf("%s:查询 %s → %s 的 MR 失败:%v", label, work, base, err))+ unverifiable = true+ continue+ }+ if problem := mrCoverageProblem(mrs, pushed.Tip); problem != "" {+ problems = append(problems, fmt.Sprintf("%s:%s → %s %s", label, work, base, problem))+ }+ }+ if len(problems) == 0 {+ return nil+ }+ err := errors.New(strings.Join(problems, ";"))+ if unverifiable {+ return fmt.Errorf("%w:%w", errMRUnverifiable, err)+ }+ return err+}++// mrCoverageProblem returns "" when one of mrs carries tip, else what is wrong.+func mrCoverageProblem(mrs []domain.DeliveryMR, tip string) string {+ var stale, merged []string+ closed := 0+ for _, mr := range mrs {+ head := strings.TrimSpace(mr.HeadSHA)+ switch deliveryMRState(mr) {+ case "opened":+ if head == "" || head == tip {+ return ""+ }+ stale = append(stale, fmt.Sprintf("%s 的源提交是 %s", mr.URL, head))+ case "merged":+ if head == tip {+ return ""+ }+ merged = append(merged, mr.URL)+ default:+ closed+++ }+ }+ switch {+ case len(stale) > 0:+ return fmt.Sprintf("的 MR 还没有包含远端工作分支的 %s:%s", tip, strings.Join(stale, ","))+ case len(merged) > 0:+ return fmt.Sprintf("只有已合并的 MR %s,不包含本轮推送的 %s,需要创建新的 MR", strings.Join(merged, ","), tip)+ case closed > 0:+ return "的 MR 已关闭,需要重新打开或创建新的 MR"+ default:+ return "在托管平台上没有 MR/PR,需要创建"+ }+}++func deliveryMRState(mr domain.DeliveryMR) string {+ state := strings.TrimSpace(mr.GongfengState)+ if state == "" {+ state = strings.TrimSpace(mr.State)+ }+ if state == "reopened" {+ return "opened"+ }+ return state+}++func parseMRPending(output string) (pushedWork, error) {+ lines := strings.Split(strings.TrimSpace(output), "\n")+ last := strings.TrimSpace(lines[len(lines)-1])+ fields := strings.Fields(last)+ if len(fields) != 2 {+ return pushedWork{}, fmt.Errorf("unexpected output %q", last)+ }+ n, err := strconv.Atoi(fields[1])+ if err != nil {+ return pushedWork{}, fmt.Errorf("unexpected output %q", last)+ }+ return pushedWork{Tip: fields[0], Ahead: n}, nil+}diff --git a/internal/engine/gate_mr_test.go b/internal/engine/gate_mr_test.gonew file mode 100644index 00000000..a03861e1--- /dev/null+++ b/internal/engine/gate_mr_test.go@@ -0,0 +1,258 @@+package engine++import (+ "errors"+ "os"+ "os/exec"+ "path/filepath"+ "strconv"+ "strings"+ "testing"++ "agentflow/internal/domain"+ "agentflow/internal/repo"+ "agentflow/internal/runtime"+)++func TestVerifyRunMRsRequiresAnMRCarryingThePushedTip(t *testing.T) {+ t.Parallel()+ run := domain.Run{ExecutionContext: domain.TelemetryContext{ProjectID: "proj", ResponsibleUserID: 7}, Repositories: []domain.RepositoryContext{+ {RepositoryID: "svc", Name: "svc", GongfengProjectID: "github:o/svc", WorkspaceDir: "svc", WorkBranch: "feat", BaseBranch: "release/1.2", DefaultBranch: "main"},+ {RepositoryID: "docs", Name: "docs", GongfengProjectID: "github:o/docs", WorkspaceDir: "docs", WorkBranch: "feat", DefaultBranch: "main"},+ {RepositoryID: "ro", Name: "ro", GongfengProjectID: "github:o/ro", WorkspaceDir: "ro", WorkBranch: "feat", ReadOnly: true},+ }}+ pushed := map[string]pushedWork{"svc": {Tip: "new", Ahead: 2}, "docs": {Tip: "-", Ahead: 0}, "ro": {Tip: "x", Ahead: 5}}+ pending := func(rc domain.RepositoryContext) (pushedWork, error) { return pushed[rc.RepositoryID], nil }+ var looked []string+ var mrs []domain.DeliveryMR+ e := &Engine{FindBranchMRsInto: func(q domain.BranchMRQuery) ([]domain.DeliveryMR, error) {+ looked = append(looked, q.ProjectID+":"+q.RemoteProject+"@"+q.SourceBranch+"->"+q.TargetBranch+" as "+q.GitToken+"/"+strconv.FormatInt(q.ResponsibleUserID, 10))+ return mrs, nil+ }}+ fails := func(want string) {+ t.Helper()+ err := e.verifyRunMRs(run, "push-token", pending)+ if err == nil || errors.Is(err, errMRUnverifiable) || !strings.Contains(err.Error(), want) {+ t.Fatalf("want a self-correctable failure containing %q, got %v", want, err)+ }+ }+ passes := func() {+ t.Helper()+ if err := e.verifyRunMRs(run, "push-token", pending); err != nil {+ t.Fatal(err)+ }+ }++ fails("svc:feat → release/1.2 在托管平台上没有 MR/PR")+ if strings.Join(looked, ",") != "proj:github:o/svc@feat->release/1.2 as push-token/7" {+ t.Fatalf("only the repository with pushed commits is looked up, into its frozen target, with the run's project and push token: %v", looked)+ }+ mrs = []domain.DeliveryMR{{URL: "pr/3", State: "merged", HeadSHA: "old"}}+ fails("只有已合并的 MR pr/3,不包含本轮推送的 new")+ mrs = []domain.DeliveryMR{{URL: "pr/3", State: "merged"}}+ fails("只有已合并的 MR pr/3")+ mrs = []domain.DeliveryMR{{URL: "pr/3", State: "closed", HeadSHA: "new"}}+ fails("的 MR 已关闭")+ mrs = []domain.DeliveryMR{{URL: "pr/4", State: "opened", HeadSHA: "older"}}+ fails("还没有包含远端工作分支的 new:pr/4 的源提交是 older")++ mrs = []domain.DeliveryMR{{URL: "pr/3", State: "merged", HeadSHA: "old"}, {URL: "pr/4", State: "opened", HeadSHA: "new"}}+ passes()+ mrs = []domain.DeliveryMR{{URL: "!4", GongfengState: "reopened"}}+ passes()+ mrs = []domain.DeliveryMR{{URL: "pr/4", State: "merged", HeadSHA: "new"}}+ passes()++ lookupDown := &Engine{FindBranchMRsInto: func(domain.BranchMRQuery) ([]domain.DeliveryMR, error) {+ return nil, errors.New("401 Bad credentials")+ }}+ if err := lookupDown.verifyRunMRs(run, "", pending); !errors.Is(err, errMRUnverifiable) || !strings.Contains(err.Error(), "401 Bad credentials") {+ t.Fatalf("a failed lookup goes to a person: %v", err)+ }+ if err := (&Engine{}).verifyRunMRs(run, "", pending); !errors.Is(err, errMRUnverifiable) {+ t.Fatalf("no MR lookup configured goes to a person: %v", err)+ }+ ssh := domain.Run{Repositories: []domain.RepositoryContext{{RepositoryID: "ssh", Provider: domain.RepositoryProviderSSH, WorkspaceDir: "ssh", WorkBranch: "feat", DefaultBranch: "main"}}}+ if err := e.verifyRunMRs(ssh, "", func(domain.RepositoryContext) (pushedWork, error) { return pushedWork{Tip: "t", Ahead: 1}, nil }); !errors.Is(err, errMRUnverifiable) || !strings.Contains(err.Error(), "ssh:托管平台不支持自动核验 MR") {+ t.Fatalf("a host without MR lookup goes to a person: %v", err)+ }+ if err := e.verifyRunMRs(run, "", func(domain.RepositoryContext) (pushedWork, error) { return pushedWork{}, errors.New("exit status 2") }); err == nil || errors.Is(err, errMRUnverifiable) {+ t.Fatalf("an unreadable remote fails the gate: %v", err)+ }+ if err := e.verifyRunMRs(domain.Run{}, "", pending); err != nil {+ t.Fatalf("a run without repositories has no MR to verify: %v", err)+ }+}++func TestMRGateRejectsAnEarlierMergedMROnAReusedWorkBranch(t *testing.T) {+ t.Parallel()+ git := func(dir string, args ...string) string {+ t.Helper()+ cmd := exec.Command("git", append([]string{"-c", "user.name=t", "-c", "[email protected]", "-c", "init.defaultBranch=main"}, args...)...)+ cmd.Dir = dir+ out, err := cmd.CombinedOutput()+ if err != nil {+ t.Fatalf("git %v: %v\n%s", args, err, out)+ }+ return strings.TrimSpace(string(out))+ }+ root := t.TempDir()+ remote := filepath.Join(root, "remote.git")+ git(root, "init", "-q", "--bare", remote)+ workspace := filepath.Join(root, "run")+ checkout := filepath.Join(workspace, "app")+ git(root, "clone", "-q", remote, checkout)+ commit := func(name string) {+ t.Helper()+ if err := os.WriteFile(filepath.Join(checkout, name), []byte(name), 0o644); err != nil {+ t.Fatal(err)+ }+ git(checkout, "add", ".")+ git(checkout, "commit", "-qm", name)+ }+ commit("base")+ git(checkout, "push", "-q", "origin", "HEAD:main")+ git(checkout, "checkout", "-qb", "feat")+ commit("first delivery")+ git(checkout, "push", "-q", "origin", "feat")+ previous := git(checkout, "rev-parse", "HEAD")+ git(checkout, "push", "-q", "origin", "feat:main")+ git(checkout, "fetch", "-q", "origin")+ commit("this run")+ git(checkout, "push", "-q", "origin", "feat")+ tip := git(checkout, "rev-parse", "HEAD")++ rc := domain.RepositoryContext{RepositoryID: "app", Name: "app", GongfengProjectID: "github:o/app", WorkspaceDir: "app", WorkBranch: "feat", RequireExistingWorkBranch: true, DefaultBranch: "main"}+ pending := func(rc domain.RepositoryContext) (pushedWork, error) {+ cmd := exec.Command("sh", "-c", bindExecutionTarget(mrPendingCommand, executionTarget{Scope: domain.ExecutionScopeRepositories, Repository: &rc}))+ cmd.Dir = workspace+ out, err := cmd.Output()+ if err != nil {+ return pushedWork{}, err+ }+ return parseMRPending(string(out))+ }+ got, err := pending(rc)+ if err != nil || got.Tip != tip || got.Ahead != 1 {+ t.Fatalf("pending = %+v %v, want tip %s with 1 commit beyond main", got, err, tip)+ }+ mrs := []domain.DeliveryMR{{URL: "https://github.com/o/app/pull/1", State: "merged", TargetBranch: "main", HeadSHA: previous}}+ e := &Engine{FindBranchMRsInto: func(domain.BranchMRQuery) ([]domain.DeliveryMR, error) { return mrs, nil }}+ run := domain.Run{Repositories: []domain.RepositoryContext{rc}}+ if err := e.verifyRunMRs(run, "push-token", pending); err == nil || !strings.Contains(err.Error(), "不包含本轮推送的 "+tip) {+ t.Fatalf("the previous merged MR must not cover this run's push: %v", err)+ }+ mrs = append(mrs, domain.DeliveryMR{URL: "https://github.com/o/app/pull/2", State: "opened", TargetBranch: "main", HeadSHA: tip})+ if err := e.verifyRunMRs(run, "push-token", pending); err != nil {+ t.Fatalf("a new MR carrying the tip must pass: %v", err)+ }+}++func TestMRPendingCommandReportsThePushedTip(t *testing.T) {+ t.Parallel()+ git := func(dir string, args ...string) string {+ t.Helper()+ cmd := exec.Command("git", append([]string{"-c", "user.name=t", "-c", "[email protected]", "-c", "init.defaultBranch=main"}, args...)...)+ cmd.Dir = dir+ out, err := cmd.CombinedOutput()+ if err != nil {+ t.Fatalf("git %v: %v\n%s", args, err, out)+ }+ return strings.TrimSpace(string(out))+ }+ root := t.TempDir()+ remote := filepath.Join(root, "remote.git")+ git(root, "init", "-q", "--bare", remote)+ workspace := filepath.Join(root, "run")+ checkout := filepath.Join(workspace, "app")+ git(root, "clone", "-q", remote, checkout)+ commit := func(dir, name string) {+ t.Helper()+ if err := os.WriteFile(filepath.Join(dir, name), []byte(name), 0o644); err != nil {+ t.Fatal(err)+ }+ git(dir, "add", ".")+ git(dir, "commit", "-qm", name)+ }+ commit(checkout, "base")+ git(checkout, "push", "-q", "origin", "HEAD:main")+ git(checkout, "checkout", "-qb", "feat")+ target := executionTarget{Scope: domain.ExecutionScopeRepositories, Repository: &domain.RepositoryContext{WorkspaceDir: "app", WorkBranch: "feat", DefaultBranch: "main"}}+ pending := func() pushedWork {+ t.Helper()+ cmd := exec.Command("sh", "-c", bindExecutionTarget(mrPendingCommand, target))+ cmd.Dir = workspace+ out, err := cmd.Output()+ if err != nil {+ t.Fatal(err)+ }+ got, err := parseMRPending(string(out))+ if err != nil {+ t.Fatal(err)+ }+ return got+ }+ if got := pending(); got != (pushedWork{Tip: "-", Ahead: 0}) {+ t.Fatalf("unpushed work branch = %+v", got)+ }+ git(checkout, "push", "-q", "origin", "feat")+ if got := pending(); got.Ahead != 0 {+ t.Fatalf("work branch at the target = %+v", got)+ }+ commit(checkout, "one")+ commit(checkout, "two")+ if got := pending(); got.Ahead != 0 {+ t.Fatalf("local commits only = %+v", got)+ }+ git(checkout, "push", "-q", "origin", "feat")+ if got := pending(); got.Ahead != 2 || got.Tip != git(checkout, "rev-parse", "HEAD") {+ t.Fatalf("pushed commits = %+v", got)+ }+ other := filepath.Join(root, "other")+ git(root, "clone", "-q", "-b", "feat", remote, other)+ commit(other, "three")+ git(other, "push", "-q", "origin", "feat")+ if got := pending(); got.Ahead != 3 || got.Tip != git(other, "rev-parse", "HEAD") {+ t.Fatalf("a remote tip the checkout has not fetched = %+v", got)+ }+ if _, err := parseMRPending("fatal: not a git repository"); err == nil {+ t.Fatal("unexpected output accepted")+ }+}++func TestMRGateRunsInTheNodeLoop(t *testing.T) {+ t.Parallel()+ dir := t.TempDir()+ s, err := repo.OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { s.Close() })+ putGateTestAgent(t, s, "mr-gate-agent", []domain.VerificationGate{{ID: "mr-opened", Name: "MR 已创建", Mode: domain.VerificationModeMR, Required: true, OnFailure: "loop"}})+ wf := domain.WorkflowDefinition{ID: "mr-gate-lab", Name: "mr gate lab", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{+ {ID: "mr", Name: "mr", Type: "agent", AgentID: "mr-gate-agent", ExecutorID: "mock", MaxAttempts: 1},+ }}+ if err := s.PutWorkflow(wf); err != nil {+ t.Fatal(err)+ }+ e := New(s, runtime.NewManager(filepath.Join(dir, "workspaces")))+ e.FindBranchMRsInto = func(domain.BranchMRQuery) ([]domain.DeliveryMR, error) {+ t.Error("a run without repositories must not look up MRs")+ return nil, nil+ }+ r, err := e.Start(wf.ID, "")+ if err != nil {+ t.Fatal(err)+ }+ waitFor(t, s, r.ID, "succeeded")+ current, _ := s.Run(r.ID)+ passed := false+ for _, event := range current.Telemetry {+ if event.Name == "gate.mr.passed" {+ passed = true+ }+ }+ if !passed {+ t.Fatal("the MR gate did not run")+ }+}diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.goindex 7234e6b9..0651e783 100644--- a/internal/engine/node_execute.go+++ b/internal/engine/node_execute.go@@ -881,6 +881,32 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workflif strings.EqualFold(gate.Mode, "manual") || strings.EqualFold(gate.Mode, "submit") {continue}+ if strings.EqualFold(gate.Mode, domain.VerificationModeMR) {+ live, _ := e.repo.RunState(runID)+ mrErr := e.verifyRunMRs(live, gitTok, func(rc domain.RepositoryContext) (pushedWork, error) {+ target := executionTarget{Scope: domain.ExecutionScopeRepositories, Repository: &rc}+ out, execErr := gateExec(mrPendingCommand, target, executionTargetSink(func(event domain.TelemetryEvent) {+ event.Category = "verification"+ sink(event)+ }, target))+ if execErr != nil {+ return pushedWork{}, execErr+ }+ return parseMRPending(out)+ })+ if mrErr != nil {+ e.observe(runID, node.ID, domain.TelemetryEvent{Category: "verification", Name: "gate.mr.failed", Phase: "finish", Level: "error", Message: "门禁未通过:" + gate.Name, Attributes: map[string]any{"gateId": gate.ID, "gateName": gate.Name, "iteration": iteration, "detail": mrErr.Error()}})+ err = fmt.Errorf("verification %s: %w", gate.Name, mrErr)+ failedAction = candidate.onFailure+ if errors.Is(mrErr, errMRUnverifiable) {+ failedAction = "human"+ }+ gateRejected = failedAction == "reject"+ break+ }+ e.observe(runID, node.ID, domain.TelemetryEvent{Category: "verification", Name: "gate.mr.passed", Phase: "finish", Message: "门禁通过:" + gate.Name, Attributes: map[string]any{"gateId": gate.ID, "gateName": gate.Name, "iteration": iteration}})+ continue+ }gateCmd := joinGateCommands(gate.Commands, effectiveNode.ArtifactOutputs)if gateCmd == "" {continuediff --git a/internal/httpapi/server.go b/internal/httpapi/server.goindex 04d36ac9..c9a906e3 100644--- a/internal/httpapi/server.go+++ b/internal/httpapi/server.go@@ -179,6 +179,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Servif syncSvc != nil {e.MergeIntoBranch = syncSvc.EnsureAndMergeBranchMRe.FindBranchMR = syncSvc.FindBranchMR+ e.FindBranchMRsInto = syncSvc.FindBranchMRsInto}// Wake long-polling CLI runners the moment the engine queues a task.e.SetRunnerDispatchNotify(func(provider string) { api.runners.runnerWaiters.notify([]string{provider}) })diff --git a/internal/repo/public_catalog_test.go b/internal/repo/public_catalog_test.goindex aaa9d99c..39779724 100644--- a/internal/repo/public_catalog_test.go+++ b/internal/repo/public_catalog_test.go@@ -1,22 +1,24 @@package repoimport (+ "agentflow/internal/domain""encoding/json""os"+ "os/exec"+ "path/filepath""regexp""strings""testing")-// The production catalog must pass the user's task to every executable role.-// Each public role stores that brief in prompt, including {{input}}.-func TestPublicCatalogPassesRunInputToEveryRole(t *testing.T) {+func publicCatalogTemplates(t *testing.T) map[string]GenericTemplate {+ t.Helper()raw, err := os.ReadFile("../../migrations/seed/001_public_catalog.sql")if err != nil {t.Fatal(err)}pattern := regexp.MustCompile(`^INSERT IGNORE INTO generic_templates .*VALUES \('([^']*)','[^']*','(.*)',UTC_TIMESTAMP\(\)\);$`)- count := 0+ templates := map[string]GenericTemplate{}for _, line := range strings.Split(string(raw), "\n") {match := pattern.FindStringSubmatch(line)if match == nil {@@ -27,14 +29,198 @@ func TestPublicCatalogPassesRunInputToEveryRole(t *testing.T) {if err := json.Unmarshal([]byte(payload), &template); err != nil {t.Fatal(err)}- count+++ templates[match[1]] = template+ }+ if len(templates) != 4 {+ t.Fatalf("expected four public templates, got %d", len(templates))+ }+ return templates+}++// The production catalog must pass the user's task to every executable role.+// Each public role stores that brief in prompt, including {{input}}.+func TestPublicCatalogPassesRunInputToEveryRole(t *testing.T) {+ for id, template := range publicCatalogTemplates(t) {+ if err := domain.ValidateWorkflowPreparation(template.Workflow); err != nil {+ t.Errorf("%s: %v", id, err)+ }+ if err := domain.ValidateWorkflowMetricStages(template.Workflow); err != nil {+ t.Errorf("%s: %v", id, err)+ }for _, agent := range template.Agents {if !strings.Contains(agent.Prompt, "{{input}}") {- t.Errorf("%s role %s drops the user's run input", match[1], agent.ID)+ t.Errorf("%s role %s drops the user's run input", id, agent.ID)+ }+ if err := domain.ValidateVerificationGates(agent.Verification); err != nil {+ t.Errorf("%s role %s: %v", id, agent.ID, err)+ }+ }+ }+}++// A code SOP must not succeed with its changes only in the reclaimed+// workspace: the MR node runs after acceptance and before the summary, and+// its command gate blocks while a checkout has unpushed work.+func TestPublicCodeSOPsOpenMRBeforeDeliver(t *testing.T) {+ templates := publicCatalogTemplates(t)+ for _, id := range []string{GenericBackendDeliveryWorkflowID, GenericFrontendDeliveryWorkflowID, "issue-fix-production"} {+ template, ok := templates[id]+ if !ok {+ t.Fatalf("%s missing", id)+ }+ next := map[string][]string{}+ for _, edge := range template.Workflow.Edges {+ next[edge.Source] = append(next[edge.Source], edge.Target)+ }+ if got := strings.Join(next["accept"], ","); got != "mr" {+ t.Errorf("%s: accept leads to %q, want mr", id, got)+ }+ if got := strings.Join(next["mr"], ","); got != "deliver" {+ t.Errorf("%s: mr leads to %q, want deliver", id, got)+ }+ var mrAgentID string+ for _, node := range template.Workflow.Nodes {+ if node.ID != "mr" {+ continue+ }+ mrAgentID = node.AgentID+ if len(node.ArtifactOutputs) != 1 || node.ArtifactOutputs[0].Name != "mr-body" || node.ArtifactOutputs[0].Path != "mr-body.md" {+ t.Errorf("%s: mr node must publish mr-body.md, got %+v", id, node.ArtifactOutputs)+ }+ }+ found := false+ for _, agent := range template.Agents {+ if agent.ID != mrAgentID {+ continue+ }+ found = true+ if len(agent.Verification) != 2 || agent.Verification[0].Mode != "command" || agent.Verification[0].ExecutionScope != "run" || len(agent.Verification[0].Commands) != 1 || agent.Verification[1].Mode != domain.VerificationModeMR || len(agent.Verification[1].Commands) != 0 {+ t.Errorf("%s: mr role needs a run-scoped push gate followed by an MR gate, got %+v", id, agent.Verification)+ }+ if !agent.Loop.Enabled || agent.Loop.OnExhausted != "human" {+ t.Errorf("%s: mr role must hand an unresolved push to a person, got %+v", id, agent.Loop)+ }+ if !strings.Contains(agent.Prompt, "{{existingMR}}") {+ t.Errorf("%s: mr role drops the existing MR context", id)}}+ if !found {+ t.Errorf("%s: mr node references missing role %q", id, mrAgentID)+ }+ }+ for _, node := range templates[GenericProductDeliveryWorkflowID].Workflow.Nodes {+ if node.ID == "mr" {+ t.Errorf("product SOP delivers documents only and must not open an MR")+ }+ }+}++func TestPublicMRGateRequiresTheRunWorkBranchPushed(t *testing.T) {+ var gate string+ for _, agent := range publicCatalogTemplates(t)[GenericBackendDeliveryWorkflowID].Agents {+ if agent.ID == GenericBackendDeliveryWorkflowID+"-mr" {+ gate = agent.Verification[0].Commands[0]+ }+ }+ if gate == "" {+ t.Fatal("mr gate missing")+ }+ git := func(dir string, args ...string) {+ t.Helper()+ cmd := exec.Command("git", append([]string{"-c", "user.name=t", "-c", "[email protected]", "-c", "init.defaultBranch=main"}, args...)...)+ cmd.Dir = dir+ if out, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("git %v: %v\n%s", args, err, out)+ }+ }+ write := func(path, body string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ workspace := t.TempDir()+ passes := func(manifest ...string) bool {+ t.Helper()+ cmd := exec.Command("sh", "-lc", gate)+ cmd.Dir = workspace+ cmd.Env = append(os.Environ(), "AGENTFLOW_WORK_BRANCHES="+strings.Join(manifest, "\n"))+ return cmd.Run() == nil+ }+ root := t.TempDir()+ remote := filepath.Join(root, "remote.git")+ git(root, "init", "-q", "--bare", remote)+ seed := filepath.Join(root, "seed")+ git(root, "clone", "-q", remote, seed)+ write(filepath.Join(seed, "a.txt"), "a\n")+ git(seed, "add", ".")+ git(seed, "commit", "-qm", "init")+ git(seed, "push", "-q", "origin", "HEAD:main")+ write(filepath.Join(seed, "r.txt"), "release\n")+ git(seed, "add", ".")+ git(seed, "commit", "-qm", "release")+ git(seed, "push", "-q", "origin", "HEAD:release")++ write(filepath.Join(workspace, "requirement.md"), "doc\n")+ if !passes() {+ t.Fatal("a run without repositories must pass")+ }+ repo := filepath.Join(workspace, "app")+ git(workspace, "clone", "-q", remote, repo)+ git(repo, "checkout", "-qb", "work")+ app := "app\twork\tmain"+ write(filepath.Join(repo, ".agentflow", "state"), "x\n")+ write(filepath.Join(repo, "node_modules", "dep.js"), "x\n")+ if !passes(app) {+ t.Fatal("a repository the run left unchanged must pass; .agentflow and node_modules are ignored")+ }+ write(filepath.Join(repo, "a.txt"), "changed\n")+ write(filepath.Join(repo, "new.txt"), "new\n")+ if passes(app) {+ t.Fatal("modified and untracked files must block")+ }+ git(repo, "add", "a.txt", "new.txt")+ git(repo, "commit", "-qm", "change")+ if passes(app) {+ t.Fatal("an unpushed commit must block")+ }+ git(repo, "push", "-q", "origin", "HEAD:other")+ if passes(app) {+ t.Fatal("HEAD pushed to another branch must block while the work branch is not pushed")+ }+ git(repo, "push", "-q", "-u", "origin", "work")+ if !passes(app) {+ t.Fatal("a pushed work branch must pass")+ }+ write(filepath.Join(repo, "later.txt"), "later\n")+ git(repo, "add", ".")+ git(repo, "commit", "-qm", "later")+ if passes(app) {+ t.Fatal("a commit after the push must block")+ }+ git(repo, "push", "-q", "origin", "work")+ git(repo, "checkout", "-q", "-b", "elsewhere", "origin/main")+ if passes(app) {+ t.Fatal("a checkout moved off the work branch that holds the commits must block")+ }+ git(repo, "checkout", "-q", "work")+ if !passes(app) {+ t.Fatal("back on the pushed work branch must pass")+ }+ if passes("app\twork\tmissing") {+ t.Fatal("a target branch missing from origin must block")+ }++ release := filepath.Join(workspace, "svc")+ git(workspace, "clone", "-q", "-b", "release", remote, release)+ git(release, "checkout", "-qb", "fix")+ if !passes(app, "svc\tfix\trelease") {+ t.Fatal("a work branch with nothing beyond its frozen release target must pass")}- if count != 4 {- t.Fatalf("expected four public templates, got %d", count)+ if passes(app, "svc\tfix\tmain") {+ t.Fatal("measured against main the release commit is unpushed work and must block")}}diff --git a/internal/tracker/branch_mr_test.go b/internal/tracker/branch_mr_test.goindex 3589194c..c59fca8d 100644--- a/internal/tracker/branch_mr_test.go+++ b/internal/tracker/branch_mr_test.go@@ -1,6 +1,13 @@package tracker-import "testing"+import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "agentflow/internal/domain"+)func TestPickBranchMR(t *testing.T) {raw := `{"data":[@@ -21,3 +28,77 @@ func TestPickBranchMR(t *testing.T) {t.Fatal("empty search must not resolve an MR")}}++func TestBranchMRsIntoKeepOnlyTheTargetAndCarryHeads(t *testing.T) {+ raw := `{"data":[+ {"id":101,"iid":7,"state":"merged","source_branch":"feature/x","target_branch":"master","sha":"old","web_url":"https://git.example.com/g/r/merge_requests/7"},+ {"id":102,"iid":9,"state":"opened","source_branch":"feature/x","target_branch":"release","sha":"new"},+ {"id":103,"iid":11,"state":"opened","source_branch":"feature/other","target_branch":"master"},+ {"id":104,"iid":12,"state":"opened","target_branch":"master","sha":"tip"}+ ]}`+ got := gongfengMRsInto(parseGongfengMRRecords(raw), "g/r", "feature/x", "master")+ if len(got) != 2 || got[0].IID != 7 || got[0].HeadSHA != "old" || got[0].GongfengState != "merged" || got[1].IID != 12 || got[1].HeadSHA != "tip" {+ t.Fatalf("gongfeng MRs into master = %+v", got)+ }+ if got := gongfengMRsInto(parseGongfengMRRecords(raw), "g/r", "feature/x", "main"); len(got) != 0 {+ t.Fatalf("no MR targets main, got %+v", got)+ }++ var pulls []githubPull+ for _, p := range []struct{ head, sha, base, state string }{{"feat", "old", "main", "closed"}, {"feat", "new", "release", "open"}, {"other", "x", "main", "open"}, {"feat", "tip", "main", "open"}} {+ var pull githubPull+ pull.Number, pull.State = len(pulls)+1, p.state+ pull.Head.Ref, pull.Head.SHA, pull.Base.Ref = p.head, p.sha, p.base+ pulls = append(pulls, pull)+ }+ prs := githubPullsInto(pulls, "github:o/r", "feat", "main")+ if len(prs) != 2 || prs[0].State != "closed" || prs[0].HeadSHA != "old" || prs[1].State != "opened" || prs[1].HeadSHA != "tip" || prs[1].TargetBranch != "main" {+ t.Fatalf("github pulls into main = %+v", prs)+ }+}++func TestFindBranchMRsIntoReadsWithTheRunCredentials(t *testing.T) {+ var auth []string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ auth = append(auth, r.Header.Get("Authorization"))+ if r.Header.Get("Authorization") == "Bearer revoked" {+ w.WriteHeader(http.StatusUnauthorized)+ return+ }+ if r.URL.Path != "/repos/o/r/pulls" || r.URL.Query().Get("base") != "main" || r.URL.Query().Get("head") != "o:feat" {+ t.Errorf("unexpected request %s", r.URL)+ }+ _, _ = w.Write([]byte(`[{"number":4,"state":"open","head":{"ref":"feat","sha":"tip"},"base":{"ref":"main"}},{"number":3,"state":"closed","merged_at":"2026-11-01T00:00:00Z","head":{"ref":"feat","sha":"old"},"base":{"ref":"main"}}]`))+ }))+ defer srv.Close()+ s := NewService()+ s.githubAPIBase = srv.URL+ s.projectAuth = projectAuthFixture{+ projects: map[string]domain.Project{"first": {ID: "first", OwnerID: 1}, "run": {ID: "run", OwnerID: 2}},+ users: map[int64]domain.User{1: {ID: 1, GitToken: "first-owner"}, 2: {ID: 2, GitToken: "run-owner"}},+ repos: []domain.Repository{+ {ID: "a", ProjectID: "first", Provider: "github", GongfengProjectID: "github:o/r"},+ {ID: "b", ProjectID: "run", Provider: "github", GongfengProjectID: "github:o/r"},+ },+ }+ q := domain.BranchMRQuery{ProjectID: "run", RemoteProject: "github:o/r", SourceBranch: "feat", TargetBranch: "main", GitToken: "pushed-with"}+ mrs, err := s.FindBranchMRsInto(q)+ if err != nil || len(mrs) != 2 || mrs[0].State != "opened" || mrs[0].HeadSHA != "tip" || mrs[1].State != "merged" || mrs[1].HeadSHA != "old" {+ t.Fatalf("mrs = %+v %v", mrs, err)+ }+ q.GitToken = ""+ if _, err := s.FindBranchMRsInto(q); err != nil {+ t.Fatal(err)+ }+ if strings.Join(auth, ",") != "Bearer pushed-with,Bearer run-owner" {+ t.Fatalf("the run's push token comes first, then the Owner of the run's project, got %v", auth)+ }+ q.GitToken = "revoked"+ if _, err := s.FindBranchMRsInto(q); err == nil || !strings.Contains(err.Error(), "本轮责任人的 Git Token") {+ t.Fatalf("a rejected lookup names the identity it used: %v", err)+ }+ gf := domain.BranchMRQuery{ProjectID: "run", RemoteProject: "group/r", SourceBranch: "feat", TargetBranch: "main", ResponsibleUserID: 9}+ if _, err := s.FindBranchMRsInto(gf); err == nil || !strings.Contains(err.Error(), "本轮责任人 9") {+ t.Fatalf("Gongfeng lookups run as the run's responsible user: %v", err)+ }+}diff --git a/internal/tracker/github.go b/internal/tracker/github.goindex b4a6ec2d..d94d49f7 100644--- a/internal/tracker/github.go+++ b/internal/tracker/github.go@@ -47,6 +47,37 @@ func (s *Service) githubClient(project string) (*githubClient, error) {return &githubClient{base: base, path: path, token: token, http: &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}}, nil}+// githubClientForRun authenticates as the run did: its push token when set,+// else the Owner of the run's project when that project binds the repository.+// It also names the identity it chose.+func (s *Service) githubClientForRun(project, localProjectID, gitToken string) (*githubClient, string, error) {+ g, err := s.githubClient(project)+ if err != nil {+ return nil, "", err+ }+ if token := strings.TrimSpace(gitToken); token != "" {+ g.token = token+ return g, "本轮责任人的 Git Token", nil+ }+ local := strings.TrimSpace(localProjectID)+ if s.projectAuth == nil || local == "" {+ return g, "首个绑定该仓库的项目 Owner 的 Git Token", nil+ }+ for _, repo := range s.projectAuth.Repositories() {+ if repo.Provider != "github" || repo.GongfengProjectID != project || repo.ProjectID != local {+ continue+ }+ g.token = ""+ if p, found := s.projectAuth.Project(local); found {+ if u, exists := s.projectAuth.User(p.OwnerID); exists {+ g.token = u.GitToken+ }+ }+ return g, "项目 " + local + " Owner 的 Git Token", nil+ }+ return g, "首个绑定该仓库的项目 Owner 的 Git Token", nil+}+func (g *githubClient) request(method, suffix string, input, output any) error {var body io.Readerif input != nil {@@ -122,20 +153,43 @@ func (p githubPull) mergedAt() time.Time {}func (g *githubClient) findPull(branch, target string) (githubPull, bool, error) {+ list, err := g.listPulls(branch, target)+ if err != nil {+ return githubPull{}, false, err+ }+ for _, p := range list {+ if p.Head.Ref == branch && (target == "" || p.Base.Ref == target) {+ return p, true, nil+ }+ }+ return githubPull{}, false, nil+}++// listPulls returns the pulls from branch (and into target when set), most+// recently updated first.+func (g *githubClient) listPulls(branch, target string) ([]githubPull, error) {q := url.Values{"state": {"all"}, "head": {strings.Split(g.path, "/")[0] + ":" + branch}, "per_page": {"100"}, "sort": {"updated"}, "direction": {"desc"}}if target != "" {q.Set("base", target)}var list []githubPullif err := g.request("GET", "/pulls?"+q.Encode(), nil, &list); err != nil {- return githubPull{}, false, err+ return nil, err}- for _, p := range list {- if p.Head.Ref == branch && (target == "" || p.Base.Ref == target) {- return p, true, nil+ return list, nil+}++func githubPullsInto(pulls []githubPull, project, branch, target string) []domain.DeliveryMR {+ var out []domain.DeliveryMR+ for _, p := range pulls {+ if p.Head.Ref != branch || p.Base.Ref != target {+ continue}+ mr := p.delivery(project)+ mr.HeadSHA = strings.TrimSpace(p.Head.SHA)+ out = append(out, mr)}- return githubPull{}, false, nil+ return out}func (s *Service) githubFindBranch(project, branch string) (domain.DeliveryMR, bool, error) {diff --git a/internal/tracker/merge_mr.go b/internal/tracker/merge_mr.goindex d3668699..e5c2593e 100644--- a/internal/tracker/merge_mr.go+++ b/internal/tracker/merge_mr.go@@ -131,6 +131,7 @@ type gongfengListedMR struct {ResolvedAt string `json:"resolved_at"`UpdatedAt string `json:"updated_at"`WebURL string `json:"web_url"`+ SHA string `json:"sha"`}// FindBranchMR returns the delivery MR whose source is sourceBranch: the@@ -176,6 +177,88 @@ func (s *Service) FindBranchMR(project, sourceBranch string) (domain.DeliveryMR,}, true, nil}+// FindBranchMRsInto lists every MR from the query's source branch into its+// target branch with the head commit the host reports. Unlike FindBranchMR it+// never answers with an MR into another branch, and it keeps all of them so a+// caller can tell an earlier merged MR from one that carries the current tip.+// It reads with the run's credentials: GitHub uses the token the run pushed+// with, else the Owner of the run's project; Gongfeng uses the MCP binding of+// the run's project.+func (s *Service) FindBranchMRsInto(q domain.BranchMRQuery) ([]domain.DeliveryMR, error) {+ project := strings.TrimSpace(q.RemoteProject)+ src, target := strings.TrimSpace(q.SourceBranch), strings.TrimSpace(q.TargetBranch)+ if project == "" || src == "" || target == "" {+ return nil, nil+ }+ if strings.HasPrefix(project, "github:") {+ g, identity, err := s.githubClientForRun(project, q.ProjectID, q.GitToken)+ if err != nil {+ return nil, err+ }+ pulls, err := g.listPulls(src, target)+ if err != nil {+ return nil, fmt.Errorf("以%s查询 GitHub 失败:%w", identity, err)+ }+ return githubPullsInto(pulls, project, src, target), nil+ }+ client, source, err := s.gongfengClientForRun(project, q)+ if err != nil {+ return nil, err+ }+ raw, err := client.Clone(15*time.Second).CallTool("search_merge_request", map[string]any{+ "project_id": project,+ "source_branch": src,+ "target_branch": target,+ "per_page": 20,+ })+ if err != nil {+ return nil, fmt.Errorf("以 %s 查询工蜂 MR %s 失败:%w", source, src, err)+ }+ return gongfengMRsInto(parseGongfengMRRecords(raw), project, src, target), nil+}++// gongfengClientForRun queries through the run project's Gongfeng MCP as the+// run's responsible user; without a run project it falls back to the first+// project that binds the repository.+func (s *Service) gongfengClientForRun(project string, q domain.BranchMRQuery) (*MCPClient, string, error) {+ local := strings.TrimSpace(q.ProjectID)+ if local == "" || s.projectAuth == nil {+ return s.gongfengClientForRemoteProject(project)+ }+ if q.ResponsibleUserID <= 0 {+ return s.trackerClientForProject("gongfeng", local)+ }+ user, ok := s.projectAuth.User(q.ResponsibleUserID)+ if !ok {+ return nil, "none", fmt.Errorf("本轮责任人 %d 不存在", q.ResponsibleUserID)+ }+ binding, err := bindProjectUserTrackerMCP("gongfeng", s.cfg.Get(), s.projectAuth.MCPServers(), local, user, "责任人")+ if err != nil {+ return nil, binding.Source, err+ }+ return NewMCPClient(binding.URL, binding.Headers), binding.Source, nil+}++func gongfengMRsInto(items []gongfengListedMR, project, sourceBranch, targetBranch string) []domain.DeliveryMR {+ var out []domain.DeliveryMR+ for _, item := range items {+ if s := strings.TrimSpace(item.SourceBranch); s != "" && !domain.SameGitBranch(s, sourceBranch) {+ continue+ }+ if !domain.SameGitBranch(item.TargetBranch, targetBranch) {+ continue+ }+ url := strings.TrimSpace(item.WebURL)+ if _, _, parsed, ok := domain.ParseGongfengMR(url); ok {+ url = parsed+ } else {+ url = domain.GongfengMRURL(project, item.IID)+ }+ out = append(out, domain.DeliveryMR{Project: project, IID: item.IID, URL: url, TargetBranch: item.TargetBranch, GongfengState: normalizeMRState(item.State), HeadSHA: strings.TrimSpace(item.SHA)})+ }+ return out+}+func pickBranchMR(items []gongfengListedMR, sourceBranch string) (gongfengListedMR, bool) {var best gongfengListedMRfound, bestClosed := false, falsediff --git a/migrations/033_generic_sop_mr_node.sql b/migrations/033_generic_sop_mr_node.sqlnew file mode 100644index 00000000..f11615d1--- /dev/null+++ b/migrations/033_generic_sop_mr_node.sql@@ -0,0 +1,81 @@+-- Idempotent MySQL migration: add a 「发起 MR」 node to the built-in code+-- delivery SOPs (backend, frontend, defect fix). The product SOP delivers+-- documents only and is left alone.+--+-- Before this, the deliver node opened a PR only when the user explicitly asked+-- for one, so a succeeded run could leave every source change uncommitted in a+-- workspace that is reclaimed right after success. The new node sits between+-- 人工验收 and 交付汇总, commits and pushes the work branch, opens the MR/PR and+-- records it in mr-body.md. Its command gate fails while a repository with+-- commits beyond the run's target branch has uncommitted changes, sits off the+-- run's work branch, or has not pushed HEAD to that work branch on origin. A+-- second gate (mode mr) has the engine look the MR up on GitHub or Gongfeng:+-- every pushed work branch with new commits needs a non-closed MR into the+-- run's target branch, and a host that cannot be queried goes to a person.+--+-- New installs get these templates from the seed. This script changes the+-- behaviour of existing SOPs, so it is not run on install or ./start.sh pull;+-- an operator runs it by hand. Only templates whose node graph and deliver+-- position are still the shipped original are rewritten; the deliver prompt is+-- replaced only when unedited. Project SOPs already adopted from these+-- templates are copies and are not touched.+SET NAMES utf8mb4;+START TRANSACTION;+UPDATE generic_templates+SET payload = JSON_ARRAY_APPEND(+ JSON_SET(payload, '$.Workflow.edges[5].target', 'mr', '$.Workflow.nodes[6].position.x', 1815),+ '$.Workflow.nodes', CAST('{"id": "mr", "name": "发起 MR", "type": "agent", "agentId": "generic-backend-delivery-mr", "maxAttempts": 2, "position": {"x": 1570, "y": 150}, "artifactOutputs": [{"name": "mr-body", "path": "mr-body.md", "mediaType": "text/markdown", "required": true}]}' AS JSON),+ '$.Workflow.edges', CAST('{"id": "e-6", "source": "mr", "target": "deliver", "when": "success"}' AS JSON),+ '$.Agents', CAST('{"version": 1, "updatedAt": "2026-11-16T00:00:00Z", "id": "generic-backend-delivery-mr", "name": "发起 MR", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。人工验收已通过,本节点把本轮代码改动提交到工作分支、推送并发起 MR/PR,不再修改业务逻辑。\\n\\n1. 未绑定代码仓库时不推送、不创建 MR/PR:在 mr-body.md 写明「未绑定代码仓库,源码保留在任务工作区」并列出交付文件,然后提交 pass。\\n2. 已绑定仓库时逐个处理每个仓库检出目录,本轮没有改动的仓库跳过,不创建空 MR/PR:确认当前在本轮工作分支上,不得在主分支提交,也不得切换或新建分支;检查 git status 与 diff,只提交本任务相关的源码改动,不提交 .agentflow、依赖目录、构建产物和 SOP 阶段文档;用概括本次改动的提交信息 commit,再 git push -u origin 当前工作分支。平台已注入 Git 凭据,不得打印、回显或写入任何令牌。\\n3. 以仓库上下文中的目标分支为目标创建 MR/PR:GitHub 仓库优先用已配置的 GitHub MCP,没有时用 curl 调 GitHub API,令牌取 $AGENTFLOW_GIT_TOKEN;其它托管平台用已配置的对应 MCP。本轮工作分支已有指向同一目标分支的 MR/PR 时更新它,不重复创建。\\n4. 标题概括本次改动;描述写需求摘要、改动要点、测试结果(依据 test-report.md)和已知限制。不得合并 MR/PR,不得推送主分支或强推。\\n5. 把每个仓库的 MR/PR 链接、源分支、目标分支和提交 SHA 写到 mr-body.md。\\n6. 推送或创建 MR/PR 失败(缺少凭据、无权限、网络错误等)时不得提交 pass:在 mr-body.md 记录失败原因,提交 human,并在 actionRequired 写明需要人工处理什么,例如配置 Git Token 后重试,或到托管平台手动创建 MR。\\n\\nMR 约束:{{existingMR}}\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}", "loop": {"enabled": true, "maxIterations": 2, "exitCondition": "all_gates_pass", "onExhausted": "human"}, "verification": [{"id": "mr-pushed", "name": "改动已提交并推送", "mode": "command", "stage": "after_execution", "commands": ["fail=0\\ntab=\\"$(printf ''\\\\t'')\\"\\nwhile IFS=\\"$tab\\" read -r d work base; do\\n [ -n \\"$d\\" ] || continue\\n dirty=\\"$(git -C \\"$d\\" status --porcelain --untracked-files=all -- . \\":(exclude).agentflow\\" \\":(exclude,glob)**/node_modules/**\\")\\" || { printf \\"%s 不是可用的 Git 检出目录\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ -n \\"$dirty\\" ]; then printf \\"%s 有未提交的改动:\\\\n%s\\\\n\\" \\"$d\\" \\"$dirty\\"; fail=1; continue; fi\\n refs=HEAD\\n if git -C \\"$d\\" rev-parse -q --verify \\"refs/heads/$work\\" >/dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone <<EOF\\n$AGENTFLOW_WORK_BRANCHES\\nEOF\\nexit \\"$fail\\""], "required": true, "onFailure": "loop", "executionScope": "run"}, {"id": "mr-opened", "name": "MR 已创建", "mode": "mr", "stage": "after_execution", "required": true, "onFailure": "loop"}]}' AS JSON)), updated_at = UTC_TIMESTAMP()+WHERE id = 'generic-backend-delivery'+ AND JSON_SEARCH(payload, 'one', 'mr', NULL, '$.Workflow.nodes[*].id') IS NULL+ AND JSON_LENGTH(payload, '$.Workflow.nodes') = 7+ AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.Workflow.nodes[6].id')) = 'deliver'+ AND JSON_EXTRACT(payload, '$.Workflow.nodes[6].position') = CAST('{"x": 1570, "y": 150}' AS JSON)+ AND JSON_EXTRACT(payload, '$.Workflow.edges[5]') = CAST('{"id": "e-5", "source": "accept", "target": "deliver", "when": "success"}' AS JSON)+ AND JSON_SEARCH(payload, 'one', 'generic-backend-delivery-mr', NULL, '$.Agents[*].id') IS NULL;+UPDATE generic_templates+SET payload = JSON_SET(payload, '$.Agents[5].prompt', '工作领域:后端服务、数据与 API。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token。代码已由「发起 MR」节点提交、推送并创建 MR/PR:按 mr-body.md 把链接、分支和提交 SHA 写进交付物清单;本节点不再修改代码、推送或创建 PR,不得合并。\n\n完成本节点约定的工作并交付产物。\n\n### 输入\n\n- 任务需求:{{input}}\n- 仓库上下文:{{repository}}'), updated_at = UTC_TIMESTAMP()+WHERE id = 'generic-backend-delivery'+ AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.Workflow.nodes[7].id')) = 'mr'+ AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.Agents[5].id')) = 'generic-backend-delivery-deliver'+ AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.Agents[5].prompt')) = '工作领域:后端服务、数据与 API。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token;仅在用户明确要求且已配置目标 GitHub 仓库及凭据时创建 PR,不得自行合并。\n\n完成本节点约定的工作并交付产物。\n\n### 输入\n\n- 任务需求:{{input}}\n- 仓库上下文:{{repository}}';+UPDATE generic_templates+SET payload = JSON_ARRAY_APPEND(+ JSON_SET(payload, '$.Workflow.edges[5].target', 'mr', '$.Workflow.nodes[6].position.x', 1815),+ '$.Workflow.nodes', CAST('{"id": "mr", "name": "发起 MR", "type": "agent", "agentId": "generic-frontend-delivery-mr", "maxAttempts": 2, "position": {"x": 1570, "y": 150}, "artifactOutputs": [{"name": "mr-body", "path": "mr-body.md", "mediaType": "text/markdown", "required": true}]}' AS JSON),+ '$.Workflow.edges', CAST('{"id": "e-6", "source": "mr", "target": "deliver", "when": "success"}' AS JSON),+ '$.Agents', CAST('{"version": 1, "updatedAt": "2026-11-16T00:00:00Z", "id": "generic-frontend-delivery-mr", "name": "发起 MR", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。人工验收已通过,本节点把本轮代码改动提交到工作分支、推送并发起 MR/PR,不再修改业务逻辑。\\n\\n1. 未绑定代码仓库时不推送、不创建 MR/PR:在 mr-body.md 写明「未绑定代码仓库,源码保留在任务工作区」并列出交付文件,然后提交 pass。\\n2. 已绑定仓库时逐个处理每个仓库检出目录,本轮没有改动的仓库跳过,不创建空 MR/PR:确认当前在本轮工作分支上,不得在主分支提交,也不得切换或新建分支;检查 git status 与 diff,只提交本任务相关的源码改动,不提交 .agentflow、依赖目录、构建产物和 SOP 阶段文档;用概括本次改动的提交信息 commit,再 git push -u origin 当前工作分支。平台已注入 Git 凭据,不得打印、回显或写入任何令牌。\\n3. 以仓库上下文中的目标分支为目标创建 MR/PR:GitHub 仓库优先用已配置的 GitHub MCP,没有时用 curl 调 GitHub API,令牌取 $AGENTFLOW_GIT_TOKEN;其它托管平台用已配置的对应 MCP。本轮工作分支已有指向同一目标分支的 MR/PR 时更新它,不重复创建。\\n4. 标题概括本次改动;描述写需求摘要、改动要点、测试结果(依据 test-report.md)和已知限制。不得合并 MR/PR,不得推送主分支或强推。\\n5. 把每个仓库的 MR/PR 链接、源分支、目标分支和提交 SHA 写到 mr-body.md。\\n6. 推送或创建 MR/PR 失败(缺少凭据、无权限、网络错误等)时不得提交 pass:在 mr-body.md 记录失败原因,提交 human,并在 actionRequired 写明需要人工处理什么,例如配置 Git Token 后重试,或到托管平台手动创建 MR。\\n\\nMR 约束:{{existingMR}}\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}", "loop": {"enabled": true, "maxIterations": 2, "exitCondition": "all_gates_pass", "onExhausted": "human"}, "verification": [{"id": "mr-pushed", "name": "改动已提交并推送", "mode": "command", "stage": "after_execution", "commands": ["fail=0\\ntab=\\"$(printf ''\\\\t'')\\"\\nwhile IFS=\\"$tab\\" read -r d work base; do\\n [ -n \\"$d\\" ] || continue\\n dirty=\\"$(git -C \\"$d\\" status --porcelain --untracked-files=all -- . \\":(exclude).agentflow\\" \\":(exclude,glob)**/node_modules/**\\")\\" || { printf \\"%s 不是可用的 Git 检出目录\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ -n \\"$dirty\\" ]; then printf \\"%s 有未提交的改动:\\\\n%s\\\\n\\" \\"$d\\" \\"$dirty\\"; fail=1; continue; fi\\n refs=HEAD\\n if git -C \\"$d\\" rev-parse -q --verify \\"refs/heads/$work\\" >/dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone <<EOF\\n$AGENTFLOW_WORK_BRANCHES\\nEOF\\nexit \\"$fail\\""], "required": true, "onFailure": "loop", "executionScope": "run"}, {"id": "mr-opened", "name": "MR 已创建", "mode": "mr", "stage": "after_execution", "required": true, "onFailure": "loop"}]}' AS JSON)), updated_at = UTC_TIMESTAMP()+WHERE id = 'generic-frontend-delivery'+ AND JSON_SEARCH(payload, 'one', 'mr', NULL, '$.Workflow.nodes[*].id') IS NULL+ AND JSON_LENGTH(payload, '$.Workflow.nodes') = 7+ AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.Workflow.nodes[6].id')) = 'deliver'+ AND JSON_EXTRACT(payload, '$.Workflow.nodes[6].position') = CAST('{"x": 1570, "y": 150}' AS JSON)+ AND JSON_EXTRACT(payload, '$.Workflow.edges[5]') = CAST('{"id": "e-5", "source": "accept", "target": "deliver", "when": "success"}' AS JSON)+ AND JSON_SEARCH(payload, 'one', 'generic-frontend-delivery-mr', NULL, '$.Agents[*].id') IS NULL;+UPDATE generic_templates+SET payload = JSON_SET(payload, '$.Agents[5].prompt', '工作领域:前端页面、交互、可访问性与响应式。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token。代码已由「发起 MR」节点提交、推送并创建 MR/PR:按 mr-body.md 把链接、分支和提交 SHA 写进交付物清单;本节点不再修改代码、推送或创建 PR,不得合并。\n\n完成本节点约定的工作并交付产物。\n\n### 输入\n\n- 任务需求:{{input}}\n- 仓库上下文:{{repository}}'), updated_at = UTC_TIMESTAMP()+WHERE id = 'generic-frontend-delivery'+ AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.Workflow.nodes[7].id')) = 'mr'+ AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.Agents[5].id')) = 'generic-frontend-delivery-deliver'+ AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.Agents[5].prompt')) = '工作领域:前端页面、交互、可访问性与响应式。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token;仅在用户明确要求且已配置目标 GitHub 仓库及凭据时创建 PR,不得自行合并。\n\n完成本节点约定的工作并交付产物。\n\n### 输入\n\n- 任务需求:{{input}}\n- 仓库上下文:{{repository}}';+UPDATE generic_templates+SET payload = JSON_ARRAY_APPEND(+ JSON_SET(payload, '$.Workflow.edges[5].target', 'mr', '$.Workflow.nodes[6].position.x', 1815),+ '$.Workflow.nodes', CAST('{"id": "mr", "name": "发起 MR", "type": "agent", "agentId": "issue-fix-production-mr", "maxAttempts": 2, "position": {"x": 1570, "y": 150}, "artifactOutputs": [{"name": "mr-body", "path": "mr-body.md", "mediaType": "text/markdown", "required": true}]}' AS JSON),+ '$.Workflow.edges', CAST('{"id": "e-6", "source": "mr", "target": "deliver", "when": "success"}' AS JSON),+ '$.Agents', CAST('{"version": 1, "updatedAt": "2026-11-16T00:00:00Z", "id": "issue-fix-production-mr", "name": "发起 MR", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。人工验收已通过,本节点把本轮代码改动提交到工作分支、推送并发起 MR/PR,不再修改业务逻辑。\\n\\n1. 未绑定代码仓库时不推送、不创建 MR/PR:在 mr-body.md 写明「未绑定代码仓库,源码保留在任务工作区」并列出交付文件,然后提交 pass。\\n2. 已绑定仓库时逐个处理每个仓库检出目录,本轮没有改动的仓库跳过,不创建空 MR/PR:确认当前在本轮工作分支上,不得在主分支提交,也不得切换或新建分支;检查 git status 与 diff,只提交本任务相关的源码改动,不提交 .agentflow、依赖目录、构建产物和 SOP 阶段文档;用概括本次改动的提交信息 commit,再 git push -u origin 当前工作分支。平台已注入 Git 凭据,不得打印、回显或写入任何令牌。\\n3. 以仓库上下文中的目标分支为目标创建 MR/PR:GitHub 仓库优先用已配置的 GitHub MCP,没有时用 curl 调 GitHub API,令牌取 $AGENTFLOW_GIT_TOKEN;其它托管平台用已配置的对应 MCP。本轮工作分支已有指向同一目标分支的 MR/PR 时更新它,不重复创建。\\n4. 标题概括本次改动;描述写需求摘要、改动要点、测试结果(依据 test-report.md)和已知限制。不得合并 MR/PR,不得推送主分支或强推。\\n5. 把每个仓库的 MR/PR 链接、源分支、目标分支和提交 SHA 写到 mr-body.md。\\n6. 推送或创建 MR/PR 失败(缺少凭据、无权限、网络错误等)时不得提交 pass:在 mr-body.md 记录失败原因,提交 human,并在 actionRequired 写明需要人工处理什么,例如配置 Git Token 后重试,或到托管平台手动创建 MR。\\n\\nMR 约束:{{existingMR}}\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}", "loop": {"enabled": true, "maxIterations": 2, "exitCondition": "all_gates_pass", "onExhausted": "human"}, "verification": [{"id": "mr-pushed", "name": "改动已提交并推送", "mode": "command", "stage": "after_execution", "commands": ["fail=0\\ntab=\\"$(printf ''\\\\t'')\\"\\nwhile IFS=\\"$tab\\" read -r d work base; do\\n [ -n \\"$d\\" ] || continue\\n dirty=\\"$(git -C \\"$d\\" status --porcelain --untracked-files=all -- . \\":(exclude).agentflow\\" \\":(exclude,glob)**/node_modules/**\\")\\" || { printf \\"%s 不是可用的 Git 检出目录\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ -n \\"$dirty\\" ]; then printf \\"%s 有未提交的改动:\\\\n%s\\\\n\\" \\"$d\\" \\"$dirty\\"; fail=1; continue; fi\\n refs=HEAD\\n if git -C \\"$d\\" rev-parse -q --verify \\"refs/heads/$work\\" >/dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone <<EOF\\n$AGENTFLOW_WORK_BRANCHES\\nEOF\\nexit \\"$fail\\""], "required": true, "onFailure": "loop", "executionScope": "run"}, {"id": "mr-opened", "name": "MR 已创建", "mode": "mr", "stage": "after_execution", "required": true, "onFailure": "loop"}]}' AS JSON)), updated_at = UTC_TIMESTAMP()+WHERE id = 'issue-fix-production'+ AND JSON_SEARCH(payload, 'one', 'mr', NULL, '$.Workflow.nodes[*].id') IS NULL+ AND JSON_LENGTH(payload, '$.Workflow.nodes') = 7+ AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.Workflow.nodes[6].id')) = 'deliver'+ AND JSON_EXTRACT(payload, '$.Workflow.nodes[6].position') = CAST('{"x": 1570, "y": 150}' AS JSON)+ AND JSON_EXTRACT(payload, '$.Workflow.edges[5]') = CAST('{"id": "e-5", "source": "accept", "target": "deliver", "when": "success"}' AS JSON)+ AND JSON_SEARCH(payload, 'one', 'issue-fix-production-mr', NULL, '$.Agents[*].id') IS NULL;+UPDATE generic_templates+SET payload = JSON_SET(payload, '$.Agents[5].prompt', '工作领域:缺陷根因、复现与回归。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token。代码已由「发起 MR」节点提交、推送并创建 MR/PR:按 mr-body.md 把链接、分支和提交 SHA 写进交付物清单;本节点不再修改代码、推送或创建 PR,不得合并。\n\n完成本节点约定的工作并交付产物。\n\n### 输入\n\n- 任务需求:{{input}}\n- 仓库上下文:{{repository}}'), updated_at = UTC_TIMESTAMP()+WHERE id = 'issue-fix-production'+ AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.Workflow.nodes[7].id')) = 'mr'+ AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.Agents[5].id')) = 'issue-fix-production-deliver'+ AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.Agents[5].prompt')) = '工作领域:缺陷根因、复现与回归。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token;仅在用户明确要求且已配置目标 GitHub 仓库及凭据时创建 PR,不得自行合并。\n\n完成本节点约定的工作并交付产物。\n\n### 输入\n\n- 任务需求:{{input}}\n- 仓库上下文:{{repository}}';+COMMIT;diff --git a/migrations/seed/001_public_catalog.sql b/migrations/seed/001_public_catalog.sqlindex 5a7fdd09..d3b98ae7 100644--- a/migrations/seed/001_public_catalog.sql+++ b/migrations/seed/001_public_catalog.sql@@ -6,9 +6,9 @@ INSERT IGNORE INTO sandboxes (`id`,`name`,`payload`) VALUES ('local','本地执INSERT IGNORE INTO sandboxes (`id`,`name`,`payload`) VALUES ('generic-docker','Docker 隔离沙箱','{"id":"generic-docker","name":"Docker 隔离沙箱","shared":true,"driver":"docker","dockerfileId":"generic-backend","readOnlyRootFS":false}');INSERT IGNORE INTO dockerfiles (`id`,`name`,`payload`) VALUES ('generic-backend','公共开发环境','{"id":"generic-backend","name":"公共开发环境","shared":true,"content":"FROM node:22-bookworm\\nRUN apt-get update && apt-get install -y --no-install-recommends git openssh-client python3 ripgrep ca-certificates curl && rm -rf /var/lib/apt/lists/*\\nRUN npm install -g @openai/codex @anthropic-ai/claude-code @tencent-ai/codebuddy-code\\nWORKDIR /workspace\\n"}');INSERT IGNORE INTO rules (`id`,`name`,`payload`) VALUES ('public-engineering','工程与验证约束','{"version":1,"updatedAt":"2026-10-15T00:00:00Z","id":"public-engineering","name":"工程与验证约束","shared":true,"priority":100,"content":"先阅读仓库约束并明确范围;只修改任务所需文件。不得泄露凭据,不得伪造测试或交付证据。使用项目现有构建与测试命令,报告真实结果与限制。发布 PR 前检查 diff;未经任务授权不得合并主分支。"}');-INSERT IGNORE INTO generic_templates (id,name,payload,updated_at) VALUES ('generic-backend-delivery','通用后端交付 SOP','{"Workflow": {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery", "name": "通用后端交付 SOP", "revision": 1, "status": "published", "description": "后端需求从需求定型到独立评审与交付。", "sandboxProfileId": "generic-docker", "generic": true, "owner": "LoopForge", "tags": ["public"], "nodes": [{"id": "clarify", "name": "需求定型", "type": "agent", "agentId": "generic-backend-delivery-clarify", "maxAttempts": 2, "position": {"x": 100, "y": 150}, "artifactOutputs": [{"name": "clarify", "path": "requirement.md", "mediaType": "text/markdown", "required": true}]}, {"id": "design", "name": "方案设计", "type": "agent", "agentId": "generic-backend-delivery-design", "maxAttempts": 2, "position": {"x": 345, "y": 150}, "artifactOutputs": [{"name": "design", "path": "design.md", "mediaType": "text/markdown", "required": true}]}, {"id": "implement", "name": "开发实现", "type": "agent", "agentId": "generic-backend-delivery-implement", "maxAttempts": 2, "position": {"x": 590, "y": 150}, "artifactOutputs": [{"name": "implement", "path": "implementation.md", "mediaType": "text/markdown", "required": true}]}, {"id": "review", "name": "独立评审", "type": "agent", "agentId": "generic-backend-delivery-review", "maxAttempts": 2, "position": {"x": 835, "y": 150}, "artifactOutputs": [{"name": "review", "path": "review.md", "mediaType": "text/markdown", "required": true}]}, {"id": "test", "name": "测试验证", "type": "agent", "agentId": "generic-backend-delivery-test", "maxAttempts": 2, "position": {"x": 1080, "y": 150}, "artifactOutputs": [{"name": "test", "path": "test-report.md", "mediaType": "text/markdown", "required": true}]}, {"id": "accept", "name": "人工验收", "type": "approval", "maxAttempts": 1, "rejectTo": "implement", "position": {"x": 1325, "y": 150}}, {"id": "deliver", "name": "交付汇总", "type": "agent", "agentId": "generic-backend-delivery-deliver", "maxAttempts": 2, "position": {"x": 1570, "y": 150}, "artifactOutputs": [{"name": "deliver", "path": "delivery.md", "mediaType": "text/markdown", "required": true}]}], "edges": [{"id": "e-0", "source": "clarify", "target": "design", "when": "success"}, {"id": "e-1", "source": "design", "target": "implement", "when": "success"}, {"id": "e-2", "source": "implement", "target": "review", "when": "success"}, {"id": "e-3", "source": "review", "target": "test", "when": "success"}, {"id": "e-4", "source": "test", "target": "accept", "when": "success"}, {"id": "e-5", "source": "accept", "target": "deliver", "when": "success"}]}, "Agents": [{"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-clarify", "name": "需求定型", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。确认目标、范围、用户、边界与可测试验收标准,输出 requirement.md。不要开始编码。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-design", "name": "方案设计", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。阅读已确认需求与可用代码,写出最小实现方案、接口影响、风险与验证计划到 design.md。未绑定仓库的新项目可在任务工作区设计和实现;修改已有系统或修复缺陷时必须取得相关源码,缺少时明确阻塞并请求补充。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-implement", "name": "开发实现", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。依据 requirement.md 和 design.md 实现需求,保持范围最小;执行适用验证,记录实现、改动和验证到 implementation.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-review", "name": "独立评审", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。独立审查改动及测试证据;按严重程度列出有位置与影响的缺陷及修复建议到 review.md。发现阻断问题必须明确写出 REJECT。不得伪造通过结论。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-test", "name": "测试验证", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。根据验收标准执行项目真实测试、构建及必要端到端场景。必要时修复问题并复测。将命令、退出码、结果、未验证范围写到 test-report.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-deliver", "name": "交付汇总", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token;仅在用户明确要求且已配置目标 GitHub 仓库及凭据时创建 PR,不得自行合并。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}], "Rules": [{"id": "public-engineering", "name": "工程与验证约束", "shared": true, "priority": 100, "content": "先阅读仓库约束并明确范围;只修改任务所需文件。不得泄露凭据,不得伪造测试或交付证据。使用项目现有构建与测试命令,报告真实结果与限制。发布 PR 前检查 diff;未经任务授权不得合并主分支。仓库绑定是可选的:未绑定时在任务工作区创建新项目并交付源码、报告;已有系统的修改或缺陷修复必须取得相关代码,缺少时明确阻塞并请求补充。没有目标仓库和凭据时不执行推送或创建 PR。"}], "Skills": []}',UTC_TIMESTAMP());-INSERT IGNORE INTO generic_templates (id,name,payload,updated_at) VALUES ('generic-frontend-delivery','通用前端交付 SOP','{"Workflow": {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery", "name": "通用前端交付 SOP", "revision": 1, "status": "published", "description": "前端需求从页面设计到交互与回归验证。", "sandboxProfileId": "generic-docker", "generic": true, "owner": "LoopForge", "tags": ["public"], "nodes": [{"id": "clarify", "name": "需求定型", "type": "agent", "agentId": "generic-frontend-delivery-clarify", "maxAttempts": 2, "position": {"x": 100, "y": 150}, "artifactOutputs": [{"name": "clarify", "path": "requirement.md", "mediaType": "text/markdown", "required": true}]}, {"id": "design", "name": "方案设计", "type": "agent", "agentId": "generic-frontend-delivery-design", "maxAttempts": 2, "position": {"x": 345, "y": 150}, "artifactOutputs": [{"name": "design", "path": "design.md", "mediaType": "text/markdown", "required": true}]}, {"id": "implement", "name": "开发实现", "type": "agent", "agentId": "generic-frontend-delivery-implement", "maxAttempts": 2, "position": {"x": 590, "y": 150}, "artifactOutputs": [{"name": "implement", "path": "implementation.md", "mediaType": "text/markdown", "required": true}]}, {"id": "review", "name": "独立评审", "type": "agent", "agentId": "generic-frontend-delivery-review", "maxAttempts": 2, "position": {"x": 835, "y": 150}, "artifactOutputs": [{"name": "review", "path": "review.md", "mediaType": "text/markdown", "required": true}]}, {"id": "test", "name": "测试验证", "type": "agent", "agentId": "generic-frontend-delivery-test", "maxAttempts": 2, "position": {"x": 1080, "y": 150}, "artifactOutputs": [{"name": "test", "path": "test-report.md", "mediaType": "text/markdown", "required": true}]}, {"id": "accept", "name": "人工验收", "type": "approval", "maxAttempts": 1, "rejectTo": "implement", "position": {"x": 1325, "y": 150}}, {"id": "deliver", "name": "交付汇总", "type": "agent", "agentId": "generic-frontend-delivery-deliver", "maxAttempts": 2, "position": {"x": 1570, "y": 150}, "artifactOutputs": [{"name": "deliver", "path": "delivery.md", "mediaType": "text/markdown", "required": true}]}], "edges": [{"id": "e-0", "source": "clarify", "target": "design", "when": "success"}, {"id": "e-1", "source": "design", "target": "implement", "when": "success"}, {"id": "e-2", "source": "implement", "target": "review", "when": "success"}, {"id": "e-3", "source": "review", "target": "test", "when": "success"}, {"id": "e-4", "source": "test", "target": "accept", "when": "success"}, {"id": "e-5", "source": "accept", "target": "deliver", "when": "success"}]}, "Agents": [{"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery-clarify", "name": "需求定型", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。确认目标、范围、用户、边界与可测试验收标准,输出 requirement.md。不要开始编码。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery-design", "name": "方案设计", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。阅读已确认需求与可用代码,写出最小实现方案、接口影响、风险与验证计划到 design.md。未绑定仓库的新项目可在任务工作区设计和实现;修改已有系统或修复缺陷时必须取得相关源码,缺少时明确阻塞并请求补充。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery-implement", "name": "开发实现", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。依据 requirement.md 和 design.md 实现需求,保持范围最小;执行适用验证,记录实现、改动和验证到 implementation.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery-review", "name": "独立评审", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。独立审查改动及测试证据;按严重程度列出有位置与影响的缺陷及修复建议到 review.md。发现阻断问题必须明确写出 REJECT。不得伪造通过结论。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery-test", "name": "测试验证", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。根据验收标准执行项目真实测试、构建及必要端到端场景。必要时修复问题并复测。将命令、退出码、结果、未验证范围写到 test-report.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery-deliver", "name": "交付汇总", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token;仅在用户明确要求且已配置目标 GitHub 仓库及凭据时创建 PR,不得自行合并。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}], "Rules": [{"id": "public-engineering", "name": "工程与验证约束", "shared": true, "priority": 100, "content": "先阅读仓库约束并明确范围;只修改任务所需文件。不得泄露凭据,不得伪造测试或交付证据。使用项目现有构建与测试命令,报告真实结果与限制。发布 PR 前检查 diff;未经任务授权不得合并主分支。仓库绑定是可选的:未绑定时在任务工作区创建新项目并交付源码、报告;已有系统的修改或缺陷修复必须取得相关代码,缺少时明确阻塞并请求补充。没有目标仓库和凭据时不执行推送或创建 PR。"}], "Skills": []}',UTC_TIMESTAMP());-INSERT IGNORE INTO generic_templates (id,name,payload,updated_at) VALUES ('issue-fix-production','通用缺陷修复 SOP','{"Workflow": {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production", "name": "通用缺陷修复 SOP", "revision": 1, "status": "published", "description": "先复现,再修复,独立评审并回归。", "sandboxProfileId": "generic-docker", "generic": true, "owner": "LoopForge", "tags": ["public"], "nodes": [{"id": "clarify", "name": "需求定型", "type": "agent", "agentId": "issue-fix-production-clarify", "maxAttempts": 2, "position": {"x": 100, "y": 150}, "artifactOutputs": [{"name": "clarify", "path": "requirement.md", "mediaType": "text/markdown", "required": true}]}, {"id": "design", "name": "方案设计", "type": "agent", "agentId": "issue-fix-production-design", "maxAttempts": 2, "position": {"x": 345, "y": 150}, "artifactOutputs": [{"name": "design", "path": "design.md", "mediaType": "text/markdown", "required": true}]}, {"id": "implement", "name": "开发实现", "type": "agent", "agentId": "issue-fix-production-implement", "maxAttempts": 2, "position": {"x": 590, "y": 150}, "artifactOutputs": [{"name": "implement", "path": "implementation.md", "mediaType": "text/markdown", "required": true}]}, {"id": "review", "name": "独立评审", "type": "agent", "agentId": "issue-fix-production-review", "maxAttempts": 2, "position": {"x": 835, "y": 150}, "artifactOutputs": [{"name": "review", "path": "review.md", "mediaType": "text/markdown", "required": true}]}, {"id": "test", "name": "测试验证", "type": "agent", "agentId": "issue-fix-production-test", "maxAttempts": 2, "position": {"x": 1080, "y": 150}, "artifactOutputs": [{"name": "test", "path": "test-report.md", "mediaType": "text/markdown", "required": true}]}, {"id": "accept", "name": "人工验收", "type": "approval", "maxAttempts": 1, "rejectTo": "implement", "position": {"x": 1325, "y": 150}}, {"id": "deliver", "name": "交付汇总", "type": "agent", "agentId": "issue-fix-production-deliver", "maxAttempts": 2, "position": {"x": 1570, "y": 150}, "artifactOutputs": [{"name": "deliver", "path": "delivery.md", "mediaType": "text/markdown", "required": true}]}], "edges": [{"id": "e-0", "source": "clarify", "target": "design", "when": "success"}, {"id": "e-1", "source": "design", "target": "implement", "when": "success"}, {"id": "e-2", "source": "implement", "target": "review", "when": "success"}, {"id": "e-3", "source": "review", "target": "test", "when": "success"}, {"id": "e-4", "source": "test", "target": "accept", "when": "success"}, {"id": "e-5", "source": "accept", "target": "deliver", "when": "success"}]}, "Agents": [{"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production-clarify", "name": "需求定型", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。确认目标、范围、用户、边界与可测试验收标准,输出 requirement.md。不要开始编码。可以不绑定仓库,但必须先取得用户提供的待修代码和复现材料;缺少时明确列出阻塞项并请求补充,不得编造复现或声称已修复。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production-design", "name": "方案设计", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。阅读已确认需求与可用代码,写出最小实现方案、接口影响、风险与验证计划到 design.md。未绑定仓库的新项目可在任务工作区设计和实现;修改已有系统或修复缺陷时必须取得相关源码,缺少时明确阻塞并请求补充。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production-implement", "name": "开发实现", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。依据 requirement.md 和 design.md 实现需求,保持范围最小;执行适用验证,记录实现、改动和验证到 implementation.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production-review", "name": "独立评审", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。独立审查改动及测试证据;按严重程度列出有位置与影响的缺陷及修复建议到 review.md。发现阻断问题必须明确写出 REJECT。不得伪造通过结论。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production-test", "name": "测试验证", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。根据验收标准执行项目真实测试、构建及必要端到端场景。必要时修复问题并复测。将命令、退出码、结果、未验证范围写到 test-report.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production-deliver", "name": "交付汇总", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token;仅在用户明确要求且已配置目标 GitHub 仓库及凭据时创建 PR,不得自行合并。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}], "Rules": [{"id": "public-engineering", "name": "工程与验证约束", "shared": true, "priority": 100, "content": "先阅读仓库约束并明确范围;只修改任务所需文件。不得泄露凭据,不得伪造测试或交付证据。使用项目现有构建与测试命令,报告真实结果与限制。发布 PR 前检查 diff;未经任务授权不得合并主分支。仓库绑定是可选的:未绑定时在任务工作区创建新项目并交付源码、报告;已有系统的修改或缺陷修复必须取得相关代码,缺少时明确阻塞并请求补充。没有目标仓库和凭据时不执行推送或创建 PR。"}], "Skills": []}',UTC_TIMESTAMP());+INSERT IGNORE INTO generic_templates (id,name,payload,updated_at) VALUES ('generic-backend-delivery','通用后端交付 SOP','{"Workflow": {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery", "name": "通用后端交付 SOP", "revision": 1, "status": "published", "description": "后端需求从需求定型到独立评审与交付。", "sandboxProfileId": "generic-docker", "generic": true, "owner": "LoopForge", "tags": ["public"], "nodes": [{"id": "clarify", "name": "需求定型", "type": "agent", "agentId": "generic-backend-delivery-clarify", "maxAttempts": 2, "position": {"x": 100, "y": 150}, "artifactOutputs": [{"name": "clarify", "path": "requirement.md", "mediaType": "text/markdown", "required": true}]}, {"id": "design", "name": "方案设计", "type": "agent", "agentId": "generic-backend-delivery-design", "maxAttempts": 2, "position": {"x": 345, "y": 150}, "artifactOutputs": [{"name": "design", "path": "design.md", "mediaType": "text/markdown", "required": true}]}, {"id": "implement", "name": "开发实现", "type": "agent", "agentId": "generic-backend-delivery-implement", "maxAttempts": 2, "position": {"x": 590, "y": 150}, "artifactOutputs": [{"name": "implement", "path": "implementation.md", "mediaType": "text/markdown", "required": true}]}, {"id": "review", "name": "独立评审", "type": "agent", "agentId": "generic-backend-delivery-review", "maxAttempts": 2, "position": {"x": 835, "y": 150}, "artifactOutputs": [{"name": "review", "path": "review.md", "mediaType": "text/markdown", "required": true}]}, {"id": "test", "name": "测试验证", "type": "agent", "agentId": "generic-backend-delivery-test", "maxAttempts": 2, "position": {"x": 1080, "y": 150}, "artifactOutputs": [{"name": "test", "path": "test-report.md", "mediaType": "text/markdown", "required": true}]}, {"id": "accept", "name": "人工验收", "type": "approval", "maxAttempts": 1, "rejectTo": "implement", "position": {"x": 1325, "y": 150}}, {"id": "deliver", "name": "交付汇总", "type": "agent", "agentId": "generic-backend-delivery-deliver", "maxAttempts": 2, "position": {"x": 1815, "y": 150}, "artifactOutputs": [{"name": "deliver", "path": "delivery.md", "mediaType": "text/markdown", "required": true}]}, {"id": "mr", "name": "发起 MR", "type": "agent", "agentId": "generic-backend-delivery-mr", "maxAttempts": 2, "position": {"x": 1570, "y": 150}, "artifactOutputs": [{"name": "mr-body", "path": "mr-body.md", "mediaType": "text/markdown", "required": true}]}], "edges": [{"id": "e-0", "source": "clarify", "target": "design", "when": "success"}, {"id": "e-1", "source": "design", "target": "implement", "when": "success"}, {"id": "e-2", "source": "implement", "target": "review", "when": "success"}, {"id": "e-3", "source": "review", "target": "test", "when": "success"}, {"id": "e-4", "source": "test", "target": "accept", "when": "success"}, {"id": "e-5", "source": "accept", "target": "mr", "when": "success"}, {"id": "e-6", "source": "mr", "target": "deliver", "when": "success"}]}, "Agents": [{"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-clarify", "name": "需求定型", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。确认目标、范围、用户、边界与可测试验收标准,输出 requirement.md。不要开始编码。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-design", "name": "方案设计", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。阅读已确认需求与可用代码,写出最小实现方案、接口影响、风险与验证计划到 design.md。未绑定仓库的新项目可在任务工作区设计和实现;修改已有系统或修复缺陷时必须取得相关源码,缺少时明确阻塞并请求补充。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-implement", "name": "开发实现", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。依据 requirement.md 和 design.md 实现需求,保持范围最小;执行适用验证,记录实现、改动和验证到 implementation.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-review", "name": "独立评审", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。独立审查改动及测试证据;按严重程度列出有位置与影响的缺陷及修复建议到 review.md。发现阻断问题必须明确写出 REJECT。不得伪造通过结论。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-test", "name": "测试验证", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。根据验收标准执行项目真实测试、构建及必要端到端场景。必要时修复问题并复测。将命令、退出码、结果、未验证范围写到 test-report.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-deliver", "name": "交付汇总", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token。代码已由「发起 MR」节点提交、推送并创建 MR/PR:按 mr-body.md 把链接、分支和提交 SHA 写进交付物清单;本节点不再修改代码、推送或创建 PR,不得合并。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-11-16T00:00:00Z", "id": "generic-backend-delivery-mr", "name": "发起 MR", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。人工验收已通过,本节点把本轮代码改动提交到工作分支、推送并发起 MR/PR,不再修改业务逻辑。\\n\\n1. 未绑定代码仓库时不推送、不创建 MR/PR:在 mr-body.md 写明「未绑定代码仓库,源码保留在任务工作区」并列出交付文件,然后提交 pass。\\n2. 已绑定仓库时逐个处理每个仓库检出目录,本轮没有改动的仓库跳过,不创建空 MR/PR:确认当前在本轮工作分支上,不得在主分支提交,也不得切换或新建分支;检查 git status 与 diff,只提交本任务相关的源码改动,不提交 .agentflow、依赖目录、构建产物和 SOP 阶段文档;用概括本次改动的提交信息 commit,再 git push -u origin 当前工作分支。平台已注入 Git 凭据,不得打印、回显或写入任何令牌。\\n3. 以仓库上下文中的目标分支为目标创建 MR/PR:GitHub 仓库优先用已配置的 GitHub MCP,没有时用 curl 调 GitHub API,令牌取 $AGENTFLOW_GIT_TOKEN;其它托管平台用已配置的对应 MCP。本轮工作分支已有指向同一目标分支的 MR/PR 时更新它,不重复创建。\\n4. 标题概括本次改动;描述写需求摘要、改动要点、测试结果(依据 test-report.md)和已知限制。不得合并 MR/PR,不得推送主分支或强推。\\n5. 把每个仓库的 MR/PR 链接、源分支、目标分支和提交 SHA 写到 mr-body.md。\\n6. 推送或创建 MR/PR 失败(缺少凭据、无权限、网络错误等)时不得提交 pass:在 mr-body.md 记录失败原因,提交 human,并在 actionRequired 写明需要人工处理什么,例如配置 Git Token 后重试,或到托管平台手动创建 MR。\\n\\nMR 约束:{{existingMR}}\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}", "loop": {"enabled": true, "maxIterations": 2, "exitCondition": "all_gates_pass", "onExhausted": "human"}, "verification": [{"id": "mr-pushed", "name": "改动已提交并推送", "mode": "command", "stage": "after_execution", "commands": ["fail=0\\ntab=\\"$(printf ''\\\\t'')\\"\\nwhile IFS=\\"$tab\\" read -r d work base; do\\n [ -n \\"$d\\" ] || continue\\n dirty=\\"$(git -C \\"$d\\" status --porcelain --untracked-files=all -- . \\":(exclude).agentflow\\" \\":(exclude,glob)**/node_modules/**\\")\\" || { printf \\"%s 不是可用的 Git 检出目录\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ -n \\"$dirty\\" ]; then printf \\"%s 有未提交的改动:\\\\n%s\\\\n\\" \\"$d\\" \\"$dirty\\"; fail=1; continue; fi\\n refs=HEAD\\n if git -C \\"$d\\" rev-parse -q --verify \\"refs/heads/$work\\" >/dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone <<EOF\\n$AGENTFLOW_WORK_BRANCHES\\nEOF\\nexit \\"$fail\\""], "required": true, "onFailure": "loop", "executionScope": "run"}, {"id": "mr-opened", "name": "MR 已创建", "mode": "mr", "stage": "after_execution", "required": true, "onFailure": "loop"}]}], "Rules": [{"id": "public-engineering", "name": "工程与验证约束", "shared": true, "priority": 100, "content": "先阅读仓库约束并明确范围;只修改任务所需文件。不得泄露凭据,不得伪造测试或交付证据。使用项目现有构建与测试命令,报告真实结果与限制。发布 PR 前检查 diff;未经任务授权不得合并主分支。仓库绑定是可选的:未绑定时在任务工作区创建新项目并交付源码、报告;已有系统的修改或缺陷修复必须取得相关代码,缺少时明确阻塞并请求补充。没有目标仓库和凭据时不执行推送或创建 PR。"}], "Skills": []}',UTC_TIMESTAMP());+INSERT IGNORE INTO generic_templates (id,name,payload,updated_at) VALUES ('generic-frontend-delivery','通用前端交付 SOP','{"Workflow": {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery", "name": "通用前端交付 SOP", "revision": 1, "status": "published", "description": "前端需求从页面设计到交互与回归验证。", "sandboxProfileId": "generic-docker", "generic": true, "owner": "LoopForge", "tags": ["public"], "nodes": [{"id": "clarify", "name": "需求定型", "type": "agent", "agentId": "generic-frontend-delivery-clarify", "maxAttempts": 2, "position": {"x": 100, "y": 150}, "artifactOutputs": [{"name": "clarify", "path": "requirement.md", "mediaType": "text/markdown", "required": true}]}, {"id": "design", "name": "方案设计", "type": "agent", "agentId": "generic-frontend-delivery-design", "maxAttempts": 2, "position": {"x": 345, "y": 150}, "artifactOutputs": [{"name": "design", "path": "design.md", "mediaType": "text/markdown", "required": true}]}, {"id": "implement", "name": "开发实现", "type": "agent", "agentId": "generic-frontend-delivery-implement", "maxAttempts": 2, "position": {"x": 590, "y": 150}, "artifactOutputs": [{"name": "implement", "path": "implementation.md", "mediaType": "text/markdown", "required": true}]}, {"id": "review", "name": "独立评审", "type": "agent", "agentId": "generic-frontend-delivery-review", "maxAttempts": 2, "position": {"x": 835, "y": 150}, "artifactOutputs": [{"name": "review", "path": "review.md", "mediaType": "text/markdown", "required": true}]}, {"id": "test", "name": "测试验证", "type": "agent", "agentId": "generic-frontend-delivery-test", "maxAttempts": 2, "position": {"x": 1080, "y": 150}, "artifactOutputs": [{"name": "test", "path": "test-report.md", "mediaType": "text/markdown", "required": true}]}, {"id": "accept", "name": "人工验收", "type": "approval", "maxAttempts": 1, "rejectTo": "implement", "position": {"x": 1325, "y": 150}}, {"id": "deliver", "name": "交付汇总", "type": "agent", "agentId": "generic-frontend-delivery-deliver", "maxAttempts": 2, "position": {"x": 1815, "y": 150}, "artifactOutputs": [{"name": "deliver", "path": "delivery.md", "mediaType": "text/markdown", "required": true}]}, {"id": "mr", "name": "发起 MR", "type": "agent", "agentId": "generic-frontend-delivery-mr", "maxAttempts": 2, "position": {"x": 1570, "y": 150}, "artifactOutputs": [{"name": "mr-body", "path": "mr-body.md", "mediaType": "text/markdown", "required": true}]}], "edges": [{"id": "e-0", "source": "clarify", "target": "design", "when": "success"}, {"id": "e-1", "source": "design", "target": "implement", "when": "success"}, {"id": "e-2", "source": "implement", "target": "review", "when": "success"}, {"id": "e-3", "source": "review", "target": "test", "when": "success"}, {"id": "e-4", "source": "test", "target": "accept", "when": "success"}, {"id": "e-5", "source": "accept", "target": "mr", "when": "success"}, {"id": "e-6", "source": "mr", "target": "deliver", "when": "success"}]}, "Agents": [{"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery-clarify", "name": "需求定型", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。确认目标、范围、用户、边界与可测试验收标准,输出 requirement.md。不要开始编码。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery-design", "name": "方案设计", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。阅读已确认需求与可用代码,写出最小实现方案、接口影响、风险与验证计划到 design.md。未绑定仓库的新项目可在任务工作区设计和实现;修改已有系统或修复缺陷时必须取得相关源码,缺少时明确阻塞并请求补充。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery-implement", "name": "开发实现", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。依据 requirement.md 和 design.md 实现需求,保持范围最小;执行适用验证,记录实现、改动和验证到 implementation.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery-review", "name": "独立评审", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。独立审查改动及测试证据;按严重程度列出有位置与影响的缺陷及修复建议到 review.md。发现阻断问题必须明确写出 REJECT。不得伪造通过结论。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery-test", "name": "测试验证", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。根据验收标准执行项目真实测试、构建及必要端到端场景。必要时修复问题并复测。将命令、退出码、结果、未验证范围写到 test-report.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-frontend-delivery-deliver", "name": "交付汇总", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token。代码已由「发起 MR」节点提交、推送并创建 MR/PR:按 mr-body.md 把链接、分支和提交 SHA 写进交付物清单;本节点不再修改代码、推送或创建 PR,不得合并。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-11-16T00:00:00Z", "id": "generic-frontend-delivery-mr", "name": "发起 MR", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:前端页面、交互、可访问性与响应式。人工验收已通过,本节点把本轮代码改动提交到工作分支、推送并发起 MR/PR,不再修改业务逻辑。\\n\\n1. 未绑定代码仓库时不推送、不创建 MR/PR:在 mr-body.md 写明「未绑定代码仓库,源码保留在任务工作区」并列出交付文件,然后提交 pass。\\n2. 已绑定仓库时逐个处理每个仓库检出目录,本轮没有改动的仓库跳过,不创建空 MR/PR:确认当前在本轮工作分支上,不得在主分支提交,也不得切换或新建分支;检查 git status 与 diff,只提交本任务相关的源码改动,不提交 .agentflow、依赖目录、构建产物和 SOP 阶段文档;用概括本次改动的提交信息 commit,再 git push -u origin 当前工作分支。平台已注入 Git 凭据,不得打印、回显或写入任何令牌。\\n3. 以仓库上下文中的目标分支为目标创建 MR/PR:GitHub 仓库优先用已配置的 GitHub MCP,没有时用 curl 调 GitHub API,令牌取 $AGENTFLOW_GIT_TOKEN;其它托管平台用已配置的对应 MCP。本轮工作分支已有指向同一目标分支的 MR/PR 时更新它,不重复创建。\\n4. 标题概括本次改动;描述写需求摘要、改动要点、测试结果(依据 test-report.md)和已知限制。不得合并 MR/PR,不得推送主分支或强推。\\n5. 把每个仓库的 MR/PR 链接、源分支、目标分支和提交 SHA 写到 mr-body.md。\\n6. 推送或创建 MR/PR 失败(缺少凭据、无权限、网络错误等)时不得提交 pass:在 mr-body.md 记录失败原因,提交 human,并在 actionRequired 写明需要人工处理什么,例如配置 Git Token 后重试,或到托管平台手动创建 MR。\\n\\nMR 约束:{{existingMR}}\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}", "loop": {"enabled": true, "maxIterations": 2, "exitCondition": "all_gates_pass", "onExhausted": "human"}, "verification": [{"id": "mr-pushed", "name": "改动已提交并推送", "mode": "command", "stage": "after_execution", "commands": ["fail=0\\ntab=\\"$(printf ''\\\\t'')\\"\\nwhile IFS=\\"$tab\\" read -r d work base; do\\n [ -n \\"$d\\" ] || continue\\n dirty=\\"$(git -C \\"$d\\" status --porcelain --untracked-files=all -- . \\":(exclude).agentflow\\" \\":(exclude,glob)**/node_modules/**\\")\\" || { printf \\"%s 不是可用的 Git 检出目录\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ -n \\"$dirty\\" ]; then printf \\"%s 有未提交的改动:\\\\n%s\\\\n\\" \\"$d\\" \\"$dirty\\"; fail=1; continue; fi\\n refs=HEAD\\n if git -C \\"$d\\" rev-parse -q --verify \\"refs/heads/$work\\" >/dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone <<EOF\\n$AGENTFLOW_WORK_BRANCHES\\nEOF\\nexit \\"$fail\\""], "required": true, "onFailure": "loop", "executionScope": "run"}, {"id": "mr-opened", "name": "MR 已创建", "mode": "mr", "stage": "after_execution", "required": true, "onFailure": "loop"}]}], "Rules": [{"id": "public-engineering", "name": "工程与验证约束", "shared": true, "priority": 100, "content": "先阅读仓库约束并明确范围;只修改任务所需文件。不得泄露凭据,不得伪造测试或交付证据。使用项目现有构建与测试命令,报告真实结果与限制。发布 PR 前检查 diff;未经任务授权不得合并主分支。仓库绑定是可选的:未绑定时在任务工作区创建新项目并交付源码、报告;已有系统的修改或缺陷修复必须取得相关代码,缺少时明确阻塞并请求补充。没有目标仓库和凭据时不执行推送或创建 PR。"}], "Skills": []}',UTC_TIMESTAMP());+INSERT IGNORE INTO generic_templates (id,name,payload,updated_at) VALUES ('issue-fix-production','通用缺陷修复 SOP','{"Workflow": {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production", "name": "通用缺陷修复 SOP", "revision": 1, "status": "published", "description": "先复现,再修复,独立评审并回归。", "sandboxProfileId": "generic-docker", "generic": true, "owner": "LoopForge", "tags": ["public"], "nodes": [{"id": "clarify", "name": "需求定型", "type": "agent", "agentId": "issue-fix-production-clarify", "maxAttempts": 2, "position": {"x": 100, "y": 150}, "artifactOutputs": [{"name": "clarify", "path": "requirement.md", "mediaType": "text/markdown", "required": true}]}, {"id": "design", "name": "方案设计", "type": "agent", "agentId": "issue-fix-production-design", "maxAttempts": 2, "position": {"x": 345, "y": 150}, "artifactOutputs": [{"name": "design", "path": "design.md", "mediaType": "text/markdown", "required": true}]}, {"id": "implement", "name": "开发实现", "type": "agent", "agentId": "issue-fix-production-implement", "maxAttempts": 2, "position": {"x": 590, "y": 150}, "artifactOutputs": [{"name": "implement", "path": "implementation.md", "mediaType": "text/markdown", "required": true}]}, {"id": "review", "name": "独立评审", "type": "agent", "agentId": "issue-fix-production-review", "maxAttempts": 2, "position": {"x": 835, "y": 150}, "artifactOutputs": [{"name": "review", "path": "review.md", "mediaType": "text/markdown", "required": true}]}, {"id": "test", "name": "测试验证", "type": "agent", "agentId": "issue-fix-production-test", "maxAttempts": 2, "position": {"x": 1080, "y": 150}, "artifactOutputs": [{"name": "test", "path": "test-report.md", "mediaType": "text/markdown", "required": true}]}, {"id": "accept", "name": "人工验收", "type": "approval", "maxAttempts": 1, "rejectTo": "implement", "position": {"x": 1325, "y": 150}}, {"id": "deliver", "name": "交付汇总", "type": "agent", "agentId": "issue-fix-production-deliver", "maxAttempts": 2, "position": {"x": 1815, "y": 150}, "artifactOutputs": [{"name": "deliver", "path": "delivery.md", "mediaType": "text/markdown", "required": true}]}, {"id": "mr", "name": "发起 MR", "type": "agent", "agentId": "issue-fix-production-mr", "maxAttempts": 2, "position": {"x": 1570, "y": 150}, "artifactOutputs": [{"name": "mr-body", "path": "mr-body.md", "mediaType": "text/markdown", "required": true}]}], "edges": [{"id": "e-0", "source": "clarify", "target": "design", "when": "success"}, {"id": "e-1", "source": "design", "target": "implement", "when": "success"}, {"id": "e-2", "source": "implement", "target": "review", "when": "success"}, {"id": "e-3", "source": "review", "target": "test", "when": "success"}, {"id": "e-4", "source": "test", "target": "accept", "when": "success"}, {"id": "e-5", "source": "accept", "target": "mr", "when": "success"}, {"id": "e-6", "source": "mr", "target": "deliver", "when": "success"}]}, "Agents": [{"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production-clarify", "name": "需求定型", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。确认目标、范围、用户、边界与可测试验收标准,输出 requirement.md。不要开始编码。可以不绑定仓库,但必须先取得用户提供的待修代码和复现材料;缺少时明确列出阻塞项并请求补充,不得编造复现或声称已修复。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production-design", "name": "方案设计", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。阅读已确认需求与可用代码,写出最小实现方案、接口影响、风险与验证计划到 design.md。未绑定仓库的新项目可在任务工作区设计和实现;修改已有系统或修复缺陷时必须取得相关源码,缺少时明确阻塞并请求补充。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production-implement", "name": "开发实现", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。依据 requirement.md 和 design.md 实现需求,保持范围最小;执行适用验证,记录实现、改动和验证到 implementation.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production-review", "name": "独立评审", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。独立审查改动及测试证据;按严重程度列出有位置与影响的缺陷及修复建议到 review.md。发现阻断问题必须明确写出 REJECT。不得伪造通过结论。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production-test", "name": "测试验证", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。根据验收标准执行项目真实测试、构建及必要端到端场景。必要时修复问题并复测。将命令、退出码、结果、未验证范围写到 test-report.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "issue-fix-production-deliver", "name": "交付汇总", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token。代码已由「发起 MR」节点提交、推送并创建 MR/PR:按 mr-body.md 把链接、分支和提交 SHA 写进交付物清单;本节点不再修改代码、推送或创建 PR,不得合并。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-11-16T00:00:00Z", "id": "issue-fix-production-mr", "name": "发起 MR", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:缺陷根因、复现与回归。人工验收已通过,本节点把本轮代码改动提交到工作分支、推送并发起 MR/PR,不再修改业务逻辑。\\n\\n1. 未绑定代码仓库时不推送、不创建 MR/PR:在 mr-body.md 写明「未绑定代码仓库,源码保留在任务工作区」并列出交付文件,然后提交 pass。\\n2. 已绑定仓库时逐个处理每个仓库检出目录,本轮没有改动的仓库跳过,不创建空 MR/PR:确认当前在本轮工作分支上,不得在主分支提交,也不得切换或新建分支;检查 git status 与 diff,只提交本任务相关的源码改动,不提交 .agentflow、依赖目录、构建产物和 SOP 阶段文档;用概括本次改动的提交信息 commit,再 git push -u origin 当前工作分支。平台已注入 Git 凭据,不得打印、回显或写入任何令牌。\\n3. 以仓库上下文中的目标分支为目标创建 MR/PR:GitHub 仓库优先用已配置的 GitHub MCP,没有时用 curl 调 GitHub API,令牌取 $AGENTFLOW_GIT_TOKEN;其它托管平台用已配置的对应 MCP。本轮工作分支已有指向同一目标分支的 MR/PR 时更新它,不重复创建。\\n4. 标题概括本次改动;描述写需求摘要、改动要点、测试结果(依据 test-report.md)和已知限制。不得合并 MR/PR,不得推送主分支或强推。\\n5. 把每个仓库的 MR/PR 链接、源分支、目标分支和提交 SHA 写到 mr-body.md。\\n6. 推送或创建 MR/PR 失败(缺少凭据、无权限、网络错误等)时不得提交 pass:在 mr-body.md 记录失败原因,提交 human,并在 actionRequired 写明需要人工处理什么,例如配置 Git Token 后重试,或到托管平台手动创建 MR。\\n\\nMR 约束:{{existingMR}}\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}", "loop": {"enabled": true, "maxIterations": 2, "exitCondition": "all_gates_pass", "onExhausted": "human"}, "verification": [{"id": "mr-pushed", "name": "改动已提交并推送", "mode": "command", "stage": "after_execution", "commands": ["fail=0\\ntab=\\"$(printf ''\\\\t'')\\"\\nwhile IFS=\\"$tab\\" read -r d work base; do\\n [ -n \\"$d\\" ] || continue\\n dirty=\\"$(git -C \\"$d\\" status --porcelain --untracked-files=all -- . \\":(exclude).agentflow\\" \\":(exclude,glob)**/node_modules/**\\")\\" || { printf \\"%s 不是可用的 Git 检出目录\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ -n \\"$dirty\\" ]; then printf \\"%s 有未提交的改动:\\\\n%s\\\\n\\" \\"$d\\" \\"$dirty\\"; fail=1; continue; fi\\n refs=HEAD\\n if git -C \\"$d\\" rev-parse -q --verify \\"refs/heads/$work\\" >/dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone <<EOF\\n$AGENTFLOW_WORK_BRANCHES\\nEOF\\nexit \\"$fail\\""], "required": true, "onFailure": "loop", "executionScope": "run"}, {"id": "mr-opened", "name": "MR 已创建", "mode": "mr", "stage": "after_execution", "required": true, "onFailure": "loop"}]}], "Rules": [{"id": "public-engineering", "name": "工程与验证约束", "shared": true, "priority": 100, "content": "先阅读仓库约束并明确范围;只修改任务所需文件。不得泄露凭据,不得伪造测试或交付证据。使用项目现有构建与测试命令,报告真实结果与限制。发布 PR 前检查 diff;未经任务授权不得合并主分支。仓库绑定是可选的:未绑定时在任务工作区创建新项目并交付源码、报告;已有系统的修改或缺陷修复必须取得相关代码,缺少时明确阻塞并请求补充。没有目标仓库和凭据时不执行推送或创建 PR。"}], "Skills": []}',UTC_TIMESTAMP());INSERT IGNORE INTO generic_templates (id,name,payload,updated_at) VALUES ('generic-product-delivery','通用产品方案 SOP','{"Workflow": {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-product-delivery", "name": "通用产品方案 SOP", "revision": 1, "status": "published", "description": "完成需求分析、产品方案文档与独立验收;无需代码仓库或 Git Token。", "sandboxProfileId": "generic-docker", "generic": true, "owner": "LoopForge", "tags": ["public"], "nodes": [{"id": "clarify", "name": "需求定型", "type": "agent", "agentId": "generic-product-delivery-clarify", "maxAttempts": 2, "position": {"x": 100, "y": 150}, "artifactOutputs": [{"name": "clarify", "path": "requirement.md", "mediaType": "text/markdown", "required": true}]}, {"id": "design", "name": "方案设计", "type": "agent", "agentId": "generic-product-delivery-design", "maxAttempts": 2, "position": {"x": 345, "y": 150}, "artifactOutputs": [{"name": "design", "path": "design.md", "mediaType": "text/markdown", "required": true}]}, {"id": "review", "name": "独立评审", "type": "agent", "agentId": "generic-product-delivery-review", "maxAttempts": 2, "position": {"x": 590, "y": 150}, "artifactOutputs": [{"name": "review", "path": "review.md", "mediaType": "text/markdown", "required": true}]}, {"id": "accept", "name": "人工验收", "type": "approval", "maxAttempts": 1, "rejectTo": "design", "position": {"x": 835, "y": 150}}, {"id": "deliver", "name": "交付汇总", "type": "agent", "agentId": "generic-product-delivery-deliver", "maxAttempts": 2, "position": {"x": 1080, "y": 150}, "artifactOutputs": [{"name": "deliver", "path": "delivery.md", "mediaType": "text/markdown", "required": true}]}], "edges": [{"id": "e-0", "source": "clarify", "target": "design", "when": "success"}, {"id": "e-1", "source": "design", "target": "review", "when": "success"}, {"id": "e-2", "source": "review", "target": "accept", "when": "success"}, {"id": "e-3", "source": "accept", "target": "deliver", "when": "success"}]}, "Agents": [{"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-product-delivery-clarify", "name": "需求定型", "executorId": "codebuddy", "rules": ["public-product-documents"], "skills": [], "mcpServers": [], "prompt": "工作领域:产品方案、用户场景与验收规范。确认目标、范围、用户场景、业务边界与可检查的验收标准,输出 requirement.md。信息不足时明确列出假设和待确认项。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-product-delivery-design", "name": "方案设计", "executorId": "codebuddy", "rules": ["public-product-documents"], "skills": [], "mcpServers": [], "prompt": "工作领域:产品方案、用户场景与验收规范。阅读 requirement.md,梳理用户旅程、功能范围、交互流程、业务规则、风险和验收标准,将产品方案写到 design.md。只交付文档,无需代码仓库,不执行编码或 Git 操作。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-product-delivery-review", "name": "独立评审", "executorId": "codebuddy", "rules": ["public-product-documents"], "skills": [], "mcpServers": [], "prompt": "工作领域:产品方案、用户场景与验收规范。依据 requirement.md 独立审查 design.md 的完整性、一致性、边界场景与验收标准。将具体问题、文档位置、影响及修改建议写到 review.md。发现阻断问题必须明确写出 REJECT;不得伪造验证结论。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-product-delivery-deliver", "name": "交付汇总", "executorId": "codebuddy", "rules": ["public-product-documents"], "skills": [], "mcpServers": [], "prompt": "工作领域:产品方案、用户场景与验收规范。在人工验收后核对 requirement.md、design.md 和 review.md,将实际完成内容、验收结论、待确认问题、已知限制及交付物清单写到 delivery.md。只交付工作区文档,无需 Git Token,不创建代码提交或 PR。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}], "Rules": [{"id": "public-product-documents", "name": "产品文档与验收约束", "shared": true, "priority": 100, "content": "根据用户输入和工作区文档完成产品方案;无需代码仓库、Git Token 或代码构建。明确假设与待确认项,不得伪造事实、验证或验收结果,不得泄露凭据。文档写入任务工作区并按节点约定归档;发现阻断问题明确说明并返工。"}], "Skills": []}',UTC_TIMESTAMP());INSERT IGNORE INTO workflows (`id`,`name`,`payload`,`version`,`revision`,`status`) VALUES ('welcome-workflow','平台验收 · 脚本与审批','{"version":1,"updatedAt":"2026-10-15T00:00:00Z","id":"welcome-workflow","name":"平台验收 · 脚本与审批","revision":1,"status":"published","projectId":"welcome","description":"无需模型密钥。真实运行脚本、查看产物,在人工审批后继续执行。","sandboxProfileId":"local","nodes":[{"id":"prepare","name":"生成验收报告","type":"script","scriptLanguage":"shell","executionScope":"run","script":"mkdir -p reports\\nprintf ''# LoopForge 本地验收\\\\n\\\\n已验证:真实脚本节点、持久化产物、人工审批与恢复。\\\\n'' > reports/welcome.md","maxAttempts":1,"position":{"x":100,"y":150},"artifactOutputs":[{"name":"welcome","path":"reports/welcome.md","mediaType":"text/markdown","required":true}]},{"id":"approve","name":"请确认验收报告","type":"approval","maxAttempts":1,"rejectTo":"prepare","position":{"x":370,"y":150}},{"id":"finish","name":"完成验收","type":"script","scriptLanguage":"shell","executionScope":"run","script":"printf ''# 验收完成\\\\n\\\\n审批已通过,执行成功恢复。\\\\n'' > completed.md","artifactOutputs":[{"name":"completed","path":"completed.md","mediaType":"text/markdown","required":true}],"maxAttempts":1,"position":{"x":640,"y":150}}],"edges":[{"id":"e-1","source":"prepare","target":"approve","when":"success"},{"id":"e-2","source":"approve","target":"finish","when":"success"}]}',1,1,'published');INSERT IGNORE INTO agents (id,name,payload,updated_at) VALUES ('baseline-align-resolver','基线对齐执行员','{"id": "baseline-align-resolver", "name": "基线对齐执行员", "version": 1, "shared": true, "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "只做基线对齐:fetch 默认分支并 merge 到当前工作分支;解决冲突时保留双方有效实现,拿不准时记录取舍。创建本地合并提交。不要自行 push 或修改默认分支,不要执行与本次基线对齐无关的测试或编写修复报告。"}',UTC_TIMESTAMP());diff --git a/web/agent_gates_test.go b/web/agent_gates_test.gonew file mode 100644index 00000000..9294659a--- /dev/null+++ b/web/agent_gates_test.go@@ -0,0 +1,16 @@+package web++import (+ "os/exec"+ "testing"+)++func TestAgentGatesKeepMRGatesOnSave(t *testing.T) {+ node, err := exec.LookPath("node")+ if err != nil {+ t.Skip("node not installed")+ }+ if out, err := exec.Command(node, "agent_gates_test.js", appBundlePath(t)).CombinedOutput(); err != nil {+ t.Fatalf("agent gates: %v\n%s", err, out)+ }+}diff --git a/web/agent_gates_test.js b/web/agent_gates_test.jsnew file mode 100644index 00000000..f4891a60--- /dev/null+++ b/web/agent_gates_test.js@@ -0,0 +1,26 @@+const fs = require('node:fs');+const vm = require('node:vm');+const assert = require('node:assert/strict');+const bundle = fs.readFileSync(process.argv[2], 'utf8');+function source(name) {+ const match = new RegExp('^(?:async )?function ' + name + '\\(', 'm').exec(bundle);+ assert(match, name);+ const tail = bundle.slice(match.index);+ const next = /\n(?:async )?function |\n(?:let|const) [A-Za-z]|\n\/\/ /.exec(tail);+ return next ? tail.slice(0, next.index) : tail;+}+const context = {};+vm.createContext(context);+vm.runInContext(source('agentGatesForSave'), context);+const saved = JSON.parse(JSON.stringify(context.agentGatesForSave([+ {id: 'mr-pushed', name: '改动已提交并推送', mode: 'command', commands: [' git status ', ''], onFailure: 'loop', executionScope: 'run'},+ {id: 'mr-opened', name: 'MR 已创建', mode: 'mr', onFailure: 'human', executionScope: 'repositories', commands: ['ignored']},+ {id: 'empty', name: '', mode: 'command', commands: [''], onFailure: 'loop'},+ {name: 'legacy', commands: ['test -f a.md'], onFailure: 'bogus', executionScope: 'repositories'},+])));+assert.deepEqual(saved, [+ {id: 'mr-pushed', name: '改动已提交并推送', stage: 'after_execution', required: true, onFailure: 'loop', mode: 'command', commands: ['git status'], executionScope: 'run'},+ {id: 'mr-opened', name: 'MR 已创建', stage: 'after_execution', required: true, onFailure: 'human', mode: 'mr'},+ {id: 'gate-4', name: 'legacy', stage: 'after_execution', required: true, onFailure: 'loop', mode: 'command', commands: ['test -f a.md'], executionScope: 'repositories'},+]);+assert.deepEqual(JSON.parse(JSON.stringify(context.agentGatesForSave(undefined))), []);diff --git a/web/app/agents.js b/web/app/agents.jsindex 99a61bc9..b8db2ed0 100644--- a/web/app/agents.js+++ b/web/app/agents.js@@ -408,7 +408,10 @@ async function persistAgent(f){state.agentSaving=true;try{return await persistAgentRequest(f,creating)}finally{state.agentSaving=false}}-async function persistAgentRequest(f,creating){const existing=state.data.agents.find(a=>a.id===f.elements.id.value);if(!catalogGeneric(state.workflow)&&existing&&catalogForeign(existing.projectId))return toast('这是其他项目的共享角色,请先复制到本项目再改');const checked=name=>[...f.querySelectorAll(`input[name="${name}"]:checked`)].map(x=>x.value);const draft=readAgentDraft(f);const artifacts=draft.artifactOutputs.map((x,i)=>({name:x.name||`artifact-${i+1}`,path:x.path||'result.md',mediaType:x.path?.endsWith('.json')?'application/json':(x.mediaType||'text/markdown'),required:!!x.required})),verification=draft.verification.map((gate,i)=>({id:gate.id||`gate-${i+1}`,name:gate.name||`门禁 ${i+1}`,mode:'command',stage:'after_execution',commands:(gate.commands||[]).map(c=>String(c||'').trim()).filter(Boolean),required:true,onFailure:['loop','reject','fail','human'].includes(gate.onFailure)?gate.onFailure:'loop',executionScope:gate.executionScope==='repositories'?'repositories':'run'})).filter(g=>g.commands.length),hooks=(draft.hooks||[]).map((h,i)=>({id:String(h.id||`hook-${i+1}`).trim(),name:String(h.name||`Hook ${i+1}`).trim(),event:h.event||'PreToolUse',matcher:String(h.matcher||'').trim(),language:h.language==='python'?'python':'shell',script:String(h.script||'').trim(),timeoutSec:Number(h.timeoutSec)||10,executionScope:h.executionScope==='repositories'?'repositories':'run'})).filter(h=>h.script),interventions=[];if(f.elements.interventionAfter?.checked)interventions.push({id:'human-review',name:'人工结果复核',stage:'after_execution',required:true});if(f.elements.interventionPublish?.checked)interventions.push({id:'publish-approval',name:'产物发布确认',stage:'before_publish',required:true});const a={id:f.elements.id.value.trim(),name:f.elements.name.value.trim(),version:(existing?.version||0)+1,projectId:existing?(existing.projectId||state.projectFilter||''):(state.projectFilter||''),shared:!!f.elements.shared?.checked,description:f.elements.description.value,prompt:draft.prompt,executorId:f.elements.executorId?.value||'',model:agentEffectiveModel(f),effort:f.elements.effort?.value||'',rules:checked('rules'),skills:checked('skills'),mcpServers:checked('mcpServers'),platformMcp:!!f.elements.platformMcp?.checked,knowledgeBase:!!f.elements.knowledgeBase?.checked,hooks,loop:{enabled:!!f.elements.loopEnabled?.checked,maxIterations:Number(f.elements.loopMaxIterations?.value)||1,exitCondition:'all_gates_pass',onExhausted:f.elements.loopOnExhausted?.value||'fail',feedbackPrompt:f.elements.loopFeedbackPrompt?.value||''},interventions,artifactOutputs:artifacts,verification};if(!a.id||!a.name)return toast('标识和名称不能为空');if(catalogGeneric(state.workflow)){if(!isPlatformAdmin())return toast('只有平台管理员可以编辑通用模板角色');const bundled=workflowAgent(a.id);if(!bundled)return toast('该角色不属于当前通用模板');a.projectId='';a.shared=false;a.rules=bundled.rules||[];a.skills=bundled.skills||[];a.mcpServers=f.querySelectorAll('input[name="mcpServers"]').length?checked('mcpServers'):(bundled.mcpServers||[]);a.hooks=Array.isArray(bundled.hooks)?bundled.hooks:a.hooks;a.version=bundled.version||0;try{const saved=await api(`/api/workflows/${encodeURIComponent(state.workflow.id)}/agents`,{method:'PUT',body:JSON.stringify(a)});const list=state.genericTemplateAgents||[];const gi=list.findIndex(x=>x.id===saved.id);if(gi>=0)list[gi]=saved;else list.push(saved);state.genericTemplateAgents=list;state.selectedAgent=saved.id;state.agentDraft=null;$('#agentModal').classList.remove('open');renderCanvas();renderProperties();toast('通用模板角色已保存,所有项目下次运行生效');}catch(err){toast(err.message)}return;}try{await api('/api/agents',{method:'PUT',body:JSON.stringify(a)});const i=state.data.agents.findIndex(x=>x.id===a.id);if(i>=0)state.data.agents[i]=a;else state.data.agents.push(a);if(a.shared){(state.data.rules||[]).forEach(item=>{if(a.rules.includes(item.id)&&item.projectId===a.projectId)item.shared=true});(state.data.skills||[]).forEach(item=>{if(a.skills.includes(item.id)&&item.projectId===a.projectId)item.shared=true})}state.selectedAgent=a.id;state.agentDraft=null;if(creating){state.agentScope='project';renderAgents();renderCanvas();toast('Agent 新版本已保存');showCreatedAgent(a);return a}$('#agentModal').classList.remove('open');renderAgents();renderCanvas();toast('Agent 新版本已保存');return a}catch(err){toast(err.message)}return null}+// MR gates are checked by the platform and carry no commands; every other+// gate is saved as a command gate and dropped while it has no command.+function agentGatesForSave(gates){return (gates||[]).map((gate,i)=>{const base={id:gate.id||`gate-${i+1}`,name:gate.name||`门禁 ${i+1}`,stage:'after_execution',required:true,onFailure:['loop','reject','fail','human'].includes(gate.onFailure)?gate.onFailure:'loop'};return gate.mode==='mr'?{...base,mode:'mr'}:{...base,mode:'command',commands:(gate.commands||[]).map(c=>String(c||'').trim()).filter(Boolean),executionScope:gate.executionScope==='repositories'?'repositories':'run'}}).filter(g=>g.mode==='mr'||g.commands.length)}+async function persistAgentRequest(f,creating){const existing=state.data.agents.find(a=>a.id===f.elements.id.value);if(!catalogGeneric(state.workflow)&&existing&&catalogForeign(existing.projectId))return toast('这是其他项目的共享角色,请先复制到本项目再改');const checked=name=>[...f.querySelectorAll(`input[name="${name}"]:checked`)].map(x=>x.value);const draft=readAgentDraft(f);const artifacts=draft.artifactOutputs.map((x,i)=>({name:x.name||`artifact-${i+1}`,path:x.path||'result.md',mediaType:x.path?.endsWith('.json')?'application/json':(x.mediaType||'text/markdown'),required:!!x.required})),verification=agentGatesForSave(draft.verification),hooks=(draft.hooks||[]).map((h,i)=>({id:String(h.id||`hook-${i+1}`).trim(),name:String(h.name||`Hook ${i+1}`).trim(),event:h.event||'PreToolUse',matcher:String(h.matcher||'').trim(),language:h.language==='python'?'python':'shell',script:String(h.script||'').trim(),timeoutSec:Number(h.timeoutSec)||10,executionScope:h.executionScope==='repositories'?'repositories':'run'})).filter(h=>h.script),interventions=[];if(f.elements.interventionAfter?.checked)interventions.push({id:'human-review',name:'人工结果复核',stage:'after_execution',required:true});if(f.elements.interventionPublish?.checked)interventions.push({id:'publish-approval',name:'产物发布确认',stage:'before_publish',required:true});const a={id:f.elements.id.value.trim(),name:f.elements.name.value.trim(),version:(existing?.version||0)+1,projectId:existing?(existing.projectId||state.projectFilter||''):(state.projectFilter||''),shared:!!f.elements.shared?.checked,description:f.elements.description.value,prompt:draft.prompt,executorId:f.elements.executorId?.value||'',model:agentEffectiveModel(f),effort:f.elements.effort?.value||'',rules:checked('rules'),skills:checked('skills'),mcpServers:checked('mcpServers'),platformMcp:!!f.elements.platformMcp?.checked,knowledgeBase:!!f.elements.knowledgeBase?.checked,hooks,loop:{enabled:!!f.elements.loopEnabled?.checked,maxIterations:Number(f.elements.loopMaxIterations?.value)||1,exitCondition:'all_gates_pass',onExhausted:f.elements.loopOnExhausted?.value||'fail',feedbackPrompt:f.elements.loopFeedbackPrompt?.value||''},interventions,artifactOutputs:artifacts,verification};if(!a.id||!a.name)return toast('标识和名称不能为空');if(catalogGeneric(state.workflow)){if(!isPlatformAdmin())return toast('只有平台管理员可以编辑通用模板角色');const bundled=workflowAgent(a.id);if(!bundled)return toast('该角色不属于当前通用模板');a.projectId='';a.shared=false;a.rules=bundled.rules||[];a.skills=bundled.skills||[];a.mcpServers=f.querySelectorAll('input[name="mcpServers"]').length?checked('mcpServers'):(bundled.mcpServers||[]);a.hooks=Array.isArray(bundled.hooks)?bundled.hooks:a.hooks;a.version=bundled.version||0;try{const saved=await api(`/api/workflows/${encodeURIComponent(state.workflow.id)}/agents`,{method:'PUT',body:JSON.stringify(a)});const list=state.genericTemplateAgents||[];const gi=list.findIndex(x=>x.id===saved.id);if(gi>=0)list[gi]=saved;else list.push(saved);state.genericTemplateAgents=list;state.selectedAgent=saved.id;state.agentDraft=null;$('#agentModal').classList.remove('open');renderCanvas();renderProperties();toast('通用模板角色已保存,所有项目下次运行生效');}catch(err){toast(err.message)}return;}try{await api('/api/agents',{method:'PUT',body:JSON.stringify(a)});const i=state.data.agents.findIndex(x=>x.id===a.id);if(i>=0)state.data.agents[i]=a;else state.data.agents.push(a);if(a.shared){(state.data.rules||[]).forEach(item=>{if(a.rules.includes(item.id)&&item.projectId===a.projectId)item.shared=true});(state.data.skills||[]).forEach(item=>{if(a.skills.includes(item.id)&&item.projectId===a.projectId)item.shared=true})}state.selectedAgent=a.id;state.agentDraft=null;if(creating){state.agentScope='project';renderAgents();renderCanvas();toast('Agent 新版本已保存');showCreatedAgent(a);return a}$('#agentModal').classList.remove('open');renderAgents();renderCanvas();toast('Agent 新版本已保存');return a}catch(err){toast(err.message)}return null}async function deleteAgent(id){const a=(state.data.agents||[]).find(x=>x.id===id);if(!a)return toast('角色不存在或已删除');diff --git a/web/app/flows.js b/web/app/flows.jsindex 16d6a1d4..a52efd57 100644--- a/web/app/flows.js+++ b/web/app/flows.js@@ -792,8 +792,10 @@ function renderAgentArtifactEditors(d){host.querySelectorAll('[data-remove-artifact]').forEach(el=>el.onclick=()=>{d.artifactOutputs.splice(Number(el.dataset.removeArtifact),1);renderAgentGovernance(d);touch();dirty()});host.querySelector('#agentAddArtifact')?.addEventListener('click',()=>{d.artifactOutputs.push({name:'',path:'',mediaType:'text/markdown',required:true});renderAgentGovernance(d);touch();dirty()});}-function gateFailureSelect(g){+function gateFailureSelect(g,noScope){const v=['loop','reject','fail','human'].includes(g.onFailure)?g.onFailure:'loop',scope=g.executionScope==='repositories'?'repositories':'run';+ const failure=`<label>失败后怎么走</label><select data-gk="onFailure"><option value="loop" ${v==='loop'?'selected':''}>本节点自修正</option><option value="reject" ${v==='reject'?'selected':''}>打回上游</option><option value="fail" ${v==='fail'?'selected':''}>本节点失败</option><option value="human" ${v==='human'?'selected':''}>转人工确认</option></select>`;+ if(noScope)return failure;return `<label>检查范围</label><select data-gk="executionScope"><option value="run" ${scope==='run'?'selected':''}>Run工作区(校验产物等场景)</option><option value="repositories" ${scope==='repositories'?'selected':''}>每个代码仓库</option></select><label>失败后怎么走</label><select data-gk="onFailure"><option value="loop" ${v==='loop'?'selected':''}>本节点自修正</option><option value="reject" ${v==='reject'?'selected':''}>打回上游</option><option value="fail" ${v==='fail'?'selected':''}>本节点失败</option><option value="human" ${v==='human'?'selected':''}>转人工确认</option></select><p class="prop-hint">范围必须显式选择。Run 工作区适合报告和产物;每个代码仓库适合测试和 Git 检查。保存后按所选范围执行,不会再根据命令是否以 git 开头自动切换目录。</p>`;}function applyGateField(gate,el){@@ -806,6 +808,7 @@ function renderAgentGateEditors(d){const host=$('#agentGatePanel');if(!host)return;const gates=d.verification||[];host.innerHTML=gates.length?gates.map((g,i)=>{+ if(g.mode==='mr')return `<article class="as-gate" data-gate-row="${i}"><div class="as-gate-head"><span class="as-file-icon">⌘</span><input data-gk="name" value="${escapeHTML(g.name||'')}" placeholder="例如:MR 已创建"><button type="button" data-remove-gate="${i}" title="删除">×</button></div><p class="prop-hint">由平台到代码托管平台核验,无需编写命令:本轮推送了新提交的每个仓库,都必须有从本轮工作分支到目标分支、且未关闭的 MR/PR。无法自动查询的平台会转人工确认。</p>${gateFailureSelect(g,true)}</article>`;const cmds=(g.commands||[]).filter(Boolean);const countText=cmds.length?`已配置 ${cmds.length} 条验收命令`:'未配置 (点击编写)';const preview=cmds.length?`<div class="script-snippet-preview" data-editor-agent-gate="${i}" title="点击在代码编辑器中修改"><code>${escapeHTML(cmds.join(' && '))}</code></div>`:'';