Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(workflow): brief project workflows as a status map (MUL-9913) (#11252)
Bohan Jiang3cb5473afce6
diff --git a/apps/docs/content/docs/workflows.fr.mdx b/apps/docs/content/docs/workflows.fr.mdxindex 00fa5339b0..14bc59f858 100644--- a/apps/docs/content/docs/workflows.fr.mdx+++ b/apps/docs/content/docs/workflows.fr.mdx@@ -42,7 +42,7 @@ Sélectionnez une colonne et choisissez ce qui se passe quand une tâche y entre</Step><Step>-Pour une étape confiée à un agent, écrivez ce qu’il doit faire, puis choisissez **Une fois terminé, passer à** (la colonne suivante si vous ne choisissez rien) et **En cas de rejet, renvoyer à** (quand cette étape juge le travail reçu insuffisant et qu’il doit être repris). Si l’étape ne peut pas continuer pour une raison extérieure, utilisez **Blocked** plutôt que le renvoi.+Pour une étape confiée à un agent, écrivez ce qu’il doit faire, puis choisissez **Une fois terminé, passer à** (si vous ne choisissez rien, la colonne suivante, en sautant les colonnes de clôture comme Won't Fix ; une colonne Terminé ou Fermée ne mène nulle part par défaut) et **En cas de rejet, renvoyer à** (quand cette étape juge le travail reçu insuffisant et qu’il doit être repris). Si l’étape ne peut pas continuer pour une raison extérieure, utilisez **Blocked** plutôt que le renvoi ; l’étape renvoie la tâche à la place seulement si le workflow n’a pas de colonne Blocked, ou si elle est elle-même une colonne Terminé ou Fermée.</Step><Step>diff --git a/apps/docs/content/docs/workflows.ja.mdx b/apps/docs/content/docs/workflows.ja.mdxindex 5ce4c7f0f7..1f6ffa05e2 100644--- a/apps/docs/content/docs/workflows.ja.mdx+++ b/apps/docs/content/docs/workflows.ja.mdx@@ -42,7 +42,7 @@ import { WorkflowDemo } from "@/components/demos/workflow-demo";</Step><Step>-エージェントに渡す場合は、このステップで行うことを書き、**完了したら移動**する先(未設定なら次の列)と**差し戻す先**(受け取った作業が不十分でやり直しが必要なときに使います)を選びます。外部の理由で進められないときは、差し戻しではなく **Blocked** を使います。+エージェントに渡す場合は、このステップで行うことを書き、**完了したら移動**する先(未設定なら次の列。ただし Won't Fix のような終了の列は飛ばし、完了・終了の列からは既定では進みません)と**差し戻す先**(受け取った作業が不十分でやり直しが必要なときに使います)を選びます。外部の理由で進められないときは、差し戻しではなく **Blocked** を使います。ワークフローに Blocked 列がない場合や、このステップ自体が完了・終了の列の場合だけ、代わりに差し戻します。</Step><Step>diff --git a/apps/docs/content/docs/workflows.ko.mdx b/apps/docs/content/docs/workflows.ko.mdxindex d86e83f0c7..c4350d49be 100644--- a/apps/docs/content/docs/workflows.ko.mdx+++ b/apps/docs/content/docs/workflows.ko.mdx@@ -42,7 +42,7 @@ import { WorkflowDemo } from "@/components/demos/workflow-demo";</Step><Step>-에이전트에게 넘긴다면 이 단계에서 할 일을 적고, **완료 후 이동**할 단계(지정하지 않으면 다음 열)와 **반려 시 되돌릴 단계**(받은 작업이 기준에 못 미쳐 다시 해야 할 때 사용)를 선택합니다. 외부 사정으로 진행할 수 없을 때는 되돌리기 대신 **Blocked**를 씁니다.+에이전트에게 넘긴다면 이 단계에서 할 일을 적고, **완료 후 이동**할 단계(지정하지 않으면 다음 열. 단, Won't Fix 같은 종료 열은 건너뛰고, 완료·종료 열에서는 기본적으로 다음으로 가지 않습니다)와 **반려 시 되돌릴 단계**(받은 작업이 기준에 못 미쳐 다시 해야 할 때 사용)를 선택합니다. 외부 사정으로 진행할 수 없을 때는 되돌리기 대신 **Blocked**를 씁니다. 워크플로에 Blocked 열이 없거나 이 단계 자체가 완료·종료 열일 때만 대신 되돌려 보냅니다.</Step><Step>diff --git a/apps/docs/content/docs/workflows.mdx b/apps/docs/content/docs/workflows.mdxindex 65dcce823b..43dea0ebc7 100644--- a/apps/docs/content/docs/workflows.mdx+++ b/apps/docs/content/docs/workflows.mdx@@ -42,7 +42,7 @@ Select a column and choose what happens when an issue enters it: **No handoff**,</Step><Step>-For an agent step, write what it should do. Then set **When done, move to** (the next column if you leave it unset) and **If rejected, send back to** (used when this step finds the work it received unacceptable and it needs rework). Use **Blocked**, not send-back, when the step cannot continue for an outside reason.+For an agent step, write what it should do. Then set **When done, move to** (if you leave it unset, the next column, skipping closed columns such as Won't Fix; a Done or Closed column moves nowhere by default) and **If rejected, send back to** (used when this step finds the work it received unacceptable and it needs rework). Use **Blocked**, not send-back, when the step cannot continue for an outside reason; the step sends the issue back instead only when the workflow has no Blocked column, or at a Done or Closed column.</Step><Step>diff --git a/apps/docs/content/docs/workflows.zh-Hant.mdx b/apps/docs/content/docs/workflows.zh-Hant.mdxindex 062b33c1cc..e4aa1e4c6c 100644--- a/apps/docs/content/docs/workflows.zh-Hant.mdx+++ b/apps/docs/content/docs/workflows.zh-Hant.mdx@@ -42,7 +42,7 @@ import { WorkflowDemo } from "@/components/demos/workflow-demo";</Step><Step>-如果交給 AI 代理,寫清這一步要做什麼,再選擇**完成後進入**哪一步(不選時預設進入下一列)、**打回時退回到**哪一步(這一步認為收到的工作不合格、需要返工時使用)。因外部原因無法繼續時用 **Blocked**,不要用退回。+如果交給 AI 代理,寫清這一步要做什麼,再選擇**完成後進入**哪一步(不選時預設進入下一列,但會跳過 Won't Fix 這類已關閉的列;已完成、已關閉類的列預設不往下走)、**打回時退回到**哪一步(這一步認為收到的工作不合格、需要返工時使用)。因外部原因無法繼續時用 **Blocked**,不要用退回;只有工作流沒有 Blocked 列,或這一步本身是已完成、已關閉類的列時,才改為退回。</Step><Step>diff --git a/apps/docs/content/docs/workflows.zh.mdx b/apps/docs/content/docs/workflows.zh.mdxindex cc22e609e9..3b15b77a42 100644--- a/apps/docs/content/docs/workflows.zh.mdx+++ b/apps/docs/content/docs/workflows.zh.mdx@@ -42,7 +42,7 @@ import { WorkflowDemo } from "@/components/demos/workflow-demo";</Step><Step>-如果交给智能体,写清这一步要做什么,再选择**完成后进入**哪一步(不选时默认进入下一列)、**打回时退回到**哪一步(这一步认为收到的工作不合格、需要返工时使用)。因外部原因无法继续时用 **Blocked**,不要用退回。+如果交给智能体,写清这一步要做什么,再选择**完成后进入**哪一步(不选时默认进入下一列,但会跳过 Won't Fix 这类已关闭的列;已完成、已关闭类的列默认不往下走)、**打回时退回到**哪一步(这一步认为收到的工作不合格、需要返工时使用)。因外部原因无法继续时用 **Blocked**,不要用退回;只有工作流没有 Blocked 列,或这一步本身是已完成、已关闭类的列时,才改为退回。</Step><Step>diff --git a/packages/core/issue-workflows/queries.test.ts b/packages/core/issue-workflows/queries.test.tsindex 0e8361199a..217db303ef 100644--- a/packages/core/issue-workflows/queries.test.ts+++ b/packages/core/issue-workflows/queries.test.ts@@ -117,6 +117,19 @@ describe("workflow helpers (MUL-7420)", () => {expect(workflowNextStatus(content, "cancelled")).toBe("");expect(workflowNextStatus(content, "missing")).toBe("");});++ it("matches the agent's brief for custom done and closed columns", () => {+ const withWontFix = { ...content, steps: columns("drafting", "editing", "wont_fix") };+ const categoryOf = (key: string) => (key === "wont_fix" || key === "cancelled" ? "closed" : key === "done" ? "done" : "started");+ // Finished work never goes to a closed column…+ expect(workflowNextStatus(withWontFix, "editing", categoryOf)).toBe("done");+ // …and a closed column routes only where its author chose.+ expect(workflowNextStatus(withWontFix, "wont_fix", categoryOf)).toBe("");+ const own = { ...withWontFix, steps: withWontFix.steps.map((s) => (s.status_key === "wont_fix" ? { ...s, next_status_key: "done" } : s)) };+ expect(workflowNextStatus(own, "wont_fix", categoryOf)).toBe("done");+ // Without a catalog the board order alone decides, as before.+ expect(workflowNextStatus(withWontFix, "editing")).toBe("wont_fix");+ });});describe("projectMoveMayHandOff", () => {diff --git a/packages/core/issue-workflows/queries.ts b/packages/core/issue-workflows/queries.tsindex dc92578e75..3d5e55f654 100644--- a/packages/core/issue-workflows/queries.ts+++ b/packages/core/issue-workflows/queries.ts@@ -79,15 +79,24 @@ export function workflowMiddleKeys(workflow: Pick<IssueWorkflow, "steps">): stri/*** The column a step's handler is told to move to when done: the step's own- * choice, else the next column (skipping blocked); empty at the end.+ * choice, else the next column, skipping blocked and closed ones; empty at the+ * end. With `categoryOf`, it matches the agent's brief for custom statuses+ * too: a closed column such as Won't Fix is never where finished work goes,+ * and a done or closed column routes only where its author chose (MUL-9913).*/-export function workflowNextStatus(workflow: Pick<IssueWorkflow, "steps">, statusKey: string): string {+export function workflowNextStatus(+ workflow: Pick<IssueWorkflow, "steps">,+ statusKey: string,+ categoryOf?: (statusKey: string) => string,+): string {const index = workflow.steps.findIndex((s) => s.status_key === statusKey);if (index < 0) return "";const own = workflow.steps[index]?.next_status_key;if (own) return own;+ const category = categoryOf?.(statusKey);+ if (category === "done" || category === "closed") return "";for (const s of workflow.steps.slice(index + 1)) {- if (s.status_key !== "blocked") return s.status_key;+ if (s.status_key !== "blocked" && categoryOf?.(s.status_key) !== "closed") return s.status_key;}return "";}diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex c8e0fc0577..3a174d214b 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -1742,7 +1742,6 @@"target_squad": "Squad · leader dispatches","target_member": "Member","instructions_hint": "Sent to the handler with this run, alongside the issue description and comments.",- "next_hint": "The handler updates the status directly and sends it back only for rework, not blockers. Finishing a run never changes the status automatically.","preview_brief": "Preview the agent’s brief","preview_title": "Brief for the “{{status}}” step","preview_description": "What the handler’s run receives when an issue enters this step. Saved changes are not required to preview.",diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.jsonindex cfd79d46c3..e040ee711b 100644--- a/packages/views/locales/es/issues.json+++ b/packages/views/locales/es/issues.json@@ -1735,7 +1735,6 @@"target_squad": "Squad · el líder reparte","target_member": "Miembro","instructions_hint": "Se envía al responsable con esta ejecución, junto con la descripción y los comentarios de la tarea.",- "next_hint": "El responsable actualiza el estado directamente y la devuelve solo para rehacer trabajo, no por bloqueos. Terminar una ejecución nunca cambia el estado automáticamente.","preview_brief": "Ver el encargo del agente","preview_title": "Encargo del paso “{{status}}”","preview_description": "Lo que recibe la ejecución del responsable cuando una tarea entra en este paso. No hace falta guardar los cambios para verlo.",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 55ce56ab8b..ebdab368d7 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -1742,7 +1742,6 @@"target_squad": "Squad · le leader répartit","target_member": "Membre","instructions_hint": "Envoyées au responsable avec cette exécution, avec la description et les commentaires de la tâche.",- "next_hint": "Le responsable met directement à jour le statut et ne la renvoie que pour une reprise, pas en cas de blocage. La fin d'une exécution ne change jamais le statut automatiquement.","preview_brief": "Aperçu des consignes de l’agent","preview_title": "Consignes de l’étape « {{status}} »","preview_description": "Ce que reçoit l’exécution du responsable quand une tâche entre dans cette étape. Pas besoin d’enregistrer pour prévisualiser.",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 3b967bd669..5bf0943b4e 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -1668,7 +1668,6 @@"target_squad": "スクワッド · リーダーが割り振り","target_member": "メンバー","instructions_hint": "今回の実行の指示として処理者に送られ、タスクの説明やコメントと一緒にコンテキストになります。",- "next_hint": "担当者が直接ステータスを更新し、差し戻すのは手直しが必要な場合のみで、ブロック時は差し戻しません。実行が完了してもステータスは自動的に変わりません。","preview_brief": "エージェントが受け取る説明をプレビュー","preview_title": "「{{status}}」ステップの説明","preview_description": "タスクがこのステップに入ったとき、処理者の実行が受け取る内容です。プレビューに保存は不要です。",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 27e1b23828..7de23ffeb4 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -1668,7 +1668,6 @@"target_squad": "스쿼드 · 리더가 배분","target_member": "멤버","instructions_hint": "이번 실행의 지침으로 처리자에게 전달되며, 태스크 설명·댓글과 함께 맥락이 됩니다.",- "next_hint": "담당자가 상태를 직접 업데이트하며, 막힌 경우가 아니라 재작업이 필요할 때만 되돌려 보냅니다. 실행이 끝나도 상태가 자동으로 바뀌지는 않습니다.","preview_brief": "에이전트가 받는 설명 미리 보기","preview_title": "“{{status}}” 단계 설명","preview_description": "태스크가 이 단계에 들어오면 처리자의 실행이 받는 내용입니다. 미리 보기에는 저장이 필요 없습니다.",diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.jsonindex 820fad05fe..405f7b2de2 100644--- a/packages/views/locales/ru/issues.json+++ b/packages/views/locales/ru/issues.json@@ -1887,7 +1887,6 @@"target_squad": "Команда · лидер распределяет работу","target_member": "Участник","instructions_hint": "Отправляются исполнителю с этим запуском вместе с описанием и комментариями задачи.",- "next_hint": "Исполнитель обновляет статус напрямую и возвращает задачу только на доработку, но не при блокировке. Завершение запуска никогда не меняет статус автоматически.","preview_brief": "Посмотреть задание для агента","preview_title": "Задание для этапа «{{status}}»","preview_description": "Что получает исполнитель при входе задачи на этот этап. Для предпросмотра сохранять изменения не нужно.",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 2a2e8ec07b..232cd544b6 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -1668,7 +1668,6 @@"target_squad": "小队 · 由队长分派","target_member": "成员","instructions_hint": "作为这次运行的说明发给处理人,和任务描述、评论一起作为上下文。",- "next_hint": "由处理人自己改状态,只有需要返工时才退回,受阻不用退回。运行结束不会自动改状态。","preview_brief": "预览智能体收到的说明","preview_title": "\"{{status}}\"这一步的说明","preview_description": "任务进入这一步时,处理人的运行会收到这段说明。预览不需要先保存。",diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.jsonindex 2a8525f7e9..894d8a706c 100644--- a/packages/views/locales/zh-Hant/issues.json+++ b/packages/views/locales/zh-Hant/issues.json@@ -1668,7 +1668,6 @@"target_squad": "小隊 · 由 leader 分派","target_member": "成員","instructions_hint": "作為這次執行的說明發給處理人,和任務描述、評論一起作為上下文。",- "next_hint": "由處理人直接更新狀態,僅在需要返工時才退回,遇到阻塞不需退回。執行結束不會自動變更狀態。","preview_brief": "預覽 AI 代理收到的說明","preview_title": "「{{status}}」這一步的說明","preview_description": "任務進入這一步時,處理人的執行會收到這段說明。預覽不需要先儲存。",diff --git a/packages/views/workflows/handoff-form.tsx b/packages/views/workflows/handoff-form.tsxindex a931f3f02f..caea3fed65 100644--- a/packages/views/workflows/handoff-form.tsx+++ b/packages/views/workflows/handoff-form.tsx@@ -299,11 +299,16 @@ export function HandoffFields({const { t } = useT("issues");const wsId = useWorkspaceId();const labelOf = useStatusLabel(wsId);+ const catalog = useIssueStatuses(wsId);const mode = modeOf(step.handler);// Not derived from the status key: a step for a status still to be created// goes by a draft id that need not be a valid element id.const instructionsId = useId();- const nextDefault = workflowNextStatus({ steps: workflow.steps.map((s) => ({ ...s, next_status_key: undefined })) }, step.status_key);+ const nextDefault = workflowNextStatus(+ { steps: workflow.steps.map((s) => ({ ...s, next_status_key: undefined })) },+ step.status_key,+ catalog.categoryOf,+ );const nextDefaultLabel = defaultNextLabel ?? (nextDefault ? labelOf(nextDefault) : "");const choose = (m: HandoffMode) => {if (m === mode) return;@@ -584,17 +589,13 @@ function NextBackFields({);})}</div>- <p className="text-caption leading-5 text-muted-foreground">- {t(($) => $.workflows.editor.next_hint)}- {onPreview && (- <>- {" "}- <button type="button" onClick={onPreview} className="text-brand hover:underline">- {t(($) => $.workflows.editor.preview_brief)}- </button>- </>- )}- </p>+ {onPreview && (+ <p className="text-caption leading-5">+ <button type="button" onClick={onPreview} className="text-brand hover:underline">+ {t(($) => $.workflows.editor.preview_brief)}+ </button>+ </p>+ )}</div>);}diff --git a/packages/views/workflows/workflow-editor-page.test.tsx b/packages/views/workflows/workflow-editor-page.test.tsxindex 7da02ce894..c048fd7e98 100644--- a/packages/views/workflows/workflow-editor-page.test.tsx+++ b/packages/views/workflows/workflow-editor-page.test.tsx@@ -7,14 +7,17 @@ import { buildIssueStatusCatalog } from "@multica/core/issue-statuses";import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";import { projectListOptions } from "@multica/core/projects/queries";import { renderWithI18n } from "../test/i18n";+import type { IssueWorkflow } from "@multica/core/types";import { WorkflowEditorPage } from "./workflow-editor-page";-const { createWorkflow } = vi.hoisted(() => ({ createWorkflow: vi.fn() }));+const { createWorkflow, statusEntries } = vi.hoisted(() => ({ createWorkflow: vi.fn(), statusEntries: { current: [] as unknown[] } }));vi.mock("@multica/core/api", () => ({ api: {}, ApiError: class extends Error {}, clientErrorMessage: () => null }));vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));vi.mock("@multica/core/paths", () => ({ useCurrentWorkspace: () => ({ id: "ws-1", name: "Acme" }) }));-vi.mock("@multica/core/issue-statuses/hooks", () => ({ useIssueStatuses: () => buildIssueStatusCatalog([]) }));+vi.mock("@multica/core/issue-statuses/hooks", () => ({+ useIssueStatuses: () => buildIssueStatusCatalog(statusEntries.current as never),+}));vi.mock("@multica/core/workspace/hooks", () => ({ useActorName: () => ({ getActorName: () => "Builder" }) }));vi.mock("@multica/core/issue-workflows", async (importOriginal) => ({...(await importOriginal<typeof import("@multica/core/issue-workflows")>()),@@ -27,14 +30,14 @@ vi.mock("../common/actor-avatar", () => ({ActorAvatar: ({ actorId }: { actorId: string }) => <span data-testid={`avatar-${actorId}`} />,}));-function renderEditor(props: { template?: "content"; canCreateStatus?: boolean } = {}) {+function renderEditor(props: { template?: "content"; canCreateStatus?: boolean; seed?: IssueWorkflow } = {}) {const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });qc.setQueryData(projectListOptions("ws-1").queryKey, [] as never);qc.setQueryData(agentListOptions("ws-1").queryKey, [{ id: "agent-1", name: "Builder", archived_at: null }] as never);qc.setQueryData(memberListOptions("ws-1").queryKey, [] as never);renderWithI18n(<QueryClientProvider client={qc}>- <WorkflowEditorPage workflowId={null} seed={null} canEdit onBack={vi.fn()} onOpen={vi.fn()} {...props} />+ <WorkflowEditorPage workflowId={null} seed={props.seed ?? null} canEdit onBack={vi.fn()} onOpen={vi.fn()} template={props.template} canCreateStatus={props.canCreateStatus} /></QueryClientProvider>,);}@@ -42,6 +45,7 @@ function renderEditor(props: { template?: "content"; canCreateStatus?: boolean }afterEach(() => {cleanup();createWorkflow.mockReset();+ statusEntries.current = [];});describe("WorkflowEditorPage", () => {@@ -93,6 +97,29 @@ describe("WorkflowEditorPage", () => {fireEvent.click(screen.getByRole("combobox", { name: "When done, move to" }));expect(screen.queryByRole("option", { name: "Deploy" })).toBeNull();});++ // The agent's brief never routes finished work into a closed column, so+ // the editor's default must not either (MUL-9913).+ it("skips a custom closed column when showing the default next", () => {+ statusEntries.current = [{ key: "wont_fix", name: "Won't Fix", category: "closed", description: "", color: "", icon: "", position: 0 }];+ const step = (status_key: string) => ({ status_key, handler: { type: "none" as const }, instructions: "" });+ // Seeded as a duplicate: a new draft pre-filled with these columns.+ renderEditor({+ seed: {+ id: "wf-1", workspace_id: "ws-1", name: "Delivery", description: "", is_default: false, owner_id: null,+ project_ids: [], created_at: "", updated_at: "",+ steps: [+ step("todo"),+ { status_key: "in_review", handler: { type: "agent", id: "agent-1" }, instructions: "" },+ step("wont_fix"),+ step("done"),+ step("cancelled"),+ ],+ },+ });+ fireEvent.click(stepCard("In Review"));+ expect(screen.getByRole("combobox", { name: "When done, move to" }).textContent).toContain("Next column (Done)");+ });});// Statuses are shared by every board, so only admins add them (MUL-8120).diff --git a/packages/views/workflows/workflow-editor-page.tsx b/packages/views/workflows/workflow-editor-page.tsxindex 64b8fe9751..a654f2fa30 100644--- a/packages/views/workflows/workflow-editor-page.tsx+++ b/packages/views/workflows/workflow-editor-page.tsx@@ -375,7 +375,7 @@ export function WorkflowEditorPage({];const current = listed.find((c) => c.id === selectedId) ?? listed[1]!;const nextOf = (column: DraftColumn, h: Handoff | undefined) =>- h?.next_status_key ?? workflowNextStatus(draftFlow, columnKey(column));+ h?.next_status_key ?? workflowNextStatus(draftFlow, columnKey(column), catalog.categoryOf);const card = (column: DraftColumn) => {const key = "status_key" in column ? column.status_key : null;const optional = key === "backlog" || key === "blocked";@@ -590,7 +590,7 @@ export function WorkflowEditorPage({off={isOff(current)}handoff={draft.handoffs[current.id]}flow={flow}- defaultNextLabel={columnLabel(workflowNextStatus(draftFlow, columnKey(current)))}+ defaultNextLabel={columnLabel(workflowNextStatus(draftFlow, columnKey(current), catalog.categoryOf))}canEdit={canEdit}statusOptions={middleIds.has(current.id) ? addable : null}onReplaceStatus={(key) => replaceStatus(current, key)}diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 1382d31b74..466377040c 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -214,6 +214,7 @@ func daemonCommonCapabilities() []string {protocol.DaemonCapabilityCheckoutKeepsWorkV1,protocol.DaemonCapabilityJoinedWakeupsV1,protocol.DaemonCapabilityWorkflowStatusRulesV1,+ protocol.DaemonCapabilityWorkflowStatusMapV1,protocol.DaemonCapabilityCLICommentSteerV1,}}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 4d3e835a67..c45f143c91 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -8435,6 +8435,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iIssueStatuses: convertIssueStatusesForEnv(task.IssueStatuses),IssueStatusesOmitted: task.IssueStatusesOmitted,HasProjectWorkflow: taskHasProjectWorkflow(task),+ ProjectWorkflowStatusMap: taskHasProjectWorkflow(task) && task.ProjectWorkflow.StatusMap,ConnectedApps: task.ConnectedApps,}diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex fd454cf706..f56901b5d7 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -232,6 +232,10 @@ type TaskContextForEnv struct {// statuses and commands are the issue's real contract (MUL-8145). Servers// that send no workflow leave it false and the brief unchanged.HasProjectWorkflow bool+ // ProjectWorkflowStatusMap is true when that block is a status map+ // rather than per-step commands (MUL-9913): the brief then states the+ // rules for choosing from the map. Only meaningful with HasProjectWorkflow.+ ProjectWorkflowStatusMap bool// ConnectedApps lists per-run external app capabilities mounted through// MCP overlays. Rendered briefly so the agent can map app names such as// Notion to the actual MCP server name (`composio`).diff --git a/server/internal/daemon/execenv/runtime_config_project_workflow_test.go b/server/internal/daemon/execenv/runtime_config_project_workflow_test.goindex d4571d1f63..4c57c0fedc 100644--- a/server/internal/daemon/execenv/runtime_config_project_workflow_test.go+++ b/server/internal/daemon/execenv/runtime_config_project_workflow_test.go@@ -97,3 +97,75 @@ func TestBriefWithoutProjectWorkflowKeepsBuiltInStatusRules(t *testing.T) {}}}++// A status-map [Project workflow] block lists no commands (MUL-9913): the+// brief states how to choose from the map instead, and keeps every invariant+// of the command form — no built-in moves, no competing status list.+func TestBriefWithStatusMapStatesTheMapRules(t *testing.T) {+ t.Parallel()+ catalog := []IssueStatusForEnv{{Key: "wont_fix", Name: "Won't Fix", Category: "closed"}}+ for name, ctx := range map[string]TaskContextForEnv{+ "agent": {IssueID: "issue-1", AgentID: "a-1", AgentName: "Eve", HasProjectWorkflow: true, ProjectWorkflowStatusMap: true},+ "squad leader": {IssueID: "issue-1", AgentID: "a-1", AgentName: "Eve", HasProjectWorkflow: true, ProjectWorkflowStatusMap: true, IsSquadLeader: true},+ "custom catalog": {IssueID: "issue-1", AgentID: "a-1", AgentName: "Eve", HasProjectWorkflow: true, ProjectWorkflowStatusMap: true, IssueStatuses: catalog},+ } {+ out := buildMetaSkillContent("claude", ctx)+ for _, rule := range builtInStatusRules {+ if strings.Contains(out, rule) {+ t.Errorf("%s: status-map brief still carries built-in rule %q", name, rule)+ }+ }+ for _, want := range []string{+ "3. Complete the task within your Agent Identity boundaries",+ "5. Before exiting, confirm the issue's status in `[Project workflow]` matches where things actually stand.",+ "`[Project workflow]` is this issue's status map.",+ "Entering a status that hands off reassigns the issue and starts its handler's run",+ "A status without a handler hands nothing off: the work stays yours",+ "At a step you handle, follow its Routes line.",+ "leave `done`-category statuses to a human unless Routes leads there",+ "a `closed`-category status that fits; comment why first",+ "add no wakeup for that",+ // A stuck step goes back to whoever can supply what is missing when+ // it cannot park the issue: at a terminal status, whose author+ // routed only the send-back, or without a blocked column.+ "at a `done`- or `closed`-category status, its send-back route if it has one; elsewhere `blocked` when the map has it, else your step's send-back route when it has one",+ "This issue's status map is in `[Project workflow]`",+ "--duplicate-of",+ "questions, discussion, and acknowledgements never touch status",+ } {+ if !strings.Contains(out, want) {+ t.Errorf("%s: status-map brief missing %q\n---\n%s", name, want, out)+ }+ }+ // The command form's wording would point at lines the map lacks.+ // The map is the only status list, and no built-in key is named.+ for _, stale := range []string{+ "Step done", "Needs changes", "Can't proceed →", "Move this issue only with its commands", "statuses and commands are in",+ "`wont_fix`", "`in_progress`", "`in_review`",+ } {+ if strings.Contains(out, stale) {+ t.Errorf("%s: status-map brief carries %q", name, stale)+ }+ }+ if got := strings.Count(out, "**Issue status"); got != 1 {+ t.Errorf("%s: brief has %d issue-status sections, want 1", name, got)+ }+ }+ leader := buildMetaSkillContent("claude", TaskContextForEnv{IssueID: "issue-1", HasProjectWorkflow: true, ProjectWorkflowStatusMap: true, IsSquadLeader: true})+ if !strings.Contains(leader, "dispatching members is not delivery — move the parent on only on a later turn") {+ t.Errorf("leader status-map brief must keep dispatch-is-not-delivery\n---\n%s", leader)+ }+}++// The status map flag only applies with a workflow block, and an issue+// without one picks closed statuses by the same rule.+func TestStatusMapFlagNeedsAWorkflowAndSharesTheClosedRule(t *testing.T) {+ t.Parallel()+ plain := buildMetaSkillContent("claude", TaskContextForEnv{IssueID: "issue-1", ProjectWorkflowStatusMap: true})+ if plain != buildMetaSkillContent("claude", TaskContextForEnv{IssueID: "issue-1"}) {+ t.Fatal("the status map flag must not change a brief without a project workflow")+ }+ if !strings.Contains(plain, issueStatusClosedRule) {+ t.Errorf("brief without a workflow must carry the closed-status rule\n---\n%s", plain)+ }+}diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex 091bcac93e..e824277d3d 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -363,6 +363,10 @@ func writeIssueStatusCommand(b *strings.Builder, ctx TaskContextForEnv) {// compete with it — built-ins the workflow may reject included. The line// stays as the command's reference for other issues, and is fixed text so// the cache prefix splits only on whether a workflow is present (MUL-8145).+ if ctx.HasProjectWorkflow && ctx.ProjectWorkflowStatusMap {+ b.WriteString("- `multica issue status <id> <status>` — flip status. This issue's status map is in `[Project workflow]`; for other issues, an invalid status errors with the full valid list.\n")+ return+ }if ctx.HasProjectWorkflow {b.WriteString("- `multica issue status <id> <status>` — flip status. This issue's statuses and commands are in `[Project workflow]`; for other issues, an invalid status errors with the full valid list.\n")return@@ -707,6 +711,11 @@ func writeWorkflowIssue(b *strings.Builder, ctx TaskContextForEnv) {} else {b.WriteString("4. **Post your final results as a comment — this step is mandatory**: post it with `multica issue comment add` using the platform-correct non-inline mode from ## Comment Formatting (never inline `--content`). When the per-turn user message carries a triggering comment, reply in its thread with the `--parent` value it gives you for THIS turn (never one from an earlier turn); when it lists several threads, post one reply per thread. With no triggering comment, post a new top-level comment. `## Output` states why this call is the only delivery channel.\n")}+ if ctx.HasProjectWorkflow && ctx.ProjectWorkflowStatusMap {+ b.WriteString("5. Before exiting, confirm the issue's status in `[Project workflow]` matches where things actually stand.\n\n")+ writeIssueStatusRulesForStatusMap(b, ctx)+ return+ }if ctx.HasProjectWorkflow {b.WriteString("5. Before exiting, confirm the issue sits where things actually stand: you ran the matching command from `[Project workflow]`, or you left it at its current step on purpose because its work continues.\n\n")writeIssueStatusRulesForWorkflow(b, ctx)@@ -722,13 +731,23 @@ func writeWorkflowIssue(b *strings.Builder, ctx TaskContextForEnv) {if ctx.IsSquadLeader {b.WriteString("- Squad leader: dispatching members is not delivery — a dispatch turn leaves the parent `in_progress`, and it moves to `in_review` only on the later turn (a member update or stage-barrier re-trigger) where you confirm the overall goal is met.\n")}+ b.WriteString(issueStatusClosedRule)// A custom catalog needs one reminder that workflow updates use exact keys.if len(ctx.IssueStatuses) > 0 {b.WriteString("- The workflow rules above refer to exact built-in status keys, not categories. Custom statuses share lifecycle semantics only, not built-in automation behavior.\n")}- b.WriteString("- Your turn produced none of the issue's own deliverable — you answered a question or consulted on work owned elsewhere → write nothing, at any point; questions, discussion, and acknowledgements never touch status. This no-write default is what keeps concurrent runs from flapping the board.\n\n")+ b.WriteString(issueStatusNoWriteRule)}+// issueStatusClosedRule and issueStatusNoWriteRule are the status rules an+// issue follows with or without a project workflow: a closed-category status+// is how an agent records that the work will not be done, whichever status+// list it picks from (MUL-9913).+const (+ issueStatusClosedRule = "- The work won't be done — out of scope, not reproducible, a duplicate → a `closed`-category status that fits; comment why first, and mark a duplicate with `multica issue status <id> cancelled --duplicate-of <original>`.\n"+ issueStatusNoWriteRule = "- Your turn produced none of the issue's own deliverable — you answered a question or consulted on work owned elsewhere → write nothing, at any point; questions, discussion, and acknowledgements never touch status. This no-write default is what keeps concurrent runs from flapping the board.\n\n"+)+// writeIssueStatusRulesForWorkflow replaces the built-in status rules for an// issue whose project workflow came with the claim (MUL-8145). The workflow// may list neither `in_progress` nor `in_review` — the server rejects a status@@ -747,7 +766,27 @@ func writeIssueStatusRulesForWorkflow(b *strings.Builder, ctx TaskContextForEnv)if ctx.IsSquadLeader {b.WriteString("- Squad leader: dispatching members is not delivery — a dispatch turn leaves the parent at its current step, and you run Step done only on the later turn (a member update or stage-barrier re-trigger) where you confirm the overall goal is met.\n")}- b.WriteString("- Your turn produced none of the issue's own deliverable — you answered a question or consulted on work owned elsewhere → write nothing, at any point; questions, discussion, and acknowledgements never touch status. This no-write default is what keeps concurrent runs from flapping the board.\n\n")+ b.WriteString(issueStatusNoWriteRule)+}++// writeIssueStatusRulesForStatusMap states the rules for an issue whose+// [Project workflow] block is a status map (MUL-9913): the block says what+// each status means and who entering it hands off to, and the agent sets the+// one that matches where the issue stands. These rules stay here, as fixed+// text, so the per-turn block carries only the map and the cache prefix+// splits only on the brief's form.+func writeIssueStatusRulesForStatusMap(b *strings.Builder, ctx TaskContextForEnv) {+ b.WriteString("**Issue status — this issue follows its project workflow** (skip any status call your Agent Identity forbids)\n\n")+ b.WriteString("`[Project workflow]` is this issue's status map. When your work changes where the issue stands, set the status whose meaning matches.\n\n")+ b.WriteString("- Entering a status that hands off reassigns the issue and starts its handler's run: go there only once your part is done. A status you handle starts your run by itself — add no wakeup for that. A status without a handler hands nothing off: the work stays yours until it is delivered or reaches one that does.\n")+ b.WriteString("- At a step you handle, follow its Routes line. Otherwise, delivered work goes to the status meaning delivered; leave `done`-category statuses to a human unless Routes leads there or the map has no delivered status.\n")+ b.WriteString(issueStatusClosedRule)+ b.WriteString("- Work continues beyond this turn → leave the status.\n")+ b.WriteString("- You cannot proceed without something you are missing → comment what is missing, then: at a `done`- or `closed`-category status, its send-back route if it has one; elsewhere `blocked` when the map has it, else your step's send-back route when it has one.\n")+ if ctx.IsSquadLeader {+ b.WriteString("- Squad leader: dispatching members is not delivery — move the parent on only on a later turn that confirms the current step's goal is met.\n")+ }+ b.WriteString(issueStatusNoWriteRule)}// writeSubIssueCreation emits the Sub-issue Creation section.diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex 519aca0129..d4691ba1e0 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -71,6 +71,9 @@ type IssueStatusData struct {// observer's — and goes into the per-turn prompt as is.type ProjectWorkflowData struct {Brief string `json:"brief"`+ // StatusMap marks a status-map brief (MUL-9913); an older server sends+ // the per-step command brief and leaves it false.+ StatusMap bool `json:"status_map,omitempty"`}// Task represents a claimed task from the server.diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex f02f350415..424e05e669 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -375,6 +375,9 @@ type TaskIssueStatusData struct {// in the per-turn prompt, never in the cached runtime brief.type TaskProjectWorkflowData struct {Brief string `json:"brief"`+ // StatusMap marks a status-map brief, which the daemon pairs with the+ // status-map rules; without it the brief lists per-step commands.+ StatusMap bool `json:"status_map,omitempty"`// stepMoved selects the server-side leader briefing without changing the wire.stepMoved bool}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex f98681f39b..c5a073e7c2 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -3334,10 +3334,14 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu// Resolved before the leader briefing, which words the owning// leader's status moves by it (MUL-8145).legacyRuntimeRules := !requestHasClientCapability(r, protocol.DaemonCapabilityWorkflowStatusRulesV1)- projectWorkflow := h.claimProjectWorkflow(r.Context(), issue, task, legacyRuntimeRules)+ stepCommands := !requestHasClientCapability(r, protocol.DaemonCapabilityWorkflowStatusMapV1)+ projectWorkflow := h.claimProjectWorkflow(r.Context(), issue, task, legacyRuntimeRules, stepCommands)leaderWorkflow := leaderNoWorkflowif projectWorkflow != nil {leaderWorkflow = leaderWorkflowCurrentDaemon+ if projectWorkflow.StatusMap {+ leaderWorkflow = leaderWorkflowStatusMap+ }if projectWorkflow.stepMoved {leaderWorkflow = leaderWorkflowStepMoved} else if legacyRuntimeRules {diff --git a/server/internal/handler/issue_workflow.go b/server/internal/handler/issue_workflow.goindex 3b519accee..c6898fabd6 100644--- a/server/internal/handler/issue_workflow.go+++ b/server/internal/handler/issue_workflow.go@@ -1350,6 +1350,12 @@ func (h *Handler) PreviewIssueWorkflowBrief(w http.ResponseWriter, r *http.RequeEffectiveStatus: func(key string) string {return resolver.Effective(ctx, h.Queries, key)},+ StatusCategory: func(key string) string {+ return resolver.Category(ctx, h.Queries, key)+ },+ StatusDescription: func(key string) string {+ return resolver.Description(ctx, h.Queries, key)+ },HandlerName: func(s issueworkflow.Step) string {switch s.Handler.Type {case issueworkflow.HandlerAgent, issueworkflow.HandlerSquad, issueworkflow.HandlerMember:diff --git a/server/internal/handler/issue_workflow_entry.go b/server/internal/handler/issue_workflow_entry.goindex 4d40fe09f6..1ed7b47333 100644--- a/server/internal/handler/issue_workflow_entry.go+++ b/server/internal/handler/issue_workflow_entry.go@@ -271,6 +271,12 @@ func (h *Handler) workflowBriefInput(ctx context.Context, issue db.Issue, def isEffectiveStatus: func(key string) string {return resolver.Effective(ctx, h.Queries, key)},+ StatusCategory: func(key string) string {+ return resolver.Category(ctx, h.Queries, key)+ },+ StatusDescription: func(key string) string {+ return resolver.Description(ctx, h.Queries, key)+ },HandlerName: func(step issueworkflow.Step) string {if !step.HandsOff() {return ""@@ -357,8 +363,10 @@ func (h *Handler) assigneeActiveRuns(ctx context.Context, issue db.Issue) []db.L// gets the observer brief, so it does not move a step it does not own.//// legacyRuntimeRules is true for a daemon that does not advertise-// protocol.DaemonCapabilityWorkflowStatusRulesV1; see BriefInput.-func (h *Handler) claimProjectWorkflow(ctx context.Context, issue db.Issue, task *db.AgentTaskQueue, legacyRuntimeRules bool) *TaskProjectWorkflowData {+// protocol.DaemonCapabilityWorkflowStatusRulesV1, and stepCommands for one+// that does not advertise protocol.DaemonCapabilityWorkflowStatusMapV1; see+// BriefInput.+func (h *Handler) claimProjectWorkflow(ctx context.Context, issue db.Issue, task *db.AgentTaskQueue, legacyRuntimeRules, stepCommands bool) *TaskProjectWorkflowData {def, project, err := issueworkflow.ForProject(ctx, h.Queries, issue.WorkspaceID, issue.ProjectID)if err != nil {slog.Warn("task claim: failed to load project workflow for brief injection",@@ -370,6 +378,7 @@ func (h *Handler) claimProjectWorkflow(ctx context.Context, issue db.Issue, task}in := h.workflowBriefInput(ctx, issue, *def, project)in.LegacyRuntimeRules = legacyRuntimeRules+ in.StepCommands = stepCommandsstepMoved := workflowStepMoved(def, issue.Status, task)if stepMoved {in.BoundStep = task.WorkflowStep.String@@ -380,7 +389,11 @@ func (h *Handler) claimProjectWorkflow(ctx context.Context, issue db.Issue, taskin.AssigneeName = h.actorDisplayName(ctx, issue.WorkspaceID, issue.AssigneeType.String, issue.AssigneeID)}}- return &TaskProjectWorkflowData{Brief: issueworkflow.Brief(in), stepMoved: stepMoved}+ return &TaskProjectWorkflowData{+ Brief: issueworkflow.Brief(in),+ StatusMap: !legacyRuntimeRules && !stepCommands,+ stepMoved: stepMoved,+ }}// taskRunsForAssignee reports whether a run works on the issue as itsdiff --git a/server/internal/handler/issue_workflow_test.go b/server/internal/handler/issue_workflow_test.goindex 6d0cb168ae..d686705956 100644--- a/server/internal/handler/issue_workflow_test.go+++ b/server/internal/handler/issue_workflow_test.go@@ -566,7 +566,7 @@ func TestStatusChangeHandsOffOnDefaultProject(t *testing.T) {t.Fatalf("handoff note = %q, want none: the brief rides the claim", tasks[0].HandoffNote.String)}brief := claimBriefForTest(t, issueID, tasks[0])- for _, want := range []string{"Implement it and open a PR.", "This project's workflow — Default (Workflow handoff project)", "Step done → multica issue status"} {+ for _, want := range []string{"Implement it and open a PR.", "This project's workflow — Default (Workflow handoff project)", "\nStatus map for "} {if !strings.Contains(brief, want) {t.Fatalf("claim brief is missing %q:\n%s", want, brief)}@@ -991,11 +991,11 @@ func TestClaimCarriesProjectWorkflow(t *testing.T) {quietProject := createWorkflowTestProject(t, "Workflow quiet project")quiet := dbfx.Issue(t, "no handoffs", testutil.Cols{"project_id": quietProject, "status": "todo"})quietIssue, _ := testHandler.Queries.GetIssue(context.Background(), util.MustParseUUID(quiet))- if testHandler.claimProjectWorkflow(context.Background(), quietIssue, nil, false) != nil {+ if testHandler.claimProjectWorkflow(context.Background(), quietIssue, nil, false, false) != nil {t.Fatal("a Default project without handoffs must not carry a workflow")}stale := db.AgentTaskQueue{AgentID: util.MustParseUUID(agentID), WorkflowStep: pgtype.Text{String: "waiting_for_merge", Valid: true}}- if testHandler.claimProjectWorkflow(context.Background(), quietIssue, &stale, false) != nil {+ if testHandler.claimProjectWorkflow(context.Background(), quietIssue, &stale, false, false) != nil {t.Fatal("a Default project without handoffs must not restrict a stale binding")}@@ -1004,18 +1004,31 @@ func TestClaimCarriesProjectWorkflow(t *testing.T) {"project_id": projectID, "status": "in_progress", "assignee_type": "agent", "assignee_id": agentID,})- // The assignee's run gets the step's instructions and its commands.+ // The assignee's run gets the step's instructions and the status map.brief := claimBriefForTest(t, issueID, db.AgentTaskQueue{AgentID: util.MustParseUUID(agentID)})for _, want := range []string{"This project's workflow — Default (Workflow claim project)","Implement it and open a PR.",+ "\nStatus map for "," ← current",- "Step done → multica issue status",} {if !strings.Contains(brief, want) {t.Fatalf("assignee brief is missing %q:\n%s", want, brief)}}+ // A daemon without the status map keeps the per-step commands its+ // runtime brief points at, and is not told the brief is a map.+ issue, _ := testHandler.Queries.GetIssue(context.Background(), util.MustParseUUID(issueID))+ assignee := db.AgentTaskQueue{AgentID: util.MustParseUUID(agentID)}+ if mapped := testHandler.claimProjectWorkflow(context.Background(), issue, &assignee, false, false); mapped == nil || !mapped.StatusMap {+ t.Fatalf("current daemon's claim must mark the status map: %+v", mapped)+ }+ for _, legacy := range []bool{false, true} {+ commands := testHandler.claimProjectWorkflow(context.Background(), issue, &assignee, legacy, true)+ if commands == nil || commands.StatusMap || !strings.Contains(commands.Brief, "Step done → multica issue status") || strings.Contains(commands.Brief, "Status map for ") {+ t.Fatalf("legacy=%v daemon must keep the command brief: %+v", legacy, commands)+ }+ }if matched := claimBriefForTest(t, issueID, db.AgentTaskQueue{AgentID: util.MustParseUUID(agentID), WorkflowStep: pgtype.Text{String: "in_progress", Valid: true}}); matched != brief {t.Fatalf("matching and NULL bindings must receive the same brief:\n%s", matched)}@@ -1029,7 +1042,7 @@ func TestClaimCarriesProjectWorkflow(t *testing.T) {plain := dbfx.Issue(t, "no workflow", testutil.Cols{"status": "todo"})plainIssue, _ := testHandler.Queries.GetIssue(context.Background(), util.MustParseUUID(plain))- if testHandler.claimProjectWorkflow(context.Background(), plainIssue, nil, false) != nil {+ if testHandler.claimProjectWorkflow(context.Background(), plainIssue, nil, false, false) != nil {t.Fatal("an issue outside a project must not carry a workflow")}}@@ -1105,7 +1118,7 @@ func TestClaimExplainsMovedWorkflowStep(t *testing.T) {if observer {claim.AgentID = other}- got := testHandler.claimProjectWorkflow(ctx, issue, &claim, legacy)+ got := testHandler.claimProjectWorkflow(ctx, issue, &claim, legacy, legacy)if got == nil {t.Fatal("missing workflow brief")}@@ -1147,15 +1160,15 @@ func TestClaimExplainsMovedWorkflowStep(t *testing.T) {agentUpdateIssue(t, issueID, agentID, taskID, map[string]any{"status": "in_review"}).Want(http.StatusConflict)}-// claimBriefForTest renders the workflow brief a claim of task would carry-// for the issue as it is now.+// claimBriefForTest renders the workflow brief a current daemon's claim of+// task would carry for the issue as it is now.func claimBriefForTest(t *testing.T, issueID string, task db.AgentTaskQueue) string {t.Helper()issue, err := testHandler.Queries.GetIssue(context.Background(), util.MustParseUUID(issueID))if err != nil {t.Fatalf("load issue: %v", err)}- got := testHandler.claimProjectWorkflow(context.Background(), issue, &task, false)+ got := testHandler.claimProjectWorkflow(context.Background(), issue, &task, false, false)if got == nil {t.Fatalf("claim of %s carries no workflow", issueID)}@@ -1207,7 +1220,7 @@ func TestPreviewIssueWorkflowBriefUsesTheDraft(t *testing.T) {"status_key": "in_progress", "handler": map[string]any{"type": "agent", "id": agentID}, "instructions": "Draft step.","project_id": projectID,}).Want(http.StatusOK).JSON(&got)- for _, want := range []string{"Default (Workflow brief project)", "Draft step.", "← current", "in_review\nCan't proceed"} {+ for _, want := range []string{"Default (Workflow brief project)", "Draft step.", "← current", " Routes: next `in_review`.\n"} {if !strings.Contains(got.Brief, want) {t.Fatalf("draft brief is missing %q:\n%s", want, got.Brief)}diff --git a/server/internal/handler/squad_briefing.go b/server/internal/handler/squad_briefing.goindex 1aaf9806bf..1d7a6ff292 100644--- a/server/internal/handler/squad_briefing.go+++ b/server/internal/handler/squad_briefing.go@@ -132,6 +132,9 @@ const (// leaderWorkflowCurrentDaemon: the runtime brief points at// [Project workflow] and states no built-in moves.leaderWorkflowCurrentDaemon+ // leaderWorkflowStatusMap: [Project workflow] is a status map with no+ // per-step commands; the runtime brief states its rules (MUL-9913).+ leaderWorkflowStatusMap// leaderWorkflowLegacyDaemon: the runtime brief still says to set// in_progress first and in_review on delivery, so responsibility 6 has// to rule those moves out for this issue.@@ -170,6 +173,23 @@ const squadParentStatusOwnedInWorkflow = `6. **Own the parent issue status — tresponsibility is itself the standing instruction that authorizes thatchange, so do it even when no comment asked you to.`+// squadParentStatusOwnedInStatusMap is squadParentStatusOwnedInWorkflow for+// a [Project workflow] status map, which lists no Step done command: the+// leader picks the status from the map once the step's goal is met.+const squadParentStatusOwnedInStatusMap = `6. **Own the parent issue status — through its project workflow.** This issue+ is assigned to your squad and follows its project workflow, so its status+ is yours to move (unless Agent Identity forbids status changes), using only+ the statuses in the ` + "`" + `[Project workflow]` + "`" + ` status map. Delegate only the current+ step's work and pass its instructions and constraints to members in your+ delegation comment; their observer brief does not include step instructions.+ The parent stays at its+ current step while members work — a successful dispatch is not completion.+ On later turns, do not move it for routine progress updates. When you+ confirm the current step's goal is met, move it to the status the map gives+ for that step's finished work — this responsibility is itself the standing+ instruction that authorizes that change, so do it even when no comment+ asked you to.`+// squadParentStatusWorkflowOverridesRuntime follows// squadParentStatusOwnedInWorkflow for a daemon whose runtime brief still// states the built-in moves.@@ -245,6 +265,8 @@ func squadOperatingProtocolFor(ownsIssueStatus bool, workflow leaderWorkflow) ststatus = squadParentStatusStepMovedcase ownsIssueStatus && workflow == leaderWorkflowCurrentDaemon:status = squadParentStatusOwnedInWorkflow+ case ownsIssueStatus && workflow == leaderWorkflowStatusMap:+ status = squadParentStatusOwnedInStatusMapcase ownsIssueStatus && workflow == leaderWorkflowLegacyDaemon:status = squadParentStatusOwnedInWorkflow + squadParentStatusWorkflowOverridesRuntimecase ownsIssueStatus:diff --git a/server/internal/handler/squad_briefing_claim_test.go b/server/internal/handler/squad_briefing_claim_test.goindex 2788d0acfe..4a66a1febc 100644--- a/server/internal/handler/squad_briefing_claim_test.go+++ b/server/internal/handler/squad_briefing_claim_test.go@@ -159,8 +159,8 @@ func TestClaim_LeaderTaskFromCommentMention_InjectsBriefing(t *testing.T) {func TestClaim_LeaderTaskWithMovedStepLeavesStatusUnchanged(t *testing.T) {seedTestCatalog(t)for _, bound := range []string{"waiting_for_merge", "in_progress", ""} {- for _, legacy := range []bool{false, true} {- t.Run(fmt.Sprintf("bound=%s/legacy=%v", bound, legacy), func(t *testing.T) {+ for _, daemon := range []string{"legacy", "commands", "map"} {+ t.Run(fmt.Sprintf("bound=%s/%s", bound, daemon), func(t *testing.T) {fx := newSquadBriefingClaimFixture(t, t.Context(), "Workflow leader")projectID := deliveryProject(t, "Leader workflow project", fx.AgentID)dbfx.Exec(t, `UPDATE issue SET project_id=$2,status='in_progress',assignee_type='squad',assignee_id=$3 WHERE id=$1`, fx.IssueID, projectID, fx.SquadID)@@ -173,8 +173,11 @@ func TestClaim_LeaderTaskWithMovedStepLeavesStatusUnchanged(t *testing.T) {}taskID := dbfx.Task(t, fx.AgentID, cols)req := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+fx.RuntimeID+"/tasks/claim", nil), "runtimeId", fx.RuntimeID)- if !legacy {+ switch daemon {+ case "commands":req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityWorkflowStatusRulesV1)+ case "map":+ req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityWorkflowStatusRulesV1+","+protocol.DaemonCapabilityWorkflowStatusMapV1)}var resp struct {Task *AgentTaskResponse `json:"task"`@@ -184,11 +187,19 @@ func TestClaim_LeaderTaskWithMovedStepLeavesStatusUnchanged(t *testing.T) {t.Fatalf("missing workflow leader claim: %+v", resp.Task)}instructions := resp.Task.Agent.Instructions+ if resp.Task.ProjectWorkflow.StatusMap != (daemon == "map") {+ t.Fatalf("status_map = %v for a %s daemon", resp.Task.ProjectWorkflow.StatusMap, daemon)+ }+ wrapUp := "run that block's Step done command"+ if daemon == "map" {+ wrapUp = "move it to the status the map gives for that step's finished work"+ }+ compact := strings.Join(strings.Fields(instructions), " ")if !strings.Contains(instructions, "## Squad Roster") {t.Fatal("workflow restriction removed the leader's coordination briefing")}if bound == "waiting_for_merge" {- if !strings.Contains(instructions, "Leave the parent issue's status unchanged") || strings.Contains(instructions, "run that block's Step done command") {+ if !strings.Contains(instructions, "Leave the parent issue's status unchanged") || strings.Contains(compact, wrapUp) {t.Fatalf("stale leader's instructions contradict its workflow brief:\n%s", instructions)}for _, move := range builtInParentMoves {@@ -196,7 +207,7 @@ func TestClaim_LeaderTaskWithMovedStepLeavesStatusUnchanged(t *testing.T) {t.Errorf("stale leader received built-in move %q", move)}}- } else if !strings.Contains(instructions, "run that block's Step done command") {+ } else if !strings.Contains(compact, wrapUp) {t.Fatalf("current or unbound leader lost its wrap-up instruction:\n%s", instructions)}})diff --git a/server/internal/handler/squad_workflow_status_contract_test.go b/server/internal/handler/squad_workflow_status_contract_test.goindex 7004647679..0e406a6b73 100644--- a/server/internal/handler/squad_workflow_status_contract_test.go+++ b/server/internal/handler/squad_workflow_status_contract_test.go@@ -22,15 +22,16 @@ import (// leaderRuntimeBriefFor renders the runtime brief file a squad leader gets// from provider, with the squad protocol as its Agent Identity.-func leaderRuntimeBriefFor(t *testing.T, provider, instructions string, hasProjectWorkflow bool) string {+func leaderRuntimeBriefFor(t *testing.T, provider, instructions string, hasProjectWorkflow, statusMap bool) string {t.Helper()dir := t.TempDir()if _, err := execenv.InjectRuntimeConfig(dir, provider, execenv.TaskContextForEnv{- IssueID: "issue-1",- TriggerCommentID: "comment-1",- AgentInstructions: instructions,- IsSquadLeader: true,- HasProjectWorkflow: hasProjectWorkflow,+ IssueID: "issue-1",+ TriggerCommentID: "comment-1",+ AgentInstructions: instructions,+ IsSquadLeader: true,+ HasProjectWorkflow: hasProjectWorkflow,+ ProjectWorkflowStatusMap: statusMap,}); err != nil {t.Fatalf("InjectRuntimeConfig(%s): %v", provider, err)}@@ -58,7 +59,7 @@ var builtInParentMoves = []string{func TestOwningLeaderInWorkflowMovesOnlyByWorkflowCommands(t *testing.T) {protocol := squadOperatingProtocolFor(true, leaderWorkflowCurrentDaemon)for _, provider := range []string{"claude", "codex"} {- combined := strings.Join(strings.Fields(protocol+"\n"+leaderRuntimeBriefFor(t, provider, protocol, true)), " ")+ combined := strings.Join(strings.Fields(protocol+"\n"+leaderRuntimeBriefFor(t, provider, protocol, true, false)), " ")for _, move := range builtInParentMoves {if strings.Contains(combined, move) {t.Errorf("%s: workflow leader instructions still carry built-in move %q", provider, move)@@ -83,6 +84,36 @@ func TestOwningLeaderInWorkflowMovesOnlyByWorkflowCommands(t *testing.T) {}}+// With a status map, neither half names a command the map lacks: the leader+// moves the parent to the status the map gives once the step's goal is met.+func TestOwningLeaderInStatusMapMovesByTheMap(t *testing.T) {+ protocol := squadOperatingProtocolFor(true, leaderWorkflowStatusMap)+ for _, provider := range []string{"claude", "codex"} {+ combined := strings.Join(strings.Fields(protocol+"\n"+leaderRuntimeBriefFor(t, provider, protocol, true, true)), " ")+ for _, move := range append(builtInParentMoves, "Step done") {+ if strings.Contains(combined, move) {+ t.Errorf("%s: status-map leader instructions carry %q", provider, move)+ }+ }+ for _, want := range []string{+ "Own the parent issue status — through its project workflow.",+ "using only the statuses in the `[Project workflow]` status map",+ "pass its instructions and constraints to members",+ "move it to the status the map gives for that step's finished work",+ "do it even when no comment asked you to",+ "The parent stays at its current step while members work",+ "dispatching members is not delivery — move the parent on only on a later turn",+ } {+ if !strings.Contains(combined, want) {+ t.Errorf("%s: status-map leader instructions missing %q", provider, want)+ }+ }+ }+ if squadOperatingProtocolFor(false, leaderWorkflowStatusMap) != squadOperatingProtocolFor(false, leaderNoWorkflow) {+ t.Fatal("guest leader protocol must not vary with the status map")+ }+}+// Without a workflow the owning leader keeps the built-in arc, so issues// outside a handoff workflow see no change.func TestOwningLeaderWithoutWorkflowKeepsBuiltInMoves(t *testing.T) {diff --git a/server/internal/issuestatus/issuestatus.go b/server/internal/issuestatus/issuestatus.goindex 4f0f34cfb0..742f4d8b8f 100644--- a/server/internal/issuestatus/issuestatus.go+++ b/server/internal/issuestatus/issuestatus.go@@ -565,6 +565,7 @@ type Resolver struct {workspaceID pgtype.UUIDcategories map[string]stringnames map[string]string+ descs map[string]stringarchived map[string]boolloaded boolloadErr error@@ -595,10 +596,12 @@ func (r *Resolver) load(ctx context.Context, q Querier) {}r.categories = make(map[string]string, len(entries))r.names = make(map[string]string, len(entries))+ r.descs = make(map[string]string, len(entries))r.archived = make(map[string]bool)for _, e := range entries {r.categories[e.Key] = e.Categoryr.names[e.Key] = e.Name+ r.descs[e.Key] = e.Descriptionif e.ArchivedAt.Valid {r.archived[e.Key] = true}@@ -682,6 +685,16 @@ func (r *Resolver) Name(ctx context.Context, q Querier, status string) string {return r.names[status]}+// Description returns a CUSTOM status's catalog description, or "" for a+// built-in — the same rule as Name — and for a key the catalog does not hold.+func (r *Resolver) Description(ctx context.Context, q Querier, status string) string {+ if IsBuiltIn(status) {+ return ""+ }+ r.load(ctx, q)+ return r.descs[status]+}+// ExpandCategories turns a set of categories into the status keys that belong// to them, for use as an INDEXED `status = ANY(...)` predicate.//diff --git a/server/internal/issueworkflow/issueworkflow.go b/server/internal/issueworkflow/issueworkflow.goindex 68bc759952..2ab2c43849 100644--- a/server/internal/issueworkflow/issueworkflow.go+++ b/server/internal/issueworkflow/issueworkflow.go@@ -300,6 +300,15 @@ func (d Definition) HandsOffAnywhere() bool {// NextStatus is where a step's handler moves the issue when done: the step's// own choice, or else the next status on the board that is not blocked.func (d Definition) NextStatus(key string) string {+ return d.nextStatus(key, nil)+}++// nextStatus is NextStatus that also passes over closed statuses on the+// board: custom statuses sit before blocked / done / cancelled, so a custom+// closed one such as wont_fix would otherwise be where finished work goes+// (MUL-9913). effective resolves a key to its canonical behavior; nil leaves+// every key as itself. A step's own choice is kept as configured.+func (d Definition) nextStatus(key string, effective func(string) string) string {step, ok := d.Step(key)if !ok {return ""@@ -312,7 +321,7 @@ func (d Definition) NextStatus(key string) string {continue}for _, next := range d.Steps[i+1:] {- if next.StatusKey != issuestatus.Blocked {+ if next.StatusKey != issuestatus.Blocked && effectiveOf(effective, next.StatusKey) != issuestatus.Cancelled {return next.StatusKey}}@@ -320,6 +329,13 @@ func (d Definition) NextStatus(key string) string {return ""}+func effectiveOf(effective func(string) string, key string) string {+ if effective == nil {+ return key+ }+ return effective(key)+}+// handlerlessSpan is the stretch of work an assignee owns from a step that// has no handler: entering such steps reassigns nothing and starts no run, so// the same assignee carries the issue until it reaches a step that hands off@@ -342,8 +358,9 @@ type handlerlessSpan struct {// issue there. Otherwise it reaches the end of the board, and delivering sets// the last status before done other than in_progress, leaving done to a// human as without a workflow; only when no such status exists does it set-// what follows (done).-func (d Definition) handlerlessSpan(key string) handlerlessSpan {+// what follows (done). A custom done or closed status ends the walk the way+// done does; effective resolves it as nextStatus does.+func (d Definition) handlerlessSpan(key string, effective func(string) string) handlerlessSpan {current, ok := d.Step(key)if !ok || current.HandsOff() {return handlerlessSpan{}@@ -357,13 +374,13 @@ func (d Definition) handlerlessSpan(key string) handlerlessSpan {var passed []stringseen := map[string]bool{key: true}for at := key; ; {- next := d.NextStatus(at)+ next := d.nextStatus(at, effective)if next == "" || seen[next] {break}seen[next] = truestep, _ := d.Step(next)- if step.HandsOff() || next == issuestatus.Done || next == issuestatus.Cancelled {+ if behavior := effectiveOf(effective, next); step.HandsOff() || behavior == issuestatus.Done || behavior == issuestatus.Cancelled {span.until = nextbreak}@@ -730,6 +747,11 @@ type BriefInput struct {// EffectiveStatus resolves a catalog key to its canonical behavior. With// no resolver, the key itself determines the behavior.EffectiveStatus func(key string) string+ // StatusCategory resolves a catalog key to its lifecycle category, and+ // StatusDescription to the catalog's description of a custom status. The+ // status map names both; without a resolver a custom status shows neither.+ StatusCategory func(key string) string+ StatusDescription func(key string) string// HandlerName describes who a step hands off to, e.g. "Sentinel" or// "Lin (project lead)". Empty means the step does not hand off.HandlerName func(step Step) string@@ -749,53 +771,43 @@ type BriefInput struct {// the zero value — also what the editor and timeline show — leaves these// lines out rather than forbid what nothing asks for (MUL-8145).LegacyRuntimeRules bool+ // StepCommands renders the per-step command list — Step done, Needs+ // changes — for a daemon whose runtime brief still points at those+ // commands (one without protocol.DaemonCapabilityWorkflowStatusMapV1).+ // The zero value renders the status map, whose rules the runtime brief+ // states (MUL-9913). LegacyRuntimeRules implies the command list.+ StepCommands bool}// Brief renders what an agent reads about the issue's project workflow: the// workflow's statuses, who each step hands off to, and — for the assignee —-// the current step's instructions and the commands for the next move. The-// runtime brief points at this block instead of stating built-in status rules;-// for an older daemon that still states them, LegacyRuntimeRules adds the-// lines that override them.+// the current step's instructions. A current daemon gets the status map+// (statusMapBrief) and states the rules for choosing from it; StepCommands+// renders the per-step commands an older daemon's runtime brief points at+// instead, and LegacyRuntimeRules adds the lines that override the built-in+// rules a still older one states.//// It is the one rendering of a workflow for agents: the claim carries it into// every run's prompt, and the editor and timeline show the same text. Names// and instructions are user-authored, so control characters are dropped and// names are kept to one line.func Brief(in BriefInput) string {+ if !in.StepCommands && !in.LegacyRuntimeRules {+ return statusMapBrief(in)+ }step, _ := in.Workflow.Step(in.StatusKey)stepMoved := in.BoundStep != "" && in.BoundStep != in.StatusKey- effectiveStatus := in.StatusKey- if in.EffectiveStatus != nil {- effectiveStatus = in.EffectiveStatus(in.StatusKey)- }- terminal := effectiveStatus == issuestatus.Done || effectiveStatus == issuestatus.Cancelled+ terminal := in.atTerminal()// Nothing on the board follows a terminal status, so its only moves are// the ones its author configured (MUL-9746).terminalMoves := terminal && (step.NextStatusKey != "" || step.BackStatusKey != "")- name := func(key string) string {- if in.StatusName == nil {- return key- }- if n := briefLine(in.StatusName(key)); n != "" {- return n- }- return key- }+ name := in.statusNamevar b strings.Builder- title := briefLine(in.Workflow.Name)- if project := briefLine(in.ProjectName); project != "" {- title = fmt.Sprintf("%s (%s)", title, project)- }- fmt.Fprintf(&b, "This project's workflow — %s\n", title)+ writeBriefTitle(&b, in)// Each move names who the target step hands off to, so the list needs no// preamble about handoffs.handsOffTo := func(key string) string {- target, ok := in.Workflow.Step(key)- if !ok || in.HandlerName == nil {- return ""- }- if who := briefLine(in.HandlerName(target)); who != "" {+ if who := in.handlerOf(key); who != "" {return " — hands off to " + who}return ""@@ -804,7 +816,7 @@ func Brief(in BriefInput) string {// keeps the per-step wording rather than add a second in_progress rule.var span handlerlessSpanif !stepMoved && !in.Observer && !in.LegacyRuntimeRules && !terminal {- span = in.Workflow.handlerlessSpan(in.StatusKey)+ span = in.Workflow.handlerlessSpan(in.StatusKey, in.EffectiveStatus)}if in.LegacyRuntimeRules && !stepMoved {b.WriteString("This workflow replaces the status rules in your runtime instructions: use only the status keys below")@@ -814,20 +826,9 @@ func Brief(in BriefInput) string {b.WriteString(".\n")}if stepMoved {- mover := briefLine(in.MovedBy)- if mover == "" {- mover = "someone else"- }- fmt.Fprintf(&b, "This run remains bound to %s, but %s is now at %s (last moved by %s).\n",- statusLabel(name(in.BoundStep), in.BoundStep), in.IssueIdentifier, statusLabel(name(in.StatusKey), in.StatusKey), mover)- b.WriteString("Do not change the issue's status in this run, including when starting or finishing work; this overrides the status rules in your runtime instructions. Do not retry a refused status change. Leave a comment if something needs attention. A member can review the current state and explicitly rerun the work.\n")+ writeStepMovedIntro(&b, in)} else if in.Observer {- assignee := "is unassigned"- if who := briefLine(in.AssigneeName); who != "" {- assignee = "is assigned to " + who- }- fmt.Fprintf(&b, "%s is at the %q step and %s. You are not its assignee: leave the status to them unless you are explicitly asked to change it.\n",- in.IssueIdentifier, name(in.StatusKey), assignee)+ writeObserverIntro(&b, in)} else if span.ok {// A step without a handler is a progress marker, not a stage: naming// it "the step you handle" made agents split one task across columns@@ -840,19 +841,11 @@ func Brief(in BriefInput) string {}} else {if terminal && !terminalMoves {- fmt.Fprintf(&b, "%s has reached the terminal status %s. Leave the issue at this status unless a member explicitly asks you to reopen it.\n",- in.IssueIdentifier, statusLabel(name(in.StatusKey), in.StatusKey))+ writeTerminalIntro(&b, in)} else {fmt.Fprintf(&b, "You are handling the %q step of %s.\n", name(in.StatusKey), in.IssueIdentifier)}- if instructions := briefText(step.Instructions); instructions != "" {- b.WriteString("\nStep instructions:\n")- for _, line := range strings.Split(instructions, "\n") {- b.WriteString("> ")- b.WriteString(line)- b.WriteString("\n")- }- }+ writeStepInstructions(&b, step)}b.WriteString("\nStatuses in this workflow:\n")for _, s := range in.Workflow.Steps {@@ -895,7 +888,7 @@ func Brief(in BriefInput) string {default:next := step.NextStatusKeyif !terminal {- next = in.Workflow.NextStatus(in.StatusKey)+ next = in.Workflow.nextStatus(in.StatusKey, in.EffectiveStatus)}if next != "" {fmt.Fprintf(&b, "Step done → multica issue status %s %s%s\n", in.IssueIdentifier, next, handsOffTo(next))@@ -925,6 +918,82 @@ func Brief(in BriefInput) string {return b.String()}+func writeBriefTitle(b *strings.Builder, in BriefInput) {+ title := briefLine(in.Workflow.Name)+ if project := briefLine(in.ProjectName); project != "" {+ title = fmt.Sprintf("%s (%s)", title, project)+ }+ fmt.Fprintf(b, "This project's workflow — %s\n", title)+}++func writeStepMovedIntro(b *strings.Builder, in BriefInput) {+ mover := briefLine(in.MovedBy)+ if mover == "" {+ mover = "someone else"+ }+ fmt.Fprintf(b, "This run remains bound to %s, but %s is now at %s (last moved by %s).\n",+ statusLabel(in.statusName(in.BoundStep), in.BoundStep), in.IssueIdentifier, statusLabel(in.statusName(in.StatusKey), in.StatusKey), mover)+ b.WriteString("Do not change the issue's status in this run, including when starting or finishing work; this overrides the status rules in your runtime instructions. Do not retry a refused status change. Leave a comment if something needs attention. A member can review the current state and explicitly rerun the work.\n")+}++func writeObserverIntro(b *strings.Builder, in BriefInput) {+ assignee := "is unassigned"+ if who := briefLine(in.AssigneeName); who != "" {+ assignee = "is assigned to " + who+ }+ fmt.Fprintf(b, "%s is at the %q step and %s. You are not its assignee: leave the status to them unless you are explicitly asked to change it.\n",+ in.IssueIdentifier, in.statusName(in.StatusKey), assignee)+}++func writeTerminalIntro(b *strings.Builder, in BriefInput) {+ fmt.Fprintf(b, "%s has reached the terminal status %s. Leave the issue at this status unless a member explicitly asks you to reopen it.\n",+ in.IssueIdentifier, statusLabel(in.statusName(in.StatusKey), in.StatusKey))+}++func writeStepInstructions(b *strings.Builder, step Step) {+ instructions := briefText(step.Instructions)+ if instructions == "" {+ return+ }+ b.WriteString("\nStep instructions:\n")+ for _, line := range strings.Split(instructions, "\n") {+ b.WriteString("> ")+ b.WriteString(line)+ b.WriteString("\n")+ }+}++// statusName is a status's display name, or its key when it has none —+// built-in statuses have no stored name, and their key reads on its own.+func (in BriefInput) statusName(key string) string {+ if in.StatusName == nil {+ return key+ }+ if n := briefLine(in.StatusName(key)); n != "" {+ return n+ }+ return key+}++// handlerOf names who entering key hands off to, or "" when it hands off to+// no one.+func (in BriefInput) handlerOf(key string) string {+ target, ok := in.Workflow.Step(key)+ if !ok || in.HandlerName == nil {+ return ""+ }+ return briefLine(in.HandlerName(target))+}++func (in BriefInput) effective(key string) string {+ return effectiveOf(in.EffectiveStatus, key)+}++func (in BriefInput) atTerminal() bool {+ behavior := in.effective(in.StatusKey)+ return behavior == issuestatus.Done || behavior == issuestatus.Cancelled+}+// briefLine keeps a user-authored name on one line of a brief: line breaks// and tabs become single spaces and other control characters are dropped.func briefLine(s string) string {diff --git a/server/internal/issueworkflow/issueworkflow_test.go b/server/internal/issueworkflow/issueworkflow_test.goindex 2d20e27257..9ce8cf2ba4 100644--- a/server/internal/issueworkflow/issueworkflow_test.go+++ b/server/internal/issueworkflow/issueworkflow_test.go@@ -258,7 +258,7 @@ func TestCheckStatusListsAllowedKeys(t *testing.T) {}func TestBriefNamesStepCommandsAndHandlers(t *testing.T) {- brief := Brief(BriefInput{+ brief := stepCommandsBrief(BriefInput{Workflow: devDefinition(),ProjectName: "Payments",StatusKey: "code_review",@@ -296,7 +296,7 @@ func TestBriefOmitsMovesAtTerminalStatuses(t *testing.T) {for _, status := range []string{"done", "cancelled"} {for _, legacy := range []bool{false, true} {t.Run(fmt.Sprintf("%s/legacy=%v", status, legacy), func(t *testing.T) {- brief := Brief(BriefInput{+ brief := stepCommandsBrief(BriefInput{Workflow: blockedOnlyDefault(),StatusKey: status,IssueIdentifier: "MUL-7",@@ -349,7 +349,7 @@ func TestBriefKeepsConfiguredMovesAtCustomTerminalStatus(t *testing.T) {},} {t.Run(tc.name, func(t *testing.T) {- brief := Brief(BriefInput{+ brief := stepCommandsBrief(BriefInput{Workflow: verifying(tc.next, tc.back),StatusKey: "verifying",IssueIdentifier: "DEP-42",@@ -377,28 +377,32 @@ func TestBriefKeepsConfiguredMovesAtCustomTerminalStatus(t *testing.T) {func TestBriefForMovedStep(t *testing.T) {for _, current := range []string{"implement", "todo"} {for _, observer := range []bool{false, true} {- for _, legacy := range []bool{false, true} {- t.Run(fmt.Sprintf("%s/observer=%v/legacy=%v", current, observer, legacy), func(t *testing.T) {+ for _, mode := range []string{"map", "commands", "legacy"} {+ t.Run(fmt.Sprintf("%s/observer=%v/%s", current, observer, mode), func(t *testing.T) {in := BriefInput{Workflow: devDefinition(), StatusKey: current, BoundStep: "waiting_for_merge",- IssueIdentifier: "MUL-7", Observer: observer, LegacyRuntimeRules: legacy,+ IssueIdentifier: "MUL-7", Observer: observer, StepCommands: mode == "commands", LegacyRuntimeRules: mode == "legacy",MovedBy: "Lin\n\tLee\x01", StatusName: func(key string) string { return testCatalog()[key].Name },}brief := Brief(in)+ heading, leaks := "Status map for MUL-7:", []string{}+ if mode != "map" {+ heading, leaks = "Statuses in this workflow:", []string{"Needs changes", "Can't proceed"}+ }for _, want := range []string{`bound to "waiting_for_merge"`, statusLabel(testCatalog()[current].Name, current),"last moved by Lin Lee", "Do not change", "overrides the status rules", "member",- "Statuses in this workflow:", " ← current",+ heading, " ← current",} {if !strings.Contains(brief, want) {t.Errorf("brief missing %q:\n%s", want, brief)}}- for _, leak := range []string{+ for _, leak := range append(leaks,"Implement it.", "Step instructions:", "You are handling", "Your moves:", "multica issue status",- "Needs changes", "Can't proceed", "unless you are explicitly asked", "Before your run ends, either run",+ "Set one with", "unless you are explicitly asked", "Before your run ends, either run","Lin\n", "\x01",- } {+ ) {if strings.Contains(brief, leak) {t.Errorf("stale run received %q:\n%s", leak, brief)}@@ -437,7 +441,7 @@ func TestBriefOverridesRuntimeRulesOnlyForLegacyDaemons(t *testing.T) {"The system does not advance the status when your run ends.",}for _, observer := range []bool{false, true} {- current := Brief(BriefInput{Workflow: devDefinition(), StatusKey: "code_review", IssueIdentifier: "MUL-7", Observer: observer})+ current := stepCommandsBrief(BriefInput{Workflow: devDefinition(), StatusKey: "code_review", IssueIdentifier: "MUL-7", Observer: observer})for _, line := range legacyOnly {if strings.Contains(current, line) {t.Errorf("observer=%v: current-daemon brief carries %q:\n%s", observer, line, current)@@ -449,7 +453,7 @@ func TestBriefOverridesRuntimeRulesOnlyForLegacyDaemons(t *testing.T) {}}}- legacy := Brief(BriefInput{Workflow: devDefinition(), StatusKey: "code_review", IssueIdentifier: "MUL-7", LegacyRuntimeRules: true})+ legacy := stepCommandsBrief(BriefInput{Workflow: devDefinition(), StatusKey: "code_review", IssueIdentifier: "MUL-7", LegacyRuntimeRules: true})for _, line := range legacyOnly {if !strings.Contains(legacy, line) {t.Errorf("legacy-daemon brief is missing %q:\n%s", line, legacy)@@ -458,7 +462,7 @@ func TestBriefOverridesRuntimeRulesOnlyForLegacyDaemons(t *testing.T) {}func TestBriefForObserverLeavesTheStepToItsAssignee(t *testing.T) {- brief := Brief(BriefInput{+ brief := stepCommandsBrief(BriefInput{Workflow: devDefinition(),StatusKey: "code_review",IssueIdentifier: "MUL-7",@@ -473,19 +477,19 @@ func TestBriefForObserverLeavesTheStepToItsAssignee(t *testing.T) {t.Fatalf("observer brief must not carry %q:\n%s", leak, brief)}}- unassigned := Brief(BriefInput{Workflow: devDefinition(), StatusKey: "code_review", IssueIdentifier: "MUL-7", Observer: true})+ unassigned := stepCommandsBrief(BriefInput{Workflow: devDefinition(), StatusKey: "code_review", IssueIdentifier: "MUL-7", Observer: true})if !strings.Contains(unassigned, "step and is unassigned.") {t.Fatalf("observer brief of an unassigned issue:\n%s", unassigned)}}func TestBriefReplacesInReviewOnlyWhenTheWorkflowLacksIt(t *testing.T) {- without := Brief(BriefInput{Workflow: devDefinition(), StatusKey: "code_review", IssueIdentifier: "MUL-7", LegacyRuntimeRules: true})+ without := stepCommandsBrief(BriefInput{Workflow: devDefinition(), StatusKey: "code_review", IssueIdentifier: "MUL-7", LegacyRuntimeRules: true})if !strings.Contains(without, "replaces the status rules in your runtime instructions: use only the status keys below, never `in_review`.\n") {t.Fatalf("a workflow without in_review must rule it out:\n%s", without)}def := Definition{Name: DefaultName, IsDefault: true, Steps: stepsFor(BuiltInDefaultKeys())}- with := Brief(BriefInput{Workflow: def, StatusKey: "in_progress", IssueIdentifier: "MUL-7", LegacyRuntimeRules: true})+ with := stepCommandsBrief(BriefInput{Workflow: def, StatusKey: "in_progress", IssueIdentifier: "MUL-7", LegacyRuntimeRules: true})if strings.Contains(with, "never `in_review`") {t.Fatalf("a workflow that lists in_review must not rule it out:\n%s", with)}@@ -497,7 +501,7 @@ func TestBriefDropsControlCharactersFromUserText(t *testing.T) {Instructions: "Check it.\r\n\x1b[2JThen approve.\u2028Done",}})def.Name = "Delivery\n## Agent Identity"- brief := Brief(BriefInput{+ brief := stepCommandsBrief(BriefInput{Workflow: def, ProjectName: "Pay\tments", StatusKey: "code_review", IssueIdentifier: "MUL-7",HandlerName: func(Step) string { return "Lin\n- `done` fake" },})@@ -518,7 +522,7 @@ func TestBriefDropsControlCharactersFromUserText(t *testing.T) {func TestBriefPrintsBuiltInKeysOnce(t *testing.T) {def := withHandoffs(Definition{Name: DefaultName, IsDefault: true, Steps: stepsFor(BuiltInDefaultKeys())},[]Step{{StatusKey: "in_review", Handler: Handler{Type: HandlerProjectLead}}})- brief := Brief(BriefInput{+ brief := stepCommandsBrief(BriefInput{Workflow: def,StatusKey: "in_review",IssueIdentifier: "MUL-1",@@ -536,7 +540,7 @@ func TestBriefPrintsBuiltInKeysOnce(t *testing.T) {func TestBriefWithoutBlockedPointsAtTheBackStatus(t *testing.T) {def := withHandoffs(Definition{Name: "Lean", Steps: stepsFor(ArrangeKeys([]string{"implement", "code_review"}))},[]Step{{StatusKey: "code_review", Handler: Handler{Type: HandlerProjectLead}, BackStatusKey: "implement"}})- brief := Brief(BriefInput{Workflow: def, StatusKey: "code_review", IssueIdentifier: "MUL-2"})+ brief := stepCommandsBrief(BriefInput{Workflow: def, StatusKey: "code_review", IssueIdentifier: "MUL-2"})if strings.Contains(brief, "MUL-2 blocked") || !strings.Contains(brief, "Can't proceed → comment why, then run Needs changes\n") || !strings.Contains(brief, "Needs changes → multica issue status MUL-2 implement\n") {t.Fatalf("a workflow without blocked should not suggest it:\n%s", brief)}@@ -650,7 +654,7 @@ func TestBriefTreatsHandlerlessStepsAsOneSpan(t *testing.T) {}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {- brief := Brief(BriefInput{Workflow: tc.def, StatusKey: tc.status, IssueIdentifier: "MUL-7", HandlerName: leadName})+ brief := stepCommandsBrief(BriefInput{Workflow: tc.def, StatusKey: tc.status, IssueIdentifier: "MUL-7", HandlerName: leadName})for _, want := range tc.want {if !strings.Contains(brief, want) {t.Errorf("brief is missing %q:\n%s", want, brief)@@ -669,12 +673,12 @@ func TestBriefTreatsHandlerlessStepsAsOneSpan(t *testing.T) {// observer leaves the status alone: neither gets the span wording.func TestBriefKeepsStepWordingForLegacyDaemonsAndObservers(t *testing.T) {def := Definition{Name: "Plain", Steps: stepsFor(ArrangeKeys([]string{"in_progress", "in_review"}))}- legacy := Brief(BriefInput{Workflow: def, StatusKey: "todo", IssueIdentifier: "MUL-7", LegacyRuntimeRules: true})+ legacy := stepCommandsBrief(BriefInput{Workflow: def, StatusKey: "todo", IssueIdentifier: "MUL-7", LegacyRuntimeRules: true})if !strings.Contains(legacy, `You are handling the "todo" step of MUL-7.`) || strings.Contains(legacy, "Starting work") ||!strings.Contains(legacy, "Step done → multica issue status MUL-7 in_progress\n") {t.Fatalf("legacy brief must keep the per-step wording:\n%s", legacy)}- observer := Brief(BriefInput{Workflow: def, StatusKey: "todo", IssueIdentifier: "MUL-7", Observer: true})+ observer := stepCommandsBrief(BriefInput{Workflow: def, StatusKey: "todo", IssueIdentifier: "MUL-7", Observer: true})if strings.Contains(observer, "Starting work") || strings.Contains(observer, "has no handler") {t.Fatalf("observer brief must not carry the span wording:\n%s", observer)}@@ -686,3 +690,85 @@ func blockedOnlyDefault() Definition {return withHandoffs(Definition{Name: DefaultName, IsDefault: true, Steps: stepsFor(BuiltInDefaultKeys())},[]Step{{StatusKey: "blocked", Handler: Handler{Type: HandlerProjectLead}}})}++// Custom statuses sit before blocked / done / cancelled on the board, so a+// custom closed status follows the handler-less steps; finished work must not+// be filed there, while a custom done status ends the work as done does+// (MUL-9913).+func TestBriefNeverDeliversToACustomClosedStatus(t *testing.T) {+ effective := func(key string) string {+ switch key {+ case "wont_fix":+ return "cancelled"+ case "shipped":+ return "done"+ }+ return key+ }+ cases := []struct {+ name string+ keys []string+ status string+ want []string+ wantNot []string+ }{+ {+ name: "closed after in_review",+ keys: []string{"in_progress", "in_review", "wont_fix", "blocked"},+ status: "in_progress",+ want: []string{"Step done → multica issue status MUL-7 in_review\n"},+ wantNot: []string{"MUL-7 wont_fix"},+ },+ {+ name: "closed right after in_progress",+ keys: []string{"in_progress", "wont_fix"},+ status: "todo",+ want: []string{"Starting work → multica issue status MUL-7 in_progress\n", "Step done → multica issue status MUL-7 done\n"},+ wantNot: []string{"MUL-7 wont_fix"},+ },+ {+ name: "done-category custom ends the work like done",+ keys: []string{"in_progress", "shipped"},+ status: "in_progress",+ want: []string{"Step done → multica issue status MUL-7 shipped\n"},+ wantNot: []string{"MUL-7 done"},+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ def := Definition{Name: "Plain", Steps: stepsFor(ArrangeKeys(tc.keys))}+ brief := stepCommandsBrief(BriefInput{Workflow: def, StatusKey: tc.status, IssueIdentifier: "MUL-7", EffectiveStatus: effective})+ for _, want := range tc.want {+ if !strings.Contains(brief, want) {+ t.Errorf("brief is missing %q:\n%s", want, brief)+ }+ }+ for _, not := range tc.wantNot {+ if strings.Contains(brief, not) {+ t.Errorf("brief carries %q:\n%s", not, brief)+ }+ }+ })+ }++ // A step that hands off falls back to the board too, and skips the+ // closed status the same way; its author's own choice is kept.+ reviewed := Definition{Name: "Reviewed", Steps: stepsFor(ArrangeKeys([]string{"in_progress", "code_review", "wont_fix"}))}+ reviewed = withHandoffs(reviewed, []Step{{StatusKey: "code_review", Handler: Handler{Type: HandlerProjectLead}}})+ brief := stepCommandsBrief(BriefInput{Workflow: reviewed, StatusKey: "code_review", IssueIdentifier: "MUL-7", EffectiveStatus: effective})+ if !strings.Contains(brief, "Step done → multica issue status MUL-7 done\n") || strings.Contains(brief, "MUL-7 wont_fix") {+ t.Fatalf("a step that hands off must skip the closed status on the board:\n%s", brief)+ }+ reviewed = withHandoffs(reviewed, []Step{{StatusKey: "code_review", Handler: Handler{Type: HandlerProjectLead}, NextStatusKey: "wont_fix"}})+ brief = stepCommandsBrief(BriefInput{Workflow: reviewed, StatusKey: "code_review", IssueIdentifier: "MUL-7", EffectiveStatus: effective})+ if !strings.Contains(brief, "Step done → multica issue status MUL-7 wont_fix\n") {+ t.Fatalf("a configured Next must be kept:\n%s", brief)+ }+}++// stepCommandsBrief renders the per-step command brief that daemons without+// the status map still read.+func stepCommandsBrief(in BriefInput) string {+ in.StepCommands = true+ return Brief(in)+}diff --git a/server/internal/issueworkflow/statusmap.go b/server/internal/issueworkflow/statusmap.gonew file mode 100644index 0000000000..65a300e98a--- /dev/null+++ b/server/internal/issueworkflow/statusmap.go@@ -0,0 +1,164 @@+package issueworkflow++import (+ "fmt"+ "strings"+ "unicode/utf8"++ "github.com/multica-ai/multica/server/internal/issuestatus"+)++// builtInMeanings name the built-in statuses the runtime rules pick by+// meaning: the one for delivered work, and done. The others read on their+// own key. Custom statuses carry their catalog description instead.+var builtInMeanings = map[string]string{+ issuestatus.InReview: "Delivered; awaiting review.",+ issuestatus.Done: "Finished and accepted.",+}++// mappedCategories are the lifecycle categories the runtime rules refer to;+// a status in any other category shows none.+var mappedCategories = map[string]bool{+ issuestatus.CategoryDone: true,+ issuestatus.CategoryClosed: true,+}++// maxEntryHintRunes caps the line a step's instructions lend to its map+// entry; the full instructions are the handler's to read.+const maxEntryHintRunes = 160++// statusMapBrief renders the workflow as a status map: every status, with+// what the runtime rules need to choose among them — the done and closed+// categories, what a status means, who entering it hands off to and where+// its author routed the work on. It repeats nothing those rules say, and the+// command lives in the runtime brief's command list. The agent picks the+// status that matches where the issue stands, under the rules its runtime+// brief states, instead of following a move computed for each step+// (MUL-9913).+func statusMapBrief(in BriefInput) string {+ step, _ := in.Workflow.Step(in.StatusKey)+ stepMoved := in.BoundStep != "" && in.BoundStep != in.StatusKey+ terminal := in.atTerminal()+ terminalMoves := terminal && (step.NextStatusKey != "" || step.BackStatusKey != "")++ var b strings.Builder+ writeBriefTitle(&b, in)+ switch {+ case stepMoved:+ writeStepMovedIntro(&b, in)+ case in.Observer:+ writeObserverIntro(&b, in)+ case terminal && !terminalMoves:+ writeTerminalIntro(&b, in)+ writeStepInstructions(&b, step)+ case step.HandsOff():+ fmt.Fprintf(&b, "You are handling the %q step of %s.\n", in.statusName(in.StatusKey), in.IssueIdentifier)+ writeStepInstructions(&b, step)+ }+ // A status without a handler needs no introduction: the runtime rules+ // say its work stays with the assignee (MUL-8231).++ fmt.Fprintf(&b, "\nStatus map for %s:\n", in.IssueIdentifier)+ for _, s := range in.Workflow.Steps {+ writeStatusMapEntry(&b, in, s)+ }+ if in.Observer && !stepMoved {+ b.WriteString("\nMoving the issue into a status that hands off reassigns it to that handler and starts their run.\n")+ }+ return b.String()+}++// writeStatusMapEntry renders one status: its key, name and category and+// what it means on the first line, then who entering it hands off to and+// where the work goes from it.+func writeStatusMapEntry(b *strings.Builder, in BriefInput, s Step) {+ fmt.Fprintf(b, "- `%s`", s.StatusKey)+ if n := in.statusName(s.StatusKey); n != s.StatusKey {+ fmt.Fprintf(b, " %s", n)+ }+ if category := in.category(s.StatusKey); mappedCategories[category] {+ fmt.Fprintf(b, " (%s)", category)+ }+ if meaning := in.meaning(s.StatusKey); meaning != "" {+ fmt.Fprintf(b, " — %s", meaning)+ }+ if s.StatusKey == in.StatusKey {+ b.WriteString(" ← current")+ }+ b.WriteString("\n")++ if who := in.handlerOf(s.StatusKey); who != "" {+ fmt.Fprintf(b, " Hands off to %s.", who)+ // The current step's instructions are printed in full above; for any+ // other step, their first line says what its handler expects to+ // receive, which a workspace-wide description cannot.+ if s.StatusKey != in.StatusKey {+ if hint := firstLine(s.Instructions); hint != "" {+ fmt.Fprintf(b, " Their step: %s", hint)+ }+ }+ b.WriteString("\n")+ }+ var routes []string+ if next := in.routedNext(s); next != "" {+ routes = append(routes, fmt.Sprintf("next `%s`", next))+ }+ if s.BackStatusKey != "" {+ routes = append(routes, fmt.Sprintf("send back `%s`", s.BackStatusKey))+ }+ if len(routes) > 0 {+ fmt.Fprintf(b, " Routes: %s.\n", strings.Join(routes, ", "))+ }+}++// routedNext is where finished work at s goes: its author's choice, or for a+// step that hands off, the next status on the board — the stage that follows+// it. A status without a handler names none; whoever owns the issue there+// works on through the map. Nothing on the board follows a terminal status,+// so it names only its author's choice (MUL-9746).+func (in BriefInput) routedNext(s Step) string {+ if s.NextStatusKey != "" {+ return s.NextStatusKey+ }+ behavior := in.effective(s.StatusKey)+ if !s.HandsOff() || behavior == issuestatus.Done || behavior == issuestatus.Cancelled {+ return ""+ }+ return in.Workflow.nextStatus(s.StatusKey, in.EffectiveStatus)+}++func (in BriefInput) category(key string) string {+ if in.StatusCategory != nil {+ if c := in.StatusCategory(key); c != "" {+ return c+ }+ }+ c, _ := issuestatus.CategoryForBehavior(key)+ return c+}++func (in BriefInput) meaning(key string) string {+ if issuestatus.IsBuiltIn(key) {+ return builtInMeanings[key]+ }+ if in.StatusDescription == nil {+ return ""+ }+ return briefLine(in.StatusDescription(key))+}++// firstLine is the first non-empty line of user-authored text, cut to+// maxEntryHintRunes.+func firstLine(s string) string {+ for _, line := range strings.Split(briefText(s), "\n") {+ line = briefLine(line)+ if line == "" {+ continue+ }+ if utf8.RuneCountInString(line) > maxEntryHintRunes {+ line = string([]rune(line)[:maxEntryHintRunes-1]) + "…"+ }+ return line+ }+ return ""+}diff --git a/server/internal/issueworkflow/statusmap_test.go b/server/internal/issueworkflow/statusmap_test.gonew file mode 100644index 0000000000..0a159e1e7a--- /dev/null+++ b/server/internal/issueworkflow/statusmap_test.go@@ -0,0 +1,196 @@+package issueworkflow++import (+ "strings"+ "testing"+)++// reviewedWithWontFix is the MUL-9913 board: a custom closed status sits+// after the review step, before blocked / done / cancelled.+func reviewedWithWontFix() BriefInput {+ def := Definition{Name: "Delivery", Steps: stepsFor(ArrangeKeys([]string{"in_progress", "in_review", "wont_fix", "blocked"}))}+ def = withHandoffs(def, []Step{{+ StatusKey: "in_review", Handler: Handler{Type: HandlerAgent, ID: testAgentID},+ Instructions: "\n Review the PR:\ttests and scope.\nThen approve.", BackStatusKey: "in_progress",+ }})+ return BriefInput{+ Workflow: def, ProjectName: "Payments", IssueIdentifier: "MUL-7",+ StatusName: func(key string) string {+ if key == "wont_fix" {+ return "Won't Fix"+ }+ return ""+ },+ StatusDescription: func(key string) string {+ if key == "wont_fix" {+ return "Decided not to do:\nduplicate or out of scope."+ }+ return "ignored for built-ins"+ },+ StatusCategory: func(key string) string {+ if key == "wont_fix" {+ return "closed"+ }+ return ""+ },+ EffectiveStatus: func(key string) string {+ if key == "wont_fix" {+ return "cancelled"+ }+ return key+ },+ HandlerName: func(step Step) string {+ if step.HandsOff() {+ return "Sentinel"+ }+ return ""+ },+ }+}++func TestStatusMapDescribesEveryStatus(t *testing.T) {+ in := reviewedWithWontFix()+ in.StatusKey = "in_progress"+ brief := Brief(in)+ for _, want := range []string{+ // A status without a handler gets no introduction: the runtime+ // rules say its work stays with the assignee.+ "This project's workflow — Delivery (Payments)\n\nStatus map for MUL-7:\n",+ "- `todo`\n",+ "- `in_progress` ← current\n",+ "- `in_review` — Delivered; awaiting review.\n" ++ " Hands off to Sentinel. Their step: Review the PR: tests and scope.\n" ++ " Routes: next `done`, send back `in_progress`.\n",+ // The custom status carries its category and catalog description, so+ // the agent can tell when it fits.+ "- `wont_fix` Won't Fix (closed) — Decided not to do: duplicate or out of scope.\n",+ "- `done` (done) — Finished and accepted.\n",+ "- `blocked`\n",+ "- `cancelled` (closed)\n",+ } {+ if !strings.Contains(brief, want) {+ t.Errorf("brief is missing %q:\n%s", want, brief)+ }+ }+ // No move is computed for the agent: nothing routes work into wont_fix.+ for _, unwanted := range []string{"Your moves:", "Step done", "Starting work", "`wont_fix`.", "ignored for built-ins"} {+ if strings.Contains(brief, unwanted) {+ t.Errorf("brief carries %q:\n%s", unwanted, brief)+ }+ }+}++func TestStatusMapForTheStepYouHandle(t *testing.T) {+ in := reviewedWithWontFix()+ in.StatusKey = "in_review"+ brief := Brief(in)+ for _, want := range []string{+ `You are handling the "in_review" step of MUL-7.` + "\n",+ "\nStep instructions:\n> Review the PR:\ttests and scope.\n> Then approve.\n",+ "awaiting review. ← current\n Hands off to Sentinel.\n",+ } {+ if !strings.Contains(brief, want) {+ t.Errorf("brief is missing %q:\n%s", want, brief)+ }+ }+ if strings.Contains(brief, "Their step:") {+ t.Errorf("the current step's instructions are already printed in full:\n%s", brief)+ }+}++func TestStatusMapRoutesOnlyWhatItsAuthorOrABoardStageDecides(t *testing.T) {+ in := reviewedWithWontFix()+ in.StatusKey = "in_progress"+ // A step that hands off falls back to the next stage on the board,+ // passing over the closed status; an author's own choice is kept.+ in.Workflow = withHandoffs(in.Workflow, []Step{{StatusKey: "in_review", Handler: Handler{Type: HandlerAgent, ID: testAgentID}}})+ if brief := Brief(in); !strings.Contains(brief, " Routes: next `done`.\n") {+ t.Errorf("board fallback must skip the closed status:\n%s", brief)+ }+ in.Workflow = withHandoffs(in.Workflow, []Step{{StatusKey: "in_review", Handler: Handler{Type: HandlerAgent, ID: testAgentID}, NextStatusKey: "wont_fix"}})+ if brief := Brief(in); !strings.Contains(brief, " Routes: next `wont_fix`.\n") {+ t.Errorf("a configured Next must be kept:\n%s", brief)+ }+ // Statuses without a handler route nothing: their owner works on.+ if brief := Brief(in); strings.Contains(brief, "underway. ← current\n Routes") {+ t.Errorf("a status without a handler must not route work:\n%s", brief)+ }+}++// The map carries no command and no rule: the runtime brief states both, and+// a status without a handler reads as current with nothing more to say.+func TestStatusMapRepeatsNoRuntimeRule(t *testing.T) {+ def := Definition{Name: "Plain", Steps: stepsFor(ArrangeKeys([]string{"in_progress"}))}+ brief := Brief(BriefInput{Workflow: def, StatusKey: "todo", IssueIdentifier: "MUL-7"})+ want := "This project's workflow — Plain\n\nStatus map for MUL-7:\n" ++ "- `todo` ← current\n- `in_progress`\n- `done` (done) — Finished and accepted.\n- `cancelled` (closed)\n"+ if brief != want {+ t.Fatalf("brief = %q, want %q", brief, want)+ }+}++func TestStatusMapForObserversAndTerminalStatuses(t *testing.T) {+ in := reviewedWithWontFix()+ in.StatusKey = "in_review"+ in.Observer = true+ in.AssigneeName = "Sentinel"+ observer := Brief(in)+ for _, want := range []string{+ `MUL-7 is at the "in_review" step and is assigned to Sentinel. You are not its assignee`,+ "\nStatus map for MUL-7:\n",+ "\nMoving the issue into a status that hands off reassigns it to that handler and starts their run.\n",+ } {+ if !strings.Contains(observer, want) {+ t.Errorf("observer brief is missing %q:\n%s", want, observer)+ }+ }+ if strings.Contains(observer, "Step instructions") {+ t.Errorf("observer brief must leave the status to the assignee:\n%s", observer)+ }++ in = reviewedWithWontFix()+ in.StatusKey = "wont_fix"+ terminal := Brief(in)+ if !strings.Contains(terminal, `MUL-7 has reached the terminal status "Won't Fix" (wont_fix). Leave the issue at this status`) ||+ !strings.Contains(terminal, "(closed) — Decided not to do: duplicate or out of scope. ← current\n") {+ t.Errorf("terminal brief must keep the issue where it is:\n%s", terminal)+ }+}++func TestStatusMapCutsLongInstructionHints(t *testing.T) {+ in := reviewedWithWontFix()+ in.StatusKey = "in_progress"+ in.Workflow = withHandoffs(in.Workflow, []Step{{+ StatusKey: "in_review", Handler: Handler{Type: HandlerAgent, ID: testAgentID},+ Instructions: strings.Repeat("a", maxEntryHintRunes+20) + "\x01",+ }})+ brief := Brief(in)+ want := "Their step: " + strings.Repeat("a", maxEntryHintRunes-1) + "…\n"+ if !strings.Contains(brief, want) {+ t.Fatalf("hint must be cut to %d runes:\n%s", maxEntryHintRunes, brief)+ }+}++// A terminal status's handler routes only where its author said: nothing on+// the board follows it, and the fallback would file "won't do" as done+// (MUL-9746).+func TestStatusMapRoutesATerminalStatusOnlyAsConfigured(t *testing.T) {+ in := reviewedWithWontFix()+ in.StatusKey = "wont_fix"+ in.Workflow = withHandoffs(in.Workflow, []Step{{+ StatusKey: "wont_fix", Handler: Handler{Type: HandlerAgent, ID: testAgentID},+ Instructions: "Confirm it should be dropped.", BackStatusKey: "in_progress",+ }})+ brief := Brief(in)+ entry := brief[strings.Index(brief, "- `wont_fix`"):]+ entry = entry[:strings.Index(entry, "\n- `blocked`")]+ if !strings.Contains(entry, " Routes: send back `in_progress`.") || strings.Contains(entry, "next `") {+ t.Fatalf("terminal status must route only its configured send-back:\n%s", brief)+ }+ in.Workflow = withHandoffs(in.Workflow, []Step{{+ StatusKey: "wont_fix", Handler: Handler{Type: HandlerAgent, ID: testAgentID}, NextStatusKey: "done",+ }})+ if brief := Brief(in); !strings.Contains(brief, " Routes: next `done`.") {+ t.Fatalf("a configured Next at a terminal status must be kept:\n%s", brief)+ }+}diff --git a/server/internal/service/builtin_skills/multica-platform/references/projects.md b/server/internal/service/builtin_skills/multica-platform/references/projects.mdindex 7189d9660f..3afab124e3 100644--- a/server/internal/service/builtin_skills/multica-platform/references/projects.md+++ b/server/internal/service/builtin_skills/multica-platform/references/projects.md@@ -205,8 +205,8 @@ add/update/remove mutate durable workspace state and affect future tasks. Ask beA project can use a workflow: its ordered status columns, where a column mayhand the issue off to a handler — a fixed agent, squad or member, the projectlead, or the issue's creator. When the issue's project uses one, the per-turn-prompt carries a `[Project workflow]` block. Its statuses and commands are-the whole status contract for this issue: the built-in moves in the issues+prompt carries a `[Project workflow]` block. Its statuses are the whole+status contract for this issue: the built-in moves in the issuesreference (`in_progress` on start, `in_review` on delivery) do not apply.- **The step's scope is its instructions.** A step that hands off carries the@@ -222,9 +222,12 @@ reference (`in_progress` on start, `in_review` on delivery) do not apply.- **Changing the status is the handoff.** Entering a column that hands offreassigns the issue to that column's handler and starts their run; a memberhandler is assigned and runs nothing. Nothing advances the status when a run- ends: finishing a step means moving the issue to the next status yourself,- with the command the block names. A column can also name a "needs changes"- status that sends the issue back.+ ends: finishing a step means moving the issue to the next status yourself.+ The block is a status map — each status's category, meaning, handler and+ where its author routes finished work ("Routes") — and you set the+ status that matches where the issue stands; an older runtime gets the+ commands to run instead. A column can also name a "needs changes" status+ that sends the issue back.- **Entering a step you handle starts your run.** Even when your own run makesthe move, a run for the new step queues behind the current one, and thewrite skips your own event wakeups so one change starts one run. Do not add@@ -239,7 +242,7 @@ reference (`in_progress` on start, `in_review` on delivery) do not apply.`workflow_step_moved`, naming who moved it. Do not retry; comment ifsomething still needs attention.- **The assignee owns the step.** Only the issue's assignee gets the step's- instructions and commands. Any other agent on the issue — mentioned in a+ instructions and is told to move it. Any other agent on the issue — mentioned in acomment, say — sees the statuses and leaves them to the assignee unlessexplicitly asked to change them.- **No `blocked` column.** When the workflow has none, comment why you cannotdiff --git a/server/internal/service/builtin_skills/multica-platform/references/squads.md b/server/internal/service/builtin_skills/multica-platform/references/squads.mdindex 9ac4351ef7..37da978be4 100644--- a/server/internal/service/builtin_skills/multica-platform/references/squads.md+++ b/server/internal/service/builtin_skills/multica-platform/references/squads.md@@ -176,7 +176,9 @@ Current behavior:and keep it there while members work; the leader moves the parent to`in_review` only when a later re-trigger confirms the overall goal is met.When the run carries a `[Project workflow]` block, the parent stays at its- current step instead and the leader runs that block's Step done command.+ current step instead, and the leader moves it on with that block — its+ Step done command, or the status its status map gives for the step's+ finished work.Completing a leader task (including the first dispatch) does not itselfchange issue status;- that status authority is granted only when the issue's `assignee_type` /@@ -257,7 +259,8 @@ These actions can trigger agent work or mutate durable state:- Backlog assignment does not immediately start work.- First leader dispatch is not parent completion — parent stays `in_progress`until the leader later confirms the overall goal and moves it to `in_review`- (under a `[Project workflow]` block: stays at its step until Step done).+ (under a `[Project workflow]` block: stays at its step until the leader+ moves it on through that block).- The server does not auto-flip parent status when child issues finish; it onlywakes the leader with an explicit ask (including `in_review` when wrapping up).- Getting the leader briefing does NOT imply status authority. A squaddiff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex de238a52e9..99776da3fe 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -84,6 +84,11 @@ const (// the server leave out the workflow brief's lines that override those// rules; an older daemon still states them, so it keeps getting them.DaemonCapabilityWorkflowStatusRulesV1 = "workflow-status-rules-v1"+ // DaemonCapabilityWorkflowStatusMapV1 advertises that the daemon's+ // runtime brief states the status-map rules for an issue whose claim+ // carries a status-map workflow brief (MUL-9913). Without it the server+ // keeps sending the per-step command brief those daemons point at.+ DaemonCapabilityWorkflowStatusMapV1 = "workflow-status-map-v1"// DaemonCapabilityTaskSupplementAuthorV1 is sent when claiming a// supplement: the daemon renders the claim's author_type, so an agent's// message is presented as an agent's. Without it the server marks an