Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(cli): control per-issue PR auto-complete (#10057)
Bohan Jiange7592c57edd4
diff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdxindex 1e34c1360c..df2bc00d85 100644--- a/apps/docs/content/docs/cli.fr.mdx+++ b/apps/docs/content/docs/cli.fr.mdx@@ -143,6 +143,8 @@ multica issue comment add MUL-123 --content-file note.md --steer-activeSi une tâche ouverte portant le même titre (sans tenir compte de la casse ni des espaces en trop) existe déjà sous le même projet et le même parent, `issue create` refuse et indique cette tâche. Pour en créer une autre malgré tout, ajoutez `--allow-duplicate`. Pour marquer une tâche comme doublon d'une autre, utilisez `multica issue status MUL-124 cancelled --duplicate-of MUL-123`.+Pour livrer plusieurs PR successives, utilisez `issue create --title "..." --pr-auto-complete off` ou `issue update <id> --pr-auto-complete off` pour conserver le statut de cette tâche après fusion. `--pr-auto-complete on` rétablit la règle de l'espace de travail au prochain événement PR. `issue pull-requests <id>` affiche le réglage de la tâche, celui de l'espace de travail, le statut cible et la décision, même sans PR liée. Les serveurs compatibles enregistrent le réglage dans la transaction de création ; les anciens reçoivent un PUT supplémentaire. En cas d'échec, le CLI indique l'ID créé et la commande update à réessayer : ne répétez pas create.+### Chronologie`issue get` montre la tâche telle qu'elle est maintenant. `issue timeline` liste dans l'ordre les changements de statut, de priorité, d'assigné, de titre et de dates ainsi que les résultats des exécutions, entremêlés avec les commentaires. C'est la commande pour savoir « quand est-elle passée en in_review » ou « depuis combien de temps est-elle bloquée dans ce statut » :@@ -366,7 +368,7 @@ Les tableaux ci-dessous couvrent toutes les commandes de premier niveau actuelle| --- | --- | --- | --- || `issue` | `list` | Lister les tâches | `--status`, `--priority`, `--assignee`, `--project`, `--updated-since` / `--updated-until` (bornes RFC3339 à fournir ensemble), `--metadata` (répétable), `--property` (répétable, `"Name=Value"` ; `__none__` correspond à une valeur non définie), `--limit`, `--offset`, `--sort` (y compris `property:<name-or-id>`), `--full-id`, `--resolve-properties` (JSON uniquement ; lignes avec les noms de propriété, d'option et de membre à côté des ID enregistrés), `--fields` (JSON uniquement ; champs à conserver, séparés par des virgules) || | `get <id>` | Afficher une tâche | `--resolve-properties` (JSON uniquement ; lignes avec les noms de propriété, d'option et de membre à côté des ID enregistrés) |-| | `create` | Créer une tâche | `--title` (obligatoire), `--description` / `--description-stdin` / `--description-file`, `--status`, `--priority`, `--assignee`, `--parent`, `--stage`, `--project`, `--start-date`, `--due-date`, `--attachment` (répétable), `--property` (répétable), `--allow-duplicate` (crée même si une tâche ouverte porte le même titre) |+| | `create` | Créer une tâche | `--title` (obligatoire), `--description` / `--description-stdin` / `--description-file`, `--pr-auto-complete on/off`, `--status`, `--priority`, `--assignee`, `--parent`, `--stage`, `--project`, `--start-date`, `--due-date`, `--attachment` (répétable), `--property` (répétable), `--allow-duplicate` (crée même si une tâche ouverte porte le même titre) || | `update <id>` | Mettre à jour les champs d'une tâche | Mêmes champs que `create`, plus `--position`, `--no-start`, `--duplicate-of` || | `assign <id>` | Assigner ou désassigner | `--to` (correspondance approximative sur le nom parmi les membres, les agents et les squads), `--to-id`, `--unassign`, `--no-start` || | `status <id> <status>` | Changer le statut | `--no-start`, `--duplicate-of` |diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex 310e2a747f..c8dda9ac8a 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -143,6 +143,8 @@ multica issue comment add MUL-123 --content-file note.md --steer-active同じプロジェクト・同じ親タスクの下に、タイトルが同じ(大文字小文字と余分な空白は区別しない)未完了のタスクがすでにあると、`issue create` は作成を拒否してそのタスクを示します。それでも作る場合は `--allow-duplicate` を付けます。あるタスクを別のタスクの重複にするには `multica issue status MUL-124 cancelled --duplicate-of MUL-123` を使います。+複数の PR を順番に作成するタスクでは、`issue create --title "..." --pr-auto-complete off` または `issue update <id> --pr-auto-complete off` で、マージ時も状態を維持できます。`--pr-auto-complete on` はワークスペースのルールを復元し、次の PR イベントから有効になります。`issue pull-requests <id>` は、PR が未関連付けでもタスクとワークスペースの設定、移行先の状態、判定結果を表示します。対応サーバーは作成トランザクション内で設定を保存し、旧サーバーには追加の PUT を送ります。失敗時は作成済み ID と再試行用の update コマンドが表示されるため、create を繰り返さないでください。+### タイムライン`issue get` はタスクの現在の状態を返します。`issue timeline` はステータス、優先度、担当者、タイトル、日付の変更と実行結果を時系列に並べ、コメントも混ぜて表示します。「いつ in_review に移ったか」「今のステータスにどれだけ留まっているか」を調べるときに使います。@@ -358,7 +360,7 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで| --- | --- | --- | --- || `issue` | `list` | タスクを一覧 | `--status`、`--priority`、`--assignee`、`--project`、`--updated-since` / `--updated-until`(RFC3339 の期間指定、両方必須)、`--metadata`(繰り返し可)、`--property`(繰り返し可、`"名前=値"` または `"Score>=3"`、`"Due<2026-01-01"`、`"Notes~=text"` のような比較;`__none__` は未設定に一致)、`--limit`、`--offset`、`--sort`(`property:<名前または id>` に対応)、`--full-id`、`--resolve-properties`(JSON のみ;保存された id に加えてプロパティ名・選択肢名・メンバー名を返します)、`--fields`(JSON のみ;カンマ区切りで残すフィールドを指定) || | `get <id>` | 単一のタスクを表示 | `--resolve-properties`(JSON のみ;保存された id に加えてプロパティ名・選択肢名・メンバー名を返します) |-| | `create` | タスクを作成 | `--title`(必須)、`--description` / `--description-stdin` / `--description-file`、`--status`、`--priority`、`--assignee`、`--parent`、`--stage`、`--project`、`--start-date`、`--due-date`、`--attachment`(繰り返し可)、`--property`(繰り返し可)、`--allow-duplicate`(同じタイトルの未完了タスクがあっても作成) |+| | `create` | タスクを作成 | `--title`(必須)、`--description` / `--description-stdin` / `--description-file`、`--pr-auto-complete on/off`、`--status`、`--priority`、`--assignee`、`--parent`、`--stage`、`--project`、`--start-date`、`--due-date`、`--attachment`(繰り返し可)、`--property`(繰り返し可)、`--allow-duplicate`(同じタイトルの未完了タスクがあっても作成) || | `update <id>` | タスクのフィールドを更新 | `create` と同系のフィールドに加え `--position`、`--no-start`、`--duplicate-of` || | `assign <id>` | 割り当てまたは割り当て解除 | `--to`(メンバー、エージェント、スクワッドを名前であいまいマッチ)、`--to-id`、`--unassign`、`--no-start` || | `status <id> <status>` | ステータスを変更 | `--no-start`、`--duplicate-of` |diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex a28a944196..337c8e9283 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -143,6 +143,8 @@ multica issue comment add MUL-123 --content-file note.md --steer-active같은 프로젝트, 같은 상위 태스크 아래에 제목이 같은(대소문자와 여분의 공백은 구분하지 않음) 닫히지 않은 태스크가 이미 있으면 `issue create`는 생성을 거부하고 그 태스크를 알려 줍니다. 그래도 만들려면 `--allow-duplicate`를 붙이세요. 한 태스크를 다른 태스크의 중복으로 표시하려면 `multica issue status MUL-124 cancelled --duplicate-of MUL-123`을 실행합니다.+여러 PR을 순서대로 만드는 태스크는 `issue create --title "..." --pr-auto-complete off` 또는 `issue update <id> --pr-auto-complete off`로 병합 후에도 상태를 유지할 수 있습니다. `--pr-auto-complete on`으로 워크스페이스 규칙을 복원하면 다음 PR 이벤트부터 적용됩니다. `issue pull-requests <id>`는 연결된 PR이 없어도 태스크 설정, 워크스페이스 설정, 대상 상태와 판단 결과를 표시합니다. 지원 서버는 생성 트랜잭션 안에서 설정을 저장하고, 이전 서버에는 추가 PUT을 보냅니다. 실패하면 생성된 태스크 ID와 재시도할 update 명령이 표시되므로 create를 반복하지 마세요.+### 타임라인`issue get`은 태스크의 현재 상태를 보여 줍니다. `issue timeline`은 상태, 우선순위, 담당자, 제목, 날짜 변경과 실행 결과를 시간순으로 나열하고 댓글도 섞어 보여 줍니다. "언제 in_review로 바뀌었나", "지금 상태에 얼마나 머물러 있나"를 확인할 때 씁니다.@@ -358,7 +360,7 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t| --- | --- | --- | --- || `issue` | `list` | 태스크 목록 | `--status`, `--priority`, `--assignee`, `--project`, `--updated-since` / `--updated-until`(RFC3339 범위, 함께 지정), `--metadata`(반복 가능), `--property`(반복 가능, `"이름=값"` 또는 `"Score>=3"`, `"Due<2026-01-01"`, `"Notes~=text"` 같은 비교; `__none__`은 미설정과 일치), `--limit`, `--offset`, `--sort`(`property:<이름 또는 id>` 지원), `--full-id`, `--resolve-properties`(JSON 전용; 저장된 id와 함께 속성, 옵션, 멤버 이름을 반환), `--fields`(JSON 전용. 남길 필드를 쉼표로 구분) || | `get <id>` | 태스크 하나 확인 | `--resolve-properties`(JSON 전용; 저장된 id와 함께 속성, 옵션, 멤버 이름을 반환) |-| | `create` | 태스크 생성 | `--title`(필수), `--description` / `--description-stdin` / `--description-file`, `--status`, `--priority`, `--assignee`, `--parent`, `--stage`, `--project`, `--start-date`, `--due-date`, `--attachment`(반복 가능), `--property`(반복 가능), `--allow-duplicate`(같은 제목의 닫히지 않은 태스크가 있어도 생성) |+| | `create` | 태스크 생성 | `--title`(필수), `--description` / `--description-stdin` / `--description-file`, `--pr-auto-complete on/off`, `--status`, `--priority`, `--assignee`, `--parent`, `--stage`, `--project`, `--start-date`, `--due-date`, `--attachment`(반복 가능), `--property`(반복 가능), `--allow-duplicate`(같은 제목의 닫히지 않은 태스크가 있어도 생성) || | `update <id>` | 태스크 필드 업데이트 | `create`와 같은 종류의 필드에 `--position`, `--no-start`, `--duplicate-of` 추가 || | `assign <id>` | 할당 또는 할당 해제 | `--to`(이름으로 멤버, 에이전트, 스쿼드 fuzzy match), `--to-id`, `--unassign`, `--no-start` || | `status <id> <status>` | 상태 변경 | `--no-start`, `--duplicate-of` |diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex 3207bbaa54..893c3e3471 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -143,6 +143,8 @@ multica issue comment add MUL-123 --content-file note.md --steer-activeIf an open issue with the same title (case-insensitive, extra spaces ignored) already exists under the same project and parent, `issue create` refuses and points to that issue. To create another one anyway, add `--allow-duplicate`. To mark an issue as a duplicate of another, run `multica issue status MUL-124 cancelled --duplicate-of MUL-123`.+For sequential PR delivery, use `issue create --title "..." --pr-auto-complete off` or `issue update <id> --pr-auto-complete off` to keep that issue's status when PRs merge. Use `--pr-auto-complete on` to restore the workspace rule; this takes effect at the next PR event. `issue pull-requests <id>` shows the issue override, workspace setting, target status, and decision state, even with no linked PRs. Supported servers save the creation override atomically; older servers receive a follow-up PUT. If that fails, the CLI reports the created issue ID and an update command to retry, so do not repeat the create.+### Timeline`issue get` shows an issue as it is now. `issue timeline` lists, in order, the changes to status, priority, assignee, title, and dates and the run outcomes, interleaved with comments, which answers questions like "when did it move to in_review" or "how long has it been stuck in this status":@@ -388,7 +390,7 @@ Migration from CSV parsing: replace `--attachment a,b` with `--attachment a --at| --- | --- | --- | --- || `issue` | `list` | List issues | `--status`, `--priority`, `--assignee`, `--project`, `--updated-since` / `--updated-until` (paired RFC3339 bounds), `--metadata` (repeatable), `--property` (repeatable, `"Name=Value"` or a comparison such as `"Score>=3"`, `"Due<2026-01-01"`, `"Notes~=text"`; `__none__` matches unset), `--limit`, `--offset`, `--sort` (incl. `property:<name-or-id>`), `--full-id`, `--fields` (JSON only; comma-separated fields to keep), `--resolve-properties` (JSON only; rows with property, option and member names beside the stored ids) || | `get <id>` | Show a single issue | `--resolve-properties` (JSON only; rows with property, option and member names beside the stored ids) |-| | `create` | Create an issue | `--title` (required), `--description` / `--description-stdin` / `--description-file`, `--status`, `--priority`, `--assignee`, `--parent`, `--stage`, `--project`, `--start-date`, `--due-date`, `--attachment` (repeatable), `--property` (repeatable), `--allow-duplicate` (create even when an open issue with the same title exists) |+| | `create` | Create an issue | `--title` (required), `--description` / `--description-stdin` / `--description-file`, `--pr-auto-complete on/off`, `--status`, `--priority`, `--assignee`, `--parent`, `--stage`, `--project`, `--start-date`, `--due-date`, `--attachment` (repeatable), `--property` (repeatable), `--allow-duplicate` (create even when an open issue with the same title exists) || | `update <id>` | Update issue fields | Same fields as `create`, plus `--position`, `--no-start`, `--duplicate-of` || | `assign <id>` | Assign or unassign | `--to` (fuzzy name match against members, agents, and squads), `--to-id`, `--unassign`, `--no-start` || | `status <id> <status>` | Change status | `--no-start`, `--duplicate-of` |diff --git a/apps/docs/content/docs/cli.zh-Hant.mdx b/apps/docs/content/docs/cli.zh-Hant.mdxindex e10ca66b2c..68cec68011 100644--- a/apps/docs/content/docs/cli.zh-Hant.mdx+++ b/apps/docs/content/docs/cli.zh-Hant.mdx@@ -143,6 +143,8 @@ multica issue comment add MUL-123 --content-file note.md --steer-active同一專案、同一父任務下已有標題相同(不區分大小寫,忽略多餘空格)且未關閉的任務時,`issue create` 會拒絕建立並給出那個任務。確實要再建一個,加 `--allow-duplicate`;要把一個任務標為另一個的重複,用 `multica issue status MUL-124 cancelled --duplicate-of MUL-123`。+一個任務要依次提交多個 PR 時,用 `issue create --title "..." --pr-auto-complete off` 或 `issue update <id> --pr-auto-complete off`,讓這個任務在 PR 合併後保持原狀態。用 `--pr-auto-complete on` 恢復工作區規則,從下一次 PR 事件起生效。`issue pull-requests <id>` 會顯示任務開關、工作區開關、目標狀態和判斷結果,沒有關聯 PR 時也會顯示。支援該欄位的伺服器會在建立交易內儲存開關;舊伺服器會補呼叫一次 PUT,失敗時 CLI 會提供已建立的任務 ID 和重試用的 update 命令,請勿重複建立。+### 時間線`issue get` 給出任務現在的狀態;`issue timeline` 按時間順序列出狀態、優先順序、負責人、標題、日期的改動和執行結果,並混排評論,用來回答"什麼時候進入 in_review""卡在當前狀態多久了":@@ -362,7 +364,7 @@ CLI 配置檔案包含可代表你訪問 Multica 的令牌。不要提交到倉| --- | --- | --- | --- || `issue` | `list` | 列出任務 | `--status`、`--priority`、`--assignee`、`--project`、`--metadata`(可重複)、`--property`(可重複,`"名稱=值"` 或 `"Score>=3"`、`"Due<2026-01-01"`、`"Notes~=text"` 這樣的比較;`__none__` 匹配未設定)、`--limit`、`--offset`、`--sort`(支援 `property:<名稱或 id>`)、`--full-id`、`--fields`(僅 JSON;逗號分隔,只輸出這些欄位)、`--resolve-properties`(僅 JSON;在儲存的 id 旁附上屬性、選項和成員名稱) || | `get <id>` | 檢視單個任務 | `--resolve-properties`(僅 JSON;在儲存的 id 旁附上屬性、選項和成員名稱) |-| | `create` | 建立任務 | `--title`(必填)、`--description` / `--description-stdin` / `--description-file`、`--status`、`--priority`、`--assignee`、`--parent`、`--stage`、`--project`、`--start-date`、`--due-date`、`--attachment`(可重複)、`--property`(可重複)、`--allow-duplicate`(已有同名未關閉任務時仍建立) |+| | `create` | 建立任務 | `--title`(必填)、`--description` / `--description-stdin` / `--description-file`、`--pr-auto-complete on/off`、`--status`、`--priority`、`--assignee`、`--parent`、`--stage`、`--project`、`--start-date`、`--due-date`、`--attachment`(可重複)、`--property`(可重複)、`--allow-duplicate`(已有同名未關閉任務時仍建立) || | `update <id>` | 更新任務欄位 | 與 `create` 同類欄位,另有 `--position`、`--no-start`、`--duplicate-of` || | `assign <id>` | 指派或取消指派 | `--to`(名稱模糊匹配成員、AI 代理或小隊)、`--to-id`、`--unassign`、`--no-start` || | `status <id> <status>` | 修改狀態 | `--no-start`、`--duplicate-of` |diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex bb761fe8b3..8e9b8875b0 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -143,6 +143,8 @@ multica issue comment add MUL-123 --content-file note.md --steer-active同一项目、同一父任务下已有标题相同(不区分大小写,忽略多余空格)且未关闭的任务时,`issue create` 会拒绝创建并给出那个任务。确实要再建一个,加 `--allow-duplicate`;要把一个任务标为另一个的重复,用 `multica issue status MUL-124 cancelled --duplicate-of MUL-123`。+一个任务要依次提交多个 PR 时,用 `issue create --title "..." --pr-auto-complete off` 或 `issue update <id> --pr-auto-complete off`,让这个任务在 PR 合并后保持原状态。用 `--pr-auto-complete on` 恢复工作区规则,从下一次 PR 事件起生效。`issue pull-requests <id>` 会显示任务开关、工作区开关、目标状态和判断结果,没有关联 PR 时也会显示。支持该字段的服务端会在创建事务内保存开关;旧服务端会补调一次 PUT,失败时 CLI 会给出已创建的任务 ID 和重试用的 update 命令,请勿重复创建。+### 时间线`issue get` 给出任务现在的状态;`issue timeline` 按时间顺序列出状态、优先级、负责人、标题、日期的改动和运行结果,并混排评论,用来回答"什么时候进入 in_review""卡在当前状态多久了":@@ -365,7 +367,7 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| --- | --- | --- | --- || `issue` | `list` | 列出任务 | `--status`、`--priority`、`--assignee`、`--project`、`--updated-since` / `--updated-until`(配套的 RFC3339 时间范围)、`--metadata`(可重复)、`--property`(可重复,`"名称=值"` 或 `"Score>=3"`、`"Due<2026-01-01"`、`"Notes~=text"` 这样的比较;`__none__` 匹配未设置)、`--limit`、`--offset`、`--sort`(支持 `property:<名称或 id>`)、`--full-id`、`--fields`(仅 JSON;逗号分隔,只输出这些字段)、`--resolve-properties`(仅 JSON;在保存的 id 旁附上属性、选项和成员名称) || | `get <id>` | 查看单个任务 | `--resolve-properties`(仅 JSON;在保存的 id 旁附上属性、选项和成员名称) |-| | `create` | 创建任务 | `--title`(必填)、`--description` / `--description-stdin` / `--description-file`、`--status`、`--priority`、`--assignee`、`--parent`、`--stage`、`--project`、`--start-date`、`--due-date`、`--attachment`(可重复)、`--property`(可重复)、`--allow-duplicate`(已有同名未关闭任务时仍创建) |+| | `create` | 创建任务 | `--title`(必填)、`--description` / `--description-stdin` / `--description-file`、`--pr-auto-complete on/off`、`--status`、`--priority`、`--assignee`、`--parent`、`--stage`、`--project`、`--start-date`、`--due-date`、`--attachment`(可重复)、`--property`(可重复)、`--allow-duplicate`(已有同名未关闭任务时仍创建) || | `update <id>` | 更新任务字段 | 与 `create` 同类字段,另有 `--position`、`--no-start`、`--duplicate-of` || | `assign <id>` | 指派或取消指派 | `--to`(名称模糊匹配成员、智能体或小队)、`--to-id`、`--unassign`、`--no-start` || | `status <id> <status>` | 修改状态 | `--no-start`、`--duplicate-of` |diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex 6c138bc637..509035a12a 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { z } from "zod";import { ApiClient, ApiError } from "./client";import { parseWithFallback } from "./schema";+import { CreateIssueResponseSchema } from "./schemas";// Helper: stub fetch with a single JSON response. Status defaults to 200.function stubFetchJson(body: unknown, status = 200) {@@ -316,6 +317,11 @@ describe("ApiClient schema fallback", () => {expect(issue.labels).toBeUndefined();});+ it.each([true, false, undefined, null, "off"])("validates the create PR override %s without breaking older responses", (value) => {+ const parsed = CreateIssueResponseSchema.parse({ ...validIssue, pr_auto_complete_disabled: value });+ expect(parsed.pr_auto_complete_disabled).toBe(typeof value === "boolean" ? value : undefined);+ });+it("validates a well-formed labels array", async () => {stubFetchJson({ ...validIssue, labels: [label] }, 201);const client = new ApiClient("https://api.example.test");diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 40cf1283a0..6a363a6798 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1547,6 +1547,7 @@ export const ListIssuesResponseSchema = z.object({export const CreateIssueResponseSchema = IssueSchema.extend({id: z.string().min(1),labels: z.array(LabelSchema).optional().catch(undefined),+ pr_auto_complete_disabled: z.boolean().optional().catch(undefined),}).loose();export const EMPTY_LIST_ISSUES_RESPONSE: ListIssuesResponse = {diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex cda593b0e5..e85fd5b305 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -669,6 +669,7 @@ func init() {issueCreateCmd.Flags().Bool("allow-external-file", false, "Allow --description-file / --attachment to read a path outside the current working directory. Off by default so a stale file from another run/environment can't be picked up (MUL-4252).")issueCreateCmd.Flags().String("status", "", "Issue status")issueCreateCmd.Flags().String("priority", "", "Issue priority")+ issueCreateCmd.Flags().String("pr-auto-complete", "", "Change status when linked PRs merge: on or off (saved atomically on supported servers)")issueCreateCmd.Flags().String("assignee", "", "Assignee name (member, agent, or squad; fuzzy match)")issueCreateCmd.Flags().String("assignee-id", "", "Assignee UUID — member, agent, or squad (mutually exclusive with --assignee)")issueCreateCmd.Flags().Bool("assignee-picker", false, "Assign to the agent or squad selected in Quick Create (requires quick-create task context; mutually exclusive with --assignee and --assignee-id)")@@ -692,6 +693,7 @@ func init() {issueUpdateCmd.Flags().StringArray("attachment", nil, "Local file path to attach (one literal path per flag; repeat --attachment for multiple files); references are appended to the end of the description")issueUpdateCmd.Flags().String("status", "", "New status")issueUpdateCmd.Flags().String("priority", "", "New priority")+ issueUpdateCmd.Flags().String("pr-auto-complete", "", "Change status when linked PRs merge: on or off (on takes effect at the next PR event)")issueUpdateCmd.Flags().String("assignee", "", "New assignee name (member, agent, or squad; fuzzy match)")issueUpdateCmd.Flags().String("assignee-id", "", "New assignee UUID — member, agent, or squad (mutually exclusive with --assignee)")issueUpdateCmd.Flags().String("project", "", "Project ID")@@ -1115,6 +1117,9 @@ func runIssuePullRequests(cmd *cobra.Command, args []string) error {prs, _ := result["pull_requests"].([]any)printIssuePullRequestsTable(normalizePullRequestList(prs))+ if autoComplete, ok := result["auto_complete"].(map[string]any); ok {+ printIssuePRAutoComplete(autoComplete)+ }return nil}@@ -1523,6 +1528,10 @@ func pickIssueCreateAssignee(ctx context.Context, client *cli.APIClient, cmd *co}func runIssueCreate(cmd *cobra.Command, _ []string) error {+ prAutoCompleteDisabled, err := issuePRAutoCompleteFlag(cmd)+ if err != nil {+ return err+ }title, _ := cmd.Flags().GetString("title")if title == "" {return fmt.Errorf("--title is required")@@ -1558,6 +1567,9 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {defer cancel()body := map[string]any{"title": title}+ if prAutoCompleteDisabled != nil {+ body["pr_auto_complete_disabled"] = *prAutoCompleteDisabled+ }propertyFlags, _ := cmd.Flags().GetStringArray("property")var createProperties map[string]json.RawMessageif len(propertyFlags) > 0 {@@ -1694,6 +1706,11 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {}return fmt.Errorf("create issue: %w", err)}+ if prAutoCompleteDisabled != nil {+ if err := confirmCreatedIssuePRAutoComplete(ctx, client, result, *prAutoCompleteDisabled); err != nil {+ return err+ }+ }if err := verifyIssueCreateProperties(createProperties, result); err != nil {return fmt.Errorf("issue %s was created, but the server did not confirm its custom properties; review it before retrying: %w", issueDisplayKey(result), err)}@@ -1757,6 +1774,10 @@ func activeDuplicateIssueCreateMessage(err error) (string, bool) {}func runIssueUpdate(cmd *cobra.Command, args []string) error {+ prAutoCompleteDisabled, err := issuePRAutoCompleteFlag(cmd)+ if err != nil {+ return err+ }attachmentPaths, err := issueAttachmentPaths(cmd)if err != nil {return err@@ -1888,7 +1909,7 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {body["position"] = v}- if len(body) == 0 && len(attachmentPaths) == 0 {+ if len(body) == 0 && len(attachmentPaths) == 0 && prAutoCompleteDisabled == nil {return fmt.Errorf("no fields to update; use flags like --title, --status, --priority, --assignee, etc.")}// Validate every path before any upload so an invalid later path cannot@@ -1897,7 +1918,7 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {if err != nil {return err}- if len(body) == 0 && len(pending) == 0 {+ if len(body) == 0 && len(pending) == 0 && prAutoCompleteDisabled == nil {return fmt.Errorf("no local attachments to update; --attachment accepts file paths, not URLs")}desc, changed := body["description"].(string)@@ -1927,22 +1948,39 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {body["description"] = appendAttachmentReferences(desc, attachmentRefs)body["attachment_ids"] = attachmentIDs}- if noStart {+ if noStart && len(body) > 0 {body["suppress_run"] = true}var result map[string]any- if err := client.PutJSON(ctx, "/api/issues/"+issueRef.ID, body, &result); err != nil {- if len(attachmentIDs) > 0 {- return fmt.Errorf("update issue (uploaded IDs: %v): %w", attachmentIDs, err)+ if len(body) > 0 {+ if err := client.PutJSON(ctx, "/api/issues/"+issueRef.ID, body, &result); err != nil {+ if len(attachmentIDs) > 0 {+ return fmt.Errorf("update issue (uploaded IDs: %v): %w", attachmentIDs, err)+ }+ return fmt.Errorf("update issue: %w", err)+ }+ } else {+ // Keep issue update's response shape without issuing an empty update.+ result, err = fetchIssue(ctx, client, issueRef.ID)+ if err != nil {+ return err}- return fmt.Errorf("update issue: %w", err)}if duplicateOf != "" {if _, err := recordedDuplicateOf(result, duplicateOf); err != nil {return err}}+ if prAutoCompleteDisabled != nil {+ if err := setIssuePRAutoComplete(ctx, client, issueRef.ID, *prAutoCompleteDisabled); err != nil {+ if len(body) > 0 {+ return fmt.Errorf("issue %s fields were updated, but PR auto-complete was not confirmed; retry with issue update %s --pr-auto-complete %s: %w", issueRef.ID, issueRef.ID, prAutoCompleteValue(*prAutoCompleteDisabled), err)+ }+ return err+ }+ result["pr_auto_complete_disabled"] = *prAutoCompleteDisabled+ }output, _ := cmd.Flags().GetString("output")if output == "table" {diff --git a/server/cmd/multica/cmd_issue_pr_auto_complete.go b/server/cmd/multica/cmd_issue_pr_auto_complete.gonew file mode 100644index 0000000000..29319bfed6--- /dev/null+++ b/server/cmd/multica/cmd_issue_pr_auto_complete.go@@ -0,0 +1,81 @@+package main++import (+ "context"+ "fmt"+ "net/url"+ "os"++ "github.com/multica-ai/multica/server/internal/cli"+ "github.com/spf13/cobra"+)++func issuePRAutoCompleteFlag(cmd *cobra.Command) (*bool, error) {+ if !cmd.Flags().Changed("pr-auto-complete") {+ return nil, nil+ }+ value, _ := cmd.Flags().GetString("pr-auto-complete")+ if value != "on" && value != "off" {+ return nil, fmt.Errorf("--pr-auto-complete must be on or off")+ }+ disabled := value == "off"+ return &disabled, nil+}++func prAutoCompleteValue(disabled bool) string {+ if disabled {+ return "off"+ }+ return "on"+}++func setIssuePRAutoComplete(ctx context.Context, client *cli.APIClient, issueID string, disabled bool) error {+ var result struct {+ AutoComplete *struct {+ IssueDisabled *bool `json:"issue_disabled"`+ } `json:"auto_complete"`+ }+ if err := client.PutJSON(ctx, "/api/issues/"+url.PathEscape(issueID)+"/pr-auto-complete", map[string]bool{"disabled": disabled}, &result); err != nil {+ return fmt.Errorf("set issue PR auto-complete: %w", err)+ }+ if result.AutoComplete == nil || result.AutoComplete.IssueDisabled == nil || *result.AutoComplete.IssueDisabled != disabled {+ return fmt.Errorf("server did not confirm --pr-auto-complete %s", prAutoCompleteValue(disabled))+ }+ return nil+}++func confirmCreatedIssuePRAutoComplete(ctx context.Context, client *cli.APIClient, issue map[string]any, disabled bool) error {+ confirmed, present := issue["pr_auto_complete_disabled"]+ var err error+ if present {+ if value, ok := confirmed.(bool); !ok || value != disabled {+ err = fmt.Errorf("server did not confirm --pr-auto-complete %s", prAutoCompleteValue(disabled))+ }+ } else {+ // Older servers ignore the create field but may support the existing PUT.+ if id := strVal(issue, "id"); id != "" {+ err = setIssuePRAutoComplete(ctx, client, id, disabled)+ } else {+ err = fmt.Errorf("server returned no created issue ID")+ }+ }+ if err != nil {+ return fmt.Errorf("issue %s (ID: %s) was created, but PR auto-complete was not confirmed; do not repeat issue create; retry with issue update %s --pr-auto-complete %s: %w", issueDisplayKey(issue), strVal(issue, "id"), strVal(issue, "id"), prAutoCompleteValue(disabled), err)+ }+ issue["pr_auto_complete_disabled"] = disabled+ return nil+}++func printIssuePRAutoComplete(autoComplete map[string]any) {+ disabled, ok := autoComplete["issue_disabled"].(bool)+ if !ok {+ return+ }+ workspaceEnabled, ok := autoComplete["workspace_enabled"].(bool)+ if !ok {+ return+ }+ fmt.Fprintf(os.Stdout, "PR auto-complete: %s | Workspace: %s | Target: %s | State: %s\n",+ prAutoCompleteValue(disabled), prAutoCompleteValue(!workspaceEnabled),+ strVal(autoComplete, "target_status"), strVal(autoComplete, "state"))+}diff --git a/server/cmd/multica/cmd_issue_pr_auto_complete_test.go b/server/cmd/multica/cmd_issue_pr_auto_complete_test.gonew file mode 100644index 0000000000..cdd519d3e5--- /dev/null+++ b/server/cmd/multica/cmd_issue_pr_auto_complete_test.go@@ -0,0 +1,218 @@+package main++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "slices"+ "strings"+ "testing"++ "github.com/spf13/cobra"+)++const prAutoCompleteTestIssueID = "11111111-1111-4111-8111-111111111111"++func TestIssuePRAutoCompleteFlagRegistration(t *testing.T) {+ for _, cmd := range []*cobra.Command{issueCreateCmd, issueUpdateCmd} {+ if cmd.Flags().Lookup("pr-auto-complete") == nil {+ t.Fatalf("%s has no --pr-auto-complete flag", cmd.Name())+ }+ }+}++func TestIssuePRAutoCompleteRejectsInvalidValuesBeforeRequest(t *testing.T) {+ for _, value := range []string{"", "true", "false", "ON", "disabled"} {+ t.Run(value, func(t *testing.T) {+ for _, create := range []bool{true, false} {+ cmd := newIssueUpdateTestCmd()+ run := func() error { return runIssueUpdate(cmd, []string{prAutoCompleteTestIssueID}) }+ if create {+ cmd = newIssueCreateTestCmd()+ _ = cmd.Flags().Set("title", "Multi PR work")+ run = func() error { return runIssueCreate(cmd, nil) }+ }+ cmd.Flags().String("pr-auto-complete", "", "")+ _ = cmd.Flags().Set("pr-auto-complete", value)+ if err := run(); err == nil || !strings.Contains(err.Error(), "must be on or off") {+ t.Fatalf("create=%v value=%q: %v", create, value, err)+ }+ }+ })+ }+}++func TestRunIssueUpdatePRAutoComplete(t *testing.T) {+ for _, tc := range []struct {+ name, value, title string+ putStatus int+ wantError string+ }{+ {name: "disable only", value: "off"},+ {name: "enable only", value: "on"},+ {name: "ordinary fields first", value: "off", title: "Updated"},+ {name: "partial failure", value: "off", title: "Updated", putStatus: http.StatusForbidden, wantError: "fields were updated"},+ {name: "unsupported endpoint", value: "on", putStatus: http.StatusNotFound, wantError: "set issue PR auto-complete"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Chdir(t.TempDir())+ var calls []string+ path := "/api/issues/" + prAutoCompleteTestIssueID+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls = append(calls, r.Method+" "+r.URL.Path)+ switch r.URL.Path {+ case path:+ if r.Method == http.MethodPut {+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body["title"] != tc.title || body["suppress_run"] != true || len(body) != 2 {+ t.Errorf("ordinary update body = %v", body)+ }+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"id": prAutoCompleteTestIssueID, "identifier": "MUL-8688", "title": "Multi PR work"})+ case path + "/pr-auto-complete":+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ if r.Method != http.MethodPut || len(body) != 1 || body["disabled"] != (tc.value == "off") {+ t.Errorf("automation request = %s %v", r.Method, body)+ }+ if tc.putStatus != 0 {+ http.Error(w, `{"error":"rejected"}`, tc.putStatus)+ return+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"auto_complete": map[string]any{"issue_disabled": tc.value == "off"}})+ default:+ http.NotFound(w, r)+ }+ }))+ defer srv.Close()+ setCLITestServerEnv(t, srv.URL)+ cmd := newIssueUpdateTestCmd()+ cmd.Flags().String("pr-auto-complete", "", "")+ _ = cmd.Flags().Set("pr-auto-complete", tc.value)+ _ = cmd.Flags().Set("no-start", "true")+ if tc.title != "" {+ _ = cmd.Flags().Set("title", tc.title)+ }+ out, err := captureStdout(t, func() error { return runIssueUpdate(cmd, []string{prAutoCompleteTestIssueID}) })+ if tc.wantError != "" {+ if err == nil || !strings.Contains(err.Error(), tc.wantError) || out != "" {+ t.Fatalf("out=%q err=%v, want %q", out, err, tc.wantError)+ }+ } else {+ var result map[string]any+ if err != nil || json.Unmarshal([]byte(out), &result) != nil || result["id"] != prAutoCompleteTestIssueID || result["pr_auto_complete_disabled"] != (tc.value == "off") {+ t.Fatalf("out=%q err=%v", out, err)+ }+ }+ firstMethod := http.MethodGet+ if tc.title != "" {+ firstMethod = http.MethodPut+ }+ if want := []string{firstMethod + " " + path, "PUT " + path + "/pr-auto-complete"}; !slices.Equal(calls, want) {+ t.Fatalf("calls=%v, want %v", calls, want)+ }+ })+ }+}++func TestRunIssueCreatePRAutoComplete(t *testing.T) {+ for _, tc := range []struct {+ name, value, echo, putResponse string+ putStatus int+ wantError bool+ }{+ {name: "atomic off", value: "off", echo: `,"pr_auto_complete_disabled":true`},+ {name: "atomic on", value: "on", echo: `,"pr_auto_complete_disabled":false`},+ {name: "omitted stays default"},+ {name: "old server fallback off", value: "off", putResponse: `{"auto_complete":{"issue_disabled":true}}`},+ {name: "old server fallback on", value: "on", putResponse: `{"auto_complete":{"issue_disabled":false}}`},+ {name: "fallback fails", value: "off", putStatus: http.StatusNotFound, wantError: true},+ {name: "fallback missing confirmation", value: "off", putResponse: `{}`, wantError: true},+ {name: "fallback wrong confirmation", value: "off", putResponse: `{"auto_complete":{"issue_disabled":false}}`, wantError: true},+ {name: "wrong echo", value: "off", echo: `,"pr_auto_complete_disabled":false`, wantError: true},+ {name: "malformed echo", value: "off", echo: `,"pr_auto_complete_disabled":"off"`, wantError: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Chdir(t.TempDir())+ var calls []string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls = append(calls, r.Method+" "+r.URL.Path)+ switch r.URL.Path {+ case "/api/issues":+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ value, present := body["pr_auto_complete_disabled"]+ if r.Method != http.MethodPost || present != (tc.value != "") || (present && value != (tc.value == "off")) {+ t.Errorf("create request = %s %v", r.Method, body)+ }+ _, _ = w.Write([]byte(`{"id":"` + prAutoCompleteTestIssueID + `","identifier":"MUL-8688","title":"Multi PR work"` + tc.echo + `}`))+ case "/api/issues/" + prAutoCompleteTestIssueID + "/pr-auto-complete":+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ if r.Method != http.MethodPut || body["disabled"] != (tc.value == "off") {+ t.Errorf("fallback request = %s %v", r.Method, body)+ }+ if tc.putStatus != 0 {+ http.Error(w, `{"error":"unsupported"}`, tc.putStatus)+ return+ }+ _, _ = w.Write([]byte(tc.putResponse))+ default:+ http.NotFound(w, r)+ }+ }))+ defer srv.Close()+ setCLITestServerEnv(t, srv.URL)+ cmd := newIssueCreateTestCmd()+ cmd.Flags().String("pr-auto-complete", "", "")+ _ = cmd.Flags().Set("title", "Multi PR work")+ if tc.value != "" {+ _ = cmd.Flags().Set("pr-auto-complete", tc.value)+ }+ out, err := captureStdout(t, func() error { return runIssueCreate(cmd, nil) })+ if tc.wantError {+ if err == nil || !strings.Contains(err.Error(), prAutoCompleteTestIssueID) || !strings.Contains(err.Error(), "do not repeat issue create") || out != "" {+ t.Fatalf("out=%q err=%v; want recoverable partial-create error", out, err)+ }+ } else if err != nil {+ t.Fatal(err)+ }+ want := []string{"POST /api/issues"}+ if tc.value != "" && tc.echo == "" {+ want = append(want, "PUT /api/issues/"+prAutoCompleteTestIssueID+"/pr-auto-complete")+ }+ if !slices.Equal(calls, want) {+ t.Fatalf("calls=%v, want %v", calls, want)+ }+ })+ }+}++func TestRunIssuePullRequestsPRAutoCompleteOutput(t *testing.T) {+ t.Chdir(t.TempDir())+ autoComplete := map[string]any{"issue_disabled": true, "workspace_enabled": false, "state": "workspace_disabled", "target_status": "none"}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _ = json.NewEncoder(w).Encode(map[string]any{"pull_requests": []any{}, "auto_complete": autoComplete})+ }))+ defer srv.Close()+ setCLITestServerEnv(t, srv.URL)+ for _, format := range []string{"table", "json"} {+ cmd := newIssuePullRequestsTestCmd()+ _ = cmd.Flags().Set("output", format)+ out, err := captureStdout(t, func() error { return runIssuePullRequests(cmd, []string{prAutoCompleteTestIssueID}) })+ if err != nil {+ t.Fatal(err)+ }+ if format == "table" {+ if !strings.Contains(out, "PR auto-complete: off | Workspace: off | Target: none | State: workspace_disabled") {+ t.Fatalf("missing automation state with no PRs: %q", out)+ }+ } else {+ var result map[string]any+ if json.Unmarshal([]byte(out), &result) != nil || result["auto_complete"].(map[string]any)["issue_disabled"] != true {+ t.Fatalf("JSON output lost automation: %q", out)+ }+ }+ }+}diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex aaa708241e..a8d3c0b1e8 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -3081,7 +3081,14 @@ type CreateIssueRequest struct {OriginType *string `json:"origin_type,omitempty"`OriginID *string `json:"origin_id,omitempty"`- AllowDuplicate bool `json:"allow_duplicate,omitempty"`+ AllowDuplicate bool `json:"allow_duplicate,omitempty"`+ PRAutoCompleteDisabled bool `json:"pr_auto_complete_disabled,omitempty"`+}++// CreateIssueResponse echoes the atomic PR setting without expanding issue reads.+type CreateIssueResponse struct {+ IssueResponse+ PRAutoCompleteDisabled bool `json:"pr_auto_complete_disabled"`}// UnmarshalJSON rejects duplicate object members before Go's ordinary map@@ -3481,26 +3488,27 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {}res, err := h.IssueService.Create(r.Context(), service.IssueCreateParams{- WorkspaceID: wsUUID,- Title: req.Title,- Description: ptrToText(req.Description),- Status: status,- Priority: priority,- AssigneeType: assigneeType,- AssigneeID: assigneeID,- CreatorType: creatorType,- CreatorID: parseUUID(actualCreatorID),- ParentIssueID: parentIssueID,- ProjectID: projectID,- StartDate: startDate,- DueDate: dueDate,- OriginType: originType,- OriginID: originID,- Stage: ptrToInt4(req.Stage),- AttachmentIDs: attachmentIDs,- LabelIDs: labelIDs,- Properties: properties,- AllowDuplicate: req.AllowDuplicate,+ WorkspaceID: wsUUID,+ Title: req.Title,+ Description: ptrToText(req.Description),+ Status: status,+ Priority: priority,+ AssigneeType: assigneeType,+ AssigneeID: assigneeID,+ CreatorType: creatorType,+ CreatorID: parseUUID(actualCreatorID),+ ParentIssueID: parentIssueID,+ ProjectID: projectID,+ StartDate: startDate,+ DueDate: dueDate,+ OriginType: originType,+ OriginID: originID,+ Stage: ptrToInt4(req.Stage),+ AttachmentIDs: attachmentIDs,+ LabelIDs: labelIDs,+ Properties: properties,+ AllowDuplicate: req.AllowDuplicate,+ PRAutoCompleteDisabled: req.PRAutoCompleteDisabled,}, service.IssueCreateOpts{ActorID: actualCreatorID,AnalyticsAgentID: analyticsAgentID,@@ -3575,7 +3583,10 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {// understood label_ids and skip its legacy post-create attach fallback.labelResponses := labelsToResponse(res.Labels)resp.Labels = &labelResponses- writeJSON(w, http.StatusCreated, resp)+ if req.PRAutoCompleteDisabled {+ h.recordPRAutoCompleteActivity(r.Context(), issue, creatorType, actualCreatorID, true)+ }+ writeJSON(w, http.StatusCreated, CreateIssueResponse{IssueResponse: resp, PRAutoCompleteDisabled: req.PRAutoCompleteDisabled})}type UpdateIssueRequest struct {diff --git a/server/internal/handler/issue_create_pr_auto_complete_test.go b/server/internal/handler/issue_create_pr_auto_complete_test.gonew file mode 100644index 0000000000..f795240d01--- /dev/null+++ b/server/internal/handler/issue_create_pr_auto_complete_test.go@@ -0,0 +1,74 @@+package handler++import (+ "context"+ "fmt"+ "net/http"+ "testing"++ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestCreateIssuePRAutoComplete(t *testing.T) {+ for _, tc := range []struct {+ name string+ value *bool+ disabled bool+ }{+ {name: "default"},+ {name: "on", value: new(false)},+ {name: "off", value: new(true), disabled: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ body := map[string]any{"title": "PR auto-complete create " + tc.name, "status": "in_progress"}+ if tc.value != nil {+ body["pr_auto_complete_disabled"] = *tc.value+ }+ var result map[string]any+ testutil.Call(t, testHandler.CreateIssue, newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, body)).Want(http.StatusCreated).JSON(&result)+ id := result["id"].(string)+ t.Cleanup(func() { deleteTestIssue(t, id) })+ dbfx.Cleanup(t, "DELETE FROM issue_pr_automation WHERE issue_id = $1", id)+ if result["pr_auto_complete_disabled"] != tc.disabled {+ t.Fatalf("create response setting = %v, want %v", result["pr_auto_complete_disabled"], tc.disabled)+ }+ disabled, err := testHandler.Queries.GetIssuePRAutoCompleteDisabled(context.Background(), parseUUID(id))+ if err != nil || disabled != tc.disabled {+ t.Fatalf("stored disabled = %v, err=%v, want %v", disabled, err, tc.disabled)+ }+ var count int+ dbfx.QueryRow(t, `SELECT count(*) FROM activity_log WHERE issue_id = $1 AND action = 'pr_auto_complete_changed' AND actor_type = 'member' AND actor_id = $2 AND details->>'disabled' = 'true'`, id, testUserID).Scan(&count)+ wantCount := 0+ if tc.disabled {+ wantCount = 1+ var actorType, actorID string+ dbfx.QueryRow(t, `SELECT updated_by_type, updated_by_id FROM issue_pr_automation WHERE issue_id = $1 AND workspace_id = $2`, id, testWorkspaceID).Scan(&actorType, &actorID)+ if actorType != "member" || actorID != testUserID {+ t.Fatalf("stored actor = %s:%s", actorType, actorID)+ }+ }+ if count != wantCount {+ t.Fatalf("setting activity count = %d, want %d", count, wantCount)+ }+ var current map[string]any+ req := withURLParam(newRequest("GET", "/api/issues/"+id, nil), "id", id)+ testutil.Call(t, testHandler.GetIssue, req).Want(http.StatusOK).JSON(¤t)+ if _, present := current["pr_auto_complete_disabled"]; present || current["status"] != "in_progress" {+ t.Fatalf("ordinary issue read changed: %v", current)+ }+ })+ }+}++func TestCreateIssueRejectsMalformedPRAutoComplete(t *testing.T) {+ for _, value := range []any{"off", 1, []bool{true}} {+ t.Run(fmt.Sprint(value), func(t *testing.T) {+ title := "invalid PR auto-complete " + fmt.Sprint(value)+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": title, "pr_auto_complete_disabled": value})+ testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusBadRequest)+ if got := countIssuesWithTitle(t, title); got != 0 {+ t.Fatalf("created %d issues for malformed setting", got)+ }+ })+ }+}diff --git a/server/internal/handler/source_context.go b/server/internal/handler/source_context.goindex 104552298c..c94834034f 100644--- a/server/internal/handler/source_context.go+++ b/server/internal/handler/source_context.go@@ -726,6 +726,7 @@ func (h *Handler) createManualCommentSubIssue(w http.ResponseWriter, r *http.ReqParentIssueID: capture.SourceIssueID, ProjectID: projectID, StartDate: startDate, DueDate: dueDate,AttachmentIDs: attachmentIDs, LabelIDs: labelIDs, Properties: properties, Stage: stage,AllowDuplicate: input.AllowDuplicate, SourceContext: &capture,+ PRAutoCompleteDisabled: input.PRAutoCompleteDisabled,}, service.IssueCreateOpts{ActorID: util.UUIDToString(userID),BroadcastPayload: func(issue db.Issue, _ []db.Attachment, labels []db.IssueLabel) map[string]any {@@ -743,7 +744,10 @@ func (h *Handler) createManualCommentSubIssue(w http.ResponseWriter, r *http.ReqlabelResponses := labelsToResponse(result.Labels)response.Labels = &labelResponsesslog.Info("sub-issue created from captured comment", append(sourceContextAuditAttrs(r, capture.ID, capture.Snapshot.SourceIssue.ID, capture.Snapshot.AnchorCommentID, userID, "manual", limits, "success"), "target_issue_id", uuidToString(result.Issue.ID))...)- writeJSON(w, http.StatusCreated, response)+ if input.PRAutoCompleteDisabled {+ h.recordPRAutoCompleteActivity(r.Context(), result.Issue, "member", uuidToString(userID), true)+ }+ writeJSON(w, http.StatusCreated, CreateIssueResponse{IssueResponse: response, PRAutoCompleteDisabled: input.PRAutoCompleteDisabled})return nil}diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.mdindex 0d67b8bcba..328dedbfcc 100644--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md@@ -32,6 +32,16 @@ Related to MUL-123 (body only) # no linkWhile a PR is open, its automatic links follow the live title, branch, andbody: removing the key drops the link. After merge or close, existing links stay.+For one issue delivered through PRs opened one after another, pass+`--pr-auto-complete off` to `issue create` or `issue update <id>` before the+first merge. The override keeps only this issue's status; other issues still+follow the workspace's PR merge rule. Restore it with `--pr-auto-complete on`+before the final PR merges, or leave it off and move the issue to `in_review`+yourself. Turning it on takes effect at the next PR event. Inspect the setting+with `issue pull-requests <id>` (JSON: `auto_complete.issue_disabled`). If an+older server creates the issue but rejects the follow-up override, use the+reported issue ID with `issue update`; do not retry `issue create`.+### Default for code-changing issue workWhen an issue run changes code in a checked-out GitHub repo, the default handoffdiff --git a/server/internal/service/issue.go b/server/internal/service/issue.goindex 63fc76f113..11a2ab8a9c 100644--- a/server/internal/service/issue.go+++ b/server/internal/service/issue.go@@ -89,6 +89,8 @@ type IssueCreateParams struct {// used by the standalone PUT path, then inserts the complete bag atomically.Properties map[pgtype.UUID]json.RawMessageAllowDuplicate bool+ // PRAutoCompleteDisabled is persisted before the issue becomes visible.+ PRAutoCompleteDisabled bool// Stage groups this issue into an ordered barrier group under its parent// (NULL = unstaged). See issue_wakeup_system.go for the staged-barrier wake.Stage pgtype.Int4@@ -428,6 +430,15 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Issreturn IssueCreateResult{}, fmt.Errorf("create issue: %w", err)}+ if p.PRAutoCompleteDisabled {+ if err := qtx.SetIssuePRAutoCompleteDisabled(ctx, db.SetIssuePRAutoCompleteDisabledParams{+ IssueID: issue.ID, WorkspaceID: issue.WorkspaceID, AutoCompleteDisabled: true,+ UpdatedByType: pgtype.Text{String: p.CreatorType, Valid: true}, UpdatedByID: p.CreatorID,+ }); err != nil {+ return IssueCreateResult{}, fmt.Errorf("set issue PR auto-complete: %w", err)+ }+ }+if p.SourceContext != nil {if _, err := PersistSourceContext(ctx, qtx, *p.SourceContext, issue.ID, pgtype.UUID{}); err != nil {return IssueCreateResult{}, fmt.Errorf("persist source context: %w", err)diff --git a/server/internal/service/issue_pr_auto_complete_test.go b/server/internal/service/issue_pr_auto_complete_test.gonew file mode 100644index 0000000000..9b76f3c274--- /dev/null+++ b/server/internal/service/issue_pr_auto_complete_test.go@@ -0,0 +1,65 @@+package service++import (+ "context"+ "errors"+ "testing"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestIssueCreatePRAutoCompleteAtomic(t *testing.T) {+ for _, rollback := range []bool{false, true} {+ name := "commit"+ if rollback {+ name = "rollback"+ }+ t.Run(name, func(t *testing.T) {+ pool := sharedTestPool(t)+ f := testutil.New(pool, "", "")+ userID := f.User(t, "PR automation creator", uuid.NewString()+"@multica.test")+ workspaceID := f.Workspace(t, "PR automation create", "pr-create-"+uuid.NewString())+ f.Cleanup(t, "DELETE FROM issue WHERE workspace_id = $1", workspaceID)+ f.Cleanup(t, "DELETE FROM issue_pr_automation WHERE workspace_id = $1", workspaceID)+ q := db.New(pool)+ bus := events.New()+ published := 0+ bus.Subscribe(protocol.EventIssueCreated, func(e events.Event) {+ published+++ id := e.Payload.(map[string]any)["issue_id"].(string)+ disabled, err := q.GetIssuePRAutoCompleteDisabled(context.Background(), util.MustParseUUID(id))+ if err != nil || !disabled {+ t.Errorf("issue became visible before its override: disabled=%v err=%v", disabled, err)+ }+ })+ var txStarter TxStarter = pool+ injected := errors.New("reject create commit")+ if rollback {+ txStarter = &rejectIssueCommitTxStarter{pool: pool, err: injected}+ }+ svc := NewIssueService(q, txStarter, bus, analytics.NoopClient{}, nil)+ _, err := svc.Create(context.Background(), IssueCreateParams{+ WorkspaceID: util.MustParseUUID(workspaceID), Title: "Sequential PR delivery", Status: "todo", Priority: "none",+ CreatorType: "member", CreatorID: util.MustParseUUID(userID), PRAutoCompleteDisabled: true,+ }, IssueCreateOpts{})+ if rollback && !errors.Is(err, injected) || !rollback && err != nil {+ t.Fatalf("Create: %v", err)+ }+ want := 1+ if rollback {+ want = 0+ }+ issues := f.Count(t, "SELECT count(*) FROM issue WHERE workspace_id = $1", workspaceID)+ overrides := f.Count(t, "SELECT count(*) FROM issue_pr_automation WHERE workspace_id = $1", workspaceID)+ if issues != want || overrides != want || published != want {+ t.Fatalf("issues=%d overrides=%d events=%d, want %d each", issues, overrides, published, want)+ }+ })+ }+}