Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(cli): add run-targeted retries with a fresh option (#9592)

Bohan Jiangd7d1831fcf39
diff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdx
index 27d95963f3..a8aae78610 100644
--- a/apps/docs/content/docs/cli.fr.mdx
+++ b/apps/docs/content/docs/cli.fr.mdx
@@ -125,11 +125,13 @@ multica issue comment add MUL-123 --content-stdin < review.md
multica issue comment update <comment-id> --expected-revision 2 --content-file revised-review.md
```
-Afficher les messages d'une exécution, ou l'arrêter :
+Consulter, arrêter ou relancer une exécution :
```bash
multica issue run-messages <task-id> --issue MUL-123
multica issue cancel-task <task-id> --issue MUL-123
+multica issue rerun-task <run-id> --issue MUL-123
+multica issue rerun-task <run-id> --issue MUL-123 --fresh
```
Si 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`.
@@ -365,7 +367,7 @@ Les tableaux ci-dessous couvrent toutes les commandes de premier niveau actuelle
| | `runs <issue-id>` | Afficher l'historique des exécutions | `--full-id` |
| | `run-messages <task-id>` | Afficher les messages d'une exécution | `--since`, `--issue` |
| | `usage <issue-id>` | Afficher la consommation de tokens agrégée | |
-| | `rerun <id>` | Remettre en file une exécution pour l'assigné actuel | |
+| | `rerun-task <run-id>` | Relancer une exécution précise avec son agent et son contexte de déclenchement d’origine | `--issue`, `--fresh` |
| | `cancel-task <task-id>` | Annuler une exécution en cours ou en file d'attente | `--issue` |
| `project` | `list/get/create/update/delete` | Gérer les projets | `create` : `--title` (obligatoire), `--lead`, `--status`, `--icon`, `--start-date`, `--due-date`, `--repo` (répétable) |
| | `status <id> <status>` | Changer le statut d'un projet | |
diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdx
index ee870df55b..58d1da5c3a 100644
--- a/apps/docs/content/docs/cli.ja.mdx
+++ b/apps/docs/content/docs/cli.ja.mdx
@@ -125,11 +125,13 @@ multica issue comment add MUL-123 --content-stdin < review.md
multica issue comment update <comment-id> --expected-revision 2 --content-file revised-review.md
```
-1 回の実行のメッセージを表示する、または実行を停止する:
+1 回の実行のメッセージを表示、実行を停止、または再試行する:
```bash
multica issue run-messages <task-id> --issue MUL-123
multica issue cancel-task <task-id> --issue MUL-123
+multica issue rerun-task <run-id> --issue MUL-123
+multica issue rerun-task <run-id> --issue MUL-123 --fresh
```
同じプロジェクト・同じ親タスクの下に、タイトルが同じ(大文字小文字と余分な空白は区別しない)未完了のタスクがすでにあると、`issue create` は作成を拒否してそのタスクを示します。それでも作る場合は `--allow-duplicate` を付けます。あるタスクを別のタスクの重複にするには `multica issue status MUL-124 cancelled --duplicate-of MUL-123` を使います。
@@ -357,7 +359,7 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで
| | `runs <issue-id>` | 実行履歴を表示 | `--full-id` |
| | `run-messages <task-id>` | 1 回の実行のメッセージを表示 | `--since`、`--issue` |
| | `usage <issue-id>` | 集計されたトークン使用量を表示 | |
-| | `rerun <id>` | 現在の担当者で実行を再キューイング | |
+| | `rerun-task <run-id>` | 元のエージェントとトリガーのコンテキストで指定した実行を再試行 | `--issue`, `--fresh` |
| | `cancel-task <task-id>` | 進行中またはキュー中の実行をキャンセル | `--issue` |
| `project` | `list/get/create/update/delete` | プロジェクトを管理 | `create`: `--title`(必須)、`--lead`、`--status`、`--icon`、`--start-date`、`--due-date`、`--repo`(繰り返し可) |
| | `status <id> <status>` | プロジェクトのステータスを変更 | |
diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdx
index 213f678694..d218afadfb 100644
--- a/apps/docs/content/docs/cli.ko.mdx
+++ b/apps/docs/content/docs/cli.ko.mdx
@@ -125,11 +125,13 @@ multica issue comment add MUL-123 --content-stdin < review.md
multica issue comment update <comment-id> --expected-revision 2 --content-file revised-review.md
```
-특정 실행의 메시지를 확인하거나 실행을 중지합니다.
+특정 실행의 메시지를 확인하거나 실행을 중지 또는 재시도합니다.
```bash
multica issue run-messages <task-id> --issue MUL-123
multica issue cancel-task <task-id> --issue MUL-123
+multica issue rerun-task <run-id> --issue MUL-123
+multica issue rerun-task <run-id> --issue MUL-123 --fresh
```
같은 프로젝트, 같은 상위 태스크 아래에 제목이 같은(대소문자와 여분의 공백은 구분하지 않음) 닫히지 않은 태스크가 이미 있으면 `issue create`는 생성을 거부하고 그 태스크를 알려 줍니다. 그래도 만들려면 `--allow-duplicate`를 붙이세요. 한 태스크를 다른 태스크의 중복으로 표시하려면 `multica issue status MUL-124 cancelled --duplicate-of MUL-123`을 실행합니다.
@@ -357,7 +359,7 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t
| | `runs <issue-id>` | 실행 기록 확인 | `--full-id` |
| | `run-messages <task-id>` | 단일 실행 메시지 확인 | `--since`, `--issue` |
| | `usage <issue-id>` | 집계 token 사용량 확인 | |
-| | `rerun <id>` | 현재 할당을 기준으로 다시 큐에 넣어 실행 | |
+| | `rerun-task <run-id>` | 원래 에이전트와 트리거 컨텍스트로 지정한 실행을 재시도 | `--issue`, `--fresh` |
| | `cancel-task <task-id>` | 진행 중 또는 큐 대기 중인 실행 취소 | `--issue` |
| `project` | `list/get/create/update/delete` | 프로젝트 관리 | `create`: `--title`(필수), `--lead`, `--status`, `--icon`, `--start-date`, `--due-date`, `--repo`(반복 가능) |
| | `status <id> <status>` | 프로젝트 상태 변경 | |
diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdx
index eeca48be33..f7f3517844 100644
--- a/apps/docs/content/docs/cli.mdx
+++ b/apps/docs/content/docs/cli.mdx
@@ -125,11 +125,13 @@ multica issue comment add MUL-123 --content-stdin < review.md
multica issue comment update <comment-id> --expected-revision 2 --content-file revised-review.md
```
-View the messages of a single run, or stop one:
+Inspect, stop, or retry a single run:
```bash
multica issue run-messages <task-id> --issue MUL-123
multica issue cancel-task <task-id> --issue MUL-123
+multica issue rerun-task <run-id> --issue MUL-123
+multica issue rerun-task <run-id> --issue MUL-123 --fresh
```
If 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`.
@@ -380,7 +382,7 @@ The tables below cover every current top-level command, grouped the way the CLI
| | `runs <issue-id>` | View run history | `--full-id` |
| | `run-messages <task-id>` | View the messages of a single run | `--since`, `--issue` |
| | `usage <issue-id>` | View aggregated token usage | |
-| | `rerun <id>` | Re-enqueue a run for the current assignee | |
+| | `rerun-task <run-id>` | Repeat a specific run with its original agent and trigger context | `--issue`, `--fresh` |
| | `cancel-task <task-id>` | Cancel a running or queued run | `--issue` |
| `project` | `list/get/create/update/delete` | Manage projects | `create`: `--title` (required), `--lead`, `--status`, `--icon`, `--start-date`, `--due-date`, `--repo` (repeatable) |
| | `status <id> <status>` | Change project status | |
diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdx
index ecb2ec0982..ef61178084 100644
--- a/apps/docs/content/docs/cli.zh.mdx
+++ b/apps/docs/content/docs/cli.zh.mdx
@@ -125,11 +125,13 @@ multica issue comment add MUL-123 --content-stdin < review.md
multica issue comment update <comment-id> --expected-revision 2 --content-file revised-review.md
```
-查看某次运行的消息,或停止运行:
+查看某次运行的消息、停止运行或重试:
```bash
multica issue run-messages <task-id> --issue MUL-123
multica issue cancel-task <task-id> --issue MUL-123
+multica issue rerun-task <run-id> --issue MUL-123
+multica issue rerun-task <run-id> --issue MUL-123 --fresh
```
同一项目、同一父任务下已有标题相同(不区分大小写,忽略多余空格)且未关闭的任务时,`issue create` 会拒绝创建并给出那个任务。确实要再建一个,加 `--allow-duplicate`;要把一个任务标为另一个的重复,用 `multica issue status MUL-124 cancelled --duplicate-of MUL-123`。
@@ -357,7 +359,7 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓
| | `runs <issue-id>` | 查看执行历史 | `--full-id` |
| | `run-messages <task-id>` | 查看单次执行的消息 | `--since`、`--issue` |
| | `usage <issue-id>` | 查看聚合 token 用量 | |
-| | `rerun <id>` | 按当前指派重新入队执行 | |
+| | `rerun-task <run-id>` | 沿用原智能体和触发上下文,重跑指定运行 | `--issue`, `--fresh` |
| | `cancel-task <task-id>` | 取消进行中或排队中的运行 | `--issue` |
| `project` | `list/get/create/update/delete` | 管理项目 | `create`:`--title`(必填)、`--lead`、`--status`、`--icon`、`--start-date`、`--due-date`、`--repo`(可重复) |
| | `status <id> <status>` | 修改项目状态 | |
diff --git a/apps/docs/content/docs/tasks.fr.mdx b/apps/docs/content/docs/tasks.fr.mdx
index 5466fbfb0b..845659510f 100644
--- a/apps/docs/content/docs/tasks.fr.mdx
+++ b/apps/docs/content/docs/tasks.fr.mdx
@@ -143,13 +143,16 @@ Cliquer sur le bouton Relancer l'exécution d'une ligne du journal d'exécution
Une relance conserve autant que possible les fichiers que l'exécution précédente a déjà écrits dans le répertoire local. Si la session d'origine est toujours sûre et que le même runtime prend en charge la relance, celle-ci poursuit aussi la session précédente. Les erreurs qui corrompent la session, comme un dépassement de contexte ou des requêtes invalides, démarrent plutôt une nouvelle session dans le répertoire de travail d'origine. Lorsque le répertoire d'origine n'existe plus, un nouveau répertoire de travail est utilisé.
-Vous pouvez aussi relancer la tâche en cours depuis le CLI :
+Retrouvez l’exécution source, puis relancez-la depuis le CLI :
```bash
-multica issue rerun <issue-id>
+multica issue runs <issue-id> --full-id
+multica issue rerun-task <run-id>
```
-Cette forme ne vise pas une exécution passée précise : elle utilise l'agent actuellement assigné à la tâche et démarre avec une nouvelle session et un nouveau répertoire de travail.
+Un UUID d’exécution complet permet d’omettre `--issue` ; un préfixe court exige `--issue`. La commande reprend l’agent et le contexte de déclenchement d’origine, avec les mêmes règles de continuité que le bouton de relance. Ajoutez `--fresh` pour démarrer une nouvelle session dans un nouveau répertoire de travail.
+
+L’ancienne commande `multica issue rerun <issue-id>` est obsolète et masquée dans l’aide. Elle reste disponible pour les scripts existants et lance toujours l’assigné actuel avec une nouvelle session et un nouveau répertoire de travail.
## Fin d'exécution et fin de tâche
diff --git a/apps/docs/content/docs/tasks.ja.mdx b/apps/docs/content/docs/tasks.ja.mdx
index 450599d597..53720e0605 100644
--- a/apps/docs/content/docs/tasks.ja.mdx
+++ b/apps/docs/content/docs/tasks.ja.mdx
@@ -143,13 +143,16 @@ import { RunLifecycleDemo } from "@/components/demos/run-lifecycle-demo";
リトライは、前回の実行がローカルディレクトリに書き込んだファイルをできる限り保持します。元のセッションがまだ安全で、同じランタイムが取得した場合は、前回のセッションを引き継ぎます。コンテキスト超過や不正なリクエストなど、セッションを汚染するエラーの場合は、元の作業ディレクトリの上で新しいセッションを開始します。元のディレクトリがすでに存在しない場合は、新しい作業ディレクトリを使います。
-CLI から現在のタスクを再実行することもできます。
+CLI で元の実行を確認し、再試行できます。
```bash
-multica issue rerun <issue-id>
+multica issue runs <issue-id> --full-id
+multica issue rerun-task <run-id>
```
-この方法は過去の特定の実行を指さないため、タスクの現在のエージェント担当者を使い、新しいセッションと作業ディレクトリから開始します。
+完全な実行 UUID を指定する場合、`--issue` は省略できます。短い ID プレフィックスには `--issue` が必要です。元のエージェントとトリガーのコンテキストを使い、再試行ボタンと同じルールでセッションとディレクトリを引き継ぎます。新しいセッションと作業ディレクトリで始めるには `--fresh` を追加します。
+
+旧コマンド `multica issue rerun <issue-id>` は非推奨となり、ヘルプ一覧から非表示になりました。既存のスクリプトでは引き続き利用でき、現在の担当者が新しいセッションと作業ディレクトリで開始する動作を維持します。
## 実行の完了とタスクの完了
diff --git a/apps/docs/content/docs/tasks.ko.mdx b/apps/docs/content/docs/tasks.ko.mdx
index 38b86e3633..eff40da7c9 100644
--- a/apps/docs/content/docs/tasks.ko.mdx
+++ b/apps/docs/content/docs/tasks.ko.mdx
@@ -143,13 +143,16 @@ import { RunLifecycleDemo } from "@/components/demos/run-lifecycle-demo";
재시도할 때 이전 실행이 로컬 디렉터리에 이미 기록한 파일을 가능한 한 유지합니다. 원래 세션이 계속 안전하고 같은 런타임이 실행을 가져가면 이전 세션을 이어갑니다. 컨텍스트 overflow나 유효하지 않은 요청처럼 세션을 오염시키는 오류가 있었다면 원래 작업 디렉터리에서 새 세션을 시작합니다. 원래 디렉터리가 없으면 새 작업 디렉터리를 사용합니다.
-CLI로 현재 태스크를 다시 실행할 수도 있습니다.
+CLI에서 원래 실행을 찾고 재시도할 수 있습니다.
```bash
-multica issue rerun <issue-id>
+multica issue runs <issue-id> --full-id
+multica issue rerun-task <run-id>
```
-이 방법은 특정 과거 실행을 지정하지 않으므로 태스크의 현재 에이전트 담당자를 사용하고 새 세션과 작업 디렉터리에서 시작합니다.
+전체 실행 UUID를 사용하면 `--issue`를 생략할 수 있습니다. 짧은 ID 접두사에는 `--issue`가 필요합니다. 원래 에이전트와 트리거 컨텍스트를 사용하며, 재시도 버튼과 같은 규칙으로 세션과 디렉터리를 이어갑니다. 새 세션과 작업 디렉터리에서 시작하려면 `--fresh`를 추가하세요.
+
+기존 `multica issue rerun <issue-id>` 명령은 사용 중단 예정이며 도움말 목록에서 숨겨집니다. 기존 스크립트에서는 계속 사용할 수 있고, 현재 담당자가 새 세션과 작업 디렉터리에서 시작하는 동작을 유지합니다.
## 실행 완료와 태스크 완료
diff --git a/apps/docs/content/docs/tasks.mdx b/apps/docs/content/docs/tasks.mdx
index 31ad7a7c24..562c170b3f 100644
--- a/apps/docs/content/docs/tasks.mdx
+++ b/apps/docs/content/docs/tasks.mdx
@@ -143,13 +143,16 @@ Clicking the retry button on a row in the execution log invokes **the agent that
A retry keeps the files the previous run already wrote to the local directory whenever possible. If the original session is still safe and the same runtime claims the retry, it continues that session. Errors that poison the session, such as context overflow or invalid requests, start a new session on top of the original working directory instead. When the original directory no longer exists, a fresh working directory is used.
-You can also rerun the current issue from the CLI:
+Find the source run and retry it from the CLI:
```bash
-multica issue rerun <issue-id>
+multica issue runs <issue-id> --full-id
+multica issue rerun-task <run-id>
```
-This form does not point at a specific past run, so it uses the issue's current agent assignee and starts with a fresh session and working directory.
+A full run UUID works without `--issue`; short prefixes require `--issue` to select the issue. This repeats the original agent and trigger context with the same continuity rules as the retry button. Add `--fresh` to start a new session and working directory.
+
+The old `multica issue rerun <issue-id>` command is deprecated and hidden from help. It remains available for existing scripts and still starts the current assignee with a fresh session and working directory.
## Run completion and issue completion
diff --git a/apps/docs/content/docs/tasks.zh.mdx b/apps/docs/content/docs/tasks.zh.mdx
index b93e4b9a7b..803d6f1da1 100644
--- a/apps/docs/content/docs/tasks.zh.mdx
+++ b/apps/docs/content/docs/tasks.zh.mdx
@@ -143,13 +143,16 @@ import { RunLifecycleDemo } from "@/components/demos/run-lifecycle-demo";
重试会尽量保留上一次已经写入本地目录的文件。原会话仍然安全、又由同一个运行时领取时,会接着之前的会话继续。上下文溢出、无效请求这类会污染会话的错误,会在原工作目录上开新会话;原目录已经不存在时,改用新的工作目录。
-也可以通过 CLI 重新运行当前任务:
+通过 CLI 找到原运行,再重试:
```bash
-multica issue rerun <issue-id>
+multica issue runs <issue-id> --full-id
+multica issue rerun-task <run-id>
```
-这条命令没有指定哪一条历史运行,所以会交给任务当前的智能体负责人,从新的会话和工作目录开始。
+使用完整运行 UUID 时可以省略 `--issue`;短 ID 前缀必须用 `--issue` 指定任务。命令会沿用原智能体和触发上下文,会话与目录的复用规则和重试按钮相同。添加 `--fresh` 可从新的会话和工作目录开始。
+
+旧命令 `multica issue rerun <issue-id>` 已弃用,并从帮助列表中隐藏。现有脚本仍可使用它,行为保持为让当前负责人从新会话和工作目录开始。
## 运行完成与任务完成
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index 37a40e6cf1..39377637f0 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -449,10 +449,23 @@ var issueUsageCmd = &cobra.Command{
}
var issueRerunCmd = &cobra.Command{
- Use: "rerun <id>",
- Short: "Re-enqueue an issue's current agent assignment as a fresh run",
- Args: exactArgs(1),
- RunE: runIssueRerun,
+ Use: "rerun <id>",
+ Short: "Re-enqueue an issue's current agent assignment as a fresh run",
+ Deprecated: "use `multica issue rerun-task <run-id>` instead; find run IDs with `multica issue runs <issue-id> --full-id`",
+ Hidden: true,
+ Args: exactArgs(1),
+ RunE: runIssueRerun,
+}
+
+var issueRerunTaskCmd = &cobra.Command{
+ Use: "rerun-task <run-id>",
+ Short: "Repeat a specific run using its original agent and trigger context",
+ Long: "Repeat a specific run, even if the issue has since been reassigned. " +
+ "Pass a full run UUID, or a short prefix with --issue <issue-id>. " +
+ "By default, reuse the source working directory and resume its session when safe. " +
+ "Use --fresh to start with a new session and working directory.",
+ Args: exactArgs(1),
+ RunE: runIssueRerunTask,
}
var issueCancelTaskCmd = &cobra.Command{
@@ -591,6 +604,7 @@ func init() {
issueCmd.AddCommand(issueRunMessagesCmd)
issueCmd.AddCommand(issueUsageCmd)
issueCmd.AddCommand(issueRerunCmd)
+ issueCmd.AddCommand(issueRerunTaskCmd)
issueCmd.AddCommand(issueCancelTaskCmd)
issueCmd.AddCommand(issueSearchCmd)
@@ -713,6 +727,10 @@ func init() {
// issue rerun
issueRerunCmd.Flags().String("output", "json", "Output format: table or json")
+ // issue rerun-task
+ issueRerunTaskCmd.Flags().String("output", "json", "Output format: table or json")
+ issueRerunTaskCmd.Flags().String("issue", "", "Issue ID/key to scope short run ID prefix resolution")
+ issueRerunTaskCmd.Flags().Bool("fresh", false, "Start with a new session and working directory")
// issue cancel-task
issueCancelTaskCmd.Flags().String("output", "json", "Output format: table or json")
issueCancelTaskCmd.Flags().String("issue", "", "Issue ID/key to scope short run ID prefix resolution")
@@ -2941,6 +2959,40 @@ func runIssueRunMessages(cmd *cobra.Command, args []string) error {
// Search command
+func runIssueRerunTask(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ issueScope := ""
+ if issueInput, _ := cmd.Flags().GetString("issue"); issueInput != "" {
+ issueRef, err := resolveIssueRef(ctx, client, issueInput)
+ if err != nil {
+ return fmt.Errorf("resolve issue: %w", err)
+ }
+ issueScope = issueRef.ID
+ }
+ taskRef, err := resolveTaskRunID(ctx, client, issueScope, args[0])
+ if err != nil {
+ return fmt.Errorf("resolve run: %w", err)
+ }
+ fresh, _ := cmd.Flags().GetBool("fresh")
+ var task map[string]any
+ if err := client.PostJSON(ctx, "/api/tasks/"+url.PathEscape(taskRef.ID)+"/rerun", map[string]any{"fresh": fresh}, &task); err != nil {
+ return fmt.Errorf("rerun run: %w", err)
+ }
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, task)
+ }
+ agent := loadActorDisplayLookup(ctx, client).agent(strVal(task, "agent_id"))
+ fmt.Fprintf(os.Stdout, "Re-enqueued run %s on agent %s\n", strVal(task, "id"), agent)
+ return nil
+}
+
func runIssueRerun(cmd *cobra.Command, args []string) error {
client, err := newAPIClient(cmd)
if err != nil {
diff --git a/server/cmd/multica/cmd_issue_rerun_test.go b/server/cmd/multica/cmd_issue_rerun_test.go
new file mode 100644
index 0000000000..db325a751c
--- /dev/null
+++ b/server/cmd/multica/cmd_issue_rerun_test.go
@@ -0,0 +1,103 @@
+package main
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/spf13/cobra"
+)
+
+func TestRunIssueRerunTask(t *testing.T) {
+ t.Chdir(t.TempDir())
+ const issueID = "1881a167-4bb6-4602-944b-f40ce4192fe6"
+ const runID = "aaaaaaaa-1111-4222-8333-444444444444"
+ for _, tc := range []struct {
+ name, input, scope, wantErr string
+ fresh, ambiguous bool
+ }{
+ {name: "full UUID needs no issue", input: runID},
+ {name: "fresh", input: runID, fresh: true},
+ {name: "short prefix", input: "aaaaaaaa", scope: issueID},
+ {name: "short prefix needs issue", input: "aaaaaaaa", wantErr: "require --issue"},
+ {name: "ambiguous prefix", input: "aaaa", scope: issueID, ambiguous: true, wantErr: "ambiguous"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ posts := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/issues/" + issueID + "/task-runs":
+ runs := []map[string]any{{"id": runID}}
+ if tc.ambiguous {
+ runs = append(runs, map[string]any{"id": "aaaaabcd-1111-4222-8333-444444444444"})
+ }
+ _ = json.NewEncoder(w).Encode(runs)
+ case "/api/tasks/" + runID + "/rerun":
+ posts++
+ if r.Method != http.MethodPost {
+ t.Errorf("method = %s, want POST", r.Method)
+ }
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode body: %v", err)
+ }
+ if len(body) != 1 || body["fresh"] != tc.fresh {
+ t.Errorf("body = %v, want fresh=%v", body, tc.fresh)
+ }
+ w.WriteHeader(http.StatusAccepted)
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "new-run", "agent_id": "original-agent"})
+ default:
+ t.Errorf("unexpected request: %s", r.URL.Path)
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+ cmd := &cobra.Command{Use: "rerun-task"}
+ cmd.Flags().String("output", "json", "")
+ cmd.Flags().String("issue", tc.scope, "")
+ cmd.Flags().Bool("fresh", tc.fresh, "")
+ out, err := captureStdout(t, func() error { return runIssueRerunTask(cmd, []string{tc.input}) })
+ if tc.wantErr != "" {
+ if err == nil || !strings.Contains(err.Error(), tc.wantErr) || posts != 0 {
+ t.Fatalf("err=%v posts=%d, want %q and no mutation", err, posts, tc.wantErr)
+ }
+ return
+ }
+ if err != nil || posts != 1 || !strings.Contains(out, "new-run") {
+ t.Fatalf("err=%v posts=%d output=%s", err, posts, out)
+ }
+ })
+ }
+}
+
+func TestRunIssueRerunLegacyBody(t *testing.T) {
+ t.Chdir(t.TempDir())
+ const issueID = "1881a167-4bb6-4602-944b-f40ce4192fe6"
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != "/api/issues/"+issueID+"/rerun" {
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
+ }
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil || len(body) != 0 {
+ t.Errorf("legacy body = %v, err=%v; want empty object", body, err)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "new-run"})
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+ cmd := &cobra.Command{Use: "rerun"}
+ cmd.Flags().String("output", "json", "")
+ if _, err := captureStdout(t, func() error { return runIssueRerun(cmd, []string{issueID}) }); err != nil {
+ t.Fatal(err)
+ }
+ if issueRerunCmd.Deprecated == "" || !issueRerunCmd.Hidden {
+ t.Fatal("legacy command must be hidden and deprecated")
+ }
+}
diff --git a/server/cmd/server/rerun_session_test.go b/server/cmd/server/rerun_session_test.go
index 4f0ac34186..599fceada6 100644
--- a/server/cmd/server/rerun_session_test.go
+++ b/server/cmd/server/rerun_session_test.go
@@ -749,7 +749,7 @@ func TestRerunIssueSetsForceFreshSession(t *testing.T) {
bus := events.New()
taskService := service.NewTaskService(queries, nil, hub, bus)
- task, err := taskService.RerunIssue(ctx, pgtype.UUID{Bytes: parseUUIDBytes(issueID), Valid: true}, pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, nil)
+ task, err := taskService.RerunIssue(ctx, pgtype.UUID{Bytes: parseUUIDBytes(issueID), Valid: true}, pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, false, nil)
if err != nil {
t.Fatalf("RerunIssue failed: %v", err)
}
@@ -825,6 +825,7 @@ func TestRerunIssueTargetsSourceTaskAgent(t *testing.T) {
pgtype.UUID{Bytes: parseUUIDBytes(sourceTaskID), Valid: true},
pgtype.UUID{},
pgtype.UUID{},
+ false,
nil,
)
if err != nil {
@@ -898,6 +899,7 @@ func TestRerunIssueRejectsCrossIssueTask(t *testing.T) {
pgtype.UUID{Bytes: parseUUIDBytes(crossTaskID), Valid: true},
pgtype.UUID{},
pgtype.UUID{},
+ false,
nil,
)
if err == nil {
@@ -963,6 +965,7 @@ func TestRerunIssueInheritsTriggerCommentFromSourceTask(t *testing.T) {
pgtype.UUID{Bytes: parseUUIDBytes(sourceTaskID), Valid: true},
pgtype.UUID{},
pgtype.UUID{},
+ false,
nil,
)
if err != nil {
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 1f1b70a8c9..7d344db5aa 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2418,6 +2418,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Tasks (user-facing, with ownership check)
r.Post("/api/tasks/{taskId}/cancel", h.CancelTaskByUser)
+ r.Post("/api/tasks/{taskId}/rerun", h.RerunTaskByUser)
// Workspace-wide agent task snapshot for presence derivation:
// every active task + each agent's most recent terminal task.
diff --git a/server/internal/handler/comment_thread_queue_test.go b/server/internal/handler/comment_thread_queue_test.go
index c6215a6bcc..be6d54c39d 100644
--- a/server/internal/handler/comment_thread_queue_test.go
+++ b/server/internal/handler/comment_thread_queue_test.go
@@ -92,7 +92,7 @@ func TestCommentThreadQueuesMergeAndExecuteIndependently(t *testing.T) {
t.Fatalf("completion duplicated another thread: got %d tasks", len(tasks))
}
// A row-specific rerun replaces only A's pending successor.
- rerun, err := testHandler.TaskService.RerunIssue(ctx, issue.ID, a.ID, pgtype.UUID{}, parseUUID(testUserID), nil)
+ rerun, err := testHandler.TaskService.RerunIssue(ctx, issue.ID, a.ID, pgtype.UUID{}, parseUUID(testUserID), false, nil)
if err != nil {
t.Fatal(err)
}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 78dcfd9ae0..8ffef0dce0 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -3391,11 +3391,11 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
}
// Resolve the prior agent session / workdir to resume.
- if task.RerunOfTaskID.Valid {
+ if task.RerunOfTaskID.Valid && !service.IsFreshRerun(*task) {
// Manual retry: resume precisely from the source task the user
// clicked, NOT the most-recent (agent, issue) row — a parallel task
// on the same issue must never hijack the resume (MUL-4869). The
- // workdir is ALWAYS reused when it still exists; the session is
+ // workdir is reused unless fresh was explicitly requested; the session is
// resumed only when the source failure did not poison the
// conversation AND the source ran on this runtime.
//
diff --git a/server/internal/handler/daemon_comment_delivery_test.go b/server/internal/handler/daemon_comment_delivery_test.go
index 1a5282c9fa..009fae47c0 100644
--- a/server/internal/handler/daemon_comment_delivery_test.go
+++ b/server/internal/handler/daemon_comment_delivery_test.go
@@ -771,7 +771,7 @@ func TestRerunIssue_PreservesSourceCommentPlanAndResetsReceipt(t *testing.T) {
testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
})
- rerun, err := testHandler.TaskService.RerunIssue(ctx, util.MustParseUUID(issueID), util.MustParseUUID(sourceID), pgtype.UUID{}, pgtype.UUID{}, nil)
+ rerun, err := testHandler.TaskService.RerunIssue(ctx, util.MustParseUUID(issueID), util.MustParseUUID(sourceID), pgtype.UUID{}, pgtype.UUID{}, false, nil)
if err != nil {
t.Fatalf("RerunIssue: %v", err)
}
@@ -818,7 +818,7 @@ func testRerunPromotesSurvivorAfterTriggerDeleted(t *testing.T, deleteTriggerSQL
t.Fatalf("delete rerun source trigger: %v", err)
}
- rerun, err := testHandler.TaskService.RerunIssue(ctx, parseUUID(fixture.issueID), parseUUID(fixture.taskID), pgtype.UUID{}, pgtype.UUID{}, nil)
+ rerun, err := testHandler.TaskService.RerunIssue(ctx, parseUUID(fixture.issueID), parseUUID(fixture.taskID), pgtype.UUID{}, pgtype.UUID{}, false, nil)
if err != nil {
t.Fatalf("RerunIssue: %v", err)
}
diff --git a/server/internal/handler/fail_task_successor_test.go b/server/internal/handler/fail_task_successor_test.go
index 66021a5406..6ed322a32a 100644
--- a/server/internal/handler/fail_task_successor_test.go
+++ b/server/internal/handler/fail_task_successor_test.go
@@ -76,7 +76,7 @@ func failTaskSuccessorCase(t *testing.T, failureReason string) {
// The operator reruns while that task is still running: allowed now, and it
// takes the single queued/dispatched slot the unique index permits.
- rerun, err := testHandler.TaskService.RerunIssue(ctx, parseUUID(issueID), pgtype.UUID{}, pgtype.UUID{}, parseUUID(testUserID), nil)
+ rerun, err := testHandler.TaskService.RerunIssue(ctx, parseUUID(issueID), pgtype.UUID{}, pgtype.UUID{}, parseUUID(testUserID), false, nil)
if err != nil {
t.Fatalf("RerunIssue behind running task: %v", err)
}
@@ -219,7 +219,7 @@ func TestFailTaskAndRerunConcurrently_NeverStrandsRunningTask(t *testing.T) {
go func() {
defer wg.Done()
<-start
- _, rerunErr = testHandler.TaskService.RerunIssue(ctx, parseUUID(issueID), pgtype.UUID{}, pgtype.UUID{}, parseUUID(testUserID), nil)
+ _, rerunErr = testHandler.TaskService.RerunIssue(ctx, parseUUID(issueID), pgtype.UUID{}, pgtype.UUID{}, parseUUID(testUserID), false, nil)
}()
close(start)
wg.Wait()
@@ -430,7 +430,7 @@ func TestFailTaskAndRerunConcurrently_NonAssigneeTarget(t *testing.T) {
go func() {
defer wg.Done()
<-start
- _, rerunErr = testHandler.TaskService.RerunIssue(ctx, parseUUID(issueID), parseUUID(sourceTaskID), pgtype.UUID{}, parseUUID(testUserID), nil)
+ _, rerunErr = testHandler.TaskService.RerunIssue(ctx, parseUUID(issueID), parseUUID(sourceTaskID), pgtype.UUID{}, parseUUID(testUserID), false, nil)
}()
close(start)
wg.Wait()
diff --git a/server/internal/handler/issue_triage_no_run_test.go b/server/internal/handler/issue_triage_no_run_test.go
index 9b34959cc7..10f3e4f1f5 100644
--- a/server/internal/handler/issue_triage_no_run_test.go
+++ b/server/internal/handler/issue_triage_no_run_test.go
@@ -337,7 +337,7 @@ func TestEnqueueRefusesADerivedRunInTriage(t *testing.T) {
return err
},
"rerun with no source": func() error {
- _, err := testHandler.TaskService.RerunIssue(ctx, issue.ID, pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, nil)
+ _, err := testHandler.TaskService.RerunIssue(ctx, issue.ID, pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, false, nil)
return err
},
}
diff --git a/server/internal/handler/rerun_task_test.go b/server/internal/handler/rerun_task_test.go
new file mode 100644
index 0000000000..7135f2ae71
--- /dev/null
+++ b/server/internal/handler/rerun_task_test.go
@@ -0,0 +1,126 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func TestRerunTaskByUserContinuity(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ for _, tc := range []struct {
+ name string
+ fresh, reassigned bool
+ }{
+ {name: "assignee reuse"},
+ {name: "assignee fresh", fresh: true},
+ {name: "reassigned reuse", reassigned: true},
+ {name: "reassigned fresh", fresh: true, reassigned: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fresh := tc.fresh
+ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, context.Background())
+ currentAgentID := agentID
+ if tc.reassigned {
+ currentAgentID = createHandlerTestAgent(t, "New assignee", []byte("[]"))
+ }
+ issueID := dbfx.Issue(t, "rerun a displaced agent", testutil.Cols{
+ "assignee_type": "agent", "assignee_id": currentAgentID,
+ })
+ commentID := dbfx.Comment(t, issueID, "continue this work")
+ sourceID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID, "issue_id": issueID, "status": "completed",
+ "session_id": "source-session", "work_dir": "/tmp/source-workdir",
+ "trigger_comment_id": commentID,
+ })
+ req := withURLParam(newRequest(http.MethodPost, "/api/tasks/"+sourceID+"/rerun", map[string]any{"fresh": fresh}), "taskId", sourceID)
+ var result struct {
+ ID string `json:"id"`
+ }
+ testutil.Call(t, testHandler.RerunTaskByUser, withChatTestWorkspaceCtx(t, req)).Want(http.StatusAccepted).JSON(&result)
+ row, err := testHandler.Queries.GetAgentTask(t.Context(), parseUUID(result.ID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, result.ID) })
+ if uuidToString(row.AgentID) != agentID || uuidToString(row.RerunOfTaskID) != sourceID || uuidToString(row.TriggerCommentID) != commentID {
+ t.Fatalf("rerun lost source agent, lineage, or comment: %+v", row)
+ }
+ if !row.ForceFreshSession || service.IsFreshRerun(row) != fresh {
+ t.Fatalf("fresh=%v: unexpected stored continuity flags", fresh)
+ }
+ claimed := claimTaskForRuntimeGuard(t, runtimeID, daemonID)
+ if fresh {
+ if claimed.PriorSessionID != "" || claimed.PriorWorkDir != "" {
+ t.Fatalf("fresh rerun resumed %q / %q", claimed.PriorSessionID, claimed.PriorWorkDir)
+ }
+ } else if claimed.PriorSessionID != "source-session" || claimed.PriorWorkDir != "/tmp/source-workdir" {
+ t.Fatalf("default rerun lost continuity: %q / %q", claimed.PriorSessionID, claimed.PriorWorkDir)
+ }
+ })
+ }
+}
+
+func TestRerunTaskByUserRejectsInvalidSource(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ agentID := createHandlerTestAgent(t, "RerunSource", []byte("[]"))
+ foreignWorkspaceID := dbfx.Workspace(t, "foreign rerun workspace", "foreign-rerun-workspace")
+ foreignIssueID := dbfx.Issue(t, "foreign issue", testutil.Cols{"workspace_id": foreignWorkspaceID})
+ foreignAgentID := dbfx.Agent(t, "foreign agent", testRuntimeID, testutil.Cols{"workspace_id": foreignWorkspaceID})
+ for _, tc := range []struct {
+ name, agent string
+ cols testutil.Cols
+ code int
+ }{
+ {name: "issue-less", agent: agentID, cols: testutil.Cols{}, code: http.StatusBadRequest},
+ {name: "foreign issue", agent: agentID, cols: testutil.Cols{"issue_id": foreignIssueID}, code: http.StatusNotFound},
+ {name: "foreign task", agent: foreignAgentID, cols: testutil.Cols{"issue_id": foreignIssueID}, code: http.StatusNotFound},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tc.cols["runtime_id"] = testRuntimeID
+ sourceID := dbfx.Task(t, tc.agent, tc.cols)
+ req := withURLParam(newRequest(http.MethodPost, "/api/tasks/"+sourceID+"/rerun", nil), "taskId", sourceID)
+ testutil.Call(t, testHandler.RerunTaskByUser, withChatTestWorkspaceCtx(t, req)).Want(tc.code)
+ row, err := testHandler.Queries.GetAgentTask(t.Context(), parseUUID(sourceID))
+ if err != nil || row.Status != "queued" {
+ t.Fatalf("rejected source mutated: %s, %v", row.Status, err)
+ }
+ })
+ }
+}
+
+func TestRerunTaskByUserPrivateHistoricalAgent(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ agentID, ownerID, _ := privateAgentTestFixture(t)
+ currentAgentID := createHandlerTestAgent(t, "Current public assignee", []byte("[]"))
+ issueID := dbfx.Issue(t, "private historical run", testutil.Cols{
+ "assignee_type": "agent", "assignee_id": currentAgentID,
+ })
+ sourceID := dbfx.Task(t, agentID, testutil.Cols{"issue_id": issueID, "runtime_id": testRuntimeID})
+ for _, fresh := range []bool{false, true} {
+ req := withURLParam(newRequest(http.MethodPost, "/api/tasks/"+sourceID+"/rerun", map[string]any{"fresh": fresh}), "taskId", sourceID)
+ testutil.Call(t, testHandler.RerunTaskByUser, withChatTestWorkspaceCtx(t, req)).Want(http.StatusForbidden)
+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, issueID); n != 1 {
+ t.Fatalf("denied rerun created tasks: count=%d", n)
+ }
+ row, err := testHandler.Queries.GetAgentTask(t.Context(), parseUUID(sourceID))
+ if err != nil || row.Status != "queued" {
+ t.Fatalf("denied rerun cancelled source: %s, %v", row.Status, err)
+ }
+ }
+ req := withURLParam(newRequestAs(ownerID, http.MethodPost, "/api/tasks/"+sourceID+"/rerun", nil), "taskId", sourceID)
+ var result struct {
+ ID string `json:"id"`
+ }
+ testutil.Call(t, testHandler.RerunTaskByUser, withChatTestWorkspaceCtx(t, req)).Want(http.StatusAccepted).JSON(&result)
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, result.ID) })
+}
diff --git a/server/internal/handler/task_lifecycle.go b/server/internal/handler/task_lifecycle.go
index 500296d0c3..7b837b8eb8 100644
--- a/server/internal/handler/task_lifecycle.go
+++ b/server/internal/handler/task_lifecycle.go
@@ -152,16 +152,8 @@ type RerunIssueRequest struct {
TaskID string `json:"task_id,omitempty"`
}
-// RerunIssue manually re-enqueues an agent run for the issue. By default it
-// targets the issue's current assignee (agent or squad leader); if the
-// request body carries task_id, the rerun targets the agent that ran that
-// specific past task instead. The new task is flagged force_fresh_session=true:
-// the daemon claim handler skips the (agent_id, issue_id) session-resume
-// lookup so the agent starts a clean session. A user clicking rerun has just
-// judged the prior output bad — replaying the same conversation would replay
-// the same poisoned state. (Automatic retry, by contrast, intentionally
-// inherits the session — that path handles infrastructure failures, not bad
-// output.)
+// RerunIssue preserves the issue-scoped API used by installed clients. A
+// task_id repeats that run; an empty body targets the current assignee.
func (h *Handler) RerunIssue(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
issue, ok := h.loadIssueForUser(w, r, id)
@@ -187,7 +179,50 @@ func (h *Handler) RerunIssue(w http.ResponseWriter, r *http.Request) {
}
sourceTaskID = parsed
}
+ h.rerunIssue(w, r, issue, sourceTaskID, false)
+}
+
+// RerunTaskByUser repeats an issue-linked run without requiring its issue ID.
+func (h *Handler) RerunTaskByUser(w http.ResponseWriter, r *http.Request) {
+ if _, ok := requireUserID(w, r); !ok {
+ return
+ }
+ workspaceID, ok := parseUUIDOrBadRequest(w, ctxWorkspaceID(r.Context()), "workspace id")
+ if !ok {
+ return
+ }
+ taskID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "taskId"), "task id")
+ if !ok {
+ return
+ }
+ source, err := h.Queries.GetAgentTaskInWorkspace(r.Context(), db.GetAgentTaskInWorkspaceParams{
+ ID: taskID, WorkspaceID: workspaceID,
+ })
+ if err != nil {
+ writeError(w, http.StatusNotFound, "task not found")
+ return
+ }
+ if !source.IssueID.Valid {
+ writeError(w, http.StatusBadRequest, "only issue-linked runs can be rerun with this endpoint")
+ return
+ }
+ issue, ok := h.loadIssueForUser(w, r, uuidToString(source.IssueID))
+ if !ok {
+ return
+ }
+ var req struct {
+ Fresh bool `json:"fresh"`
+ }
+ if r.ContentLength != 0 {
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil && err != io.EOF {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ }
+ h.rerunIssue(w, r, issue, source.ID, req.Fresh)
+}
+func (h *Handler) rerunIssue(w http.ResponseWriter, r *http.Request, issue db.Issue, sourceTaskID pgtype.UUID, fresh bool) {
// A manual rerun is a direct human action: attribute the new run to the
// rerunning member (MUL-4302 §5). Resolve the actor the same way assign/promote
// does; an agent A2A actor is not a human and threads an invalid actor.
@@ -208,7 +243,7 @@ func (h *Handler) RerunIssue(w http.ResponseWriter, r *http.Request) {
return h.canInvokeAgent(r.Context(), agent, actorType, actorID, originatorUserID, workspaceID)
}
- task, err := h.TaskService.RerunIssue(r.Context(), issue.ID, sourceTaskID, pgtype.UUID{}, actorUserID, canInvoke)
+ task, err := h.TaskService.RerunIssue(r.Context(), issue.ID, sourceTaskID, pgtype.UUID{}, actorUserID, fresh, canInvoke)
if errors.Is(err, service.ErrRerunInvokeNotAllowed) {
h.writeDispatchBlocked(w, http.StatusForbidden, ReasonInvocationNotAllowed)
return
@@ -221,7 +256,7 @@ func (h *Handler) RerunIssue(w http.ResponseWriter, r *http.Request) {
// source is ineligible. It falls through to the 400 below with the
// sentinel's own sentence, like the sibling "does not belong to this issue".
if err != nil {
- slog.Warn("issue rerun failed", "issue_id", id, "error", err)
+ slog.Warn("issue rerun failed", "issue_id", uuidToString(issue.ID), "error", err)
writeError(w, http.StatusBadRequest, err.Error())
return
}
diff --git a/server/internal/service/admission_mul4525_test.go b/server/internal/service/admission_mul4525_test.go
index 9143a98acc..ac8e32fa98 100644
--- a/server/internal/service/admission_mul4525_test.go
+++ b/server/internal/service/admission_mul4525_test.go
@@ -66,7 +66,7 @@ func TestRerunIssueBlockedBeforeMutationWhenInvokeDenied(t *testing.T) {
return false
}
- _, err = svc.RerunIssue(ctx, util.MustParseUUID(issueID), orig.ID, pgtype.UUID{}, util.MustParseUUID(creatorID), deny)
+ _, err = svc.RerunIssue(ctx, util.MustParseUUID(issueID), orig.ID, pgtype.UUID{}, util.MustParseUUID(creatorID), false, deny)
if !errors.Is(err, ErrRerunInvokeNotAllowed) {
t.Fatalf("RerunIssue with denying gate: err = %v, want ErrRerunInvokeNotAllowed", err)
}
@@ -83,7 +83,7 @@ func TestRerunIssueBlockedBeforeMutationWhenInvokeDenied(t *testing.T) {
// A permitting gate reruns normally (cancels the original, enqueues fresh).
allow := func(db.Agent) bool { return true }
- rerun, err := svc.RerunIssue(ctx, util.MustParseUUID(issueID), orig.ID, pgtype.UUID{}, util.MustParseUUID(creatorID), allow)
+ rerun, err := svc.RerunIssue(ctx, util.MustParseUUID(issueID), orig.ID, pgtype.UUID{}, util.MustParseUUID(creatorID), false, allow)
if err != nil {
t.Fatalf("RerunIssue with permitting gate: %v", err)
}
diff --git a/server/internal/service/attribution_stamp_test.go b/server/internal/service/attribution_stamp_test.go
index d40c2a9643..b25d05297f 100644
--- a/server/internal/service/attribution_stamp_test.go
+++ b/server/internal/service/attribution_stamp_test.go
@@ -1223,7 +1223,7 @@ func TestRerunIssueAttributesToRerunningMember(t *testing.T) {
}
// The rerun, performed by a different member.
- task, err := svc.RerunIssue(ctx, util.MustParseUUID(issueID), orig.ID, pgtype.UUID{}, util.MustParseUUID(rerunnerID), nil)
+ task, err := svc.RerunIssue(ctx, util.MustParseUUID(issueID), orig.ID, pgtype.UUID{}, util.MustParseUUID(rerunnerID), false, nil)
if err != nil {
t.Fatalf("RerunIssue: %v", err)
}
diff --git a/server/internal/service/delegated_failure_recovery_settled_test.go b/server/internal/service/delegated_failure_recovery_settled_test.go
index a9a77521e5..0739e6bc96 100644
--- a/server/internal/service/delegated_failure_recovery_settled_test.go
+++ b/server/internal/service/delegated_failure_recovery_settled_test.go
@@ -268,7 +268,7 @@ func TestManualRerunSettlesDeliveredRecovery(t *testing.T) {
if err != nil {
t.Fatalf("parse actor id: %v", err)
}
- if _, err := svc.RerunIssue(ctx, issueID, recoveryTaskID, pgtype.UUID{}, actorID, func(db.Agent) bool { return true }); err != nil {
+ if _, err := svc.RerunIssue(ctx, issueID, recoveryTaskID, pgtype.UUID{}, actorID, false, func(db.Agent) bool { return true }); err != nil {
t.Fatalf("RerunIssue: %v", err)
}
diff --git a/server/internal/service/delegated_failure_recovery_test.go b/server/internal/service/delegated_failure_recovery_test.go
index c90a0734ff..71f4c1017e 100644
--- a/server/internal/service/delegated_failure_recovery_test.go
+++ b/server/internal/service/delegated_failure_recovery_test.go
@@ -836,7 +836,7 @@ func TestManualRerunKeepsDelegatedFailureRecoveryReplayable(t *testing.T) {
util.MustParseUUID(f.issueID),
util.MustParseUUID(f.sourceTask),
pgtype.UUID{},
- util.MustParseUUID(f.userID),
+ util.MustParseUUID(f.userID), false,
nil,
)
if err != nil {
diff --git a/server/internal/service/rerun_queue_behind_active_test.go b/server/internal/service/rerun_queue_behind_active_test.go
index 5cc19613fc..0db4b28d7b 100644
--- a/server/internal/service/rerun_queue_behind_active_test.go
+++ b/server/internal/service/rerun_queue_behind_active_test.go
@@ -66,7 +66,7 @@ func TestRerunIssueQueuesBehindActiveTaskWithoutCancelling(t *testing.T) {
svc, pool, creatorID, agentID, issueID, runtimeID := rerunQueueFixture(t)
activeID := seedRerunTask(t, pool, agentID, runtimeID, issueID, activeStatus)
- task, err := svc.RerunIssue(context.Background(), util.MustParseUUID(issueID), pgtype.UUID{}, pgtype.UUID{}, util.MustParseUUID(creatorID), nil)
+ task, err := svc.RerunIssue(context.Background(), util.MustParseUUID(issueID), pgtype.UUID{}, pgtype.UUID{}, util.MustParseUUID(creatorID), false, nil)
if err != nil {
t.Fatalf("RerunIssue: %v", err)
}
@@ -100,7 +100,7 @@ func TestRerunIssueReplacesNotYetStartedTask(t *testing.T) {
svc, pool, creatorID, agentID, issueID, runtimeID := rerunQueueFixture(t)
pendingID := seedRerunTask(t, pool, agentID, runtimeID, issueID, pendingStatus)
- task, err := svc.RerunIssue(context.Background(), util.MustParseUUID(issueID), pgtype.UUID{}, pgtype.UUID{}, util.MustParseUUID(creatorID), nil)
+ task, err := svc.RerunIssue(context.Background(), util.MustParseUUID(issueID), pgtype.UUID{}, pgtype.UUID{}, util.MustParseUUID(creatorID), false, nil)
if err != nil {
t.Fatalf("RerunIssue: %v", err)
}
diff --git a/server/internal/service/rerun_workdir_reuse_test.go b/server/internal/service/rerun_workdir_reuse_test.go
index d855add990..533c0cb0a9 100644
--- a/server/internal/service/rerun_workdir_reuse_test.go
+++ b/server/internal/service/rerun_workdir_reuse_test.go
@@ -60,7 +60,7 @@ func TestRerunIssuePinsForceFreshSessionForRollbackSafety(t *testing.T) {
}
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, sourceID) })
- task, err := svc.RerunIssue(ctx, util.MustParseUUID(issueID), sourceID, pgtype.UUID{}, util.MustParseUUID(creatorID), nil)
+ task, err := svc.RerunIssue(ctx, util.MustParseUUID(issueID), sourceID, pgtype.UUID{}, util.MustParseUUID(creatorID), false, nil)
if err != nil {
t.Fatalf("RerunIssue: %v", err)
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 2171ed092a..18198dd842 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -1279,10 +1279,10 @@ func (s *TaskService) ResolveIssueReviewSHAParam(ctx context.Context, issueID pg
}
func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, fireAt pgtype.Timestamptz, origin RunOrigin) (db.AgentTaskQueue, error) {
- return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, nil, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID, fireAt, origin)
+ return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, nil, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID, fireAt, origin, false)
}
-func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, fireAt pgtype.Timestamptz, origin RunOrigin) (db.AgentTaskQueue, error) {
+func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, fireAt pgtype.Timestamptz, origin RunOrigin, freshRerun bool) (db.AgentTaskQueue, error) {
if !issue.AssigneeID.Valid {
slog.Error("task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "error", "issue has no assignee")
return db.AgentTaskQueue{}, fmt.Errorf("issue has no assignee")
@@ -1336,6 +1336,7 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue
AccountableUserID: attr.AccountableUserID,
RuleVersionID: attr.RuleVersionID,
RerunOfTaskID: rerunOfTaskID,
+ FreshRerun: pgtype.Bool{Bool: freshRerun, Valid: true},
RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,
RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,
OriginatorSource: attrSource,
@@ -1457,10 +1458,10 @@ func (s *TaskService) EnqueueTaskForSquadLeaderWithHandoff(ctx context.Context,
}
func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, origin RunOrigin) (db.AgentTaskQueue, error) {
- return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, nil, isLeader, squadID, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID, origin)
+ return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, nil, isLeader, squadID, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID, origin, false)
}
-func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, origin RunOrigin) (db.AgentTaskQueue, error) {
+func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, origin RunOrigin, freshRerun bool) (db.AgentTaskQueue, error) {
if err := guardIssueNotInTriage(ctx, s.Queries, issue.ID, origin); err != nil {
return db.AgentTaskQueue{}, err
}
@@ -1510,6 +1511,7 @@ func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, iss
AccountableUserID: attr.AccountableUserID,
RuleVersionID: attr.RuleVersionID,
RerunOfTaskID: rerunOfTaskID,
+ FreshRerun: pgtype.Bool{Bool: freshRerun, Valid: true},
RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,
RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,
OriginatorSource: attrSource,
@@ -5825,7 +5827,7 @@ func transferPendingSourceContextToRetry(ctx context.Context, q *db.Queries, par
// or squad leader). This preserves the CLI / API contract for callers
// that have an issue ID but no specific task to target.
//
-// A retry ALWAYS reuses the source task's workdir when it still exists on
+// Unless fresh is requested, a retry reuses the source workdir when it exists on
// disk (MUL-4869): a transient failure — network, provider 5xx/rate-limit,
// runtime_offline, timeout, or an auth/quota/config error the user has since
// fixed — should not throw away the work already done. Only the agent SESSION
@@ -5847,6 +5849,15 @@ func transferPendingSourceContextToRetry(ctx context.Context, q *db.Queries, par
// to a structured 403 (no task was cancelled or created).
var ErrRerunInvokeNotAllowed = errors.New("rerun: operator not allowed to invoke target agent")
+// IsFreshRerun reports whether a manual rerun explicitly discards continuity.
+// The source lineage stays intact for attribution and execution history.
+func IsFreshRerun(task db.AgentTaskQueue) bool {
+ var context struct {
+ Fresh bool `json:"fresh_rerun"`
+ }
+ return json.Unmarshal(task.Context, &context) == nil && context.Fresh
+}
+
// Only tasks belonging to the target agent on this issue are cancelled.
// Tasks owned by other agents on the same issue (e.g. a parallel
// @-mention agent) are left alone — rerun must not collateral-cancel
@@ -5859,7 +5870,7 @@ var ErrRerunInvokeNotAllowed = errors.New("rerun: operator not allowed to invoke
// caller who can see the issue but cannot invoke its private agent cannot use
// rerun as a back door — and a blocked rerun mutates nothing. Pass nil only
// from trusted internal callers (tests, backfill) that have already gated.
-func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourceTaskID pgtype.UUID, triggerCommentID pgtype.UUID, actorUserID pgtype.UUID, canInvoke func(agent db.Agent) bool) (*db.AgentTaskQueue, error) {
+func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourceTaskID pgtype.UUID, triggerCommentID pgtype.UUID, actorUserID pgtype.UUID, fresh bool, canInvoke func(agent db.Agent) bool) (*db.AgentTaskQueue, error) {
issue, err := s.Queries.GetIssue(ctx, issueID)
if err != nil {
return nil, fmt.Errorf("load issue: %w", err)
@@ -6024,7 +6035,7 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
// sourceTaskID is the rerun lineage: it rides the CreateAgentTask insert
// (rerun_of_task_id) so the queued event / daemon claim never sees a NULL
// lineage, and it stays distinct from system-retry's retry_of_task_id (§5).
- task, err := s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, actorUserID, sourceTaskID, rerunOrigin)
+ task, err := s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, actorUserID, sourceTaskID, rerunOrigin, fresh)
if pendingSlotTakenErr(err) {
// The clear above and this enqueue are separate commits, so a system
// retry created by a concurrent FailTask can take the pending slot in
@@ -6040,7 +6051,7 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
"agent_id", util.UUIDToString(agentID),
)
cancelledCount += clearPendingSlot()
- task, err = s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, actorUserID, sourceTaskID, rerunOrigin)
+ task, err = s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, actorUserID, sourceTaskID, rerunOrigin, fresh)
}
if err != nil {
return nil, err
@@ -6123,13 +6134,14 @@ func (s *TaskService) promoteNewestSurvivingComment(ctx context.Context, ids []p
// pick a different execution than the one the user clicked. The NEW claim
// handler ignores this flag for reruns and instead reads the exact source task
// (rerun_of_task_id) to reuse its workdir and, when the failure did not poison
-// the conversation, resume its session (MUL-4869).
-func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, origin RunOrigin) (db.AgentTaskQueue, error) {
+// the conversation, resume its session (MUL-4869). An explicit fresh rerun stamps
+// context.fresh_rerun in the same insert so claim cannot race ahead of that choice.
+func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, origin RunOrigin, fresh bool) (db.AgentTaskQueue, error) {
if issue.AssigneeType.String == "agent" && issue.AssigneeID.Valid &&
util.UUIDToString(issue.AssigneeID) == util.UUIDToString(agentID) {
- return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, coalescedCommentIDs, true, "", actorUserID, rerunOfTaskID, pgtype.Timestamptz{}, origin)
+ return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, coalescedCommentIDs, true, "", actorUserID, rerunOfTaskID, pgtype.Timestamptz{}, origin, fresh)
}
- return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, true, "", actorUserID, rerunOfTaskID, origin)
+ return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, true, "", actorUserID, rerunOfTaskID, origin, fresh)
}
// The bulk terminal writes below are the sweeper, archive and daemon-recovery
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index f455618cf1..140a2f1f22 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -2279,12 +2279,15 @@ SELECT
COALESCE($9::boolean, FALSE),
$10,
$11,
- CASE
+ NULLIF(CASE
WHEN COALESCE($12::text, '') <> ''
THEN jsonb_build_object('head_sha', $12::text)
- ELSE NULL
- END,
- $13,
+ ELSE '{}'::jsonb
+ END || CASE
+ WHEN COALESCE($13::boolean, FALSE)
+ THEN '{"fresh_rerun":true}'::jsonb
+ ELSE '{}'::jsonb
+ END, '{}'::jsonb),
$14,
$15,
$16,
@@ -2294,9 +2297,10 @@ SELECT
$20,
$21,
$22,
+ $23,
-- The issue's status as this task is queued: the workflow step it works on (MUL-7420).
(SELECT i.status FROM issue i WHERE i.id = $3),
- COALESCE($23::uuid, gen_random_uuid())
+ COALESCE($24::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
@@ -2314,6 +2318,7 @@ type CreateAgentTaskParams struct {
HandoffNote pgtype.Text `json:"handoff_note"`
SquadID pgtype.UUID `json:"squad_id"`
HeadSha pgtype.Text `json:"head_sha"`
+ FreshRerun pgtype.Bool `json:"fresh_rerun"`
OriginatorUserID pgtype.UUID `json:"originator_user_id"`
AccountableUserID pgtype.UUID `json:"accountable_user_id"`
RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
@@ -2334,8 +2339,9 @@ type CreateAgentTaskParams struct {
// head_sha stamps the commit under review into the task's context JSONB so the
// reviewer-loop dedup (HasPendingTaskForIssueAndAgent) can tell a pending run
// against an OLD head apart from a fresh request against a NEW head (TEN-356).
-// Empty/absent head_sha leaves context NULL, preserving pre-TEN-356 behavior for
-// issues with no linked PR. Issue-linked tasks never hit quick-create context
+// Empty/absent head_sha leaves context NULL unless fresh_rerun is requested.
+// fresh_rerun disables source session/workdir reuse without losing rerun lineage.
+// Issue-linked tasks never hit quick-create context
// parsing (parseQuickCreateContext short-circuits on IssueID.Valid), so this
// key rides harmlessly alongside.
// id is minted by the application as a UUIDv7 (pkg/dbid) so consecutive
@@ -2359,6 +2365,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
arg.HandoffNote,
arg.SquadID,
arg.HeadSha,
+ arg.FreshRerun,
arg.OriginatorUserID,
arg.AccountableUserID,
arg.RuntimeMcpOverlay,
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 23c798fe73..4f3bcdc487 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -324,8 +324,9 @@ LIMIT @page_limit;
-- head_sha stamps the commit under review into the task's context JSONB so the
-- reviewer-loop dedup (HasPendingTaskForIssueAndAgent) can tell a pending run
-- against an OLD head apart from a fresh request against a NEW head (TEN-356).
--- Empty/absent head_sha leaves context NULL, preserving pre-TEN-356 behavior for
--- issues with no linked PR. Issue-linked tasks never hit quick-create context
+-- Empty/absent head_sha leaves context NULL unless fresh_rerun is requested.
+-- fresh_rerun disables source session/workdir reuse without losing rerun lineage.
+-- Issue-linked tasks never hit quick-create context
-- parsing (parseQuickCreateContext short-circuits on IssueID.Valid), so this
-- key rides harmlessly alongside.
-- id is minted by the application as a UUIDv7 (pkg/dbid) so consecutive
@@ -350,11 +351,15 @@ SELECT
COALESCE(sqlc.narg('is_leader_task')::boolean, FALSE),
sqlc.narg(handoff_note),
sqlc.narg(squad_id),
- CASE
+ NULLIF(CASE
WHEN COALESCE(sqlc.narg('head_sha')::text, '') <> ''
THEN jsonb_build_object('head_sha', sqlc.narg('head_sha')::text)
- ELSE NULL
- END,
+ ELSE '{}'::jsonb
+ END || CASE
+ WHEN COALESCE(sqlc.narg('fresh_rerun')::boolean, FALSE)
+ THEN '{"fresh_rerun":true}'::jsonb
+ ELSE '{}'::jsonb
+ END, '{}'::jsonb),
sqlc.narg(originator_user_id),
sqlc.narg(accountable_user_id),
sqlc.narg(runtime_mcp_overlay),