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
fix(schedule): make unattended AI loops reliable (#546)
Robert06222441f232e8ad
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex af025a19..81ae2442 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -1631,7 +1631,7 @@ paths:tags: [Assets]operationId: upsertRulerequestBody:- $ref: "#/components/requestBodies/Asset"+ $ref: "#/components/requestBodies/RuleAsset"responses:"200":$ref: "#/components/responses/Ok"@@ -1669,7 +1669,7 @@ paths:tags: [Assets]operationId: upsertSkillrequestBody:- $ref: "#/components/requestBodies/Asset"+ $ref: "#/components/requestBodies/SkillAsset"responses:"200":$ref: "#/components/responses/Ok"@@ -1873,7 +1873,7 @@ paths:tags: [Assets]operationId: upsertMcpServerrequestBody:- $ref: "#/components/requestBodies/Asset"+ $ref: "#/components/requestBodies/MCPServerAsset"responses:"200":$ref: "#/components/responses/Ok"@@ -1996,7 +1996,7 @@ paths:tags: [Assets]operationId: upsertDockerfilerequestBody:- $ref: "#/components/requestBodies/Asset"+ $ref: "#/components/requestBodies/DockerfileAsset"responses:"200":$ref: "#/components/responses/Ok"@@ -2034,7 +2034,7 @@ paths:tags: [Assets]operationId: upsertEnvironmentrequestBody:- $ref: "#/components/requestBodies/Asset"+ $ref: "#/components/requestBodies/EnvironmentAsset"responses:"200":$ref: "#/components/responses/Ok"@@ -2072,7 +2072,7 @@ paths:tags: [Assets]operationId: upsertSandboxProfilerequestBody:- $ref: "#/components/requestBodies/Asset"+ $ref: "#/components/requestBodies/SandboxProfile"responses:"200":$ref: "#/components/responses/Ok"@@ -3639,12 +3639,42 @@ components:application/json:schema:$ref: "#/components/schemas/AgentDefinition"- Asset:+ RuleAsset:required: truecontent:application/json:schema:- $ref: "#/components/schemas/OpenObject"+ $ref: "#/components/schemas/RuleAsset"+ SkillAsset:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/SkillAsset"+ MCPServerAsset:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/MCPServerAsset"+ DockerfileAsset:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/DockerfileAsset"+ EnvironmentAsset:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/EnvironmentAsset"+ SandboxProfile:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/SandboxProfile"Workflow:required: truecontent:@@ -3841,6 +3871,96 @@ components:OpenObject:type: objectadditionalProperties: true+ RuleAsset:+ type: object+ required: [id, name, content]+ additionalProperties: true+ properties:+ id: {type: string}+ name: {type: string}+ projectId: {type: string, description: Owning project}+ shared: {type: boolean, description: Visible to every project}+ description: {type: string}+ content: {type: string, description: Rule text injected into bound roles}+ priority: {type: integer}+ global: {type: boolean, description: Apply to every node of the workflows in workflowIds}+ workflowIds: {type: array, items: {type: string}}+ SkillAsset:+ type: object+ required: [id, name, content]+ additionalProperties: true+ properties:+ id: {type: string}+ name: {type: string}+ projectId: {type: string}+ shared: {type: boolean}+ description: {type: string}+ content: {type: string, description: SKILL.md body}+ files: {type: object, additionalProperties: {type: string}, description: Extra text files keyed by relative path}+ MCPServerAsset:+ type: object+ required: [id, name, transport]+ additionalProperties: true+ properties:+ id: {type: string}+ name: {type: string}+ projectId: {type: string}+ scope: {type: string, enum: [project, personal]}+ description: {type: string}+ transport: {type: string, enum: [stdio, http]}+ command: {type: string, description: stdio executable}+ args: {type: array, items: {type: string}}+ url: {type: string, description: http endpoint}+ environment: {type: object, additionalProperties: {type: string}}+ headers: {type: object, additionalProperties: {type: string}}+ installScript: {type: string}+ workingDirectory: {type: string}+ pathEntries: {type: array, items: {type: string}}+ authType: {type: string, enum: ["", github-token]}+ timeoutSec: {type: integer}+ DockerfileAsset:+ type: object+ required: [id, name, projectId, content]+ additionalProperties: true+ properties:+ id: {type: string}+ name: {type: string}+ projectId: {type: string}+ shared: {type: boolean}+ description: {type: string}+ content: {type: string, description: Dockerfile text}+ files: {type: object, additionalProperties: {type: string}, description: Build-context files keyed by relative path}+ EnvironmentAsset:+ type: object+ required: [id, name, projectId]+ additionalProperties: true+ properties:+ id: {type: string}+ name: {type: string}+ projectId: {type: string}+ shared: {type: boolean}+ description: {type: string}+ variables: {type: object, additionalProperties: {type: string}}+ pathEntries: {type: array, items: {type: string}}+ installScript: {type: string, description: Runs once with PREFIX set to the isolated environment root}+ SandboxProfile:+ type: object+ required: [id, name, projectId, driver]+ additionalProperties: true+ description: >-+ Execution environment for SOP runs and conversation workspaces. Conversation workspaces+ need driver=docker with an existing dockerfileId; the built-in shared generic-docker+ profile already satisfies this, so create a new profile only for a different toolchain.+ properties:+ id: {type: string}+ name: {type: string}+ projectId: {type: string, description: Owning project (required)}+ shared: {type: boolean, description: Visible to every project}+ driver: {type: string, enum: [local, native, docker]}+ dockerfileId: {type: string, description: Required for driver=docker; see dockerfiles_list}+ environmentId: {type: string, description: Toolchain for native/local drivers; see environments_list}+ readOnlyRootFS: {type: boolean}+ environment: {type: object, additionalProperties: {type: string}}APIToken:type: objectrequired: [id, userId, name, prefix, createdAt]diff --git a/internal/httpapi/agent_tool_github.go b/internal/httpapi/agent_tool_github.goindex b67eb35f..9aad5cac 100644--- a/internal/httpapi/agent_tool_github.go+++ b/internal/httpapi/agent_tool_github.go@@ -15,7 +15,8 @@ import ("agentflow/internal/gitwork")-// Main Bot 的轻量 GitHub 工具:列 Issue/PR、查 PR 状态、加评论、加标签。+// Main Bot 的轻量 GitHub 工具:列 Issue/PR、查 PR 状态与改动、加评论、加标签,+// 以及审查、合并 PR 和关闭 Issue。//// 设计目标是不要求先 workbench_workspace_open 打开工作区(那条路径是为// "真的要改代码、推分支、开 PR" 准备的重路径),同时仍然复用@@ -28,14 +29,21 @@ import (// 「帮我批准」(ExecMode.ReviewWrites)时,评论、加标签这两个写操作在调用// GitHub 之前先交给独立审查器逐项审查——它们对外公开可见,而列表工具会把// 不可信的 Issue/PR 标题带进上下文,正是最需要审查器把关的地方。-// 操作范围限定在当前项目已绑定的 GitHub 仓库,写操作只开放评论和加标签,-// 不提供关闭、合并、删除。+// 操作范围限定在当前项目已绑定的 GitHub 仓库。审查、合并、关闭 Issue 只在+// 会话允许直接写入时执行(见 githubWriteAllowed),不提供删除。const (- mainBotGitHubIssuesList = "workbench_github_issues_list"- mainBotGitHubPullsList = "workbench_github_pulls_list"- mainBotGitHubPRStatus = "workbench_github_pr_status"- mainBotGitHubCommentAdd = "workbench_github_comment_add"- mainBotGitHubLabelsAdd = "workbench_github_labels_add"+ mainBotGitHubIssuesList = "workbench_github_issues_list"+ mainBotGitHubIssueGet = "workbench_github_issue_get"+ mainBotGitHubPullsList = "workbench_github_pulls_list"+ mainBotGitHubPRStatus = "workbench_github_pr_status"+ mainBotGitHubPRFiles = "workbench_github_pr_files"+ mainBotGitHubCommentAdd = "workbench_github_comment_add"+ mainBotGitHubLabelsAdd = "workbench_github_labels_add"+ mainBotGitHubPRReview = "workbench_github_pr_review"+ mainBotGitHubPRMerge = "workbench_github_pr_merge"+ mainBotGitHubIssueClose = "workbench_github_issue_close"+ mainBotGitHubIssueCreate = "workbench_github_issue_create"+ mainBotGitHubPRClose = "workbench_github_pr_close")const (@@ -44,6 +52,8 @@ const (// githubIssuesMaxPages 限制 issues_list 为凑够 limit 最多翻的页数:// /issues 端点混有 PR,PR 多的仓库要往后翻才能凑够纯 Issue。githubIssuesMaxPages = 5+ // githubIssueListBodyRunes 是 issues_list 里每条正文摘要的长度。+ githubIssueListBodyRunes = 300)// mainBotGitHubTools 只在普通 Main Bot 会话(AgentToolAssistant)且已知项目时@@ -57,22 +67,34 @@ func mainBotGitHubTools(s *AgentToolSession) []agentToolDescriptor {return []agentToolDescriptor{{Name: mainBotGitHubIssuesList,- Description: "列出项目绑定的 GitHub 仓库里的 Issue(不包含 PR)。只读,不需要打开工作区,用请求人自己的 Git Token 直连 GitHub。结果里 hasMore=true 表示还有符合条件但没列出的 Issue,不能把本次结果当成完整列表。",+ Description: "列出项目绑定的 GitHub 仓库里的 Issue(不包含 PR)。只读,不需要打开工作区,用请求人自己的 Git Token 直连 GitHub。body 只是正文开头,要按 Issue 干活先用 workbench_github_issue_get 读完整正文和评论。结果里 hasMore=true 表示还有符合条件但没列出的 Issue,不能把本次结果当成完整列表。",InputSchema: json.RawMessage(`{"type":"object","properties":{` + repoProp + `,"state":{"type":"string","enum":["open","closed","all"],"description":"默认 open"},"labels":{"type":"string","description":"按标签过滤,逗号分隔的标签名"},"limit":{"type":"integer","minimum":1,"maximum":50,"description":"默认 20"}},"required":["repository"],"additionalProperties":false}`),Kind: "github",},+ {+ Name: mainBotGitHubIssueGet,+ Description: "读取一个 Issue 的完整正文和最近的评论(最多 30 条,按时间先后)。只读,不需要打开工作区。按 Issue 修改代码或判断是否已处理前先读它:需求细节和验收要求通常写在正文和评论里,而不是标题。",+ InputSchema: json.RawMessage(`{"type":"object","properties":{` + repoProp + `,` + numberProp + `},"required":["repository","number"],"additionalProperties":false}`),+ Kind: "github",+ },{Name: mainBotGitHubPullsList,- Description: "列出项目绑定的 GitHub 仓库里的 Pull Request。只读,不需要打开工作区,用请求人自己的 Git Token 直连 GitHub。结果里 hasMore=true 表示还有没列出的 PR。",- InputSchema: json.RawMessage(`{"type":"object","properties":{` + repoProp + `,"state":{"type":"string","enum":["open","closed","all"],"description":"默认 open"},"limit":{"type":"integer","minimum":1,"maximum":50,"description":"默认 20"}},"required":["repository"],"additionalProperties":false}`),+ Description: "列出项目绑定的 GitHub 仓库里的 Pull Request。只读,不需要打开工作区,用请求人自己的 Git Token 直连 GitHub。结果里 hasMore=true 表示还有没列出的 PR。改动行数、审查状态用 workbench_github_pr_status 查。",+ InputSchema: json.RawMessage(`{"type":"object","properties":{` + repoProp + `,"state":{"type":"string","enum":["open","closed","all"],"description":"默认 open"},"author":{"type":"string","description":"只列这个 GitHub 用户(login,忽略大小写)提交的 PR"},"limit":{"type":"integer","minimum":1,"maximum":50,"description":"默认 20"}},"required":["repository"],"additionalProperties":false}`),Kind: "github",},{Name: mainBotGitHubPRStatus,- Description: "查看一个 Pull Request 的详情(状态、是否可合并)和检查结果(CI checks / commit status)。只读,不需要打开工作区。checksState 为 unknown 时表示部分检查结果读取失败,原因见 checksWarnings。",+ Description: "查看一个 Pull Request 的详情:作者、描述、改动规模(additions/deletions/changedFiles)、是否可合并(mergeable/mergeableState)、head sha、每位审查人的最新结论(reviews/approvals)和检查结果(CI checks / commit status)。只读,不需要打开工作区。checksState 为 unknown 时表示部分检查结果读取失败,原因见 checksWarnings。",InputSchema: json.RawMessage(`{"type":"object","properties":{` + repoProp + `,` + numberProp + `},"required":["repository","number"],"additionalProperties":false}`),Kind: "github",},+ {+ Name: mainBotGitHubPRFiles,+ Description: "列出一个 Pull Request 改动的文件及每个文件的 diff(patch,过长会截断),用于审查代码。只读,不需要打开工作区。",+ InputSchema: json.RawMessage(`{"type":"object","properties":{` + repoProp + `,` + numberProp + `,"limit":{"type":"integer","minimum":1,"maximum":100,"description":"最多返回的文件数,默认 50"}},"required":["repository","number"],"additionalProperties":false}`),+ Kind: "github",+ },{Name: mainBotGitHubCommentAdd,Description: "给一个 Issue 或 PR 加评论,对外公开可见。用请求人自己的 Git Token 直接提交,不经过草稿确认(「帮我批准」模式下会先经自动审批);调用前请把内容和目标 number 向用户确认清楚。",@@ -85,6 +107,36 @@ func mainBotGitHubTools(s *AgentToolSession) []agentToolDescriptor {InputSchema: json.RawMessage(`{"type":"object","properties":{` + repoProp + `,` + numberProp + `,"labels":{"type":"array","items":{"type":"string"},"minItems":1,"maxItems":20}},"required":["repository","number","labels"],"additionalProperties":false}`),Kind: "github",},+ {+ Name: mainBotGitHubPRReview,+ Description: "对一个 Pull Request 提交审查:APPROVE 批准、REQUEST_CHANGES 要求修改、COMMENT 只留审查意见。用请求人自己的 Git Token 提交,对外公开可见。GitHub 不允许作者批准自己的 PR。需要「完全权限」或「帮我批准」模式。",+ InputSchema: json.RawMessage(`{"type":"object","properties":{` + repoProp + `,` + numberProp + `,"event":{"type":"string","enum":["APPROVE","REQUEST_CHANGES","COMMENT"]},"body":{"type":"string","maxLength":10000,"description":"审查意见;REQUEST_CHANGES 和 COMMENT 必填"}},"required":["repository","number","event"],"additionalProperties":false}`),+ Kind: "github",+ },+ {+ Name: mainBotGitHubPRMerge,+ Description: "合并一个 Pull Request。合并前先用 workbench_github_pr_status 确认状态、检查和审查结论,并把读到的 head sha 传入 sha,防止合并后来又被推送的改动。用请求人自己的 Git Token 执行,合并后只能在 GitHub 上手动回滚。需要「完全权限」或「帮我批准」模式。",+ InputSchema: json.RawMessage(`{"type":"object","properties":{` + repoProp + `,` + numberProp + `,"method":{"type":"string","enum":["merge","squash","rebase"],"description":"默认 merge;仓库不允许时按报错换一种"},"sha":{"type":"string","description":"期望的 PR head sha;与实际不符时 GitHub 拒绝合并"},"commitTitle":{"type":"string","maxLength":250},"commitMessage":{"type":"string","maxLength":10000}},"required":["repository","number"],"additionalProperties":false}`),+ Kind: "github",+ },+ {+ Name: mainBotGitHubIssueClose,+ Description: "关闭一个 GitHub Issue(不能用来关闭 PR,关闭 PR 用 workbench_github_pr_close)。reason=completed 表示已解决,not_planned 表示不处理;可同时留一条说明评论(先评论再关闭)。已关闭的 Issue 直接返回 alreadyClosed。需要「完全权限」或「帮我批准」模式。",+ InputSchema: json.RawMessage(`{"type":"object","properties":{` + repoProp + `,` + numberProp + `,"reason":{"type":"string","enum":["completed","not_planned"],"description":"默认 completed"},"comment":{"type":"string","maxLength":10000,"description":"关闭前留下的说明,例如由哪个 PR 解决"}},"required":["repository","number"],"additionalProperties":false}`),+ Kind: "github",+ },+ {+ Name: mainBotGitHubIssueCreate,+ Description: "在项目绑定的 GitHub 仓库里新建一个 Issue,对外公开可见,建好后只能关闭不能删除。用请求人自己的 Git Token 直接提交(「帮我批准」模式下会先经自动审批)。labels 必须是仓库里已存在的标签。",+ InputSchema: json.RawMessage(`{"type":"object","properties":{` + repoProp + `,"title":{"type":"string","minLength":1,"maxLength":256},"body":{"type":"string","maxLength":20000,"description":"Markdown 正文:背景、要做什么、验收要求"},"labels":{"type":"array","items":{"type":"string"},"maxItems":20}},"required":["repository","title"],"additionalProperties":false}`),+ Kind: "github",+ },+ {+ Name: mainBotGitHubPRClose,+ Description: "关闭一个 Pull Request 但不合并(例如过时、重复或被拒绝的 PR);可同时留一条说明评论(先评论再关闭)。已合并的 PR 不能关闭,已关闭的直接返回 alreadyClosed。需要「完全权限」或「帮我批准」模式。",+ InputSchema: json.RawMessage(`{"type":"object","properties":{` + repoProp + `,` + numberProp + `,"comment":{"type":"string","maxLength":10000,"description":"关闭原因,会作为评论公开可见"}},"required":["repository","number"],"additionalProperties":false}`),+ Kind: "github",+ },}}@@ -113,16 +165,49 @@ func (h *agentToolGateway) callMainBotGitHub(ctx context.Context, session *Agentswitch name {case mainBotGitHubIssuesList:result, err = githubIssuesList(ctx, token, path, args)+ case mainBotGitHubIssueGet:+ result, err = githubIssueGet(ctx, token, path, args)case mainBotGitHubPullsList:result, err = githubPullsList(ctx, token, path, args)case mainBotGitHubPRStatus:result, err = githubPRStatus(ctx, token, path, args)+ case mainBotGitHubPRFiles:+ result, err = githubPRFiles(ctx, token, path, args)+ case mainBotGitHubPRReview, mainBotGitHubPRMerge, mainBotGitHubIssueClose, mainBotGitHubPRClose:+ if _, verr := githubArgNumber(args); verr != nil {+ return "", verr+ }+ if werr := githubWriteAllowed(session, name); werr != nil {+ return "", werr+ }+ if rerr := reviewGitHubWrite(ctx, session, name, path, args, githubWriteActions[name]); rerr != nil {+ return "", rerr+ }+ switch name {+ case mainBotGitHubPRReview:+ result, err = githubPRReview(ctx, token, path, args)+ case mainBotGitHubPRMerge:+ result, err = githubPRMerge(ctx, token, path, args)+ case mainBotGitHubPRClose:+ result, err = githubPRClose(ctx, token, path, args)+ default:+ result, err = githubIssueClose(ctx, token, path, args)+ }+ case mainBotGitHubIssueCreate:+ title, body, labels, verr := githubIssueCreateArgs(args)+ if verr != nil {+ return "", verr+ }+ if rerr := reviewGitHubWrite(ctx, session, name, path, args, githubWriteActions[name]); rerr != nil {+ return "", rerr+ }+ result, err = githubIssueCreate(ctx, token, path, title, body, labels)case mainBotGitHubCommentAdd:number, body, verr := githubCommentArgs(args)if verr != nil {return "", verr}- if rerr := reviewGitHubWrite(ctx, session, name, path, args); rerr != nil {+ if rerr := reviewGitHubWrite(ctx, session, name, path, args, githubWriteActions[name]); rerr != nil {return "", rerr}result, err = githubIssueCommentAdd(ctx, token, path, number, body)@@ -131,7 +216,7 @@ func (h *agentToolGateway) callMainBotGitHub(ctx context.Context, session *Agentif verr != nil {return "", verr}- if rerr := reviewGitHubWrite(ctx, session, name, path, args); rerr != nil {+ if rerr := reviewGitHubWrite(ctx, session, name, path, args, githubWriteActions[name]); rerr != nil {return "", rerr}result, err = githubIssueLabelsAdd(ctx, token, path, number, labels)@@ -147,12 +232,23 @@ func (h *agentToolGateway) callMainBotGitHub(ctx context.Context, session *Agent// reviewGitHubWrite 和 callMainBotWorkspace 对写操作的处理一致:会话开启// 「帮我批准」时,先把这一项具体操作交给独立审查器,未获批准不调用 GitHub。// 没有可用的审查器时 reviewAssistantAction 返回 unavailable,同样拒绝执行。-func reviewGitHubWrite(ctx context.Context, s *AgentToolSession, name, path string, args map[string]any) error {+// githubWriteActions describes each write for the independent reviewer.+var githubWriteActions = map[string]string{+ mainBotGitHubCommentAdd: "用请求人自己的 Git Token 向项目绑定的 GitHub 仓库写入评论,对外公开可见,执行后只能到 GitHub 上手动撤销",+ mainBotGitHubLabelsAdd: "用请求人自己的 Git Token 给项目绑定的 GitHub 仓库里的 Issue/PR 加标签,执行后只能到 GitHub 上手动撤销",+ mainBotGitHubPRReview: "用请求人自己的 Git Token 对项目绑定的 GitHub 仓库里的 PR 提交审查(批准/要求修改/评论),对外公开可见",+ mainBotGitHubPRMerge: "用请求人自己的 Git Token 合并项目绑定的 GitHub 仓库里的 PR,代码进入目标分支,执行后只能到 GitHub 上手动回滚",+ mainBotGitHubIssueClose: "用请求人自己的 Git Token 关闭项目绑定的 GitHub 仓库里的 Issue(可附说明评论),执行后需要到 GitHub 上手动重新打开",+ mainBotGitHubIssueCreate: "用请求人自己的 Git Token 在项目绑定的 GitHub 仓库里新建 Issue,对外公开可见,建好后只能关闭不能删除",+ mainBotGitHubPRClose: "用请求人自己的 Git Token 关闭(不合并)项目绑定的 GitHub 仓库里的 PR(可附说明评论),执行后需要到 GitHub 上手动重新打开",+}++func reviewGitHubWrite(ctx context.Context, s *AgentToolSession, name, path string, args map[string]any, action string) error {if !s.ExecMode.ReviewWrites {return nil}ctx = withAssistantApprovalReviewer(ctx, s.approvalReviewer)- review := reviewAssistantAction(ctx, name, "用请求人自己的 Git Token 向项目绑定的 GitHub 仓库写入评论或标签,对外公开可见,执行后只能到 GitHub 上手动撤销", map[string]any{"projectId": s.ProjectID, "repository": path, "arguments": args})+ review := reviewAssistantAction(ctx, name, action, map[string]any{"projectId": s.ProjectID, "repository": path, "arguments": args})if !review.allows() {return assistantReviewRefusal(name, review)}@@ -295,22 +391,7 @@ func githubHTTPClient() *http.Client {// githubToolError 按具体操作给出报错。githubPRError 是为提交 PR 写的,403// 一律提示 Pull requests 权限;这组工具各自需要的权限不同,单独说明。func githubToolError(action, permission string, status int, raw []byte) error {- var body struct {- Message string `json:"message"`- Errors []struct {- Message string `json:"message"`- } `json:"errors"`- }- _ = json.Unmarshal(raw, &body)- detail := strings.TrimSpace(body.Message)- for _, e := range body.Errors {- if e.Message != "" {- detail = strings.TrimSpace(detail + " " + e.Message)- }- }- if detail == "" {- detail = strings.TrimSpace(truncateRunes(string(raw), 300))- }+ detail := githubErrorDetail(raw)switch status {case http.StatusUnauthorized:return fmt.Errorf("GitHub Git Token 无效或已过期(HTTP 401):请到「个人配置 → 个人凭证」重新配置")@@ -329,6 +410,7 @@ type githubIssueOut struct {URL string `json:"url"`Author string `json:"author"`Labels []string `json:"labels,omitempty"`+ Body string `json:"body,omitempty"`Created string `json:"createdAt"`Updated string `json:"updatedAt"`}@@ -336,6 +418,7 @@ type githubIssueOut struct {type githubIssueItem struct {Number int64 `json:"number"`Title string `json:"title"`+ Body string `json:"body"`State string `json:"state"`HTMLURL string `json:"html_url"`User struct {@@ -392,7 +475,7 @@ func githubIssuesList(ctx context.Context, token, path string, args map[string]afor _, l := range it.Labels {labels = append(labels, l.Name)}- out = append(out, githubIssueOut{Number: it.Number, Title: it.Title, State: it.State, URL: it.HTMLURL, Author: it.User.Login, Labels: labels, Created: it.CreatedAt, Updated: it.UpdatedAt})+ out = append(out, githubIssueOut{Number: it.Number, Title: it.Title, State: it.State, URL: it.HTMLURL, Author: it.User.Login, Labels: labels, Body: truncateRunes(it.Body, githubIssueListBodyRunes), Created: it.CreatedAt, Updated: it.UpdatedAt})}if hasMore || len(items) < githubListPageSize {break@@ -419,50 +502,73 @@ type githubPullOut struct {Updated string `json:"updatedAt"`}-// githubPullsList 列 PR。/pulls 不需要事后过滤,多取一条即可判断 hasMore。+// githubPullsList 列 PR。不按作者过滤时多取一条即可判断 hasMore;按作者+// 过滤发生在取回之后(/pulls 不支持 author 参数),像 issues_list 一样按满页+// 翻页,最多 githubIssuesMaxPages 页。func githubPullsList(ctx context.Context, token, path string, args map[string]any) (string, error) {state, err := githubArgState(args)if err != nil {return "", err}limit := githubArgLimit(args)- q := url.Values{"state": {state}, "per_page": {strconv.Itoa(limit + 1)}}- client := githubHTTPClient()- resp, raw, err := githubRequest(ctx, client, http.MethodGet, githubAPIBase+"/repos/"+path+"/pulls?"+q.Encode(), token, nil)- if err != nil {- return "", fmt.Errorf("无法连接 GitHub:%v", err)- }- if resp.StatusCode != http.StatusOK {- return "", githubToolError("读取 PR 列表", "Pull requests 读取", resp.StatusCode, raw)+ author, _ := args["author"].(string)+ author = strings.TrimSpace(author)+ perPage, maxPages := limit+1, 1+ if author != "" {+ perPage, maxPages = githubListPageSize, githubIssuesMaxPages}- var items []struct {- Number int64 `json:"number"`- Title string `json:"title"`- State string `json:"state"`- Draft bool `json:"draft"`- HTMLURL string `json:"html_url"`- User struct {- Login string `json:"login"`- } `json:"user"`- Head struct {- Ref string `json:"ref"`- } `json:"head"`- Base struct {- Ref string `json:"ref"`- } `json:"base"`- CreatedAt string `json:"created_at"`- UpdatedAt string `json:"updated_at"`- }- if json.Unmarshal(raw, &items) != nil {- return "", fmt.Errorf("GitHub 返回的 PR 列表无法解析")- }- hasMore := len(items) > limit- if hasMore {- items = items[:limit]- }- out := make([]githubPullOut, 0, len(items))- for _, it := range items {- out = append(out, githubPullOut{Number: it.Number, Title: it.Title, State: it.State, Draft: it.Draft, URL: it.HTMLURL, Author: it.User.Login, Head: it.Head.Ref, Base: it.Base.Ref, Created: it.CreatedAt, Updated: it.UpdatedAt})+ q := url.Values{"state": {state}, "per_page": {strconv.Itoa(perPage)}}+ client := githubHTTPClient()+ out := make([]githubPullOut, 0, limit)+ hasMore := false+ for page := 1; page <= maxPages; page++ {+ if author != "" {+ q.Set("page", strconv.Itoa(page))+ }+ resp, raw, err := githubRequest(ctx, client, http.MethodGet, githubAPIBase+"/repos/"+path+"/pulls?"+q.Encode(), token, nil)+ if err != nil {+ return "", fmt.Errorf("无法连接 GitHub:%v", err)+ }+ if resp.StatusCode != http.StatusOK {+ return "", githubToolError("读取 PR 列表", "Pull requests 读取", resp.StatusCode, raw)+ }+ var items []struct {+ Number int64 `json:"number"`+ Title string `json:"title"`+ State string `json:"state"`+ Draft bool `json:"draft"`+ HTMLURL string `json:"html_url"`+ User struct {+ Login string `json:"login"`+ } `json:"user"`+ Head struct {+ Ref string `json:"ref"`+ } `json:"head"`+ Base struct {+ Ref string `json:"ref"`+ } `json:"base"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+ }+ if json.Unmarshal(raw, &items) != nil {+ return "", fmt.Errorf("GitHub 返回的 PR 列表无法解析")+ }+ for _, it := range items {+ if author != "" && !strings.EqualFold(it.User.Login, author) {+ continue+ }+ if len(out) == limit {+ hasMore = true+ break+ }+ out = append(out, githubPullOut{Number: it.Number, Title: it.Title, State: it.State, Draft: it.Draft, URL: it.HTMLURL, Author: it.User.Login, Head: it.Head.Ref, Base: it.Base.Ref, Created: it.CreatedAt, Updated: it.UpdatedAt})+ }+ if hasMore || len(items) < perPage {+ break+ }+ if page == maxPages && author != "" {+ hasMore = true+ }}body, _ := json.Marshal(map[string]any{"repository": path, "pulls": out, "count": len(out), "hasMore": hasMore})return string(body), nil@@ -597,40 +703,39 @@ func githubPRStatus(ctx context.Context, token, path string, args map[string]anyif resp.StatusCode != http.StatusOK {return "", githubToolError("读取 PR 详情", "Pull requests 读取", resp.StatusCode, raw)}- var pr struct {- Number int64 `json:"number"`- Title string `json:"title"`- State string `json:"state"`- Draft bool `json:"draft"`- Merged bool `json:"merged"`- MergeableState string `json:"mergeable_state"`- HTMLURL string `json:"html_url"`- Head struct {- SHA string `json:"sha"`- Ref string `json:"ref"`- } `json:"head"`- Base struct {- Ref string `json:"ref"`- } `json:"base"`- }+ var pr githubPRDetailif json.Unmarshal(raw, &pr) != nil || pr.Number == 0 {return "", fmt.Errorf("GitHub 返回的 PR 信息无法解析")}checks, checksState, warnings := githubCombinedChecks(ctx, client, token, path, pr.Head.SHA)+ reviews, approvals, reviewsWarning := githubLatestReviews(ctx, client, token, path, number)result := map[string]any{"repository": path,"number": pr.Number,"title": pr.Title,+ "author": pr.User.Login,+ "body": truncateRunes(pr.Body, githubPRBodyRunes),"state": pr.State,"draft": pr.Draft,"merged": pr.Merged,+ "mergeable": pr.Mergeable,"mergeableState": pr.MergeableState,"url": pr.HTMLURL,"head": pr.Head.Ref,+ "headSha": pr.Head.SHA,"base": pr.Base.Ref,+ "additions": pr.Additions,+ "deletions": pr.Deletions,+ "changedFiles": pr.ChangedFiles,+ "commits": pr.Commits,+ "reviews": reviews,+ "approvals": approvals,"checksState": checksState,"checks": checks,}+ if reviewsWarning != "" {+ result["reviewsWarning"] = reviewsWarning+ }if len(warnings) > 0 {result["checksWarnings"] = warnings}diff --git a/internal/httpapi/agent_tool_github_pr.go b/internal/httpapi/agent_tool_github_pr.gonew file mode 100644index 00000000..f38f3cf3--- /dev/null+++ b/internal/httpapi/agent_tool_github_pr.go@@ -0,0 +1,527 @@+package httpapi++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/url"+ "sort"+ "strconv"+ "strings"+)++// PR 审查与合并、Issue 关闭这组工具让定时 Loop 不打开工作区也能完成+// "列 PR → 看改动 → 审查 → 合并 → 关闭关联 Issue" 的闭环。它们和评论、+// 加标签共用同一套令牌与仓库范围校验;合并、审查、关闭对外不可轻易撤销,+// 因此只在会话允许直接写入(完全权限或帮我批准)时执行。+const (+ githubPRFilesMaxPages = 3+ githubPRFilePatchRunes = 3000+ githubPRFilesPatchBudget = 40000+ githubPRBodyRunes = 4000+ githubIssueBodyRunes = 20000+ githubIssueCommentRunes = 2000+ githubIssueMaxComments = 30+)++// githubWriteAllowed 拒绝在「请求批准」模式下执行合并、审查、关闭:这些+// 操作没有可供用户确认的草稿,执行后只能在 GitHub 上手动撤销。+func githubWriteAllowed(s *AgentToolSession, name string) error {+ if s.ExecMode.AutoWrite {+ return nil+ }+ return fmt.Errorf("%s 会直接修改 GitHub,当前「请求批准」模式没有可确认的草稿,不能执行。请让用户把审批模式切到「完全权限」或「帮我批准」后再试,或告诉用户在 GitHub 上手动完成", name)+}++func githubArgString(args map[string]any, key string) string {+ v, _ := args[key].(string)+ return strings.TrimSpace(v)+}++type githubPRDetail struct {+ Number int64 `json:"number"`+ Title string `json:"title"`+ Body string `json:"body"`+ State string `json:"state"`+ Draft bool `json:"draft"`+ Merged bool `json:"merged"`+ Mergeable *bool `json:"mergeable"`+ MergeableState string `json:"mergeable_state"`+ HTMLURL string `json:"html_url"`+ Additions int `json:"additions"`+ Deletions int `json:"deletions"`+ ChangedFiles int `json:"changed_files"`+ Commits int `json:"commits"`+ User struct {+ Login string `json:"login"`+ } `json:"user"`+ Head struct {+ SHA string `json:"sha"`+ Ref string `json:"ref"`+ } `json:"head"`+ Base struct {+ Ref string `json:"ref"`+ } `json:"base"`+}++type githubReviewSummary struct {+ Reviewer string `json:"reviewer"`+ State string `json:"state"`+}++// githubLatestReviews 取每位审查人最近一次有效结论(APPROVED /+// CHANGES_REQUESTED / DISMISSED);只留言的 COMMENTED 不覆盖之前的结论。+func githubLatestReviews(ctx context.Context, client *http.Client, token, path string, number int) ([]githubReviewSummary, int, string) {+ resp, raw, err := githubRequest(ctx, client, http.MethodGet, fmt.Sprintf("%s/repos/%s/pulls/%d/reviews?per_page=%d", githubAPIBase, path, number, githubListPageSize), token, nil)+ if err != nil {+ return nil, 0, fmt.Sprintf("审查记录读取失败:%v", err)+ }+ if resp.StatusCode != http.StatusOK {+ return nil, 0, fmt.Sprintf("审查记录读取失败(HTTP %d),审查状态未知", resp.StatusCode)+ }+ var items []struct {+ State string `json:"state"`+ User struct {+ Login string `json:"login"`+ } `json:"user"`+ }+ if json.Unmarshal(raw, &items) != nil {+ return nil, 0, "审查记录无法解析,审查状态未知"+ }+ latest := map[string]string{}+ for _, it := range items {+ login := strings.TrimSpace(it.User.Login)+ if login == "" {+ continue+ }+ switch it.State {+ case "APPROVED", "CHANGES_REQUESTED", "DISMISSED":+ latest[login] = it.State+ case "COMMENTED":+ if _, ok := latest[login]; !ok {+ latest[login] = it.State+ }+ }+ }+ out := make([]githubReviewSummary, 0, len(latest))+ approvals := 0+ for login, state := range latest {+ out = append(out, githubReviewSummary{Reviewer: login, State: state})+ if state == "APPROVED" {+ approvals+++ }+ }+ sort.Slice(out, func(i, j int) bool { return out[i].Reviewer < out[j].Reviewer })+ return out, approvals, ""+}++func githubPRFiles(ctx context.Context, token, path string, args map[string]any) (string, error) {+ number, err := githubArgNumber(args)+ if err != nil {+ return "", err+ }+ limit := githubArgInt(args, "limit", 50)+ if limit <= 0 || limit > githubListPageSize {+ limit = 50+ }+ type fileOut struct {+ Filename string `json:"filename"`+ Status string `json:"status"`+ Additions int `json:"additions"`+ Deletions int `json:"deletions"`+ Patch string `json:"patch,omitempty"`+ PatchOmitted bool `json:"patchOmitted,omitempty"`+ }+ client := githubHTTPClient()+ out := make([]fileOut, 0, limit)+ budget := githubPRFilesPatchBudget+ hasMore := false+ for page := 1; page <= githubPRFilesMaxPages && len(out) < limit; page++ {+ q := url.Values{"per_page": {strconv.Itoa(githubListPageSize)}, "page": {strconv.Itoa(page)}}+ resp, raw, err := githubRequest(ctx, client, http.MethodGet, fmt.Sprintf("%s/repos/%s/pulls/%d/files?%s", githubAPIBase, path, number, q.Encode()), token, nil)+ if err != nil {+ return "", fmt.Errorf("无法连接 GitHub:%v", err)+ }+ if resp.StatusCode != http.StatusOK {+ return "", githubToolError("读取 PR 改动文件", "Pull requests 读取", resp.StatusCode, raw)+ }+ var items []struct {+ Filename string `json:"filename"`+ Status string `json:"status"`+ Additions int `json:"additions"`+ Deletions int `json:"deletions"`+ Patch string `json:"patch"`+ }+ if json.Unmarshal(raw, &items) != nil {+ return "", fmt.Errorf("GitHub 返回的 PR 文件列表无法解析")+ }+ for _, it := range items {+ if len(out) == limit {+ hasMore = true+ break+ }+ f := fileOut{Filename: it.Filename, Status: it.Status, Additions: it.Additions, Deletions: it.Deletions}+ patch := it.Patch+ if len([]rune(patch)) > githubPRFilePatchRunes {+ patch = string([]rune(patch)[:githubPRFilePatchRunes]) + "\n…(该文件 diff 过长已截断)"+ }+ if n := len([]rune(patch)); n > 0 && n <= budget {+ f.Patch = patch+ budget -= n+ } else if n > 0 {+ f.PatchOmitted = true+ }+ out = append(out, f)+ }+ if hasMore || len(items) < githubListPageSize {+ break+ }+ if page == githubPRFilesMaxPages {+ hasMore = true+ }+ }+ body, _ := json.Marshal(map[string]any{"repository": path, "number": number, "files": out, "count": len(out), "hasMore": hasMore})+ return string(body), nil+}++func githubPRReview(ctx context.Context, token, path string, args map[string]any) (string, error) {+ number, err := githubArgNumber(args)+ if err != nil {+ return "", err+ }+ event := strings.ToUpper(githubArgString(args, "event"))+ body := githubArgString(args, "body")+ switch event {+ case "APPROVE":+ case "REQUEST_CHANGES", "COMMENT":+ if body == "" {+ return "", fmt.Errorf("event=%s 时 body 必填,写清楚审查意见", event)+ }+ default:+ return "", fmt.Errorf("event 只能是 APPROVE、REQUEST_CHANGES 或 COMMENT")+ }+ if len([]rune(body)) > 10000 {+ return "", fmt.Errorf("body must be at most 10000 characters")+ }+ payload := map[string]string{"event": event}+ if body != "" {+ payload["body"] = body+ }+ raw, _ := json.Marshal(payload)+ resp, out, err := githubRequest(ctx, githubHTTPClient(), http.MethodPost, fmt.Sprintf("%s/repos/%s/pulls/%d/reviews", githubAPIBase, path, number), token, raw)+ if err != nil {+ return "", fmt.Errorf("无法连接 GitHub:%v", err)+ }+ if resp.StatusCode != http.StatusOK {+ if resp.StatusCode == http.StatusUnprocessableEntity {+ return "", fmt.Errorf("GitHub 拒绝提交审查(HTTP 422):%s。GitHub 不允许 PR 作者审批自己的 PR;这种情况下改用 event=COMMENT 留下审查结论", githubErrorDetail(out))+ }+ return "", githubToolError("提交审查", "Pull requests 读写", resp.StatusCode, out)+ }+ var review struct {+ ID int64 `json:"id"`+ State string `json:"state"`+ HTMLURL string `json:"html_url"`+ }+ _ = json.Unmarshal(out, &review)+ result, _ := json.Marshal(map[string]any{"repository": path, "number": number, "reviewId": review.ID, "state": review.State, "url": review.HTMLURL})+ return string(result), nil+}++func githubPRMerge(ctx context.Context, token, path string, args map[string]any) (string, error) {+ number, err := githubArgNumber(args)+ if err != nil {+ return "", err+ }+ method := strings.ToLower(githubArgString(args, "method"))+ if method == "" {+ method = "merge"+ }+ if method != "merge" && method != "squash" && method != "rebase" {+ return "", fmt.Errorf("method 只能是 merge、squash 或 rebase")+ }+ payload := map[string]string{"merge_method": method}+ if sha := githubArgString(args, "sha"); sha != "" {+ payload["sha"] = sha+ }+ if title := githubArgString(args, "commitTitle"); title != "" {+ payload["commit_title"] = title+ }+ if message := githubArgString(args, "commitMessage"); message != "" {+ payload["commit_message"] = message+ }+ raw, _ := json.Marshal(payload)+ resp, out, err := githubRequest(ctx, githubHTTPClient(), http.MethodPut, fmt.Sprintf("%s/repos/%s/pulls/%d/merge", githubAPIBase, path, number), token, raw)+ if err != nil {+ return "", fmt.Errorf("无法连接 GitHub:%v", err)+ }+ switch resp.StatusCode {+ case http.StatusOK:+ case http.StatusMethodNotAllowed:+ return "", fmt.Errorf("PR #%d 当前不能合并(HTTP 405):%s。常见原因:分支保护要求审批或 CI 通过、存在冲突、PR 是草稿或已关闭。先用 workbench_github_pr_status 查看 mergeableState、checksState 和 reviews,不满足条件就跳过并在汇报中说明", number, githubErrorDetail(out))+ case http.StatusConflict:+ return "", fmt.Errorf("PR #%d 的 head 已变化(HTTP 409):%s。重新用 workbench_github_pr_status 读取最新 sha 并复核改动后再决定是否合并", number, githubErrorDetail(out))+ case http.StatusUnprocessableEntity:+ return "", fmt.Errorf("GitHub 拒绝合并 PR #%d(HTTP 422):%s。如果是合并方式不被仓库允许,换 method=squash 或 rebase 再试", number, githubErrorDetail(out))+ default:+ return "", githubToolError("合并 PR", "Contents 读写和 Pull requests 读写", resp.StatusCode, out)+ }+ var merged struct {+ SHA string `json:"sha"`+ Merged bool `json:"merged"`+ Message string `json:"message"`+ }+ _ = json.Unmarshal(out, &merged)+ result, _ := json.Marshal(map[string]any{"repository": path, "number": number, "merged": merged.Merged, "sha": merged.SHA, "method": method, "message": merged.Message})+ return string(result), nil+}++// githubIssueGet returns an issue's full body and its latest comments, which+// the list tool leaves out.+func githubIssueGet(ctx context.Context, token, path string, args map[string]any) (string, error) {+ number, err := githubArgNumber(args)+ if err != nil {+ return "", err+ }+ client := githubHTTPClient()+ resp, raw, err := githubRequest(ctx, client, http.MethodGet, fmt.Sprintf("%s/repos/%s/issues/%d", githubAPIBase, path, number), token, nil)+ if err != nil {+ return "", fmt.Errorf("无法连接 GitHub:%v", err)+ }+ if resp.StatusCode != http.StatusOK {+ return "", githubToolError("读取 Issue", "Issues 读取", resp.StatusCode, raw)+ }+ var it struct {+ githubIssueItem+ Comments int `json:"comments"`+ }+ if json.Unmarshal(raw, &it) != nil {+ return "", fmt.Errorf("GitHub 返回的 Issue 信息无法解析")+ }+ labels := make([]string, 0, len(it.Labels))+ for _, l := range it.Labels {+ labels = append(labels, l.Name)+ }+ out := map[string]any{+ "repository": path, "number": it.Number, "title": it.Title, "state": it.State, "url": it.HTMLURL,+ "author": it.User.Login, "labels": labels, "body": truncateRunes(it.Body, githubIssueBodyRunes),+ "isPullRequest": len(it.PullRequest) > 0, "createdAt": it.CreatedAt, "updatedAt": it.UpdatedAt, "commentCount": it.Comments,+ }+ comments := []map[string]string{}+ if it.Comments > 0 {+ lastPage := (it.Comments + githubListPageSize - 1) / githubListPageSize+ resp, raw, err := githubRequest(ctx, client, http.MethodGet, fmt.Sprintf("%s/repos/%s/issues/%d/comments?per_page=%d&page=%d", githubAPIBase, path, number, githubListPageSize, lastPage), token, nil)+ var items []struct {+ Body string `json:"body"`+ User struct {+ Login string `json:"login"`+ } `json:"user"`+ CreatedAt string `json:"created_at"`+ }+ switch {+ case err != nil:+ out["commentsWarning"] = fmt.Sprintf("评论读取失败:无法连接 GitHub:%v", err)+ case resp.StatusCode != http.StatusOK || json.Unmarshal(raw, &items) != nil:+ out["commentsWarning"] = fmt.Sprintf("评论读取失败(HTTP %d):%s", resp.StatusCode, githubErrorDetail(raw))+ default:+ if len(items) > githubIssueMaxComments {+ items = items[len(items)-githubIssueMaxComments:]+ }+ for _, c := range items {+ comments = append(comments, map[string]string{"author": c.User.Login, "createdAt": c.CreatedAt, "body": truncateRunes(c.Body, githubIssueCommentRunes)})+ }+ }+ }+ out["comments"] = comments+ body, _ := json.Marshal(out)+ return string(body), nil+}++func githubIssueClose(ctx context.Context, token, path string, args map[string]any) (string, error) {+ number, err := githubArgNumber(args)+ if err != nil {+ return "", err+ }+ reason := strings.ToLower(githubArgString(args, "reason"))+ if reason == "" {+ reason = "completed"+ }+ if reason != "completed" && reason != "not_planned" {+ return "", fmt.Errorf("reason 只能是 completed 或 not_planned")+ }+ comment := githubArgString(args, "comment")+ if len([]rune(comment)) > 10000 {+ return "", fmt.Errorf("comment must be at most 10000 characters")+ }+ client := githubHTTPClient()+ resp, raw, err := githubRequest(ctx, client, http.MethodGet, fmt.Sprintf("%s/repos/%s/issues/%d", githubAPIBase, path, number), token, nil)+ if err != nil {+ return "", fmt.Errorf("无法连接 GitHub:%v", err)+ }+ if resp.StatusCode != http.StatusOK {+ return "", githubToolError("读取 Issue", "Issues 读取", resp.StatusCode, raw)+ }+ var current struct {+ State string `json:"state"`+ HTMLURL string `json:"html_url"`+ PullRequest json.RawMessage `json:"pull_request"`+ }+ if json.Unmarshal(raw, ¤t) != nil {+ return "", fmt.Errorf("GitHub 返回的 Issue 信息无法解析")+ }+ if len(current.PullRequest) > 0 {+ return "", fmt.Errorf("#%d 是 PR 不是 Issue;这个工具只关闭 Issue,PR 请用 workbench_github_pr_merge 合并", number)+ }+ if current.State == "closed" {+ out, _ := json.Marshal(map[string]any{"repository": path, "number": number, "state": "closed", "alreadyClosed": true, "url": current.HTMLURL})+ return string(out), nil+ }+ commentURL := ""+ if comment != "" {+ added, err := githubIssueCommentAdd(ctx, token, path, number, comment)+ if err != nil {+ return "", err+ }+ var c struct {+ URL string `json:"url"`+ }+ _ = json.Unmarshal([]byte(added), &c)+ commentURL = c.URL+ }+ payload, _ := json.Marshal(map[string]string{"state": "closed", "state_reason": reason})+ resp, raw, err = githubRequest(ctx, client, http.MethodPatch, fmt.Sprintf("%s/repos/%s/issues/%d", githubAPIBase, path, number), token, payload)+ if err != nil {+ return "", fmt.Errorf("无法连接 GitHub:%v", err)+ }+ if resp.StatusCode != http.StatusOK {+ return "", githubToolError("关闭 Issue", githubIssueWritePermission, resp.StatusCode, raw)+ }+ out := map[string]any{"repository": path, "number": number, "state": "closed", "reason": reason, "url": current.HTMLURL}+ if commentURL != "" {+ out["commentUrl"] = commentURL+ }+ result, _ := json.Marshal(out)+ return string(result), nil+}++func githubIssueCreateArgs(args map[string]any) (string, string, []string, error) {+ title := githubArgString(args, "title")+ if title == "" || len([]rune(title)) > 256 {+ return "", "", nil, fmt.Errorf("title is required and must be at most 256 characters")+ }+ body := githubArgString(args, "body")+ if len([]rune(body)) > 20000 {+ return "", "", nil, fmt.Errorf("body must be at most 20000 characters")+ }+ labels := []string{}+ if raw, ok := args["labels"]; ok && raw != nil {+ items, ok := raw.([]any)+ if !ok || len(items) > 20 {+ return "", "", nil, fmt.Errorf("labels must be an array of at most 20 strings")+ }+ for _, item := range items {+ label, ok := item.(string)+ if !ok || strings.TrimSpace(label) == "" {+ return "", "", nil, fmt.Errorf("labels must be non-empty strings")+ }+ labels = append(labels, strings.TrimSpace(label))+ }+ }+ return title, body, labels, nil+}++func githubIssueCreate(ctx context.Context, token, path, title, body string, labels []string) (string, error) {+ payload, _ := json.Marshal(map[string]any{"title": title, "body": body, "labels": labels})+ resp, raw, err := githubRequest(ctx, githubHTTPClient(), http.MethodPost, fmt.Sprintf("%s/repos/%s/issues", githubAPIBase, path), token, payload)+ if err != nil {+ return "", fmt.Errorf("无法连接 GitHub:%v", err)+ }+ if resp.StatusCode != http.StatusCreated {+ return "", githubToolError("新建 Issue", githubIssueWritePermission, resp.StatusCode, raw)+ }+ var created struct {+ Number int64 `json:"number"`+ HTMLURL string `json:"html_url"`+ }+ _ = json.Unmarshal(raw, &created)+ out, _ := json.Marshal(map[string]any{"repository": path, "number": created.Number, "url": created.HTMLURL, "labels": labels})+ return string(out), nil+}++func githubPRClose(ctx context.Context, token, path string, args map[string]any) (string, error) {+ number, err := githubArgNumber(args)+ if err != nil {+ return "", err+ }+ comment := githubArgString(args, "comment")+ if len([]rune(comment)) > 10000 {+ return "", fmt.Errorf("comment must be at most 10000 characters")+ }+ client := githubHTTPClient()+ prURL := fmt.Sprintf("%s/repos/%s/pulls/%d", githubAPIBase, path, number)+ resp, raw, err := githubRequest(ctx, client, http.MethodGet, prURL, token, nil)+ if err != nil {+ return "", fmt.Errorf("无法连接 GitHub:%v", err)+ }+ if resp.StatusCode != http.StatusOK {+ return "", githubToolError("读取 PR", "Pull requests 读取", resp.StatusCode, raw)+ }+ var current struct {+ State string `json:"state"`+ Merged bool `json:"merged"`+ HTMLURL string `json:"html_url"`+ }+ if json.Unmarshal(raw, ¤t) != nil {+ return "", fmt.Errorf("GitHub 返回的 PR 信息无法解析")+ }+ if current.Merged {+ return "", fmt.Errorf("PR #%d 已经合并,不能再关闭;要撤销改动请另开 revert PR", number)+ }+ if current.State == "closed" {+ out, _ := json.Marshal(map[string]any{"repository": path, "number": number, "state": "closed", "alreadyClosed": true, "url": current.HTMLURL})+ return string(out), nil+ }+ out := map[string]any{"repository": path, "number": number, "state": "closed", "url": current.HTMLURL}+ if comment != "" {+ added, err := githubIssueCommentAdd(ctx, token, path, number, comment)+ if err != nil {+ return "", err+ }+ var c struct {+ URL string `json:"url"`+ }+ _ = json.Unmarshal([]byte(added), &c)+ out["commentUrl"] = c.URL+ }+ payload, _ := json.Marshal(map[string]string{"state": "closed"})+ resp, raw, err = githubRequest(ctx, client, http.MethodPatch, prURL, token, payload)+ if err != nil {+ return "", fmt.Errorf("无法连接 GitHub:%v", err)+ }+ if resp.StatusCode != http.StatusOK {+ return "", githubToolError("关闭 PR", "Pull requests 读写", resp.StatusCode, raw)+ }+ result, _ := json.Marshal(out)+ return string(result), nil+}++func githubErrorDetail(raw []byte) string {+ var body struct {+ Message string `json:"message"`+ Errors []struct {+ Message string `json:"message"`+ } `json:"errors"`+ }+ _ = json.Unmarshal(raw, &body)+ detail := strings.TrimSpace(body.Message)+ for _, e := range body.Errors {+ if e.Message != "" {+ detail = strings.TrimSpace(detail + " " + e.Message)+ }+ }+ if detail == "" {+ detail = strings.TrimSpace(truncateRunes(string(raw), 300))+ }+ return detail+}diff --git a/internal/httpapi/agent_tool_github_pr_test.go b/internal/httpapi/agent_tool_github_pr_test.gonew file mode 100644index 00000000..90f47b76--- /dev/null+++ b/internal/httpapi/agent_tool_github_pr_test.go@@ -0,0 +1,267 @@+package httpapi++import (+ "context"+ "io"+ "net/http"+ "strconv"+ "strings"+ "testing"+)++func TestGitHubPRStatusReportsSizeAuthorAndReviews(t *testing.T) {+ f := newGitHubToolFixture(t)+ f.set(githubToolTestToken)+ api := &fakeGitHubAPI{routes: map[string]func(http.ResponseWriter, *http.Request){+ "GET /repos/octo/app/pulls/7": githubJSON(http.StatusOK, `{"number":7,"title":"Feature","body":"Fixes #3","state":"open","mergeable":true,"mergeable_state":"clean","additions":12,"deletions":3,"changed_files":2,"commits":1,"user":{"login":"alice"},"head":{"sha":"abc123","ref":"topic"},"base":{"ref":"main"}}`),+ "GET /repos/octo/app/pulls/7/reviews": githubJSON(http.StatusOK, `[+ {"state":"CHANGES_REQUESTED","user":{"login":"bob"}},+ {"state":"APPROVED","user":{"login":"bob"}},+ {"state":"COMMENTED","user":{"login":"bob"}},+ {"state":"COMMENTED","user":{"login":"carol"}}+ ]`),+ "GET /repos/octo/app/commits/abc123/status": githubJSON(http.StatusOK, `{"statuses":[]}`),+ "GET /repos/octo/app/commits/abc123/check-runs": githubJSON(http.StatusOK, `{"check_runs":[]}`),+ }}+ api.serve(t)+ text, isErr := callGitHubTool(t, f, mainBotGitHubPRStatus, `{"repository":"app","number":7}`)+ for _, want := range []string{`"author":"alice"`, `"additions":12`, `"deletions":3`, `"changedFiles":2`, `"headSha":"abc123"`, `"mergeable":true`, `"approvals":1`, `{"reviewer":"bob","state":"APPROVED"}`, `{"reviewer":"carol","state":"COMMENTED"}`, `"body":"Fixes #3"`} {+ if isErr || !strings.Contains(text, want) {+ t.Fatalf("pr status missing %s: %s (error=%t)", want, text, isErr)+ }+ }+}++func TestGitHubPullsListFiltersByAuthorAcrossPages(t *testing.T) {+ f := newGitHubToolFixture(t)+ f.set(githubToolTestToken)+ var pages []string+ api := &fakeGitHubAPI{routes: map[string]func(http.ResponseWriter, *http.Request){+ "GET /repos/octo/app/pulls": func(w http.ResponseWriter, r *http.Request) {+ pages = append(pages, r.URL.Query().Get("page"))+ if r.URL.Query().Get("page") == "1" {+ items := make([]string, 0, githubListPageSize)+ for i := 0; i < githubListPageSize; i++ {+ items = append(items, `{"number":1000,"title":"other","user":{"login":"bot"}}`)+ }+ _, _ = io.WriteString(w, "["+strings.Join(items, ",")+"]")+ return+ }+ _, _ = io.WriteString(w, `[{"number":5,"title":"mine","user":{"login":"Alice"}},{"number":4,"title":"theirs","user":{"login":"bob"}}]`)+ },+ }}+ api.serve(t)+ text, isErr := callGitHubTool(t, f, mainBotGitHubPullsList, `{"repository":"app","author":"alice"}`)+ if isErr || !strings.Contains(text, `"count":1`) || !strings.Contains(text, `"mine"`) || strings.Contains(text, `"theirs"`) || strings.Contains(text, `"other"`) || !strings.Contains(text, `"hasMore":false`) {+ t.Fatalf("author filter = %s (error=%t)", text, isErr)+ }+ if strings.Join(pages, ",") != "1,2" {+ t.Fatalf("pages = %v", pages)+ }+}++func TestGitHubPRFilesTruncatesPatches(t *testing.T) {+ f := newGitHubToolFixture(t)+ f.set(githubToolTestToken)+ long := strings.Repeat("+x\n", githubPRFilePatchRunes)+ api := &fakeGitHubAPI{routes: map[string]func(http.ResponseWriter, *http.Request){+ "GET /repos/octo/app/pulls/7/files": githubJSON(http.StatusOK, `[{"filename":"a.go","status":"modified","additions":1,"deletions":0,"patch":"@@ -1 +1 @@\n+ok"},{"filename":"big.txt","status":"added","additions":3000,"deletions":0,"patch":"`+strings.ReplaceAll(long, "\n", `\n`)+`"}]`),+ }}+ api.serve(t)+ text, isErr := callGitHubTool(t, f, mainBotGitHubPRFiles, `{"repository":"app","number":7}`)+ if isErr || !strings.Contains(text, `"filename":"a.go"`) || !strings.Contains(text, `+ok`) || !strings.Contains(text, "已截断") || !strings.Contains(text, `"count":2`) {+ t.Fatalf("pr files = %.400s (error=%t)", text, isErr)+ }+}++func TestGitHubMergeReviewCloseNeedDirectWriteMode(t *testing.T) {+ f := newGitHubToolFixture(t)+ f.set(githubToolTestToken)+ api := &fakeGitHubAPI{routes: map[string]func(http.ResponseWriter, *http.Request){}}+ api.serve(t)+ for _, tc := range []struct{ name, args string }{+ {mainBotGitHubPRMerge, `{"repository":"app","number":7}`},+ {mainBotGitHubPRReview, `{"repository":"app","number":7,"event":"APPROVE"}`},+ {mainBotGitHubIssueClose, `{"repository":"app","number":3}`},+ } {+ text, isErr := callGitHubTool(t, f, tc.name, tc.args)+ if !isErr || !strings.Contains(text, "「请求批准」") || !strings.Contains(text, "「完全权限」") {+ t.Fatalf("%s in confirm mode = %s (error=%t)", tc.name, text, isErr)+ }+ }+ if len(api.requests) != 0 {+ t.Fatalf("confirm mode called GitHub: %v", api.requests)+ }+}++func TestGitHubMergeReviewCloseInFullAccess(t *testing.T) {+ f := newGitHubToolFixture(t)+ f.set(githubToolTestToken)+ f.session.ExecMode = assistantExecModeForApproval(AssistantApprovalAuto)+ api := &fakeGitHubAPI{routes: map[string]func(http.ResponseWriter, *http.Request){+ "PUT /repos/octo/app/pulls/7/merge": githubJSON(http.StatusOK, `{"sha":"m1","merged":true,"message":"Pull Request successfully merged"}`),+ "PUT /repos/octo/app/pulls/8/merge": githubJSON(http.StatusMethodNotAllowed, `{"message":"Required status check \"ci\" is expected."}`),+ "PUT /repos/octo/app/pulls/9/merge": githubJSON(http.StatusConflict, `{"message":"Head branch was modified."}`),+ "POST /repos/octo/app/pulls/7/reviews": githubJSON(http.StatusOK, `{"id":5,"state":"APPROVED","html_url":"https://github.com/octo/app/pull/7#r5"}`),+ "POST /repos/octo/app/pulls/8/reviews": githubJSON(http.StatusUnprocessableEntity, `{"message":"Unprocessable Entity","errors":["Can not approve your own pull request"]}`),+ "GET /repos/octo/app/issues/3": githubJSON(http.StatusOK, `{"number":3,"state":"open","html_url":"https://github.com/octo/app/issues/3"}`),+ "POST /repos/octo/app/issues/3/comments": githubJSON(http.StatusCreated, `{"id":1,"html_url":"https://github.com/octo/app/issues/3#c1"}`),+ "PATCH /repos/octo/app/issues/3": githubJSON(http.StatusOK, `{"number":3,"state":"closed"}`),+ "GET /repos/octo/app/issues/4": githubJSON(http.StatusOK, `{"number":4,"state":"closed"}`),+ "GET /repos/octo/app/issues/7": githubJSON(http.StatusOK, `{"number":7,"state":"open","pull_request":{"url":"x"}}`),+ }}+ api.serve(t)++ text, isErr := callGitHubTool(t, f, mainBotGitHubPRMerge, `{"repository":"app","number":7,"method":"squash","sha":"abc123"}`)+ if isErr || !strings.Contains(text, `"merged":true`) || !strings.Contains(text, `"method":"squash"`) {+ t.Fatalf("merge = %s (error=%t)", text, isErr)+ }+ if text, isErr = callGitHubTool(t, f, mainBotGitHubPRMerge, `{"repository":"app","number":8}`); !isErr || !strings.Contains(text, "当前不能合并") || !strings.Contains(text, "Required status check") {+ t.Fatalf("blocked merge = %s (error=%t)", text, isErr)+ }+ if text, isErr = callGitHubTool(t, f, mainBotGitHubPRMerge, `{"repository":"app","number":9,"sha":"old"}`); !isErr || !strings.Contains(text, "head 已变化") {+ t.Fatalf("stale merge = %s (error=%t)", text, isErr)+ }+ if text, isErr = callGitHubTool(t, f, mainBotGitHubPRMerge, `{"repository":"app","number":7,"method":"fast-forward"}`); !isErr || !strings.Contains(text, "method") {+ t.Fatalf("invalid method = %s (error=%t)", text, isErr)+ }++ if text, isErr = callGitHubTool(t, f, mainBotGitHubPRReview, `{"repository":"app","number":7,"event":"approve"}`); isErr || !strings.Contains(text, `"state":"APPROVED"`) {+ t.Fatalf("review = %s (error=%t)", text, isErr)+ }+ if text, isErr = callGitHubTool(t, f, mainBotGitHubPRReview, `{"repository":"app","number":8,"event":"APPROVE"}`); !isErr || !strings.Contains(text, "event=COMMENT") {+ t.Fatalf("self approval = %s (error=%t)", text, isErr)+ }+ if text, isErr = callGitHubTool(t, f, mainBotGitHubPRReview, `{"repository":"app","number":7,"event":"REQUEST_CHANGES"}`); !isErr || !strings.Contains(text, "body 必填") {+ t.Fatalf("request changes without body = %s (error=%t)", text, isErr)+ }++ if text, isErr = callGitHubTool(t, f, mainBotGitHubIssueClose, `{"repository":"app","number":3,"comment":"由 #7 解决"}`); isErr || !strings.Contains(text, `"state":"closed"`) || !strings.Contains(text, `"reason":"completed"`) || !strings.Contains(text, "commentUrl") {+ t.Fatalf("close = %s (error=%t)", text, isErr)+ }+ if text, isErr = callGitHubTool(t, f, mainBotGitHubIssueClose, `{"repository":"app","number":4}`); isErr || !strings.Contains(text, `"alreadyClosed":true`) {+ t.Fatalf("already closed = %s (error=%t)", text, isErr)+ }+ if text, isErr = callGitHubTool(t, f, mainBotGitHubIssueClose, `{"repository":"app","number":7}`); !isErr || !strings.Contains(text, "是 PR") {+ t.Fatalf("close PR = %s (error=%t)", text, isErr)+ }++ api.mu.Lock()+ defer api.mu.Unlock()+ bodies := strings.Join(api.bodies, "\n")+ for _, want := range []string{`"merge_method":"squash"`, `"sha":"abc123"`, `"event":"APPROVE"`, `{"state":"closed","state_reason":"completed"}`, `{"body":"由 #7 解决"}`} {+ if !strings.Contains(bodies, want) {+ t.Fatalf("payloads missing %s: %s", want, bodies)+ }+ }+ for _, req := range api.requests {+ if req == "PATCH /repos/octo/app/issues/4" || req == "PATCH /repos/octo/app/issues/7" {+ t.Fatalf("closed an already-closed issue or a PR: %v", api.requests)+ }+ }+}++func TestGitHubMergeReviewedInAssistedMode(t *testing.T) {+ f := newGitHubToolFixture(t)+ f.set(githubToolTestToken)+ f.session.ExecMode = assistantExecModeForApproval(AssistantApprovalAssisted)+ var described string+ f.session.approvalReviewer = func(_ context.Context, tool, description string, args map[string]any) assistantApprovalReview {+ described = description+ return assistantApprovalReview{Outcome: "deny", RiskLevel: "high", UserAuthorization: "low", Rationale: "未授权合并"}+ }+ api := &fakeGitHubAPI{routes: map[string]func(http.ResponseWriter, *http.Request){+ "PUT /repos/octo/app/pulls/7/merge": githubJSON(http.StatusOK, `{"merged":true}`),+ }}+ api.serve(t)+ text, isErr := callGitHubTool(t, f, mainBotGitHubPRMerge, `{"repository":"app","number":7}`)+ if !isErr || !strings.Contains(text, "帮我批准未执行") || !strings.Contains(described, "合并") {+ t.Fatalf("assisted merge = %s (error=%t) description=%q", text, isErr, described)+ }+ if len(api.requests) != 0 {+ t.Fatalf("merge executed without approval: %v", api.requests)+ }+}++func TestGitHubIssueGetReturnsBodyAndLatestComments(t *testing.T) {+ f := newGitHubToolFixture(t)+ f.set(githubToolTestToken)+ var commentPage string+ api := &fakeGitHubAPI{routes: map[string]func(http.ResponseWriter, *http.Request){+ "GET /repos/octo/app/issues/9": githubJSON(http.StatusOK, `{"number":9,"title":"multiply","body":"Add multiply and a test_m5.py","state":"open","html_url":"https://github.com/octo/app/issues/9","user":{"login":"alice"},"labels":[{"name":"auto-fix"}],"comments":140}`),+ "GET /repos/octo/app/issues/9/comments": func(w http.ResponseWriter, r *http.Request) {+ commentPage = r.URL.Query().Get("page")+ items := make([]string, 0, 40)+ for i := 0; i < 40; i++ {+ items = append(items, `{"body":"note`+strconv.Itoa(i)+`","user":{"login":"bob"}}`)+ }+ _, _ = io.WriteString(w, "["+strings.Join(items, ",")+"]")+ },+ }}+ api.serve(t)+ text, isErr := callGitHubTool(t, f, mainBotGitHubIssueGet, `{"repository":"app","number":9}`)+ for _, want := range []string{`"body":"Add multiply and a test_m5.py"`, `"labels":["auto-fix"]`, `"commentCount":140`, `"isPullRequest":false`, `"body":"note10"`, `"body":"note39"`} {+ if isErr || !strings.Contains(text, want) {+ t.Fatalf("issue get missing %s: %.600s (error=%t)", want, text, isErr)+ }+ }+ if strings.Contains(text, `"body":"note9"`) || commentPage != "2" {+ t.Fatalf("issue get should keep the latest %d comments from the last page (page=%s): %.300s", githubIssueMaxComments, commentPage, text)+ }+}++func TestGitHubIssuesListIncludesBodyExcerpt(t *testing.T) {+ f := newGitHubToolFixture(t)+ f.set(githubToolTestToken)+ api := &fakeGitHubAPI{routes: map[string]func(http.ResponseWriter, *http.Request){+ "GET /repos/octo/app/issues": githubJSON(http.StatusOK, `[{"number":9,"title":"multiply","body":"`+strings.Repeat("a", githubIssueListBodyRunes+50)+`","state":"open"}]`),+ }}+ api.serve(t)+ text, isErr := callGitHubTool(t, f, mainBotGitHubIssuesList, `{"repository":"app"}`)+ if isErr || !strings.Contains(text, `"body":"`+strings.Repeat("a", githubIssueListBodyRunes)+`…"`) {+ t.Fatalf("issues list = %.200s (error=%t)", text, isErr)+ }+}++func TestGitHubIssueCreateAndPRClose(t *testing.T) {+ f := newGitHubToolFixture(t)+ f.set(githubToolTestToken)+ api := &fakeGitHubAPI{routes: map[string]func(http.ResponseWriter, *http.Request){+ "POST /repos/octo/app/issues": githubJSON(http.StatusCreated, `{"number":21,"html_url":"https://github.com/octo/app/issues/21"}`),+ "GET /repos/octo/app/pulls/7": githubJSON(http.StatusOK, `{"state":"open","merged":false,"html_url":"https://github.com/octo/app/pull/7"}`),+ "GET /repos/octo/app/pulls/8": githubJSON(http.StatusOK, `{"state":"closed","merged":true}`),+ "GET /repos/octo/app/pulls/9": githubJSON(http.StatusOK, `{"state":"closed","merged":false}`),+ "POST /repos/octo/app/issues/7/comments": githubJSON(http.StatusCreated, `{"id":1,"html_url":"https://github.com/octo/app/pull/7#c1"}`),+ "PATCH /repos/octo/app/pulls/7": githubJSON(http.StatusOK, `{"state":"closed"}`),+ }}+ api.serve(t)+ lastBody := func(request string) string {+ for i := len(api.requests) - 1; i >= 0; i-- {+ if api.requests[i] == request {+ return api.bodies[i]+ }+ }+ return ""+ }+ text, isErr := callGitHubTool(t, f, mainBotGitHubIssueCreate, `{"repository":"app","title":"Bug","body":"steps","labels":["bug"]}`)+ if isErr || !strings.Contains(text, `"number":21`) || !strings.Contains(lastBody("POST /repos/octo/app/issues"), `"labels":["bug"]`) {+ t.Fatalf("issue create = %s body=%s (error=%t)", text, lastBody("POST /repos/octo/app/issues"), isErr)+ }+ if text, isErr = callGitHubTool(t, f, mainBotGitHubIssueCreate, `{"repository":"app","title":" "}`); !isErr {+ t.Fatalf("blank title accepted: %s", text)+ }+ if text, isErr = callGitHubTool(t, f, mainBotGitHubPRClose, `{"repository":"app","number":7}`); !isErr || !strings.Contains(text, "「请求批准」") {+ t.Fatalf("pr close in confirm mode = %s", text)+ }+ f.session.ExecMode = assistantExecModeForApproval(AssistantApprovalAuto)+ text, isErr = callGitHubTool(t, f, mainBotGitHubPRClose, `{"repository":"app","number":7,"comment":"superseded"}`)+ if isErr || !strings.Contains(text, `"commentUrl":"https://github.com/octo/app/pull/7#c1"`) || lastBody("PATCH /repos/octo/app/pulls/7") != `{"state":"closed"}` {+ t.Fatalf("pr close = %s (error=%t)", text, isErr)+ }+ if text, isErr = callGitHubTool(t, f, mainBotGitHubPRClose, `{"repository":"app","number":8}`); !isErr || !strings.Contains(text, "已经合并") {+ t.Fatalf("merged pr close = %s", text)+ }+ if text, isErr = callGitHubTool(t, f, mainBotGitHubPRClose, `{"repository":"app","number":9}`); isErr || !strings.Contains(text, `"alreadyClosed":true`) {+ t.Fatalf("closed pr close = %s", text)+ }+}diff --git a/internal/httpapi/agent_tool_github_test.go b/internal/httpapi/agent_tool_github_test.goindex 7ee0d11b..6f657592 100644--- a/internal/httpapi/agent_tool_github_test.go+++ b/internal/httpapi/agent_tool_github_test.go@@ -31,7 +31,7 @@ func TestMainBotGitHubToolsOnlyForAssistantWithProject(t *testing.T) {}}tools := mainBotGitHubTools(&AgentToolSession{Mode: AgentToolAssistant, ProjectID: "p"})- want := map[string]bool{mainBotGitHubIssuesList: true, mainBotGitHubPullsList: true, mainBotGitHubPRStatus: true, mainBotGitHubCommentAdd: true, mainBotGitHubLabelsAdd: true}+ want := map[string]bool{mainBotGitHubIssuesList: true, mainBotGitHubIssueGet: true, mainBotGitHubPullsList: true, mainBotGitHubPRStatus: true, mainBotGitHubPRFiles: true, mainBotGitHubCommentAdd: true, mainBotGitHubLabelsAdd: true, mainBotGitHubPRReview: true, mainBotGitHubPRMerge: true, mainBotGitHubIssueClose: true, mainBotGitHubIssueCreate: true, mainBotGitHubPRClose: true}if len(tools) != len(want) {t.Fatalf("tools = %v", tools)}diff --git a/internal/httpapi/agent_tool_mcp.go b/internal/httpapi/agent_tool_mcp.goindex 271d0bed..7e178c83 100644--- a/internal/httpapi/agent_tool_mcp.go+++ b/internal/httpapi/agent_tool_mcp.go@@ -445,7 +445,7 @@ func (h *agentToolGateway) dispatch(ctx context.Context, session *AgentToolSessi// confirm mode cannot run it.name := mcpCallName(kind, call)if !session.ExecMode.AutoWrite {- return "", fmt.Errorf("%s 会写入外部系统,当前审批模式需要逐项确认,而外部 MCP 写入没有待确认草稿。请让用户把审批模式切到「自动」或「辅助」后再试,或告诉用户要做的改动由其手动完成", name)+ return "", fmt.Errorf("%s 会写入外部系统,当前审批模式需要逐项确认,而外部 MCP 写入没有待确认草稿。请让用户把审批模式切到「完全权限」或「帮我批准」后再试,或告诉用户要做的改动由其手动完成", name)}if session.ExecMode.ReviewWrites {review := reviewAssistantAction(ctx, name, mcpServerName(h, session, call.Server)+" MCP 写入外部系统", map[string]any{"server": call.Server, "tool": call.Tool, "arguments": call.Arguments})diff --git a/internal/httpapi/assistant_cases_test.go b/internal/httpapi/assistant_cases_test.goindex fa6c625d..84f89821 100644--- a/internal/httpapi/assistant_cases_test.go+++ b/internal/httpapi/assistant_cases_test.go@@ -176,11 +176,17 @@ func TestAssistantTaskHandlersAndExecution(t *testing.T) {if task.LastStatus != "ok" || strings.Contains(task.LastMessage, "secret") || task.SessionID == "" {t.Fatalf("executed task = %+v", task)}- h.active.Store(user.ID, true)+ h.active.Store(assistantTaskActiveKey(task.ID, user.ID), true)if err := h.executeAssistantTask(context.Background(), user, &task); !errors.Is(err, errAssistantBusy) {t.Fatalf("busy error = %v", err)}- h.active.Delete(user.ID)+ // Another task of the same owner is not blocked by this one.+ other := assistantTask{ID: "job-other", Name: "other", ProjectID: task.ProjectID, Prompt: "other"}+ h.generate = func(context.Context, string, domain.User) (string, error) { return "完成", nil }+ if err := h.executeAssistantTask(context.Background(), user, &other); err != nil {+ t.Fatalf("other task blocked by a running one: %v", err)+ }+ h.active.Delete(assistantTaskActiveKey(task.ID, user.ID))h.generate = func(context.Context, string, domain.User) (string, error) { return "", errors.New("upstream") }if err := h.executeAssistantTask(context.Background(), user, &task); err == nil || task.LastStatus != "error" {t.Fatalf("generation failure = %v %+v", err, task)diff --git a/internal/httpapi/assistant_engines.go b/internal/httpapi/assistant_engines.goindex df01700a..d5c589ed 100644--- a/internal/httpapi/assistant_engines.go+++ b/internal/httpapi/assistant_engines.go@@ -287,14 +287,17 @@ func assistantAllowedUserModel(id string, catalog assistantModelCatalog, user do}// assistantScheduledModel normalizes the model of an AI scheduled task on-// save. The run uses the project owner's keys, not the editor's, so a-// well-formed CLI model is kept as-is; the owner's key for that CLI is-// checked when it runs.+// save. The run uses the project owner's keys and CodeBuddy environment, not+// the editor's, so a well-formed model is kept as-is; it is checked against+// the owner's account when it runs (see scheduledRunModel).func assistantScheduledModel(id string, catalog assistantModelCatalog) string {engine, model := assistantModelEngine(id)if engine != assistantEngineCodeBuddy && assistantValidEngineModel(model) {return engine + ":" + model}+ if engine == assistantEngineCodeBuddy && assistantValidEngineModel(model) {+ return model+ }return assistantAllowedModel(id, catalog)}diff --git a/internal/httpapi/assistant_task_engines_test.go b/internal/httpapi/assistant_task_engines_test.goindex f4699870..b8e326b7 100644--- a/internal/httpapi/assistant_task_engines_test.go+++ b/internal/httpapi/assistant_task_engines_test.go@@ -19,8 +19,9 @@ func TestAssistantScheduledModelKeepsCLIModels(t *testing.T) {"codex:gpt-6-sol": "codex:gpt-6-sol"," claude-code:opus ": "claude-code:opus",catalog.Default: catalog.Default,- "glm-5.3-ioa": catalog.Default,- "unknown-model": catalog.Default,+ "glm-5.3-ioa": "glm-5.3-ioa",+ " unknown-model ": "unknown-model",+ "bad model": catalog.Default,"codex:bad model": catalog.Default,"": catalog.Default,} {@@ -30,6 +31,37 @@ func TestAssistantScheduledModelKeepsCLIModels(t *testing.T) {}}+// The CodeBuddy model list is empty after a restart: a scheduled run refreshes+// it with the owner's key and never swaps an unavailable model for the default.+func TestScheduledRunModelRefreshesAndNeverFallsBack(t *testing.T) {+ old := discoverCLIModels+ discoverCLIModels = func(_ context.Context, environment, apiKey string) []string {+ if environment == "internal" && apiKey == "owner-key" {+ return []string{"deepseek-v4.1-flash"}+ }+ return nil+ }+ cliModelMu.Lock()+ cliModelCache = map[string]cliModelEntry{}+ cliModelMu.Unlock()+ t.Cleanup(func() {+ discoverCLIModels = old+ cliModelMu.Lock()+ cliModelCache = map[string]cliModelEntry{}+ cliModelMu.Unlock()+ })+ owner := domain.User{CodeBuddyAPIKey: "owner-key", CodeBuddyInternetEnvironment: "internal"}+ if got, err := scheduledRunModel(context.Background(), "deepseek-v4.1-flash", owner); err != nil || got != "deepseek-v4.1-flash" {+ t.Fatalf("model = %q, %v", got, err)+ }+ if got, err := scheduledRunModel(context.Background(), "", owner); err != nil || got != assistantFixedCatalog().Default {+ t.Fatalf("empty model = %q, %v", got, err)+ }+ if got, err := scheduledRunModel(context.Background(), "gone-model", owner); err == nil || !strings.Contains(err.Error(), "gone-model") {+ t.Fatalf("unavailable model = %q, %v", got, err)+ }+}+// A scheduled task on another CLI runs with that CLI's own key, needs no// CodeBuddy key, and records the CLI on its conversation.func TestScheduledTaskRunsOnTaskCLI(t *testing.T) {diff --git a/internal/httpapi/assistant_tasks.go b/internal/httpapi/assistant_tasks.goindex f69c8f7c..72deb542 100644--- a/internal/httpapi/assistant_tasks.go+++ b/internal/httpapi/assistant_tasks.go@@ -5,6 +5,7 @@ import ("encoding/json""errors""flag"+ "fmt""log""os""strconv"@@ -144,8 +145,8 @@ func (h *assistantHandlers) runTaskNow(c *gin.Context) {c.JSON(404, gin.H{"error": "定时任务不存在"})return}- if _, loaded := h.active.Load(current.ID); loaded {- c.JSON(429, gin.H{"error": "已有对话正在生成,请稍后重试"})+ if _, loaded := h.active.Load(assistantTaskActiveKey(task.ID, current.ID)); loaded {+ c.JSON(429, gin.H{"error": "该定时任务正在运行,请稍后重试"})return}go h.runStoredAssistantTask(user, task)@@ -197,12 +198,6 @@ func (h *assistantHandlers) runStoredAssistantTask(user domain.User, task assist// Only the trigger lives here: who runs it, what is asked, the session's// metadata and how the result is reported.func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domain.User, task *assistantTask) error {- if _, loaded := h.active.LoadOrStore(user.ID, true); loaded {- return errAssistantBusy- }- defer h.active.Delete(user.ID)- ctx = withAssistantExecMode(ctx, assistantExecModeForApproval(AssistantApprovalAuto))- mode := assistantExecModeFrom(ctx)origin := assistantSessionOriginFrom(ctx)if origin.Source == "" {origin.Source = domain.AssistantSourceScheduled@@ -210,6 +205,15 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domaiif origin.TaskID == "" {origin.TaskID = strings.TrimSpace(task.ID)}+ // Each task runs in its own conversation, so one owner's loops run side+ // by side; only the same task is kept from overlapping itself.+ activeKey := assistantTaskActiveKey(origin.TaskID, user.ID)+ if _, loaded := h.active.LoadOrStore(activeKey, true); loaded {+ return errAssistantBusy+ }+ defer h.active.Delete(activeKey)+ ctx = withAssistantExecMode(ctx, assistantExecModeForApproval(AssistantApprovalAuto))+ mode := assistantExecModeFrom(ctx)task.NotificationResult = ""task.LastStatus = "running"@@ -232,7 +236,10 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domai}return fail("未配置 CodeBuddy API Key")}- model := assistantAllowedUserModel(task.Model, loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment), user)+ model, err := scheduledRunModel(ctx, task.Model, user)+ if err != nil {+ return fail(err.Error())+ }cliEngine, _ := assistantModelEngine(model)prevSession := strings.TrimSpace(task.SessionID)sessionID := newAssistantSessionID()@@ -324,7 +331,11 @@ func (h *assistantHandlers) readScheduledTurn(user domain.User, task *assistantT}func scheduledAssistantPrompt(task assistantTask, mode assistantExecMode) string {- prefix := "这是当前项目「" + task.ProjectID + "」下的无人值守定时任务「" + task.Name + "」。直接调用当前项目和个人已安装的 MCP,以及 agentflow__* 平台工具,读写立即生效。issues_save 把需求 id 放在 body.id(也可同时放 path.id)。全部完成后用自然语言汇报结果。"+ prefix := "这是当前项目「" + task.ProjectID + "」下的无人值守定时任务「" + task.Name + "」。直接调用当前项目和个人已安装的 MCP,以及 agentflow__* 平台工具,读写立即生效。issues_save 把需求 id 放在 body.id(也可同时放 path.id)。" ++ "运行期间没有人回答问题或确认操作:不要向用户提问或等待确认,有歧义时按最合理、影响最小的理解执行并在汇报里写明假设;某项条件不满足时跳过该项并说明原因,继续处理其余项。" ++ "除非提示词明确要求,不要为完成任务新建或修改沙箱、角色、SOP、项目等平台配置。" ++ "GitHub 的查看、审查、合并 PR 和关闭 Issue 使用 workbench_github_* 工具,不要在终端里读取令牌直接调用 GitHub API。" ++ "全部完成后用自然语言汇报结果。"if mode.DeferSOP {prefix += " 不要调用 issues_dispatch、runs_start、schedule_jobs_run、schedule_jobs_save;需要派发 SOP 时请单独创建触发任务。"} else {@@ -393,6 +404,13 @@ func normalizeAssistantTask(in assistantTask, existing assistantTask) (assistantreturn in, nil}+func assistantTaskActiveKey(taskID string, userID int64) string {+ if taskID = strings.TrimSpace(taskID); taskID != "" {+ return "task/" + taskID+ }+ return "task-user/" + strconv.FormatInt(userID, 10)+}+func newAssistantTaskID() string {return "at" + strconv.FormatInt(time.Now().UnixNano(), 36)}@@ -410,6 +428,26 @@ func firstNonEmpty(values ...string) string {return ""}+// scheduledRunModel resolves the model a scheduled run uses. The CodeBuddy+// model list is an in-memory cache that is empty after a restart, so it is+// refreshed with the owner's key before a model is rejected. A run never+// silently switches to another, possibly more expensive, model.+func scheduledRunModel(ctx context.Context, requested string, user domain.User) (string, error) {+ requested = strings.TrimSpace(requested)+ env := user.CodeBuddyInternetEnvironment+ model := assistantAllowedUserModel(requested, loadAssistantModels(ctx, env), user)+ if requested == "" || model == requested {+ return model, nil+ }+ if engine, _ := assistantModelEngine(requested); engine == assistantEngineCodeBuddy {+ refreshCLIModels(ctx, env, user.CodeBuddyAPIKey)+ if model = assistantAllowedUserModel(requested, loadAssistantModels(ctx, env), user); model == requested {+ return model, nil+ }+ }+ return "", fmt.Errorf("定时任务指定的模型 %s 在负责人的账号下不可用,本次没有运行;请在定时任务里改选可用的模型", requested)+}+func truncateRunes(text string, max int) string {runes := []rune(strings.TrimSpace(text))if len(runes) <= max {diff --git a/internal/httpapi/assistant_workspace.go b/internal/httpapi/assistant_workspace.goindex 6e688aa0..f3662ae9 100644--- a/internal/httpapi/assistant_workspace.go+++ b/internal/httpapi/assistant_workspace.go@@ -61,7 +61,7 @@ func mainBotWorkspaceTools(s *AgentToolSession) []agentToolDescriptor {descriptors := []struct{ name, description, schema string }{{"tree", "列出当前工作区的文件(任务会话是任务工作区;普通对话是用 workbench_workspace_open 打开的临时工作区)。路径相对工作区,不是控制平面目录。", `{"type":"object","properties":{"path":{"type":"string"}},"additionalProperties":false}`},{"read", "读取当前工作区文件,返回 content 与 sha256;修改前先读取。", `{"type":"object","properties":{"path":{"type":"string"}},"required":["path"],"additionalProperties":false}`},- {"write", "直接保存当前工作区文件。expectedSha256 必须为读取时的 sha256;新文件传 missing。若文件已变更,重新读取并对齐,不能盲目覆盖。SOP 正在执行时需先暂停;临时工作区允许直接写入。", `{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"},"expectedSha256":{"type":"string"}},"required":["path","content","expectedSha256"],"additionalProperties":false}`},+ {"write", "直接保存当前工作区文件。expectedSha256 必须为读取时的 sha256;新建文件传字符串 \"missing\"(不是空串,也不是空内容的 sha256),且父目录必须已存在。若文件已变更,重新读取并对齐,不能盲目覆盖。SOP 正在执行时需先暂停;临时工作区允许直接写入。", `{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"},"expectedSha256":{"type":"string","description":"workbench_workspace_read 返回的 sha256;新建文件传 \"missing\""}},"required":["path","content","expectedSha256"],"additionalProperties":false}`},{"command", "在当前工作区运行 shell 命令并返回 output、exitCode,用于小改动与验证。最长 120 秒;SOP 正在执行时需先暂停。", `{"type":"object","properties":{"command":{"type":"string"},"timeoutSeconds":{"type":"integer","minimum":1,"maximum":120}},"required":["command"],"additionalProperties":false}`},{"attach", "把工作区里的文本文件(HTML demo、Markdown/文本报告、JSON、CSV 等,单个不超过 1MB)附在本轮回复里交给用户。工作区地址只在工作区存活时能在侧栏「浏览器」页签打开,要让用户留存或下载文件就用它:HTML 在产物栏以沙箱方式可交互预览,其他文件可查看和下载。每轮最多 4 个;同名文件再次附加时以最新内容为准,所以改完文件后重新附加即可。", `{"type":"object","properties":{"path":{"type":"string"}},"required":["path"],"additionalProperties":false}`},}@@ -448,15 +448,8 @@ func (h *agentToolGateway) mainBotWorkspaceCommand(ctx context.Context, s *Agentreturn "", err}}- // Treat the requested command as a single shell argument, preserving quotes,- // substitutions and newlines without letting it alter our status wrapper.- quoted := "'" + strings.ReplaceAll(command, "'", "'\"'\"'") + "'"- // One input line: the shell reads it whole before running anything, so- // line-editor output (e.g. bash 5 bracketed-paste toggles around every- // read) lands before the begin line and none follows the exit line.begin := "__main_bot_begin_" + token- input := "printf '\\n%s\\n' '" + begin + "'; /bin/sh -c " + quoted + "; printf '\\n" + marker + "%s\\n' \"$?\"; exit\n"- if _, err = terminal(ctx, "input", opened.ID, input); err != nil {+ if _, err = terminal(ctx, "input", opened.ID, workspaceCommandInput(command, begin, marker)); err != nil {return "", err}for {@@ -481,6 +474,19 @@ func (h *agentToolGateway) mainBotWorkspaceCommand(ctx context.Context, s *Agent}}+// workspaceCommandInput wraps a command for the workspace terminal. The+// command is one shell argument, preserving quotes, substitutions and+// newlines without letting it alter the status wrapper. It is all one input+// line: the shell reads it whole before running anything, so line-editor+// output (e.g. bash 5 bracketed-paste toggles around every read) lands before+// the begin line and none follows the exit line. Nobody types into this+// terminal, so pagers are disabled and stdin is empty: `git log` or a prompt+// would otherwise wait for a key until the timeout.+func workspaceCommandInput(command, begin, marker string) string {+ quoted := "'" + strings.ReplaceAll(command, "'", "'\"'\"'") + "'"+ return "printf '\\n%s\\n' '" + begin + "'; export PAGER=cat GIT_PAGER=cat MANPAGER=cat SYSTEMD_PAGER=; /bin/sh -c " + quoted + " </dev/null; printf '\\n" + marker + "%s\\n' \"$?\"; exit\n"+}+// workspaceCommandTimeout tells the model what the stopped command printed and// how to proceed, instead of a bare "context deadline exceeded".func workspaceCommandTimeout(seconds int, raw, begin string) error {diff --git a/internal/httpapi/assistant_workspace_open_test.go b/internal/httpapi/assistant_workspace_open_test.goindex 1b8adcf6..6b8dea51 100644--- a/internal/httpapi/assistant_workspace_open_test.go+++ b/internal/httpapi/assistant_workspace_open_test.go@@ -4,6 +4,7 @@ import ("bytes""context""encoding/json"+ "io""os""os/exec""path/filepath"@@ -19,6 +20,7 @@ import ("agentflow/internal/runtime""agentflow/internal/tracker"+ "github.com/creack/pty""github.com/gin-gonic/gin")@@ -578,3 +580,45 @@ func TestWorkspaceOpenSchemaDescribesBranchModes(t *testing.T) {t.Fatal("tool description does not explain branchMode")}}++// The workspace terminal is a TTY nobody types into: `git log` must not open a+// pager and a command reading stdin must not wait for a key.+func TestWorkspaceCommandInputNeverWaitsForKeys(t *testing.T) {+ if _, err := exec.LookPath("git"); err != nil {+ t.Skip("git is required")+ }+ dir := t.TempDir()+ for _, args := range [][]string{{"init", "-q"}, {"-c", "[email protected]", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "first"}} {+ cmd := exec.Command("git", args...)+ cmd.Dir = dir+ if out, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("git %v: %v %s", args, err, out)+ }+ }+ begin, marker := "__main_bot_begin_tok", "__main_bot_exit_tok:"+ shell := exec.Command("/bin/sh")+ shell.Dir = dir+ shell.Env = append(os.Environ(), "PAGER=less", "GIT_PAGER=", "LESS=")+ tty, err := pty.Start(shell)+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = shell.Process.Kill(); _ = tty.Close() }()+ if _, err := io.WriteString(tty, workspaceCommandInput("git log --oneline; read line || echo no-input", begin, marker)); err != nil {+ t.Fatal(err)+ }+ done := make(chan string, 1)+ go func() {+ raw, _ := io.ReadAll(tty)+ done <- string(raw)+ }()+ select {+ case raw := <-done:+ out, code, err := workspaceCommandOutput(raw, begin, marker)+ if err != nil || code != 0 || !strings.Contains(out, "first") || !strings.Contains(out, "no-input") {+ t.Fatalf("output=%q code=%d err=%v", out, code, err)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("command waited for terminal input")+ }+}diff --git a/internal/httpapi/shared_schedules_test.go b/internal/httpapi/shared_schedules_test.goindex 2f61a49e..18bdc119 100644--- a/internal/httpapi/shared_schedules_test.go+++ b/internal/httpapi/shared_schedules_test.go@@ -19,6 +19,14 @@ import (func TestSharedScheduleSubscriptionUsesPinnedVersionAndTargetOwner(t *testing.T) {t.Setenv("AGENTFLOW_AUTH_REQUIRED", "true")t.Setenv("AGENTFLOW_SESSION_SECRET", "shared-schedules-test-secret")+ oldDiscover := discoverCLIModels+ discoverCLIModels = func(context.Context, string, string) []string { return []string{"glm-5.3-flash-ioa"} }+ t.Cleanup(func() {+ discoverCLIModels = oldDiscover+ cliModelMu.Lock()+ cliModelCache = map[string]cliModelEntry{}+ cliModelMu.Unlock()+ })h, sourceOwner := workbenchFixture(t)st := h.repofor _, login := range []string{"subscriber", "outsider", "viewer"} {diff --git a/internal/repo/catalog.go b/internal/repo/catalog.goindex 3ae2c08a..82b4c871 100644--- a/internal/repo/catalog.go+++ b/internal/repo/catalog.go@@ -319,6 +319,9 @@ func (r *CatalogRepo) DeleteEnvironment(id string) error {func (r *CatalogRepo) Sandboxes() []domain.SandboxProfile {profiles := payloadList[domain.SandboxProfile](r.DB, "sandboxes", "")+ for i := range profiles {+ profiles[i] = platformSandboxProfile(profiles[i])+ }for _, profile := range profiles {if profile.ID == DefaultSandboxProfileID {return profiles@@ -342,7 +345,17 @@ func (r *CatalogRepo) Sandbox(id string) (domain.SandboxProfile, bool) {if err != nil || json.Unmarshal(row.Payload, &profile) != nil {return domain.SandboxProfile{}, false}- return profile, true+ return platformSandboxProfile(profile), true+}++// platformSandboxProfile keeps the built-in generic Docker sandbox shared:+// conversation workspaces fall back to it, and rows seeded before it carried+// the shared flag would otherwise hide it from every project.+func platformSandboxProfile(profile domain.SandboxProfile) domain.SandboxProfile {+ if profile.ID == GenericDockerSandboxID {+ profile.Shared = true+ }+ return profile}func (r *CatalogRepo) PutSandbox(v domain.SandboxProfile) error {diff --git a/internal/repo/sandbox_defaults_test.go b/internal/repo/sandbox_defaults_test.goindex a8bdc6aa..286bef37 100644--- a/internal/repo/sandbox_defaults_test.go+++ b/internal/repo/sandbox_defaults_test.go@@ -92,3 +92,31 @@ func TestDefaultSandboxDoesNotMaskCorruptConfigurationOrDatabaseFailure(t *testit.Fatalf("database failure reported available sandboxes: %+v", profiles)}}++// The public catalog seed stored generic-docker without the shared flag; it is+// still the platform fallback for conversation workspaces in every project.+func TestSeededGenericDockerSandboxIsSharedForConversations(t *testing.T) {+ s, err := OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { s.Close() })+ seeded := `{"id":"generic-docker","name":"Docker 隔离沙箱","driver":"docker","dockerfileId":"generic-backend","readOnlyRootFS":false}`+ if err := s.DB.Table("sandboxes").Where("id = ?", GenericDockerSandboxID).Update("payload", seeded).Error; err != nil {+ t.Fatal(err)+ }+ profile, ok := s.Sandbox(GenericDockerSandboxID)+ if !ok || !profile.Shared {+ t.Fatalf("seeded generic-docker is not shared: %+v", profile)+ }+ if got, err := s.ResolveConversationSandbox("any-project", ""); err != nil || got.ID != GenericDockerSandboxID {+ t.Fatalf("default conversation sandbox = %+v, %v", got, err)+ }+ found := false+ for _, candidate := range s.ConversationSandboxes("any-project") {+ found = found || candidate.ID == GenericDockerSandboxID+ }+ if !found {+ t.Fatal("generic-docker missing from the project's conversation sandboxes")+ }+}diff --git a/internal/runtime/workspace_edit.go b/internal/runtime/workspace_edit.goindex 3cb1e90f..7f952696 100644--- a/internal/runtime/workspace_edit.go+++ b/internal/runtime/workspace_edit.go@@ -100,6 +100,12 @@ func resolveWorkspaceEditPath(root, path, expected string) (string, error) {if os.IsNotExist(err) && current == rel && expected == "missing" {continue}+ if os.IsNotExist(err) && current == rel {+ return "", fmt.Errorf("文件 %s 不存在:新建文件时 expectedSha256 传 \"missing\"", filepath.ToSlash(rel))+ }+ if os.IsNotExist(err) {+ return "", fmt.Errorf("目录 %s 不存在:先在终端里 mkdir -p 创建目录,再新建文件", filepath.ToSlash(current))+ }if err != nil {return "", err}diff --git a/internal/runtime/workspace_edit_test.go b/internal/runtime/workspace_edit_test.goindex a6ca4ed8..88269570 100644--- a/internal/runtime/workspace_edit_test.go+++ b/internal/runtime/workspace_edit_test.go@@ -3,6 +3,7 @@ package runtimeimport ("os""path/filepath"+ "strings""testing")@@ -41,8 +42,11 @@ func TestWorkspaceEditCreateRequiresMissingVersion(t *testing.T) {if _, err = WriteWorkspaceFile(root, "new.txt", "overwrite", "missing"); err == nil {t.Fatal("new file overwrote existing file")}- if _, err = WriteWorkspaceFile(root, "absent.txt", "new", ""); err == nil {- t.Fatal("creation without missing version")+ if _, err = WriteWorkspaceFile(root, "absent.txt", "new", ""); err == nil || !strings.Contains(err.Error(), `"missing"`) {+ t.Fatalf("creation without missing version: %v", err)+ }+ if _, err = WriteWorkspaceFile(root, "absent/new.txt", "new", "missing"); err == nil || !strings.Contains(err.Error(), "mkdir -p") {+ t.Fatalf("creation under a missing directory: %v", err)}os.Symlink(t.TempDir(), filepath.Join(root, "link"))if _, err = WriteWorkspaceFile(root, "link/escape.txt", "new", "missing"); err == nil {diff --git a/internal/schedule/service.go b/internal/schedule/service.goindex 69cdb26e..88d1aa28 100644--- a/internal/schedule/service.go+++ b/internal/schedule/service.go@@ -15,9 +15,9 @@ import ("agentflow/internal/tracker")-// ErrAlreadyRunning is returned when a second job is started while another-// schedule job is still executing on this instance.-var ErrAlreadyRunning = errors.New("已有定时任务正在运行")+// ErrAlreadyRunning is returned when a job is started while that same job is+// still executing on this instance. Different jobs run concurrently.+var ErrAlreadyRunning = errors.New("该定时任务正在运行")var errNotDue = errors.New("schedule job is not due")@@ -41,12 +41,15 @@ type Service struct {mu sync.MutexstopCh chan struct{}stopped bool- runningJob string- lastFinishedAt time.Time+ running map[string]bool+ lastFinishedAt map[string]time.Time+ // dispatchMu serializes issue scanning and SOP dispatch across jobs so two+ // trigger jobs cannot both claim the same issue; AI prompts run outside it.+ dispatchMu sync.Mutex}func New(st *repo.Store, sy *tracker.Service, d Dispatcher) *Service {- return &Service{repo: st, sync: sy, dispatch: d}+ return &Service{repo: st, sync: sy, dispatch: d, running: map[string]bool{}, lastFinishedAt: map[string]time.Time{}}}func (s *Service) SetBaselineGuard(g BaselineGuard) {@@ -180,7 +183,7 @@ func (s *Service) StartNow(id string) (domain.ScheduleJob, error) {func (s *Service) executeAsync(job domain.ScheduleJob, triggerOrigin string) {go func() {- defer s.release()+ defer s.release(job.ID)if _, execErr := s.execute(job, triggerOrigin); execErr != nil {log.Printf("schedule job %s: %v", job.ID, execErr)}@@ -192,7 +195,7 @@ func (s *Service) runJob(id, triggerOrigin string) (domain.ScheduleJob, error) {if err != nil {return job, err}- defer s.release()+ defer s.release(job.ID)return s.execute(job, triggerOrigin)}@@ -207,28 +210,22 @@ func (s *Service) claimJob(id string, dueAt time.Time) (domain.ScheduleJob, erroif !ok {return domain.ScheduleJob{}, fmt.Errorf("schedule job not found")}- if s.runningJob != "" {- if current, ok := s.repo.ScheduleJob(s.runningJob); ok {- return current, ErrAlreadyRunning- }- return job, ErrAlreadyRunning- }- if job.LastStatus == "running" {+ if s.running[id] || job.LastStatus == "running" {return job, ErrAlreadyRunning}if !dueAt.IsZero() {candidate := job- // Cron occurrences during any running job are dropped, not queued.+ // Cron occurrences while this job runs are dropped, not queued.// Use completion as the lower bound without changing LastRunAt,// which continues to describe the actual execution shown in the UI.- if strings.TrimSpace(job.Cron) != "" && s.lastFinishedAt.After(candidate.LastRunAt) {- candidate.LastRunAt = s.lastFinishedAt+ if finished := s.lastFinishedAt[id]; strings.TrimSpace(job.Cron) != "" && finished.After(candidate.LastRunAt) {+ candidate.LastRunAt = finished}if !jobDue(candidate, dueAt) {return job, errNotDue}}- s.runningJob = id+ s.running[id] = truejob.LastRunAt = time.Now().UTC()job.LastStatus = "running"job.LastError = ""@@ -239,10 +236,10 @@ func (s *Service) claimJob(id string, dueAt time.Time) (domain.ScheduleJob, erroreturn s.saveResult(job), nil}-func (s *Service) release() {+func (s *Service) release(id string) {s.mu.Lock()- s.runningJob = ""- s.lastFinishedAt = time.Now().UTC()+ delete(s.running, id)+ s.lastFinishedAt[id] = time.Now().UTC()s.mu.Unlock()}@@ -270,6 +267,8 @@ func (s *Service) execute(job domain.ScheduleJob, triggerOrigin string) (domain.job = s.saveResult(job)return job, nil}+ s.dispatchMu.Lock()+ defer s.dispatchMu.Unlock()matched := s.matchingIssues(job)job.LastPulled = len(matched)eligible := s.eligibleIssues(job, matched)diff --git a/internal/schedule/service_test.go b/internal/schedule/service_test.goindex 7a475569..eed38060 100644--- a/internal/schedule/service_test.go+++ b/internal/schedule/service_test.go@@ -4,6 +4,7 @@ import ("errors""fmt""strings"+ "sync""testing""time"@@ -589,7 +590,9 @@ func TestStartNowReturnsBeforeCompletion(t *testing.T) {}}-func TestStartNowRejectsOverlap(t *testing.T) {+// Loops are long-running AI jobs: one must not block another job, while the+// same job never overlaps itself.+func TestStartNowRunsDifferentJobsConcurrently(t *testing.T) {st, err := repo.OpenTest()if err != nil {t.Fatal(err)@@ -603,47 +606,97 @@ func TestStartNowRejectsOverlap(t *testing.T) {if err := st.PutScheduleJob(second); err != nil {t.Fatal(err)}- started := make(chan struct{})+ started := make(chan string, 2)release := make(chan struct{})svc := New(st, tracker.NewService(), nil)- svc.SetAssistantPrep(func(domain.ScheduleJob) (string, error) {- select {- case <-started:- default:- close(started)- }+ svc.SetAssistantPrep(func(job domain.ScheduleJob) (string, error) {+ started <- job.ID<-releasereturn "ok", nil})if _, err := svc.StartNow(first.ID); err != nil {t.Fatal(err)}- select {- case <-started:- case <-time.After(2 * time.Second):- t.Fatal("first job did not start")+ if _, err := svc.StartNow(second.ID); err != nil {+ t.Fatalf("a running job blocked another job: %v", err)}- got, err := svc.StartNow(second.ID)- if !errors.Is(err, ErrAlreadyRunning) {- t.Fatalf("overlap err=%v job=%+v", err, got)+ seen := map[string]bool{}+ for len(seen) < 2 {+ select {+ case id := <-started:+ seen[id] = true+ case <-time.After(2 * time.Second):+ t.Fatalf("jobs did not run concurrently: %v", seen)+ }}- if got.ID != first.ID || got.LastStatus != "running" {- t.Fatalf("conflict should return the running job: %+v", got)+ got, err := svc.StartNow(first.ID)+ if !errors.Is(err, ErrAlreadyRunning) || got.ID != first.ID || got.LastStatus != "running" {+ t.Fatalf("same job overlap err=%v job=%+v", err, got)}close(release)deadline := time.Now().Add(2 * time.Second)for {- current, _ := st.ScheduleJob(first.ID)- if current.LastStatus == "success" {+ a, _ := st.ScheduleJob(first.ID)+ b, _ := st.ScheduleJob(second.ID)+ if a.LastStatus == "success" && b.LastStatus == "success" {return}if time.Now().After(deadline) {- t.Fatalf("first job did not finish: %+v", current)+ t.Fatalf("jobs did not finish: %+v %+v", a, b)}time.Sleep(20 * time.Millisecond)}}+func TestDispatchIsSerializedAcrossJobs(t *testing.T) {+ st, err := repo.OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(st.Close)+ wf := domain.WorkflowDefinition{ID: "wf", ProjectID: "platform", Name: "wf", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "n", Name: "n", Type: "approval", MaxAttempts: 1}}}+ if err := st.PutWorkflow(wf); err != nil {+ t.Fatal(err)+ }+ if err := st.PutIssue(domain.Issue{ID: "shared-issue", ProjectID: "platform", Title: "t", Status: "todo"}); err != nil {+ t.Fatal(err)+ }+ for _, id := range []string{"trigger-a", "trigger-b"} {+ if err := st.PutScheduleJob(domain.ScheduleJob{ID: id, ProjectID: "platform", Enabled: true, WorkflowID: wf.ID, IssueStatuses: []string{"todo"}}); err != nil {+ t.Fatal(err)+ }+ }+ var mu sync.Mutex+ active, maxActive := 0, 0+ svc := New(st, tracker.NewService(), func(domain.ScheduleJob, domain.Issue, string) error {+ mu.Lock()+ active+++ if active > maxActive {+ maxActive = active+ }+ mu.Unlock()+ time.Sleep(50 * time.Millisecond)+ mu.Lock()+ active--+ mu.Unlock()+ return nil+ })+ var wg sync.WaitGroup+ for _, id := range []string{"trigger-a", "trigger-b"} {+ wg.Add(1)+ go func(id string) {+ defer wg.Done()+ if _, err := svc.RunNow(id); err != nil {+ t.Error(err)+ }+ }(id)+ }+ wg.Wait()+ if maxActive != 1 {+ t.Fatalf("dispatch ran concurrently across jobs: max=%d", maxActive)+ }+}+func TestRecoverInterruptedJobs(t *testing.T) {st, err := repo.OpenTest()if err != nil {@@ -705,17 +758,18 @@ func TestCronDropsOccurrencesDuringRun(t *testing.T) {}}svc := New(st, tracker.NewService(), nil)- svc.lastFinishedAt = finish- for _, id := range []string{job.ID, neverRun.ID} {- for _, now := range []time.Time{finish, start.Add(179 * time.Minute)} {- if _, err := svc.claimJob(id, now); !errors.Is(err, errNotDue) {- t.Fatalf("missed cron must not run: id=%s now=%s err=%v", id, now, err)- }- }- if _, err := svc.claimJob(id, start.Add(180*time.Minute)); err != nil {- t.Fatalf("next cron must run: id=%s err=%v", id, err)+ svc.lastFinishedAt[job.ID] = finish+ for _, now := range []time.Time{finish, start.Add(179 * time.Minute)} {+ if _, err := svc.claimJob(job.ID, now); !errors.Is(err, errNotDue) {+ t.Fatalf("missed cron must not run: now=%s err=%v", now, err)}- svc.runningJob = ""+ }+ if _, err := svc.claimJob(job.ID, start.Add(180*time.Minute)); err != nil {+ t.Fatalf("next cron must run: err=%v", err)+ }+ // Another job's run does not delay a job that never ran.+ if _, err := svc.claimJob(neverRun.ID, finish); err != nil {+ t.Fatalf("other job must not wait for this one: err=%v", err)}got, _ := st.ScheduleJob(job.ID)if got.LastRunAt.Equal(start) {@@ -743,7 +797,7 @@ func TestTimerRunsAsyncAndSkipsOverlap(t *testing.T) {deadline := time.Now().Add(2 * time.Second)for {svc.mu.Lock()- running := svc.runningJob != ""+ running := len(svc.running) > 0svc.mu.Unlock()if !running {breakdiff --git a/migrations/030_generic_docker_shared.sql b/migrations/030_generic_docker_shared.sqlnew file mode 100644index 00000000..4fe532b2--- /dev/null+++ b/migrations/030_generic_docker_shared.sql@@ -0,0 +1,13 @@+-- Manual, idempotent MySQL migration: mark the built-in generic-docker sandbox+-- as shared.+--+-- The public catalog seed stored it without the shared flag, so conversation+-- workspaces (which fall back to generic-docker) and sandbox lists filtered by+-- project could not see it. The application already treats generic-docker as+-- shared when reading; running this only makes the stored value and the UI+-- agree.++UPDATE sandboxes+SET payload = JSON_SET(payload, '$.shared', true)+WHERE id = 'generic-docker'+ AND COALESCE(JSON_EXTRACT(payload, '$.shared'), false) <> true;diff --git a/migrations/seed/001_public_catalog.sql b/migrations/seed/001_public_catalog.sqlindex 2d817ca5..2c429a9e 100644--- a/migrations/seed/001_public_catalog.sql+++ b/migrations/seed/001_public_catalog.sql@@ -3,7 +3,7 @@SET NAMES utf8mb4;START TRANSACTION;INSERT IGNORE INTO sandboxes (`id`,`name`,`payload`) VALUES ('local','本地执行(仅可信任务)','{"id":"local","name":"本地执行(仅可信任务)","driver":"local"}');-INSERT IGNORE INTO sandboxes (`id`,`name`,`payload`) VALUES ('generic-docker','Docker 隔离沙箱','{"id":"generic-docker","name":"Docker 隔离沙箱","driver":"docker","dockerfileId":"generic-backend","readOnlyRootFS":false}');+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 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());