Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(cli): link and unlink an issue's pull requests (#10593)
xiaoke1234567868859e29beb6
diff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdxindex c16a99ad84..1919940de8 100644--- a/apps/docs/content/docs/cli.fr.mdx+++ b/apps/docs/content/docs/cli.fr.mdx@@ -423,6 +423,8 @@ Les tableaux ci-dessous couvrent toutes les commandes de premier niveau actuelle| | `search <query>` | Rechercher des tâches | `--limit`, `--include-closed`, `--project` || | `children <id>` | Lister les sous-tâches regroupées par étape | || | `pull-requests <id>` | Lister les PR associées | |+| | `pull-requests link <id> <pr-url>` | Associer une PR synchronisée dont le titre et la branche ne contiennent pas la clé de la tâche | Rétablit aussi une PR retirée avec `unlink` |+| | `pull-requests unlink <id> <pr>` | Retirer une PR associée sans qu'elle soit réassociée automatiquement | `<pr>` : URL, numéro ou id de la PR || | `comment list/add/update/delete/resolve/unresolve` | Gérer les commentaires | `add` : `--content` / `--content-stdin` / `--content-file`, `--parent`, `--attachment` ; `update` : `--expected-revision` (obligatoire), `--content` / `--content-stdin` / `--content-file` ; `list` : `--since`, `--thread`, `--tail`, `--recent`, `--roots-only`, `--summary`, `--compact`, `--full` || | `timeline <id>` | Lister l'activité et les commentaires dans l'ordre chronologique | `--action` (répétable), `--activity-only`, `--since`, `--tail` || | `wakeup events/list/get/create/update/disable/trigger/delete/checkin/runs` | Gérer les réveils de tâche ; voir [Réveils de tâche](/issue-wakeups) | `create` / `update` : `--agent-id`, `--kind` (`event`, `at`, `every`, `cron`), `--event`, `--at` / `--after`, `--every`, `--cron`, `--timezone`, conditions `--until-*`, `--expires-in` / `--expires-at`, `--instruction` / `--instruction-file` ; `checkin` : `--note` |diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex dda89c5c26..9a8abd5c7d 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -415,6 +415,8 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで| | `search <query>` | タスクを検索 | `--limit`、`--include-closed`、`--project` || | `children <id>` | サブタスクをステージごとに一覧 | || | `pull-requests <id>` | 関連付けられた PR を一覧 | |+| | `pull-requests link <id> <pr-url>` | タイトルとブランチにタスクキーがない同期済み PR を関連付け | `unlink` で外した PR の復元にも使えます |+| | `pull-requests unlink <id> <pr>` | 関連付けた PR を外し、以後自動で関連付けない | `<pr>` は PR の URL、番号、または id || | `comment list/add/update/delete/resolve/unresolve` | コメントを管理 | `add`: `--content` / `--content-stdin` / `--content-file`、`--parent`、`--attachment`;`update`: `--expected-revision`(必須)、`--content` / `--content-stdin` / `--content-file`;`list`: `--since`、`--thread`、`--tail`、`--recent`、`--roots-only`、`--summary`、`--compact`、`--full` || | `timeline <id>` | アクティビティ記録とコメントを時系列で表示 | `--action`(繰り返し可)、`--activity-only`、`--since`、`--tail` || | `wakeup events/list/get/create/update/disable/trigger/delete/checkin/runs` | タスクのウェイクアップを管理。詳しくは[タスクのウェイクアップ](/issue-wakeups) | `create` / `update`: `--agent-id`、`--kind`(`event`、`at`、`every`、`cron`)、`--event`、`--at` / `--after`、`--every`、`--cron`、`--timezone`、`--until-*` 条件、`--expires-in` / `--expires-at`、`--instruction` / `--instruction-file`;`checkin`: `--note` |diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex 66a3ee0c26..badc3d314e 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -415,6 +415,8 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t| | `search <query>` | 태스크 검색 | `--limit`, `--include-closed`, `--project` || | `children <id>` | 단계별로 묶은 하위 태스크 목록 | || | `pull-requests <id>` | 연결된 PR 목록 | |+| | `pull-requests link <id> <pr-url>` | 제목과 브랜치에 태스크 키가 없는 동기화된 PR 연결 | `unlink`로 제거한 PR 복원에도 사용 |+| | `pull-requests unlink <id> <pr>` | 연결된 PR을 제거하고 이후 자동으로 다시 연결하지 않음 | `<pr>`은 PR URL, 번호 또는 id || | `comment list/add/update/delete/resolve/unresolve` | 댓글 관리 | `add`: `--content` / `--content-stdin` / `--content-file`, `--parent`, `--attachment`. `update`: `--expected-revision`(필수), `--content` / `--content-stdin` / `--content-file`. `list`: `--since`, `--thread`, `--tail`, `--recent`, `--roots-only`, `--summary`, `--compact`, `--full` || | `timeline <id>` | 활동 기록과 댓글을 시간순으로 표시 | `--action`(반복 가능), `--activity-only`, `--since`, `--tail` || | `wakeup events/list/get/create/update/disable/trigger/delete/checkin/runs` | 태스크 깨우기 관리. 자세한 내용은 [태스크 깨우기](/issue-wakeups) | `create` / `update`: `--agent-id`, `--kind`(`event`, `at`, `every`, `cron`), `--event`, `--at` / `--after`, `--every`, `--cron`, `--timezone`, `--until-*` 조건, `--expires-in` / `--expires-at`, `--instruction` / `--instruction-file`. `checkin`: `--note` |diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex 86023ec10c..2240bb3e35 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -446,6 +446,8 @@ Migration from CSV parsing: replace `--attachment a,b` with `--attachment a --at| | `search <query>` | Search issues | `--limit`, `--include-closed`, `--project` || | `children <id>` | List sub-issues grouped by stage | || | `pull-requests <id>` | List linked PRs | |+| | `pull-requests link <id> <pr-url>` | Link a synced PR whose title and branch lack the issue key | Also restores a PR removed with `unlink` |+| | `pull-requests unlink <id> <pr>` | Remove a linked PR and keep it removed | `<pr>` is the PR URL, its number, or its id || | `comment list/add/update/delete/resolve/unresolve` | Manage comments | `add`: `--content` / `--content-stdin` / `--content-file`, `--parent`, `--attachment`; `update`: `--expected-revision` (required), `--content` / `--content-stdin` / `--content-file`; `list`: `--since`, `--thread`, `--tail`, `--recent`, `--roots-only`, `--summary`, `--compact`, `--full` || | `timeline <id>` | List activity records and comments in time order | `--action` (repeatable), `--activity-only`, `--since`, `--tail` || | `wakeup events/list/get/create/update/disable/trigger/delete/checkin/runs` | Manage issue wakeups; see [Issue wakeups](/issue-wakeups) | `create` / `update`: `--agent-id`, `--kind` (`event`, `at`, `every`, `cron`), `--event`, `--at` / `--after`, `--every`, `--cron`, `--timezone`, `--until-*` conditions, `--expires-in` / `--expires-at`, `--instruction` / `--instruction-file`; `checkin`: `--note` |diff --git a/apps/docs/content/docs/cli.zh-Hant.mdx b/apps/docs/content/docs/cli.zh-Hant.mdxindex f265a9926b..932fbb772d 100644--- a/apps/docs/content/docs/cli.zh-Hant.mdx+++ b/apps/docs/content/docs/cli.zh-Hant.mdx@@ -420,6 +420,8 @@ CLI 配置檔案包含可代表你訪問 Multica 的令牌。不要提交到倉| | `search <query>` | 搜尋任務 | `--limit`、`--include-closed`、`--project` || | `children <id>` | 按階段分組列出子任務 | || | `pull-requests <id>` | 列出關聯的 PR | |+| | `pull-requests link <id> <pr-url>` | 關聯一個已同步、但標題和分支裡沒有任務編號的 PR | 也能恢復用 `unlink` 移除的 PR |+| | `pull-requests unlink <id> <pr>` | 移除關聯的 PR,之後不會再自動關聯 | `<pr>` 可以是 PR 連結、編號或 id || | `comment list/add/update/delete/resolve/unresolve` | 管理評論 | `add`:`--content` / `--content-stdin` / `--content-file`、`--parent`、`--attachment`;`update`:`--expected-revision`(必填)、`--content` / `--content-stdin` / `--content-file`;`list`:`--since`、`--thread`、`--tail`、`--recent`、`--roots-only`、`--summary`、`--compact`、`--full` || | `timeline <id>` | 按時間列出活動記錄和評論 | `--action`(可重複)、`--activity-only`、`--since`、`--tail` || | `wakeup events/list/get/create/update/disable/trigger/delete/checkin/runs` | 管理任務喚醒,詳見[任務喚醒](/issue-wakeups) | `create` / `update`:`--agent-id`、`--kind`(`event`、`at`、`every`、`cron`)、`--event`、`--at` / `--after`、`--every`、`--cron`、`--timezone`、`--until-*` 條件、`--expires-in` / `--expires-at`、`--instruction` / `--instruction-file`;`checkin`:`--note` |diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex 78b0e36d96..6301540edb 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -423,6 +423,8 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| | `search <query>` | 搜索任务 | `--limit`、`--include-closed`、`--project` || | `children <id>` | 按阶段分组列出子任务 | || | `pull-requests <id>` | 列出关联的 PR | |+| | `pull-requests link <id> <pr-url>` | 关联一个已同步、但标题和分支里没有任务编号的 PR | 也能恢复用 `unlink` 移除的 PR |+| | `pull-requests unlink <id> <pr>` | 移除关联的 PR,之后不会再自动关联 | `<pr>` 可以是 PR 链接、编号或 id || | `comment list/add/update/delete/resolve/unresolve` | 管理评论 | `add`:`--content` / `--content-stdin` / `--content-file`、`--parent`、`--attachment`;`update`:`--expected-revision`(必填)、`--content` / `--content-stdin` / `--content-file`;`list`:`--since`、`--thread`、`--tail`、`--recent`、`--roots-only`、`--summary`、`--compact`、`--full` || | `timeline <id>` | 按时间列出活动记录和评论 | `--action`(可重复)、`--activity-only`、`--since`、`--tail` || | `wakeup events/list/get/create/update/disable/trigger/delete/checkin/runs` | 管理任务唤醒,详见[任务唤醒](/issue-wakeups) | `create` / `update`:`--agent-id`、`--kind`(`event`、`at`、`every`、`cron`)、`--event`、`--at` / `--after`、`--every`、`--cron`、`--timezone`、`--until-*` 条件、`--expires-in` / `--expires-at`、`--instruction` / `--instruction-file`;`checkin`:`--note` |diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex 750b570cdd..30aac22531 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -259,6 +259,26 @@ var issuePullRequestsCmd = &cobra.Command{RunE: runIssuePullRequests,}+var issuePullRequestsLinkCmd = &cobra.Command{+ Use: "link <issue> <pr-url>",+ Short: "Link a pull request to an issue",+ Long: `Link a pull request to an issue by its URL, for a PR whose title or branch+does not mention the issue key. The PR must already be synced from a connected+repository. Linking also undoes an earlier unlink of the same PR.`,+ Args: exactArgs(2),+ RunE: runIssuePullRequestsLink,+}++var issuePullRequestsUnlinkCmd = &cobra.Command{+ Use: "unlink <issue> <pr>",+ Short: "Unlink a pull request from an issue",+ Long: `Remove a pull request from an issue. <pr> is the PR's URL, its number (42 or #42),+or its id from "multica issue pull-requests <issue> --output json". The choice is+remembered, so later activity on the PR does not link it again; "link" restores it.`,+ Args: exactArgs(2),+ RunE: runIssuePullRequestsUnlink,+}+var issueChildrenCmd = &cobra.Command{Use: "children <id>",Aliases: []string{"subissues"},@@ -658,6 +678,10 @@ func init() {// issue pull-requestsissuePullRequestsCmd.Flags().String("output", "table", "Output format: table or json")+ issuePullRequestsCmd.AddCommand(issuePullRequestsLinkCmd)+ issuePullRequestsCmd.AddCommand(issuePullRequestsUnlinkCmd)+ issuePullRequestsLinkCmd.Flags().String("output", "table", "Output format: table or json")+ issuePullRequestsUnlinkCmd.Flags().String("output", "table", "Output format: table or json")issueChildrenCmd.Flags().String("output", "table", "Output format: table or json")issueChildrenCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")@@ -1113,10 +1137,19 @@ func runIssuePullRequests(cmd *cobra.Command, args []string) error {}var result map[string]any- if err := client.GetJSON(ctx, "/api/issues/"+url.PathEscape(issueRef.ID)+"/pull-requests", &result); err != nil {+ if err := client.GetJSON(ctx, issuePullRequestsPath(issueRef.ID), &result); err != nil {return fmt.Errorf("list issue pull requests: %w", err)}+ return printIssuePullRequestsResult(cmd, result)+}++func issuePullRequestsPath(issueID string) string {+ return "/api/issues/" + url.PathEscape(issueID) + "/pull-requests"+}+// printIssuePullRequestsResult prints the issue's pull request list, which is+// also what link and unlink return, so every subcommand shows the result.+func printIssuePullRequestsResult(cmd *cobra.Command, result map[string]any) error {output, _ := cmd.Flags().GetString("output")if output == "json" {return cli.PrintJSON(os.Stdout, result)@@ -1130,6 +1163,151 @@ func runIssuePullRequests(cmd *cobra.Command, args []string) error {return nil}+func runIssuePullRequestsLink(cmd *cobra.Command, args []string) error {+ ref := strings.TrimSpace(args[1])+ if ref == "" {+ return fmt.Errorf("pull request URL is required")+ }+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ issueRef, err := resolveIssueRef(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve issue: %w", err)+ }++ // The endpoint also accepts the id of a PR this workspace mirrors, which+ // is how an unlinked PR (still listed by its id) is restored.+ body := map[string]string{"url": ref}+ if uuidRegexp.MatchString(ref) {+ body = map[string]string{"pull_request_id": strings.ToLower(ref)}+ }+ var result map[string]any+ if err := client.PostJSON(ctx, issuePullRequestsPath(issueRef.ID), body, &result); err != nil {+ if isUnsyncedPullRequestError(err) {+ // The generic not-found message would send the user hunting for a+ // wrong ID; the PR is simply not mirrored here yet.+ return fmt.Errorf("pull request %s is not in this workspace yet: it can be linked once its repository is connected to Multica and the PR has synced", ref)+ }+ return fmt.Errorf("link pull request: %w", err)+ }+ return printIssuePullRequestsResult(cmd, result)+}++func runIssuePullRequestsUnlink(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ issueRef, err := resolveIssueRef(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve issue: %w", err)+ }++ // The endpoint takes the PR's id; find it among the issue's linked PRs so+ // a URL or number works too.+ var listed map[string]any+ if err := client.GetJSON(ctx, issuePullRequestsPath(issueRef.ID), &listed); err != nil {+ return fmt.Errorf("list issue pull requests: %w", err)+ }+ prs, _ := listed["pull_requests"].([]any)+ prID, err := matchLinkedPullRequest(normalizePullRequestList(prs), args[1])+ if err != nil {+ return fmt.Errorf("%w; see \"multica issue pull-requests %s\"", err, args[0])+ }++ var result map[string]any+ if err := client.DeleteJSONResponse(ctx, issuePullRequestsPath(issueRef.ID)+"/"+url.PathEscape(prID), &result); err != nil {+ return fmt.Errorf("unlink pull request: %w", err)+ }+ return printIssuePullRequestsResult(cmd, result)+}++func isUnsyncedPullRequestError(err error) bool {+ var httpErr *cli.HTTPError+ return errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusNotFound &&+ strings.Contains(httpErr.Body, "pull request not found")+}++// matchLinkedPullRequest finds the id of the linked PR that ref names: its id,+// its URL (any trailing /files, query or fragment ignored), or its number. A+// number shared by PRs from different repositories is ambiguous.+func matchLinkedPullRequest(prs []map[string]any, ref string) (string, error) {+ ref = strings.TrimSpace(ref)+ if ref == "" {+ return "", fmt.Errorf("pull request is required")+ }+ if uuidRegexp.MatchString(ref) {+ for _, pr := range prs {+ if strings.EqualFold(strVal(pr, "id"), ref) {+ return strVal(pr, "id"), nil+ }+ }+ return "", fmt.Errorf("pull request %s is not linked to this issue", ref)+ }+ if number := strings.TrimPrefix(ref, "#"); isAllDigits(number) {+ var matches []map[string]any+ for _, pr := range prs {+ if strVal(pr, "number") == number {+ matches = append(matches, pr)+ }+ }+ switch len(matches) {+ case 1:+ return strVal(matches[0], "id"), nil+ case 0:+ return "", fmt.Errorf("no linked pull request has number %s", number)+ default:+ urls := make([]string, 0, len(matches))+ for _, pr := range matches {+ urls = append(urls, pullRequestURL(pr))+ }+ return "", fmt.Errorf("pull request number %s matches %d linked PRs (%s); pass its URL instead", number, len(matches), strings.Join(urls, ", "))+ }+ }+ want := canonicalPullRequestURL(ref)+ for _, pr := range prs {+ if want != "" && canonicalPullRequestURL(pullRequestURL(pr)) == want {+ return strVal(pr, "id"), nil+ }+ }+ return "", fmt.Errorf("pull request %s is not linked to this issue", ref)+}++var pullRequestURLPathPattern = regexp.MustCompile(`^(.+?/(?:pull|pulls|merge_requests)/\d+)(?:[/?#].*)?$`)++// canonicalPullRequestURL reduces a PR URL to host and path up to the PR+// number, lowercased, so a pasted ".../pull/42/files" matches the stored URL.+func canonicalPullRequestURL(raw string) string {+ raw = strings.ToLower(strings.TrimSpace(raw))+ raw = strings.TrimPrefix(strings.TrimPrefix(raw, "https://"), "http://")+ if m := pullRequestURLPathPattern.FindStringSubmatch(raw); m != nil {+ return m[1]+ }+ return strings.TrimRight(raw, "/")+}++func isAllDigits(s string) bool {+ if s == "" {+ return false+ }+ for _, r := range s {+ if r < '0' || r > '9' {+ return false+ }+ }+ return true+}+func normalizePullRequestList(raw []any) []map[string]any {prs := make([]map[string]any, 0, len(raw))for _, item := range raw {diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.goindex 28c5f024ed..820213c3b4 100644--- a/server/cmd/multica/cmd_issue_test.go+++ b/server/cmd/multica/cmd_issue_test.go@@ -6265,3 +6265,154 @@ func TestIssueSearchCommandRegistration(t *testing.T) {t.Errorf("project flag usage = %q, want %q", got, "Filter by project ID")}}++// issuePullRequestServer serves one issue's linked PRs and records the link and+// unlink calls the CLI makes against it.+type issuePullRequestServer struct {+ linkBody map[string]any+ unlinkPath string+}++func (s *issuePullRequestServer) start(t *testing.T) {+ t.Helper()+ listed := map[string]any{+ "pull_requests": []map[string]any{+ {"id": "11111111-1111-1111-1111-111111111111", "number": float64(42), "state": "open", "title": "Fix the thing", "html_url": "https://github.com/acme/app/pull/42"},+ {"id": "22222222-2222-2222-2222-222222222222", "number": float64(7), "state": "merged", "title": "API side", "html_url": "https://github.com/acme/api/pull/7"},+ {"id": "33333333-3333-3333-3333-333333333333", "number": float64(7), "state": "open", "title": "Web side", "html_url": "https://github.com/acme/web/pull/7"},+ },+ }+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.URL.Path == "/api/issues/MUL-9" && r.Method == http.MethodGet:+ json.NewEncoder(w).Encode(map[string]any{"id": "issue-uuid", "identifier": "MUL-9"})+ case r.URL.Path == "/api/issues/issue-uuid/pull-requests" && r.Method == http.MethodGet:+ json.NewEncoder(w).Encode(listed)+ case r.URL.Path == "/api/issues/issue-uuid/pull-requests" && r.Method == http.MethodPost:+ _ = json.NewDecoder(r.Body).Decode(&s.linkBody)+ if strings.Contains(fmt.Sprint(s.linkBody["url"]), "/pull/999") {+ w.WriteHeader(http.StatusNotFound)+ json.NewEncoder(w).Encode(map[string]any{"error": "pull request not found; it appears here once its repository is connected and the PR has been synced"})+ return+ }+ json.NewEncoder(w).Encode(listed)+ case strings.HasPrefix(r.URL.Path, "/api/issues/issue-uuid/pull-requests/") && r.Method == http.MethodDelete:+ s.unlinkPath = r.URL.Path+ json.NewEncoder(w).Encode(listed)+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(srv.Close)+ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")+}++func runQuiet(t *testing.T, run func() error) (string, error) {+ t.Helper()+ old := os.Stdout+ r, w, _ := os.Pipe()+ os.Stdout = w+ drainCh := make(chan []byte, 1)+ go func() { b, _ := io.ReadAll(r); drainCh <- b }()+ err := run()+ _ = w.Close()+ os.Stdout = old+ return string(<-drainCh), err+}++func TestRunIssuePullRequestsLinkPostsURL(t *testing.T) {+ s := &issuePullRequestServer{}+ s.start(t)++ out, err := runQuiet(t, func() error {+ return runIssuePullRequestsLink(newIssuePullRequestsTestCmd(), []string{"MUL-9", "https://github.com/acme/app/pull/42/files"})+ })+ if err != nil {+ t.Fatalf("link: %v", err)+ }+ // The server normalizes the URL; the CLI passes it through untouched.+ if s.linkBody["url"] != "https://github.com/acme/app/pull/42/files" || s.linkBody["pull_request_id"] != nil {+ t.Fatalf("link body = %#v", s.linkBody)+ }+ if !strings.Contains(out, "https://github.com/acme/app/pull/42") {+ t.Fatalf("expected the updated PR list in the output:\n%s", out)+ }+}++func TestRunIssuePullRequestsLinkByIDRestoresUnlinkedPR(t *testing.T) {+ s := &issuePullRequestServer{}+ s.start(t)++ if _, err := runQuiet(t, func() error {+ return runIssuePullRequestsLink(newIssuePullRequestsTestCmd(), []string{"MUL-9", "22222222-2222-2222-2222-222222222222"})+ }); err != nil {+ t.Fatalf("link: %v", err)+ }+ if s.linkBody["pull_request_id"] != "22222222-2222-2222-2222-222222222222" || s.linkBody["url"] != nil {+ t.Fatalf("link body = %#v", s.linkBody)+ }+}++func TestRunIssuePullRequestsUnlinkResolvesPR(t *testing.T) {+ cases := []struct {+ name, ref, wantID string+ }{+ {"by URL with a trailing page", "https://github.com/acme/app/pull/42/files?w=1", "11111111-1111-1111-1111-111111111111"},+ {"by URL without a scheme, any case", "GitHub.com/acme/web/pull/7", "33333333-3333-3333-3333-333333333333"},+ {"by unique number", "#42", "11111111-1111-1111-1111-111111111111"},+ {"by id", "22222222-2222-2222-2222-222222222222", "22222222-2222-2222-2222-222222222222"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ s := &issuePullRequestServer{}+ s.start(t)+ if _, err := runQuiet(t, func() error {+ return runIssuePullRequestsUnlink(newIssuePullRequestsTestCmd(), []string{"MUL-9", tc.ref})+ }); err != nil {+ t.Fatalf("unlink: %v", err)+ }+ if want := "/api/issues/issue-uuid/pull-requests/" + tc.wantID; s.unlinkPath != want {+ t.Fatalf("DELETE %s, want %s", s.unlinkPath, want)+ }+ })+ }+}++func TestRunIssuePullRequestsUnlinkRefusesAmbiguousOrUnknownPR(t *testing.T) {+ cases := []struct {+ name, ref, wantErr string+ }{+ {"number shared by two repos", "7", "matches 2 linked PRs"},+ {"number not linked", "99", "no linked pull request has number 99"},+ {"URL not linked", "https://github.com/acme/app/pull/43", "is not linked to this issue"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ s := &issuePullRequestServer{}+ s.start(t)+ _, err := runQuiet(t, func() error {+ return runIssuePullRequestsUnlink(newIssuePullRequestsTestCmd(), []string{"MUL-9", tc.ref})+ })+ if err == nil || !strings.Contains(err.Error(), tc.wantErr) {+ t.Fatalf("err = %v, want it to mention %q", err, tc.wantErr)+ }+ if s.unlinkPath != "" {+ t.Fatalf("expected no DELETE, got %s", s.unlinkPath)+ }+ })+ }+}++func TestRunIssuePullRequestsLinkExplainsUnsyncedPR(t *testing.T) {+ s := &issuePullRequestServer{}+ s.start(t)++ _, err := runQuiet(t, func() error {+ return runIssuePullRequestsLink(newIssuePullRequestsTestCmd(), []string{"MUL-9", "https://github.com/acme/app/pull/999"})+ })+ if err == nil || !strings.Contains(err.Error(), "not in this workspace yet") {+ t.Fatalf("err = %v, want the not-synced explanation", err)+ }+}diff --git a/server/cmd/multica/help.go b/server/cmd/multica/help.goindex 5463018af2..647787186e 100644--- a/server/cmd/multica/help.go+++ b/server/cmd/multica/help.go@@ -151,6 +151,9 @@ LEARN MOREvar subHelpTemplate = `{{.Short}}USAGE+{{- if .Runnable}}+ {{.UseLine}}+{{- end}}{{.CommandPath}} <command> [flags]COMMANDSdiff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.mdindex 55cd9671ab..19c985f62c 100644--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md@@ -105,8 +105,10 @@ a draft?" is `state == "draft"`; coarse CI status is `checks_conclusion`.If the command returns no linked PRs after a PR was opened, check the syntaxfirst: the key must be in the PR title or branch, or right after a closingkeyword in the body — a bare body mention does not count. When the syntax is the-problem, editing the title re-runs the scan. If a person removed-the PR from the issue, it stays removed until someone links it again.+problem, editing the title re-runs the scan. Otherwise link the synced PR with+`multica issue pull-requests link <issue-id> <pr-url>`; that also restores a PR+someone removed (removed PRs stay off until relinked). `unlink <issue-id> <pr>`+(URL, number, or id) removes one and keeps it removed.If the key is already written correctly and the list is still empty, stop editingthe PR blind: another no-op edit cannot fix an integration that never received the