Skip to content

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

Go

MUL-6813: fix: surface private runtime owner mismatch as explicit failure (#7805)

makesomethingshit78a5f69ae1da
diff --git a/apps/mobile/lib/dispatch-reason.test.ts b/apps/mobile/lib/dispatch-reason.test.ts
index dfbf85a445..895659c0f8 100644
--- a/apps/mobile/lib/dispatch-reason.test.ts
+++ b/apps/mobile/lib/dispatch-reason.test.ts
@@ -47,6 +47,17 @@ describe("sendFailureMessage", () => {
).toMatch(/runtime/i);
});
+ // PUCK-89: a private-runtime owner mismatch never resolves by retrying. The
+ // message must name the real fixes instead of the generic retry advice.
+ it("gives runtime_access_denied actionable copy, not a retry", () => {
+ const message = sendFailureMessage(
+ apiError({ reason_code: "runtime_access_denied" }),
+ );
+ expect(message).toMatch(/private runtime/i);
+ expect(message).toMatch(/public|rebind/i);
+ expect(message).not.toMatch(/try again/i);
+ });
+
it("falls back to a retryable message for anything else", () => {
expect(sendFailureMessage(new Error("timeout"))).toMatch(/try again/i);
});
diff --git a/apps/mobile/lib/dispatch-reason.ts b/apps/mobile/lib/dispatch-reason.ts
index da0d192c08..267d6b789c 100644
--- a/apps/mobile/lib/dispatch-reason.ts
+++ b/apps/mobile/lib/dispatch-reason.ts
@@ -1,3 +1,5 @@
+import { RUNTIME_ACCESS_DENIED_RECOVERY_COPY } from "./runtime-access-copy";
+
/**
* Mobile-owned mirror of `packages/core/api/client.ts:dispatchReasonCode`.
*
@@ -28,6 +30,11 @@ export function sendFailureMessage(err: unknown): string {
return "You no longer have permission to run this agent, so the message was not sent.";
case "agent_runtime_required":
return "Bind a runtime to this agent before sending a message.";
+ case "runtime_access_denied":
+ // The agent's owner cannot execute it on the selected private runtime.
+ // Retrying never fixes this — the fix is making that runtime public or
+ // rebinding/copying the agent to a runtime its owner can use.
+ return `Message not sent — ${RUNTIME_ACCESS_DENIED_RECOVERY_COPY}`;
default:
return "Your message could not be sent. Please try again.";
}
diff --git a/apps/mobile/lib/failure-reason-label.test.ts b/apps/mobile/lib/failure-reason-label.test.ts
new file mode 100644
index 0000000000..948adc52f0
--- /dev/null
+++ b/apps/mobile/lib/failure-reason-label.test.ts
@@ -0,0 +1,13 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+
+import { failureReasonLabel } from "./failure-reason-label";
+
+describe("failureReasonLabel", () => {
+ it("uses actionable recovery copy for persisted runtime access denial", () => {
+ const label = failureReasonLabel("runtime_access_denied");
+ expect(label).toMatch(/make the runtime public/i);
+ expect(label).toMatch(/rebind\/copy/i);
+ expect(label).not.toBe("Failed");
+ });
+});
diff --git a/apps/mobile/lib/failure-reason-label.ts b/apps/mobile/lib/failure-reason-label.ts
index ab5695e89f..ff1661218d 100644
--- a/apps/mobile/lib/failure-reason-label.ts
+++ b/apps/mobile/lib/failure-reason-label.ts
@@ -1,3 +1,5 @@
+import { RUNTIME_ACCESS_DENIED_RECOVERY_COPY } from "./runtime-access-copy";
+
/**
* Mirror of `packages/views/agents/components/tabs/task-failure.ts:REASON_LABEL`.
*
@@ -29,6 +31,7 @@ const LABELS: Record<string, string> = {
skill_bundle_unavailable: "Couldn't download the agent's skills",
runtime_cli_timeout: "Local runtime CLI timed out",
environment_prepare_failed: "Couldn't prepare the execution environment",
+ runtime_access_denied: RUNTIME_ACCESS_DENIED_RECOVERY_COPY,
// Agent process side — provider.
"agent_error.provider_auth_or_access": "Provider auth failed",
diff --git a/apps/mobile/lib/run-failure-badge.test.ts b/apps/mobile/lib/run-failure-badge.test.ts
index c079fbb57d..196e5e69c1 100644
--- a/apps/mobile/lib/run-failure-badge.test.ts
+++ b/apps/mobile/lib/run-failure-badge.test.ts
@@ -16,6 +16,9 @@ describe("runFailureBadgeLabel", () => {
expect(runFailureBadgeLabel("environment_prepare_failed")).toBe(
"Environment setup failed",
);
+ expect(runFailureBadgeLabel("runtime_access_denied")).toBe(
+ "No runtime access",
+ );
});
it("keeps the pre-MUL-1949 coarse values readable", () => {
diff --git a/apps/mobile/lib/run-failure-badge.ts b/apps/mobile/lib/run-failure-badge.ts
index c15688d171..16885507e4 100644
--- a/apps/mobile/lib/run-failure-badge.ts
+++ b/apps/mobile/lib/run-failure-badge.ts
@@ -1,3 +1,5 @@
+import { RUNTIME_ACCESS_DENIED_BADGE } from "./runtime-access-copy";
+
/**
* Short badge copy for a run's `failure_reason`, shown inline on the agent-runs
* row next to the status word and a timestamp.
@@ -28,6 +30,7 @@ const FAILURE_REASON_BADGE: Record<string, string> = {
skill_bundle_unavailable: "Skill download failed",
runtime_cli_timeout: "Runtime CLI timeout",
environment_prepare_failed: "Environment setup failed",
+ runtime_access_denied: RUNTIME_ACCESS_DENIED_BADGE,
"agent_error.provider_auth_or_access": "Auth failed",
"agent_error.provider_quota_limit": "Quota exhausted",
diff --git a/apps/mobile/lib/runtime-access-copy.ts b/apps/mobile/lib/runtime-access-copy.ts
new file mode 100644
index 0000000000..df942945c2
--- /dev/null
+++ b/apps/mobile/lib/runtime-access-copy.ts
@@ -0,0 +1,7 @@
+// Shared copy for the persisted and admission-time runtime ownership failure.
+// Keep this in one mobile-owned module because mobile cannot import the web
+// locale bundles.
+export const RUNTIME_ACCESS_DENIED_RECOVERY_COPY =
+ "This agent can't run on its private runtime. Make the runtime public, or rebind/copy the agent to a runtime its owner can use.";
+
+export const RUNTIME_ACCESS_DENIED_BADGE = "No runtime access";
diff --git a/packages/views/agents/components/tabs/task-failure.test.ts b/packages/views/agents/components/tabs/task-failure.test.ts
index 698b2637cd..db47afe682 100644
--- a/packages/views/agents/components/tabs/task-failure.test.ts
+++ b/packages/views/agents/components/tabs/task-failure.test.ts
@@ -156,6 +156,13 @@ describe("failureReasonLabel", () => {
);
});
+ it("maps runtime access denial to actionable recovery copy", () => {
+ const label = failureReasonLabel("runtime_access_denied", enT);
+ expect(label).toMatch(/make the runtime public/i);
+ expect(label).toMatch(/rebind\/copy/i);
+ expect(label).not.toBe("Task identity mismatch");
+ });
+
it("covers operational reasons emitted outside the canonical taxonomy", () => {
expect(failureReasonLabel("agent_fallback_message", enT)).toBe(
"Agent returned a fallback message",
diff --git a/packages/views/agents/components/tabs/task-failure.ts b/packages/views/agents/components/tabs/task-failure.ts
index 97fabdb3e9..383016740f 100644
--- a/packages/views/agents/components/tabs/task-failure.ts
+++ b/packages/views/agents/components/tabs/task-failure.ts
@@ -20,6 +20,7 @@ export const FAILURE_REASON_I18N_KEYS = {
runtime_cli_timeout: "runtime_cli_timeout",
environment_prepare_failed: "environment_prepare_failed",
invalid_task_identity: "invalid_task_identity",
+ runtime_access_denied: "runtime_access_denied",
// Agent process side — provider.
"agent_error.provider_auth_or_access":
diff --git a/packages/views/autopilots/components/run-now-toast.test.ts b/packages/views/autopilots/components/run-now-toast.test.ts
index d99b50f742..87fde1c2f5 100644
--- a/packages/views/autopilots/components/run-now-toast.test.ts
+++ b/packages/views/autopilots/components/run-now-toast.test.ts
@@ -40,6 +40,12 @@ describe("runNowBlockedKey", () => {
);
});
+ it("maps runtime_access_denied to its dedicated key (PUCK-89)", () => {
+ expect(runNowBlockedKey("runtime_access_denied")).toBe(
+ "run_blocked_runtime_access_denied",
+ );
+ });
+
it("degrades an unknown or absent code to the generic message", () => {
expect(runNowBlockedKey("some_future_code")).toBe("run_blocked_generic");
expect(runNowBlockedKey(undefined)).toBe("run_blocked_generic");
diff --git a/packages/views/autopilots/components/run-now-toast.ts b/packages/views/autopilots/components/run-now-toast.ts
index 535b8791ef..7b60ebda03 100644
--- a/packages/views/autopilots/components/run-now-toast.ts
+++ b/packages/views/autopilots/components/run-now-toast.ts
@@ -33,6 +33,7 @@ export type RunNowBlockedKey =
| "run_blocked_invocation_not_allowed"
| "run_blocked_runtime_offline"
| "run_blocked_agent_runtime_required"
+ | "run_blocked_runtime_access_denied"
| "run_blocked_target_unavailable"
| "run_blocked_attribution"
| "run_blocked_already_active"
@@ -50,6 +51,10 @@ export function runNowBlockedKey(reasonCode: string | undefined): RunNowBlockedK
// to a runtime (MUL-5559).
case "agent_runtime_required":
return "run_blocked_agent_runtime_required";
+ // Bound but not permitted there: the agent's owner cannot execute it on
+ // the selected private runtime. Retrying never fixes this.
+ case "runtime_access_denied":
+ return "run_blocked_runtime_access_denied";
case "target_unavailable":
return "run_blocked_target_unavailable";
case "attribution_blocked":
diff --git a/packages/views/chat/components/chat-message-list.test.tsx b/packages/views/chat/components/chat-message-list.test.tsx
index c1d0e20374..f8863a8116 100644
--- a/packages/views/chat/components/chat-message-list.test.tsx
+++ b/packages/views/chat/components/chat-message-list.test.tsx
@@ -746,6 +746,14 @@ describe("ChatMessageList failure copy (MUL-5370 regression)", () => {
expect(screen.queryByText(FALLBACK)).not.toBeInTheDocument();
});
+ it("renders dedicated recovery copy for persisted runtime access denial", async () => {
+ renderFailure("runtime_access_denied");
+ expect(
+ await screen.findByText(enChat.message_list.failure.runtime_access_denied),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(FALLBACK)).not.toBeInTheDocument();
+ });
+
it("renders dedicated copy for a refined reason the map names", async () => {
renderFailure("agent_error.provider_network");
expect(
diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsx
index 31203576e3..e8552207c1 100644
--- a/packages/views/chat/components/chat-message-list.tsx
+++ b/packages/views/chat/components/chat-message-list.tsx
@@ -995,6 +995,7 @@ function FailureBubble({
timeout: t(($) => $.message_list.failure.timeout),
codex_semantic_inactivity: t(($) => $.message_list.failure.codex_semantic_inactivity),
runtime_offline: t(($) => $.message_list.failure.runtime_offline),
+ runtime_access_denied: t(($) => $.message_list.failure.runtime_access_denied),
runtime_recovery: t(($) => $.message_list.failure.runtime_recovery),
manual: t(($) => $.message_list.failure.manual),
cancelled: t(($) => $.message_list.failure.manual),
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index 1366924e9d..075184bad4 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -494,7 +494,9 @@ export function ChatWindow() {
? t(($) => $.input.send_blocked_toast)
: reason === "agent_runtime_required"
? t(($) => $.input.runtime_required_toast)
- : t(($) => $.input.send_failed_toast),
+ : reason === "runtime_access_denied"
+ ? t(($) => $.input.runtime_access_denied_toast)
+ : t(($) => $.input.send_failed_toast),
);
return false;
}
@@ -520,7 +522,9 @@ export function ChatWindow() {
? t(($) => $.input.send_blocked_toast)
: reason === "agent_runtime_required"
? t(($) => $.input.runtime_required_toast)
- : t(($) => $.input.send_failed_toast),
+ : reason === "runtime_access_denied"
+ ? t(($) => $.input.runtime_access_denied_toast)
+ : t(($) => $.input.send_failed_toast),
);
return false;
}
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index 541bc584b9..e5661a23e4 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -553,7 +553,9 @@ export function useChatController(opts?: { isActive?: boolean }) {
? t(($) => $.input.send_blocked_toast)
: reason === "agent_runtime_required"
? t(($) => $.input.runtime_required_toast)
- : t(($) => $.input.send_failed_toast),
+ : reason === "runtime_access_denied"
+ ? t(($) => $.input.runtime_access_denied_toast)
+ : t(($) => $.input.send_failed_toast),
);
return false;
}
@@ -583,7 +585,9 @@ export function useChatController(opts?: { isActive?: boolean }) {
? t(($) => $.input.send_blocked_toast)
: reason === "agent_runtime_required"
? t(($) => $.input.runtime_required_toast)
- : t(($) => $.input.send_failed_toast),
+ : reason === "runtime_access_denied"
+ ? t(($) => $.input.runtime_access_denied_toast)
+ : t(($) => $.input.send_failed_toast),
);
return false;
}
diff --git a/packages/views/issues/blocked-trigger-copy.test.ts b/packages/views/issues/blocked-trigger-copy.test.ts
index afaf8ae0ce..c3d082ec3b 100644
--- a/packages/views/issues/blocked-trigger-copy.test.ts
+++ b/packages/views/issues/blocked-trigger-copy.test.ts
@@ -57,6 +57,22 @@ describe("blocked trigger copy", () => {
);
});
+ // PUCK-89: the agent is bound but its owner cannot
+ // execute it on the selected private runtime. Retrying never fixes this, so
+ // the copy must name the two real fixes and must not read as a transient
+ // failure.
+ it("gives runtime_access_denied dedicated actionable copy", () => {
+ const denied = blockedReasonLabel("runtime_access_denied", t);
+
+ expect(denied).toBe(en.comment.trigger_blocked_runtime_access_denied);
+ expect(denied.toLowerCase()).toContain("public");
+ expect(denied.toLowerCase()).toContain("rebind");
+ expect(denied.toLowerCase()).not.toContain("try again");
+ expect(blockedShortReasonLabel("runtime_access_denied", t)).toBe(
+ en.comment.trigger_blocked_short_runtime_access_denied,
+ );
+ });
+
// A missing runtime profile is not a broken CLI: the CLI runs, and the
// reinstall the unusable copy asks for fixes nothing. Sharing one label was
// what told DSH users to reinstall a CLI that was never the problem.
diff --git a/packages/views/issues/blocked-trigger-copy.ts b/packages/views/issues/blocked-trigger-copy.ts
index dc79c65464..88c6562b69 100644
--- a/packages/views/issues/blocked-trigger-copy.ts
+++ b/packages/views/issues/blocked-trigger-copy.ts
@@ -24,7 +24,12 @@ import type { useT } from "../i18n";
// reinstall on that machine, and the system comment the server leaves on the
// issue carries the exact command.
//
-// `runtime_profile_missing` is the fourth, and is split from `runtime_unusable`
+// `runtime_access_denied` is another member of that family (PUCK-89): the
+// target is permitted but its agent owner cannot execute it on the selected
+// private runtime. No retry helps — the fix is making the runtime public or
+// rebinding/copying the agent to a runtime its owner can use.
+//
+// `runtime_profile_missing` is split from `runtime_unusable`
// on the same rule: the CLI there runs perfectly and is missing a runtime
// profile (DSH's `multica` profile, which supplies the protocol Multica
// drives). "Reinstall the CLI" copy sends the user to re-run an install that
@@ -46,6 +51,8 @@ export function blockedReasonLabel(reasonCode: string, t: IssuesT): string {
return t(($) => $.comment.trigger_blocked_runtime_profile_missing);
case "agent_runtime_required":
return t(($) => $.comment.trigger_blocked_agent_runtime_required);
+ case "runtime_access_denied":
+ return t(($) => $.comment.trigger_blocked_runtime_access_denied);
default:
return t(($) => $.comment.trigger_blocked_generic);
}
@@ -67,6 +74,8 @@ export function blockedShortReasonLabel(reasonCode: string, t: IssuesT): string
return t(($) => $.comment.trigger_blocked_short_runtime_profile_missing);
case "agent_runtime_required":
return t(($) => $.comment.trigger_blocked_short_agent_runtime_required);
+ case "runtime_access_denied":
+ return t(($) => $.comment.trigger_blocked_short_runtime_access_denied);
default:
return t(($) => $.comment.trigger_blocked_short_generic);
}
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index ab7e00c356..786d654b95 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -928,6 +928,7 @@
"skill_bundle_unavailable": "Couldn't download the agent's skills",
"runtime_cli_timeout": "Local runtime CLI timed out",
"environment_prepare_failed": "Couldn't prepare the execution environment",
+ "runtime_access_denied": "This agent can't run on its private runtime, so it couldn't reply. Make the runtime public, or rebind/copy the agent to a runtime its owner can use.",
"invalid_task_identity": "Run identity mismatch",
"agent_error_provider_auth_or_access": "Provider auth failed",
"agent_error_provider_quota_limit": "Provider quota exhausted",
diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.json
index 894a715245..63547451bb 100644
--- a/packages/views/locales/en/autopilots.json
+++ b/packages/views/locales/en/autopilots.json
@@ -80,6 +80,7 @@
"run_blocked_invocation_not_allowed": "Not triggered — you don't have permission to use this autopilot's agent",
"run_blocked_runtime_offline": "Not triggered — the agent's runtime is offline",
"run_blocked_agent_runtime_required": "Not triggered — the agent has no runtime; bind one to run it",
+ "run_blocked_runtime_access_denied": "Not triggered — the agent can't run on its private runtime; make it public or rebind/copy the agent",
"run_blocked_target_unavailable": "Not triggered — the agent is unavailable",
"run_blocked_attribution": "Not triggered — the run couldn't be attributed to a responsible member",
"run_blocked_already_active": "Not triggered — a recent run already covers this",
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index 06e67d4ef9..3f1a19429d 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -24,6 +24,7 @@
"send_failed_toast": "Failed to send message",
"send_blocked_toast": "Message not sent — you no longer have permission to use this agent",
"runtime_required_toast": "Message not sent — bind a runtime to this agent first",
+ "runtime_access_denied_toast": "Message not sent — this agent can't run on its private runtime. Make the runtime public, or rebind/copy the agent to a runtime its owner can use",
"attachment_bind_failed_toast": "Message sent, but files were not attached. Please try again in a moment.",
"add_tooltip": "Add",
"upload_file": "Image or files",
@@ -58,6 +59,7 @@
"timeout": "The agent took too long and stopped before finishing. Try again, or break your request into smaller steps.",
"codex_semantic_inactivity": "The agent went idle and stopped before finishing. Please try again.",
"runtime_offline": "The agent is offline right now, so it couldn't reply. Please try again once it's back online.",
+ "runtime_access_denied": "This agent can't run on its private runtime, so it couldn't reply. Make the runtime public, or rebind/copy the agent to a runtime its owner can use.",
"runtime_recovery": "The agent restarted before it could finish. Please try again.",
"manual": "This reply was cancelled.",
"skill_bundle_unavailable": "The agent's skills couldn't be downloaded, so it never got started. This is usually a connection problem — please try again.",
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 2f9c513aca..1ee3dde548 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -525,6 +525,7 @@
"trigger_blocked_runtime_unusable": "This target's agent CLI can't run on its machine — reinstall it there",
"trigger_blocked_runtime_profile_missing": "This target's agent CLI is missing a runtime profile on its machine — install it there",
"trigger_blocked_agent_runtime_required": "This target has no runtime — bind one to run it",
+ "trigger_blocked_runtime_access_denied": "This target's agent can't run on its private runtime — make the runtime public, or rebind/copy the agent to one its owner can use",
"trigger_blocked_generic": "This target won't be triggered",
"trigger_blocked_short_invocation_not_allowed": "Not found or no permission",
"trigger_blocked_short_target_unavailable": "Unavailable",
@@ -532,6 +533,7 @@
"trigger_blocked_short_runtime_unusable": "CLI can't run",
"trigger_blocked_short_runtime_profile_missing": "Runtime profile missing",
"trigger_blocked_short_agent_runtime_required": "Needs a runtime",
+ "trigger_blocked_short_runtime_access_denied": "No runtime access",
"trigger_blocked_short_generic": "Won't start",
"send_reply_failed": "Failed to send reply",
"delete_failed": "Failed to delete comment",
diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.json
index f083c27f9d..a7631100c6 100644
--- a/packages/views/locales/fr/agents.json
+++ b/packages/views/locales/fr/agents.json
@@ -928,6 +928,7 @@
"skill_bundle_unavailable": "Impossible de télécharger les skills de l'agent",
"runtime_cli_timeout": "Délai du CLI du runtime local dépassé",
"environment_prepare_failed": "Impossible de préparer l'environnement d'exécution",
+ "runtime_access_denied": "Cet agent ne peut pas s'exécuter sur son runtime privé et n'a donc pas pu répondre. Passez le runtime en public, ou réassociez/copiez l'agent vers un runtime que son propriétaire peut utiliser.",
"invalid_task_identity": "Identité d'exécution incohérente",
"agent_error_provider_auth_or_access": "Échec de l'authentification auprès du fournisseur",
"agent_error_provider_quota_limit": "Quota du fournisseur épuisé",
diff --git a/packages/views/locales/fr/autopilots.json b/packages/views/locales/fr/autopilots.json
index 1bd8dc2745..65fed0eaf7 100644
--- a/packages/views/locales/fr/autopilots.json
+++ b/packages/views/locales/fr/autopilots.json
@@ -80,6 +80,7 @@
"run_blocked_invocation_not_allowed": "Non déclenchée — vous n'avez pas la permission d'utiliser l'agent de cette automatisation",
"run_blocked_runtime_offline": "Non déclenchée — le runtime de l'agent est hors ligne",
"run_blocked_agent_runtime_required": "Non déclenchée — l'agent n'a pas de runtime ; associez-en un pour l'exécuter",
+ "run_blocked_runtime_access_denied": "Non déclenchée — l'agent ne peut pas s'exécuter sur son runtime privé ; passez-le en public ou réassociez/copiez l'agent",
"run_blocked_target_unavailable": "Non déclenchée — l'agent est indisponible",
"run_blocked_attribution": "Non déclenchée — l'exécution n'a pas pu être attribuée à un membre responsable",
"run_blocked_already_active": "Non déclenchée — une exécution récente couvre déjà ce cas",
diff --git a/packages/views/locales/fr/chat.json b/packages/views/locales/fr/chat.json
index 703a18a1a2..d9f9ca0d09 100644
--- a/packages/views/locales/fr/chat.json
+++ b/packages/views/locales/fr/chat.json
@@ -24,6 +24,7 @@
"send_failed_toast": "Échec de l'envoi du message",
"send_blocked_toast": "Message non envoyé — vous n'avez plus la permission d'utiliser cet agent",
"runtime_required_toast": "Message non envoyé — associez d'abord un runtime à cet agent",
+ "runtime_access_denied_toast": "Message non envoyé — cet agent ne peut pas s'exécuter sur son runtime privé. Passez le runtime en public, ou réassociez/copiez l'agent vers un runtime que son propriétaire peut utiliser.",
"attachment_bind_failed_toast": "Message envoyé, mais les fichiers n'ont pas été joints. Veuillez réessayer dans un instant.",
"add_tooltip": "Ajouter",
"upload_file": "Image ou fichiers",
@@ -58,6 +59,7 @@
"timeout": "L'agent a mis trop de temps et s'est arrêté avant de terminer. Réessayez, ou découpez votre demande en étapes plus courtes.",
"codex_semantic_inactivity": "L'agent est resté inactif et s'est arrêté avant de terminer. Veuillez réessayer.",
"runtime_offline": "L'agent est actuellement hors ligne et n'a donc pas pu répondre. Veuillez réessayer dès son retour en ligne.",
+ "runtime_access_denied": "Cet agent ne peut pas s'exécuter sur son runtime privé et n'a donc pas pu répondre. Passez le runtime en public, ou réassociez/copiez l'agent vers un runtime que son propriétaire peut utiliser.",
"runtime_recovery": "L'agent a redémarré avant d'avoir pu terminer. Veuillez réessayer.",
"manual": "Cette réponse a été annulée.",
"skill_bundle_unavailable": "Les skills de l'agent n'ont pas pu être téléchargés : il n'a donc jamais démarré. C'est généralement un problème de connexion — veuillez réessayer.",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 2f980d4253..91d962a57a 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -525,6 +525,7 @@
"trigger_blocked_runtime_unusable": "Le CLI d'agent de cette cible ne peut pas s'exécuter sur sa machine — réinstallez-le sur place",
"trigger_blocked_runtime_profile_missing": "Le CLI de l'agent cible n'a pas de profil de runtime sur sa machine : installez-le sur celle-ci",
"trigger_blocked_agent_runtime_required": "Cette cible n'a pas de runtime — associez-en un pour l'exécuter",
+ "trigger_blocked_runtime_access_denied": "L'agent de cette cible ne peut pas s'exécuter sur son runtime privé — passez le runtime en public, ou réassociez/copiez l'agent vers un runtime que son propriétaire peut utiliser",
"trigger_blocked_generic": "Cette cible ne sera pas déclenchée",
"trigger_blocked_short_invocation_not_allowed": "Introuvable ou sans permission",
"trigger_blocked_short_target_unavailable": "Indisponible",
@@ -532,6 +533,7 @@
"trigger_blocked_short_runtime_unusable": "CLI inexécutable",
"trigger_blocked_short_runtime_profile_missing": "Profil de runtime manquant",
"trigger_blocked_short_agent_runtime_required": "Runtime requis",
+ "trigger_blocked_short_runtime_access_denied": "Pas d'accès au runtime",
"trigger_blocked_short_generic": "Ne démarrera pas",
"send_reply_failed": "Échec de l'envoi de la réponse",
"delete_failed": "Échec de la suppression du commentaire",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index acdd3bf60a..902b8bc64c 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -807,6 +807,7 @@
"skill_bundle_unavailable": "エージェントのスキルをダウンロードできませんでした",
"runtime_cli_timeout": "ローカルランタイム CLI がタイムアウトしました",
"environment_prepare_failed": "実行環境を準備できませんでした",
+ "runtime_access_denied": "このエージェントはプライベートランタイムで実行できないため、返信できませんでした。ランタイムを公開にするか、所有者が利用できるランタイムへエージェントを再設定/コピーしてください。",
"invalid_task_identity": "実行のエージェント情報が一致しません",
"agent_error_provider_auth_or_access": "プロバイダーの認証に失敗しました",
"agent_error_provider_quota_limit": "プロバイダーのクォータを使い切りました",
diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.json
index 2ab4747b9f..d2a40d07a2 100644
--- a/packages/views/locales/ja/autopilots.json
+++ b/packages/views/locales/ja/autopilots.json
@@ -80,6 +80,7 @@
"run_blocked_invocation_not_allowed": "実行されませんでした — このオートパイロットのエージェントを使用する権限がありません",
"run_blocked_runtime_offline": "実行されませんでした — エージェントのランタイムがオフラインです",
"run_blocked_agent_runtime_required": "実行されませんでした — エージェントにランタイムがありません。実行するにはバインドしてください",
+ "run_blocked_runtime_access_denied": "実行されませんでした — エージェントはプライベートランタイムで実行できません。ランタイムを公開にするか、エージェントを再設定/コピーしてください",
"run_blocked_target_unavailable": "実行されませんでした — エージェントを利用できません",
"run_blocked_attribution": "実行されませんでした — 実行の責任者を特定できませんでした",
"run_blocked_already_active": "実行されませんでした — 直近の実行が本件をカバーしています",
diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.json
index 6b8b346413..c8d221f716 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -23,6 +23,7 @@
"send_failed_toast": "メッセージを送信できませんでした",
"send_blocked_toast": "メッセージは送信されませんでした — このエージェントを使用する権限がありません",
"runtime_required_toast": "メッセージは送信されませんでした — 先にこのエージェントのランタイムを設定してください",
+ "runtime_access_denied_toast": "メッセージは送信されませんでした — このエージェントはプライベートランタイムで実行できません。ランタイムを公開にするか、所有者が利用できるランタイムへエージェントを再設定/コピーしてください",
"attachment_bind_failed_toast": "メッセージは送信されましたが、ファイルを添付できませんでした。しばらくしてからもう一度お試しください。",
"add_tooltip": "追加",
"upload_file": "画像・ファイル",
@@ -56,6 +57,7 @@
"timeout": "処理に時間がかかりすぎたため、完了前に停止しました。もう一度お試しいただくか、リクエストを分けてみてください。",
"codex_semantic_inactivity": "エージェントが応答しなくなり、完了前に停止しました。もう一度お試しください。",
"runtime_offline": "エージェントは現在オフラインのため、返信できませんでした。オンラインに戻ってから再度お試しください。",
+ "runtime_access_denied": "このエージェントはプライベートランタイムで実行できないため、返信できませんでした。ランタイムを公開にするか、所有者が利用できるランタイムへエージェントを再設定/コピーしてください。",
"runtime_recovery": "完了する前にエージェントが再起動しました。もう一度お試しください。",
"manual": "この返信はキャンセルされました。",
"skill_bundle_unavailable": "エージェントの skill をダウンロードできず、返信を開始できませんでした。多くの場合はネットワークの問題です。もう一度お試しください。",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 0856a6ece3..71a096dc49 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -515,6 +515,7 @@
"trigger_blocked_runtime_unusable": "この対象の CLI はそのマシンで実行できません — そのマシンで再インストールしてください",
"trigger_blocked_runtime_profile_missing": "この対象の CLI はそのマシンでランタイム プロファイルが不足しています — そのマシンでインストールしてください",
"trigger_blocked_agent_runtime_required": "この対象にはランタイムがありません — 実行するにはバインドしてください",
+ "trigger_blocked_runtime_access_denied": "この対象のエージェントはプライベートランタイムで実行できません — ランタイムを公開にするか、所有者が利用できるランタイムへエージェントを再設定/コピーしてください",
"trigger_blocked_generic": "この対象はトリガーされません",
"trigger_blocked_short_invocation_not_allowed": "未検出または権限なし",
"trigger_blocked_short_target_unavailable": "利用不可",
@@ -522,6 +523,7 @@
"trigger_blocked_short_runtime_unusable": "CLI を実行できません",
"trigger_blocked_short_runtime_profile_missing": "ランタイム プロファイル未導入",
"trigger_blocked_short_agent_runtime_required": "ランタイム未設定",
+ "trigger_blocked_short_runtime_access_denied": "ランタイムアクセス拒否",
"trigger_blocked_short_generic": "トリガーされません",
"send_reply_failed": "返信を送信できませんでした",
"delete_failed": "コメントを削除できませんでした",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index f37d9e2b67..41f896e72a 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -815,6 +815,7 @@
"skill_bundle_unavailable": "에이전트 스킬을 다운로드할 수 없음",
"runtime_cli_timeout": "로컬 런타임 CLI 시간 초과",
"environment_prepare_failed": "실행 환경을 준비하지 못함",
+ "runtime_access_denied": "이 에이전트는 비공개 런타임에서 실행할 수 없어 답변할 수 없습니다. 런타임을 공개로 변경하거나, 소유자가 사용할 수 있는 런타임으로 에이전트를 다시 연결/복사하세요.",
"invalid_task_identity": "실행 ID 정보가 일치하지 않음",
"agent_error_provider_auth_or_access": "공급자 인증 실패",
"agent_error_provider_quota_limit": "공급자 할당량 소진",
diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.json
index 563d2f4505..7dba31c99c 100644
--- a/packages/views/locales/ko/autopilots.json
+++ b/packages/views/locales/ko/autopilots.json
@@ -80,6 +80,7 @@
"run_blocked_invocation_not_allowed": "실행되지 않음 — 이 오토파일럿의 에이전트를 사용할 권한이 없습니다",
"run_blocked_runtime_offline": "실행되지 않음 — 에이전트의 런타임이 오프라인입니다",
"run_blocked_agent_runtime_required": "실행되지 않음 — 에이전트에 런타임이 없습니다. 실행하려면 런타임을 연결하세요",
+ "run_blocked_runtime_access_denied": "실행되지 않음 — 에이전트가 비공개 런타임에서 실행할 수 없습니다. 런타임을 공개로 변경하거나 에이전트를 다시 연결/복사하세요",
"run_blocked_target_unavailable": "실행되지 않음 — 에이전트를 사용할 수 없습니다",
"run_blocked_attribution": "실행되지 않음 — 실행의 책임 구성원을 확인할 수 없습니다",
"run_blocked_already_active": "실행되지 않음 — 최근 실행이 이미 이 건을 처리했습니다",
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index 1541034208..0e64492af1 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -23,6 +23,7 @@
"send_failed_toast": "메시지를 보내지 못했습니다",
"send_blocked_toast": "메시지가 전송되지 않았습니다 — 이 에이전트를 사용할 권한이 없습니다",
"runtime_required_toast": "메시지가 전송되지 않았습니다 — 먼저 이 에이전트에 런타임을 연결하세요",
+ "runtime_access_denied_toast": "메시지가 전송되지 않았습니다 — 이 에이전트는 비공개 런타임에서 실행할 수 없습니다. 런타임을 공개로 변경하거나, 소유자가 사용할 수 있는 런타임으로 에이전트를 다시 연결/복사하세요",
"attachment_bind_failed_toast": "메시지는 보냈지만 파일이 첨부되지 않았습니다. 잠시 후 다시 시도해 주세요.",
"add_tooltip": "추가",
"upload_file": "이미지 또는 파일",
@@ -56,6 +57,7 @@
"timeout": "시간이 너무 오래 걸려 완료 전에 중단되었습니다. 다시 시도하거나 요청을 더 작게 나눠 보세요.",
"codex_semantic_inactivity": "에이전트가 응답하지 않아 완료 전에 중단되었습니다. 다시 시도해 주세요.",
"runtime_offline": "에이전트가 현재 오프라인 상태여서 답변할 수 없습니다. 다시 온라인이 되면 시도해 주세요.",
+ "runtime_access_denied": "이 에이전트는 비공개 런타임에서 실행할 수 없어 답변할 수 없습니다. 런타임을 공개로 변경하거나, 소유자가 사용할 수 있는 런타임으로 에이전트를 다시 연결/복사하세요.",
"runtime_recovery": "완료 전에 에이전트가 다시 시작되었습니다. 다시 시도해 주세요.",
"manual": "이 답변이 취소되었습니다.",
"skill_bundle_unavailable": "에이전트의 skill을 내려받지 못해 답변을 시작하지 못했습니다. 대개 네트워크 연결 문제입니다. 다시 시도해 주세요.",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 78bafc23fe..188223a058 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -515,6 +515,7 @@
"trigger_blocked_runtime_unusable": "이 대상의 CLI를 해당 기기에서 실행할 수 없습니다 — 그 기기에서 다시 설치하세요",
"trigger_blocked_runtime_profile_missing": "이 대상의 CLI에 해당 기기의 런타임 프로필이 없습니다 — 그 기기에서 설치하세요",
"trigger_blocked_agent_runtime_required": "이 대상에 런타임이 없습니다 — 실행하려면 런타임을 연결하세요",
+ "trigger_blocked_runtime_access_denied": "이 대상의 에이전트는 비공개 런타임에서 실행할 수 없습니다 — 런타임을 공개로 변경하거나, 소유자가 사용할 수 있는 런타임으로 에이전트를 다시 연결/복사하세요",
"trigger_blocked_generic": "이 대상은 트리거되지 않습니다",
"trigger_blocked_short_invocation_not_allowed": "찾을 수 없음 또는 권한 없음",
"trigger_blocked_short_target_unavailable": "사용 불가",
@@ -522,6 +523,7 @@
"trigger_blocked_short_runtime_unusable": "CLI 실행 불가",
"trigger_blocked_short_runtime_profile_missing": "런타임 프로필 없음",
"trigger_blocked_short_agent_runtime_required": "런타임 필요",
+ "trigger_blocked_short_runtime_access_denied": "런타임 접근 거부",
"trigger_blocked_short_generic": "트리거 안 됨",
"send_reply_failed": "답글을 보내지 못했습니다",
"delete_failed": "댓글을 삭제하지 못했습니다",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 055b860342..05542b1495 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -909,6 +909,7 @@
"skill_bundle_unavailable": "无法下载智能体的 skill",
"runtime_cli_timeout": "本地运行时 CLI 超时",
"environment_prepare_failed": "无法准备执行环境",
+ "runtime_access_denied": "该智能体无法在其私有运行时上运行,暂时无法回复。请将该运行时设为公开,或将智能体重新绑定/复制到其所有者可用的运行时。",
"invalid_task_identity": "运行身份不匹配",
"agent_error_provider_auth_or_access": "提供商认证失败",
"agent_error_provider_quota_limit": "提供商配额已用尽",
diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.json
index e32ec73bf6..c58211f10a 100644
--- a/packages/views/locales/zh-Hans/autopilots.json
+++ b/packages/views/locales/zh-Hans/autopilots.json
@@ -80,6 +80,7 @@
"run_blocked_invocation_not_allowed": "未触发——你没有该自动化所用智能体的使用权限",
"run_blocked_runtime_offline": "未触发——该智能体的运行时已离线",
"run_blocked_agent_runtime_required": "未触发——该智能体未绑定运行时,绑定后才能运行",
+ "run_blocked_runtime_access_denied": "未触发——该智能体无法在其私有运行时上运行。请将该运行时设为公开,或重新绑定/复制智能体",
"run_blocked_target_unavailable": "未触发——该智能体不可用",
"run_blocked_attribution": "未触发——无法确定本次运行的负责成员",
"run_blocked_already_active": "未触发——最近已有一次运行覆盖了本次",
diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.json
index 589c9a00f1..598feaf651 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -23,6 +23,7 @@
"send_failed_toast": "发送消息失败",
"send_blocked_toast": "消息未发送——你已没有该智能体的使用权限",
"runtime_required_toast": "消息未发送——请先为该智能体绑定运行时",
+ "runtime_access_denied_toast": "消息未发送——该智能体无法在其私有运行时上运行。请将该运行时设为公开,或将智能体重新绑定/复制到其所有者可用的运行时",
"attachment_bind_failed_toast": "消息已发送,但文件未能附加。请稍后重试。",
"add_tooltip": "添加",
"upload_file": "图片或文件",
@@ -56,6 +57,7 @@
"timeout": "智能体处理超时,未能完成。可以重试,或把需求拆得更小一些。",
"codex_semantic_inactivity": "智能体长时间无响应,已停止。请重试。",
"runtime_offline": "智能体当前离线,暂时无法回复。等它恢复在线后再试。",
+ "runtime_access_denied": "该智能体无法在其私有运行时上运行,暂时无法回复。请将该运行时设为公开,或将智能体重新绑定/复制到其所有者可用的运行时。",
"runtime_recovery": "智能体在完成前重启了。请重试。",
"manual": "这次回复已取消。",
"skill_bundle_unavailable": "没能下载到智能体的 skill,这次回复没有启动。通常是网络连接问题,请重试。",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 4397aa116e..1b037dffdb 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -515,6 +515,7 @@
"trigger_blocked_runtime_unusable": "该目标的 CLI 在它所在的机器上无法运行 —— 需要在那台机器上重装",
"trigger_blocked_runtime_profile_missing": "该目标的 CLI 在它所在的机器上缺少运行时 profile —— 需要在那台机器上安装",
"trigger_blocked_agent_runtime_required": "该目标未绑定运行时——绑定后才能运行",
+ "trigger_blocked_runtime_access_denied": "该目标的智能体无法在其私有运行时上运行 —— 请将该运行时设为公开,或将智能体重新绑定/复制到其所有者可用的运行时",
"trigger_blocked_generic": "该目标不会被触发",
"trigger_blocked_short_invocation_not_allowed": "找不到或无权限",
"trigger_blocked_short_target_unavailable": "不可用",
@@ -522,6 +523,7 @@
"trigger_blocked_short_runtime_unusable": "CLI 无法运行",
"trigger_blocked_short_runtime_profile_missing": "缺少运行时 profile",
"trigger_blocked_short_agent_runtime_required": "需绑定运行时",
+ "trigger_blocked_short_runtime_access_denied": "无运行时权限",
"trigger_blocked_short_generic": "不会触发",
"send_reply_failed": "发送回复失败",
"delete_failed": "删除评论失败",
diff --git a/server/internal/dispatch/reason.go b/server/internal/dispatch/reason.go
index e1e7d7f9df..935cd90544 100644
--- a/server/internal/dispatch/reason.go
+++ b/server/internal/dispatch/reason.go
@@ -39,6 +39,11 @@ const (
// machine is already on, and the fix is a command the user runs on it, which
// the daemon reports with this verdict so clients can show it.
ReasonRuntimeUnusable ReasonCode = "runtime_unusable"
+ // ReasonRuntimeAccessDenied: the target is permitted, but its agent owner
+ // cannot execute it on the private runtime selected for the task. This is
+ // distinct from invocation_not_allowed: the caller may invoke the agent,
+ // while the runtime/agent ownership binding still prevents execution.
+ ReasonRuntimeAccessDenied ReasonCode = "runtime_access_denied"
// ReasonRuntimeProfileMissing: the target is bound to a reachable runtime
// whose agent CLI runs fine, but a runtime profile that CLI needs in order
// to speak Multica's protocol is not installed on that machine — DeepSeek
diff --git a/server/internal/handler/admission.go b/server/internal/handler/admission.go
index be6437bd56..df2bac855c 100644
--- a/server/internal/handler/admission.go
+++ b/server/internal/handler/admission.go
@@ -57,6 +57,7 @@ const (
ReasonTargetUnavailable = dispatch.ReasonTargetUnavailable
ReasonRuntimeOffline = dispatch.ReasonRuntimeOffline
ReasonRuntimeUnusable = dispatch.ReasonRuntimeUnusable
+ ReasonRuntimeAccessDenied = dispatch.ReasonRuntimeAccessDenied
ReasonRuntimeProfileMissing = dispatch.ReasonRuntimeProfileMissing
ReasonAgentRuntimeRequired = dispatch.ReasonAgentRuntimeRequired
ReasonAttributionBlocked = dispatch.ReasonAttributionBlocked
@@ -121,6 +122,8 @@ func dispatchBlockedFallbackMessage(code DispatchReasonCode) string {
return "the target's runtime is offline"
case ReasonRuntimeUnusable:
return "the target's agent CLI cannot run on its machine"
+ case ReasonRuntimeAccessDenied:
+ return "the target cannot run on this runtime"
case ReasonRuntimeProfileMissing:
return "the target's agent CLI is missing a runtime profile on its machine"
case ReasonAgentRuntimeRequired:
diff --git a/server/internal/handler/admission_security_mul4525_test.go b/server/internal/handler/admission_security_mul4525_test.go
index d28929498e..2146d4ca89 100644
--- a/server/internal/handler/admission_security_mul4525_test.go
+++ b/server/internal/handler/admission_security_mul4525_test.go
@@ -59,6 +59,10 @@ func TestSendChatMessage_InvokeRevokedAfterSessionCreate(t *testing.T) {
}
ctx := context.Background()
ownerID := seedSecurityTestOwner(t, "chat-agent-owner")
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Chat revoke runtime")
+ if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, runtimeID); err != nil {
+ t.Fatalf("make runtime public: %v", err)
+ }
// public_to agent owned by someone else, with testUserID on its member
// allow-list — so testUserID may invoke it while it is public_to.
@@ -69,7 +73,7 @@ func TestSendChatMessage_InvokeRevokedAfterSessionCreate(t *testing.T) {
instructions, custom_env, custom_args)
VALUES ($1, 'chat-revoke-agent', '', 'cloud', '{}'::jsonb, $2, 'private', 'public_to', 1, $3,
'', '{}'::jsonb, '[]'::jsonb)
- RETURNING id`, testWorkspaceID, handlerTestRuntimeID(t), ownerID).Scan(&agentID); err != nil {
+ RETURNING id`, testWorkspaceID, runtimeID, ownerID).Scan(&agentID); err != nil {
t.Fatalf("seed agent: %v", err)
}
t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID) })
diff --git a/server/internal/handler/admission_test.go b/server/internal/handler/admission_test.go
index 6e159c3ce8..3b99b7b621 100644
--- a/server/internal/handler/admission_test.go
+++ b/server/internal/handler/admission_test.go
@@ -36,6 +36,7 @@ func TestRunToResponseDoesNotReverseEngineerReasonCode(t *testing.T) {
func TestDispatchBlockedFallbackMessageIsNonEnumerating(t *testing.T) {
codes := []DispatchReasonCode{
ReasonInvocationNotAllowed, ReasonTargetUnavailable, ReasonRuntimeOffline,
+ ReasonRuntimeAccessDenied,
ReasonAttributionBlocked, ReasonAlreadyActive, ReasonInternalError,
DispatchReasonCode("some_future_code"),
}
diff --git a/server/internal/handler/agent_access_test.go b/server/internal/handler/agent_access_test.go
index 0d4edce29c..de0d8e49fe 100644
--- a/server/internal/handler/agent_access_test.go
+++ b/server/internal/handler/agent_access_test.go
@@ -119,6 +119,20 @@ func privateAgentTestFixture(t *testing.T) (agentID, ownerID, memberID string) {
t.Helper()
ctx := context.Background()
+ // Keep these permission-focused fixtures out of the private-runtime owner
+ // fence. Their agents remain private; the public runtime isolates invocation
+ // authorization from the separate runtime/agent ownership rule.
+ runtimeID := handlerTestRuntimeID(t)
+ var runtimeVisibility string
+ if err := testPool.QueryRow(ctx, `SELECT visibility FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&runtimeVisibility); err != nil {
+ t.Fatalf("read fixture runtime visibility: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, runtimeID); err != nil {
+ t.Fatalf("make fixture runtime public: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `UPDATE agent_runtime SET visibility = $1 WHERE id = $2`, runtimeVisibility, runtimeID)
+ })
if err := testPool.QueryRow(ctx, `
INSERT INTO "user" (name, email)
VALUES ('Private Agent Owner', '[email protected]')
@@ -166,7 +180,7 @@ func privateAgentTestFixture(t *testing.T) (agentID, ownerID, memberID string) {
VALUES ($1, 'private-access-test-agent', '', 'cloud', '{}'::jsonb,
$2, 'private', 1, $3, '', '{}'::jsonb, '[]'::jsonb)
RETURNING id
- `, testWorkspaceID, handlerTestRuntimeID(t), ownerID).Scan(&agentID); err != nil {
+ `, testWorkspaceID, runtimeID, ownerID).Scan(&agentID); err != nil {
t.Fatalf("create private agent: %v", err)
}
t.Cleanup(func() {
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 8fd754087a..20dbe45249 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -3074,8 +3074,9 @@ type commentMentionTarget struct {
ExecAgentID string
Status DispatchStatus
ReasonCode DispatchReasonCode
- // unusable carries the refused agent and its verdict for the one reason
- // that needs a durable trace (runtime_unusable). Internal to the handler:
+ // unusable carries the refused agent and its verdict for the reasons that
+ // need a durable trace (runtime_unusable or runtime_access_denied). Internal
+ // to the handler:
// the resolver runs for the composer PREVIEW as well, so it only records
// what happened — writing the notice is the trigger path's job.
unusable *blockedRuntimeNotice
@@ -3131,7 +3132,7 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu
blockTarget := func(targetType, targetID string, reason DispatchReasonCode) {
addTarget(commentMentionTarget{TargetType: targetType, TargetID: targetID, Status: DispatchBlocked, ReasonCode: reason})
}
- // blockUnusableTarget is blockTarget for the one verdict that also needs a
+ // blockUnusableTarget is blockTarget for the verdicts that also need a
// durable trace. Every author gets it, including a human: the chip and toast
// carry the reason code but not the repair command, and an agent-authored
// mention has nobody watching a response at all.
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 5a84da2ca6..b5defe43b6 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1887,9 +1887,12 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {
// Route through the SAME finalization as the per-runtime endpoint so the
// token and the comment-delivery receipt (delivered_comment_ids for
// comment/coalesced-comment tasks) are persisted atomically; on failure
- // the exact claim is requeued and omitted from this batch.
+ // the exact claim is requeued and omitted from this batch. The shared
+ // final delivery gate re-verifies current runtime ownership inside the
+ // same transaction; a rejected task is settled via FailTask and skipped
+ // while valid tasks in the same batch continue.
commentBackedTask := task.TriggerCommentID.Valid || len(task.CoalescedCommentIds) > 0
- receipt, ferr := h.TaskService.FinalizeTaskClaim(r.Context(), task, db.CreateTaskTokenParams{
+ receipt, deliveryFailure, ferr := h.finalizeClaimDelivery(r.Context(), &task, rt, uuidToString(task.RuntimeID), rtWorkspaceID, &resp, db.CreateTaskTokenParams{
ID: dbid.NewV7(),
TokenHash: auth.HashToken(tokenStr),
TaskID: task.ID,
@@ -1907,6 +1910,14 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {
}
continue
}
+ if deliveryFailure != nil {
+ if !deliveryFailure.settled {
+ slog.Error("batch claim: delivery rejection settlement failed",
+ "task_id", uuidToString(task.ID), "outcome", deliveryFailure.outcome,
+ "error", deliveryFailure.message)
+ }
+ continue
+ }
resp.AuthToken = tokenStr
resp.RemoteMCPDaemonToken = remoteMCPToken
resp.DeliveredCommentIDs = uuidStringsOrEmpty(receipt)
@@ -1951,6 +1962,131 @@ func claimPollHintDelay(now, fireAt time.Time) time.Duration {
return delay
}
+// finalizeClaimDelivery is the shared final delivery gate for the singular and
+// batch claim paths. It re-verifies the current agent/runtime authorization
+// INSIDE the FinalizeTaskClaim transaction, under a FOR UPDATE row lock on the
+// runtime row, so the decision and the task-token mint commit atomically:
+//
+// - runtime.owner_id is re-read authoritatively (no stale claim-time
+// snapshot), and a concurrent re-registration that would change owner_id
+// blocks until this gate commits — closing the TOCTOU window between the
+// claim-time runtime read and daemon delivery (PUCK-89 blocker 1);
+// - the private-runtime owner fence re-runs against the locked row;
+// - agent.runtime_id still equals the claimed task's runtime (rebind fence);
+// - agent ownership still satisfies the private-runtime binding.
+// - response requesting-user identity is refreshed from that same owner;
+//
+// On mismatch the task is settled through the existing
+// failClaimedTaskBeforeLaunch -> TaskService.FailTask path and never returned
+// to the daemon. The delivery failure reports whether settlement succeeded so
+// callers can keep their poll semantics (singular: 200 {"task":null} only
+// after settlement; batch: skip the task, keep returning valid ones).
+func (h *Handler) finalizeClaimDelivery(
+ ctx context.Context,
+ task *db.AgentTaskQueue,
+ runtime db.AgentRuntime,
+ runtimeID, runtimeWorkspaceID string,
+ response *AgentTaskResponse,
+ token db.CreateTaskTokenParams,
+ deliveredCommentIDs []pgtype.UUID,
+ recordCommentReceipt bool,
+ issueSnapshot []byte,
+ daemonTokens ...db.CreateDaemonTokenParams,
+) (receipt []pgtype.UUID, deliveryFailure *claimBuildFailure, err error) {
+ var agentOwnerID pgtype.UUID
+ authorize := func(qtx *db.Queries, tokenParams *db.CreateTaskTokenParams) error {
+ // FOR UPDATE on the runtime row: any concurrent
+ // UpsertAgentRuntime/visibility flip that would change owner_id or
+ // visibility blocks until this transaction commits, so the values read
+ // here are the ones delivery is authorized against.
+ locked, lerr := qtx.LockAgentRuntime(ctx, runtime.ID)
+ if lerr != nil {
+ return fmt.Errorf("lock runtime for delivery authorization: %w", lerr)
+ }
+ if response != nil {
+ // The response was built from the claim-time runtime snapshot. Clear
+ // that identity before resolving the locked owner so a failed lookup
+ // can never leak stale user context to the daemon.
+ response.RequestingUserName = ""
+ response.RequestingUserProfileDescription = ""
+ }
+ agent, aerr := qtx.GetAgentForUpdate(ctx, task.AgentID)
+ if aerr != nil {
+ return fmt.Errorf("re-read agent for delivery authorization: %w", aerr)
+ }
+ if agent.RuntimeID != task.RuntimeID {
+ return &service.ClaimDeliveryAuthzError{
+ Reason: "error_agent_runtime_changed",
+ Detail: "agent runtime changed before delivery",
+ }
+ }
+ if locked.Visibility == "private" && locked.OwnerID.Valid &&
+ (!agent.OwnerID.Valid || agent.OwnerID != locked.OwnerID) {
+ agentOwnerID = agent.OwnerID
+ return &service.ClaimDeliveryAuthzError{
+ Reason: "error_runtime_access_denied",
+ Detail: "private runtime does not permit task agent at delivery gate",
+ }
+ }
+ if !locked.OwnerID.Valid {
+ return &service.ClaimDeliveryAuthzError{
+ Reason: "error_runtime_owner_missing",
+ Detail: "runtime owner missing before task delivery",
+ }
+ }
+ if owner, oerr := qtx.GetUser(ctx, locked.OwnerID); oerr != nil {
+ slog.Debug("failed to load locked runtime owner for brief injection",
+ "runtime_id", runtimeID,
+ "owner_id", uuidToString(locked.OwnerID),
+ "error", oerr,
+ )
+ } else if response != nil {
+ response.RequestingUserName = owner.Name
+ response.RequestingUserProfileDescription = owner.ProfileDescription
+ }
+ // The runtime row is locked for the duration of FinalizeTaskClaim. Use
+ // its current owner as the task-token identity rather than the stale
+ // claim-time snapshot captured by the caller.
+ tokenParams.UserID = locked.OwnerID
+ return nil
+ }
+
+ receipt, err = h.TaskService.FinalizeTaskClaim(ctx, *task, token, deliveredCommentIDs, recordCommentReceipt, authorize, issueSnapshot, daemonTokens...)
+ if err == nil {
+ return receipt, nil, nil
+ }
+ var authzErr *service.ClaimDeliveryAuthzError
+ if !errors.As(err, &authzErr) {
+ return nil, nil, err
+ }
+ // Authorization rejected at the delivery boundary: settle through the
+ // existing failure path so the task never reaches the daemon.
+ switch authzErr.Reason {
+ case "error_agent_runtime_changed":
+ failure := h.failClaimedTaskBeforeLaunch(
+ ctx, task,
+ "The agent moved to another runtime before this task could start. Retry the task to run it on the agent's current runtime.",
+ taskfailure.ReasonInvalidTaskIdentity,
+ "error_agent_runtime_changed", http.StatusConflict, "agent runtime changed before task delivery",
+ )
+ return nil, failure, nil
+ default:
+ userMessage := "This private runtime cannot run the assigned agent because the agent and runtime have different owners."
+ if authzErr.Reason == "error_runtime_owner_missing" {
+ userMessage = "This runtime cannot run the assigned agent because the runtime has no owner."
+ } else if !agentOwnerID.Valid {
+ userMessage = "This private runtime cannot run the assigned agent because the agent has no owner."
+ }
+ failure := h.failClaimedTaskBeforeLaunch(
+ ctx, task,
+ userMessage,
+ taskfailure.ReasonRuntimeAccessDenied,
+ "error_runtime_access_denied", http.StatusForbidden, "private runtime does not permit task agent",
+ )
+ return nil, failure, nil
+ }
+}
+
// claimBuildFailure captures a pre-response failure from
// buildClaimedTaskResponse (workspace isolation, chat-input load/empty, ...) so
// the per-runtime handler can render the exact status/message/outcome and the
@@ -1960,6 +2096,7 @@ type claimBuildFailure struct {
outcome string
status int
message string
+ settled bool
}
// rejectClaimSourceLoad settles a claim whose SOURCE row — the issue, chat
@@ -2139,7 +2276,7 @@ func (h *Handler) failClaimedTaskBeforeLaunch(
message: "failed to settle a task rejected before launch",
}
}
- return &claimBuildFailure{outcome: outcome, status: status, message: claimMessage}
+ return &claimBuildFailure{outcome: outcome, status: status, message: claimMessage, settled: true}
}
func chatSessionResumeFallbackNeeded(priorSessionID, priorWorkDir string) bool {
@@ -2302,7 +2439,7 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
return resp, deliveredCommentIDs, issueSnapshot, agentSkillCount, builtinSkillCount, h.failClaimedTaskBeforeLaunch(
r.Context(), task,
userMessage,
- taskfailure.ReasonInvalidTaskIdentity,
+ taskfailure.ReasonRuntimeAccessDenied,
"error_runtime_access_denied", http.StatusForbidden, "private runtime does not permit task agent",
)
}
@@ -3630,6 +3767,10 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
resp, deliveredCommentIDs, issueSnapshot, agentSkillCount, builtinSkillCount, failure := h.buildClaimedTaskResponse(r, task, runtime, runtimeID, runtimeWorkspaceID)
if failure != nil {
outcome = failure.outcome
+ if failure.settled {
+ payloadBytes, _ = writeMeasuredJSON(w, http.StatusOK, map[string]any{"task": nil})
+ return
+ }
writeError(w, failure.status, failure.message)
return
}
@@ -3686,7 +3827,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to mint Remote MCP daemon token")
return
}
- receipt, ferr := h.TaskService.FinalizeTaskClaim(r.Context(), *task, db.CreateTaskTokenParams{
+ receipt, deliveryFailure, ferr := h.finalizeClaimDelivery(r.Context(), task, runtime, runtimeID, runtimeWorkspaceID, &resp, db.CreateTaskTokenParams{
ID: dbid.NewV7(),
TokenHash: auth.HashToken(tokenStr),
TaskID: task.ID,
@@ -3707,6 +3848,20 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to finalize task claim")
return
}
+ if deliveryFailure != nil {
+ if !deliveryFailure.settled {
+ outcome = deliveryFailure.outcome
+ writeError(w, deliveryFailure.status, deliveryFailure.message)
+ return
+ }
+ // The final delivery gate rejected the task (agent rebound, or the
+ // runtime's current ownership no longer permits this agent). The task
+ // is already terminal via the FailTask path — return the same empty
+ // successful poll the queued-mismatch settle path returns.
+ outcome = deliveryFailure.outcome
+ payloadBytes, _ = writeMeasuredJSON(w, http.StatusOK, map[string]any{"task": nil})
+ return
+ }
resp.AuthToken = tokenStr
resp.RemoteMCPDaemonToken = remoteMCPToken
task.DeliveredCommentIds = receipt
diff --git a/server/internal/handler/daemon_comment_delivery_test.go b/server/internal/handler/daemon_comment_delivery_test.go
index 24b5cc2416..6b7b10c153 100644
--- a/server/internal/handler/daemon_comment_delivery_test.go
+++ b/server/internal/handler/daemon_comment_delivery_test.go
@@ -1003,7 +1003,7 @@ func TestFinalizeTaskClaim_ReceiptCASFailureRollsBackInsertedToken(t *testing.T)
WorkspaceID: parseUUID(testWorkspaceID),
UserID: parseUUID(testUserID),
ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true},
- }, []pgtype.UUID{parseUUID("00000000-0000-0000-0000-000000000099")}, true, nil, db.CreateDaemonTokenParams{
+ }, []pgtype.UUID{parseUUID("00000000-0000-0000-0000-000000000099")}, true, nil, nil, db.CreateDaemonTokenParams{
TokenHash: daemonTokenHash,
WorkspaceID: parseUUID(testWorkspaceID),
DaemonID: "daemon-claim-rollback",
@@ -1056,7 +1056,7 @@ func TestFinalizeTaskClaim_TriggerDeletedAfterClaimRejectsStaleProvenance(t *tes
WorkspaceID: parseUUID(testWorkspaceID),
UserID: parseUUID(testUserID),
ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true},
- }, []pgtype.UUID{parseUUID(fixture.commentID[0]), parseUUID(fixture.commentID[1])}, true, nil)
+ }, []pgtype.UUID{parseUUID(fixture.commentID[0]), parseUUID(fixture.commentID[1])}, true, nil, nil)
if err == nil {
t.Fatalf("FinalizeTaskClaim accepted a receipt after persisted trigger changed")
}
diff --git a/server/internal/handler/daemon_runtime_access_test.go b/server/internal/handler/daemon_runtime_access_test.go
index 343be3bc7c..b86cde3116 100644
--- a/server/internal/handler/daemon_runtime_access_test.go
+++ b/server/internal/handler/daemon_runtime_access_test.go
@@ -2,13 +2,19 @@ package handler
import (
"context"
+ "encoding/json"
+ "fmt"
"net/http"
"strings"
"testing"
+ "time"
"github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/testutil"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/taskfailure"
)
@@ -25,9 +31,9 @@ func TestClaimTaskByRuntime_OwnerlessAgentOnPrivateRuntimeFailsExplicitly(t *tes
req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
testWorkspaceID, "ownerless-agent-claim")
req = withURLParam(req, "runtimeId", runtimeID)
- w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusForbidden)
- if !strings.Contains(w.Body.String(), "private runtime does not permit task agent") {
- t.Fatalf("ClaimTaskByRuntime body = %q, want explicit private-runtime access error", w.Body.String())
+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
+ if strings.TrimSpace(w.Body.String()) != `{"task":null}` {
+ t.Fatalf("ClaimTaskByRuntime body = %q, want empty successful poll", w.Body.String())
}
var status, errorMessage, failureReason string
@@ -42,8 +48,111 @@ func TestClaimTaskByRuntime_OwnerlessAgentOnPrivateRuntimeFailsExplicitly(t *tes
if !strings.Contains(errorMessage, "agent has no owner") {
t.Fatalf("task error = %q, want actionable missing-owner error", errorMessage)
}
- if failureReason != taskfailure.ReasonInvalidTaskIdentity.String() {
- t.Fatalf("failure_reason = %q, want %q", failureReason, taskfailure.ReasonInvalidTaskIdentity)
+ if failureReason != taskfailure.ReasonRuntimeAccessDenied.String() {
+ t.Fatalf("failure_reason = %q, want %q", failureReason, taskfailure.ReasonRuntimeAccessDenied)
+ }
+}
+
+func TestClaimTaskByRuntime_SettlesPrivateOwnerMismatch(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ foreignOwnerID := dbfx.User(t, "Daemon mismatch owner", "daemon-mismatch-owner-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, foreignOwnerID, "member")
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Mismatch issue runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Mismatch issue agent")
+ dbfx.Exec(t, `UPDATE agent SET owner_id = $1 WHERE id = $2`, foreignOwnerID, agentID)
+ taskID := seedQueuedIssueTask(t, ctx, agentID, runtimeID, issueID)
+
+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "mismatch-issue-claim")
+ req = withURLParam(req, "runtimeId", runtimeID)
+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
+ if strings.TrimSpace(w.Body.String()) != `{"task":null}` {
+ t.Fatalf("ClaimTaskByRuntime body = %q, want empty successful poll", w.Body.String())
+ }
+
+ var status, failureReason string
+ dbfx.QueryRow(t, `SELECT status, failure_reason FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status, &failureReason)
+ // Regression A (PUCK-132): a queued issue task whose agent lost access to
+ // its private runtime settles as runtime_access_denied — matching the
+ // admission-time dispatch reason — not invalid_task_identity, so clients
+ // reach the dedicated recovery copy.
+ if status != "failed" || failureReason != taskfailure.ReasonRuntimeAccessDenied.String() {
+ t.Fatalf("task state = %q/%q, want failed/%s", status, failureReason, taskfailure.ReasonRuntimeAccessDenied)
+ }
+}
+
+func TestClaimTaskByRuntime_SettlesPrivateOwnerMismatchChatFailure(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ foreignOwnerID := dbfx.User(t, "Daemon chat mismatch owner", "daemon-chat-mismatch-owner-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, foreignOwnerID, "member")
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Mismatch chat runtime")
+ agentID, _ := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Mismatch chat agent")
+ dbfx.Exec(t, `UPDATE agent SET owner_id = $1 WHERE id = $2`, foreignOwnerID, agentID)
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "chat_session_id": sessionID, "issue_id": nil})
+
+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "mismatch-chat-claim")
+ req = withURLParam(req, "runtimeId", runtimeID)
+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
+ if strings.TrimSpace(w.Body.String()) != `{"task":null}` {
+ t.Fatalf("ClaimTaskByRuntime body = %q, want empty successful poll", w.Body.String())
+ }
+
+ var status, failureReason, assistantContent string
+ dbfx.QueryRow(t, `SELECT status, failure_reason FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status, &failureReason)
+ dbfx.QueryRow(t, `SELECT content FROM chat_message WHERE task_id = $1 AND role = 'assistant'`, taskID).Scan(&assistantContent)
+ // Regression B (PUCK-132): queued chat task settlement carries
+ // runtime_access_denied AND still produces the assistant failure message
+ // through the existing FailTask path.
+ if status != "failed" || failureReason != taskfailure.ReasonRuntimeAccessDenied.String() {
+ t.Fatalf("task state = %q/%q, want failed/%s", status, failureReason, taskfailure.ReasonRuntimeAccessDenied)
+ }
+ if !strings.Contains(assistantContent, "agent and runtime have different owners") {
+ t.Fatalf("assistant failure = %q, want owner-mismatch message", assistantContent)
+ }
+}
+
+func TestClaimTasksByRuntime_SettlesMismatchAndReturnsValidTask(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ foreignOwnerID := dbfx.User(t, "Daemon batch mismatch owner", "daemon-batch-mismatch-owner-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, foreignOwnerID, "member")
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Mismatch batch runtime")
+ mismatchAgentID, mismatchIssueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Mismatch batch agent")
+ dbfx.Exec(t, `UPDATE agent SET owner_id = $1 WHERE id = $2`, foreignOwnerID, mismatchAgentID)
+ validAgentID, validIssueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Valid batch agent")
+ mismatchTaskID := seedQueuedIssueTask(t, ctx, mismatchAgentID, runtimeID, mismatchIssueID)
+ validTaskID := seedQueuedIssueTask(t, ctx, validAgentID, runtimeID, validIssueID)
+
+ w := postBatchClaim(t, testWorkspaceID, []string{runtimeID}, 2)
+ if w.Code != http.StatusOK {
+ t.Fatalf("batch claim status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ var resp batchClaimResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode batch claim: %v", err)
+ }
+ if len(resp.Tasks) != 1 || resp.Tasks[0].ID != validTaskID {
+ t.Fatalf("batch tasks = %+v, want valid task %s", resp.Tasks, validTaskID)
+ }
+
+ var mismatchStatus, mismatchReason, validStatus string
+ dbfx.QueryRow(t, `SELECT status, failure_reason FROM agent_task_queue WHERE id = $1`, mismatchTaskID).Scan(&mismatchStatus, &mismatchReason)
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, validTaskID).Scan(&validStatus)
+ if mismatchStatus != "failed" || mismatchReason != taskfailure.ReasonRuntimeAccessDenied.String() {
+ t.Fatalf("mismatch task state = %q/%q, want failed/%s", mismatchStatus, mismatchReason, taskfailure.ReasonRuntimeAccessDenied)
+ }
+ if validStatus != "dispatched" {
+ t.Fatalf("valid task status = %q, want dispatched", validStatus)
}
}
@@ -98,8 +207,8 @@ func TestBuildClaimedTaskResponseRejectsAgentOwnerChangedAfterClaim(t *testing.T
if strings.Contains(errorMessage, "agent has no owner") {
t.Fatalf("task error = %q, must not describe a non-null owner as missing", errorMessage)
}
- if failureReason != taskfailure.ReasonInvalidTaskIdentity.String() {
- t.Fatalf("failure_reason = %q, want %q", failureReason, taskfailure.ReasonInvalidTaskIdentity)
+ if failureReason != taskfailure.ReasonRuntimeAccessDenied.String() {
+ t.Fatalf("failure_reason = %q, want %q", failureReason, taskfailure.ReasonRuntimeAccessDenied)
}
}
@@ -150,7 +259,443 @@ func TestBuildClaimedTaskResponseRejectsAgentReboundAfterClaim(t *testing.T) {
if !strings.Contains(errorMessage, "moved to another runtime") {
t.Fatalf("task error = %q, want actionable rebind error", errorMessage)
}
+ // Regression C (PUCK-132): a genuine identity violation — the agent
+ // rebound to another runtime — must keep invalid_task_identity and must
+ // never be conflated with the runtime_access_denied ownership reason.
if failureReason != taskfailure.ReasonInvalidTaskIdentity.String() {
t.Fatalf("failure_reason = %q, want %q", failureReason, taskfailure.ReasonInvalidTaskIdentity)
}
}
+
+// PUCK-89 blocker 1: the claim path reads the runtime BEFORE claiming, so a
+// concurrent re-registration can flip runtime.owner_id between that read and
+// final delivery. The final delivery gate must re-authorize against the
+// CURRENT owner inside the finalize transaction — the singular claim must not
+// return the task to the daemon, must settle it through the existing failure
+// path, and must keep the empty successful-poll response.
+// finalizeClaimDeliveryForTest drives the singular finalize+delivery path
+// (shared gate included) against a task already claimed out-of-band, so a test
+// can mutate the runtime between claim and finalize the way a concurrent
+// re-registration would in production.
+func (h *Handler) finalizeClaimDeliveryForTest(
+ r *http.Request, task *db.AgentTaskQueue, runtimeID, runtimeWorkspaceID string,
+) (AgentTaskResponse, []pgtype.UUID, int, int, *claimBuildFailure, error) {
+ runtime, err := h.Queries.GetAgentRuntimeForWorkspace(r.Context(), db.GetAgentRuntimeForWorkspaceParams{
+ ID: parseUUID(runtimeID),
+ WorkspaceID: parseUUID(runtimeWorkspaceID),
+ })
+ if err != nil {
+ return AgentTaskResponse{}, nil, 0, 0, nil, fmt.Errorf("load runtime: %w", err)
+ }
+ return h.finalizeClaimDeliveryForTestWithRuntime(r, task, runtime, runtimeID, runtimeWorkspaceID)
+}
+
+func (h *Handler) finalizeClaimDeliveryForTestWithRuntime(
+ r *http.Request, task *db.AgentTaskQueue, runtime db.AgentRuntime, runtimeID, runtimeWorkspaceID string,
+) (AgentTaskResponse, []pgtype.UUID, int, int, *claimBuildFailure, error) {
+ resp, deliveredCommentIDs, _, agentSkillCount, builtinSkillCount, buildFailure := h.buildClaimedTaskResponse(
+ r, task, runtime, runtimeID, runtimeWorkspaceID,
+ )
+ if buildFailure != nil {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, buildFailure, nil
+ }
+ if !runtime.OwnerID.Valid {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount,
+ &claimBuildFailure{outcome: "error_token", status: http.StatusInternalServerError, message: "runtime owner required"}, nil
+ }
+ tokenStr, terr := auth.GenerateAgentTaskToken()
+ if terr != nil {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, nil, fmt.Errorf("generate token: %w", terr)
+ }
+ remoteMCPToken, daemonTokens, derr := remoteMCPDaemonTokenForClaim(resp, runtime)
+ if derr != nil {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, nil, fmt.Errorf("remote mcp token: %w", derr)
+ }
+ commentBackedTask := task.TriggerCommentID.Valid || len(task.CoalescedCommentIds) > 0
+ receipt, deliveryFailure, ferr := h.finalizeClaimDelivery(r.Context(), task, runtime, runtimeID, runtimeWorkspaceID, &resp, db.CreateTaskTokenParams{
+ ID: dbid.NewV7(),
+ TokenHash: auth.HashToken(tokenStr),
+ TaskID: task.ID,
+ AgentID: task.AgentID,
+ WorkspaceID: parseUUID(resp.WorkspaceID),
+ UserID: runtime.OwnerID,
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},
+ }, deliveredCommentIDs, commentBackedTask, nil, daemonTokens...)
+ if ferr != nil {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, nil, ferr
+ }
+ if deliveryFailure != nil {
+ return AgentTaskResponse{}, deliveredCommentIDs, agentSkillCount, builtinSkillCount, deliveryFailure, nil
+ }
+ resp.AuthToken = tokenStr
+ resp.RemoteMCPDaemonToken = remoteMCPToken
+ resp.DeliveredCommentIDs = uuidStringsOrEmpty(receipt)
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, nil, nil
+}
+
+func TestClaimTaskByRuntime_RuntimeOwnerChangedAfterClaimNeverDelivered(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ newOwnerID := dbfx.User(t, "Delivery gate owner", "delivery-gate-owner-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, newOwnerID, "member")
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Delivery gate runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Delivery gate agent")
+ taskID := seedQueuedIssueTask(t, ctx, agentID, runtimeID, issueID)
+
+ // Initial runtime access read (owner = the workspace fixture user) happens
+ // inside the handler; flip the runtime owner AFTER the task is claimed by
+ // mutating the row directly between claim and finalize. To force that
+ // interleaving deterministically, claim first, then change the owner, then
+ // drive the finalize+delivery path through the handler's gate helper.
+ task, err := testHandler.TaskService.ClaimTaskForRuntime(ctx, parseUUID(runtimeID))
+ if err != nil {
+ t.Fatalf("claim task: %v", err)
+ }
+ if task == nil || uuidToString(task.ID) != taskID {
+ t.Fatalf("claimed task = %+v, want %s", task, taskID)
+ }
+ runtimeSnapshot, err := testHandler.Queries.GetAgentRuntimeForWorkspace(ctx, db.GetAgentRuntimeForWorkspaceParams{
+ ID: parseUUID(runtimeID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatalf("load claim-time runtime: %v", err)
+ }
+ if !runtimeSnapshot.OwnerID.Valid {
+ t.Fatal("claim-time runtime owner unexpectedly missing")
+ }
+ dbfx.Exec(t, `UPDATE agent_runtime SET owner_id = $1 WHERE id = $2`, newOwnerID, runtimeID)
+
+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "delivery-gate-owner-change")
+ resp, deliveredCommentIDs, _, _, settledFailure, finalizeErr := testHandler.finalizeClaimDeliveryForTestWithRuntime(
+ req, task, runtimeSnapshot, runtimeID, testWorkspaceID,
+ )
+ if finalizeErr != nil {
+ t.Fatalf("finalize delivery: %v", finalizeErr)
+ }
+ if settledFailure == nil || settledFailure.outcome != "error_runtime_access_denied" || !settledFailure.settled {
+ t.Fatalf("settled failure = %+v, want settled runtime-access denial", settledFailure)
+ }
+ if len(deliveredCommentIDs) != 0 {
+ t.Fatalf("delivered comment ids = %v, want none", deliveredCommentIDs)
+ }
+ if resp.AuthToken != "" || resp.RemoteMCPDaemonToken != "" {
+ t.Fatalf("resp carries credentials %+v/%+v, want none — nothing may be delivered", resp.AuthToken, resp.RemoteMCPDaemonToken)
+ }
+
+ // No task token was minted and the task settled terminal.
+ var tokenCount int
+ dbfx.QueryRow(t, `SELECT count(*) FROM task_token WHERE task_id = $1`, taskID).Scan(&tokenCount)
+ if tokenCount != 0 {
+ t.Fatalf("task token count = %d, want 0 — no credential may accompany a rejected delivery", tokenCount)
+ }
+ var status, errorMessage, failureReason string
+ dbfx.QueryRow(t, `
+ SELECT status, error, failure_reason
+ FROM agent_task_queue
+ WHERE id = $1
+ `, taskID).Scan(&status, &errorMessage, &failureReason)
+ if status != "failed" {
+ t.Fatalf("task status = %q, want failed", status)
+ }
+ if !strings.Contains(errorMessage, "agent and runtime have different owners") {
+ t.Fatalf("task error = %q, want actionable owner-mismatch error", errorMessage)
+ }
+ if failureReason != taskfailure.ReasonRuntimeAccessDenied.String() {
+ t.Fatalf("failure_reason = %q, want %q", failureReason, taskfailure.ReasonRuntimeAccessDenied)
+ }
+
+ // And the full HTTP claim surface stays an empty successful poll.
+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, func() *http.Request {
+ r := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "delivery-gate-poll")
+ return testutil.WithURLParams(r, "runtimeId", runtimeID)
+ }()).Want(http.StatusOK)
+ if strings.TrimSpace(w.Body.String()) != `{"task":null}` {
+ t.Fatalf("post-settle poll body = %q, want empty successful poll", w.Body.String())
+ }
+}
+
+// PUCK-89 blocker 1: a public runtime may keep delivering after its owner
+// changes, but the task token must identify the owner from the locked runtime
+// row rather than the claim-time snapshot.
+func TestFinalizeClaimDelivery_UsesCurrentRuntimeOwnerForTaskToken(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ newOwnerID := dbfx.User(t, "Public delivery owner", "public-delivery-owner-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, newOwnerID, "member")
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Public delivery owner runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Public delivery owner agent")
+ taskID := seedQueuedIssueTask(t, ctx, agentID, runtimeID, issueID)
+
+ task, err := testHandler.TaskService.ClaimTaskForRuntime(ctx, parseUUID(runtimeID))
+ if err != nil || task == nil {
+ t.Fatalf("claim task: task=%v err=%v", task, err)
+ }
+ runtimeSnapshot, err := testHandler.Queries.GetAgentRuntimeForWorkspace(ctx, db.GetAgentRuntimeForWorkspaceParams{
+ ID: parseUUID(runtimeID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatalf("load claim-time runtime: %v", err)
+ }
+ if !runtimeSnapshot.OwnerID.Valid {
+ t.Fatal("claim-time runtime owner unexpectedly missing")
+ }
+ claimOwner, err := testHandler.Queries.GetUser(ctx, runtimeSnapshot.OwnerID)
+ if err != nil {
+ t.Fatalf("load claim-time runtime owner: %v", err)
+ }
+ const staleProfile = "stale claim-time owner profile"
+ const currentProfile = "current delivery owner profile"
+ dbfx.Exec(t, `UPDATE "user" SET profile_description = $1 WHERE id = $2`, staleProfile, runtimeSnapshot.OwnerID)
+ dbfx.Exec(t, `UPDATE "user" SET profile_description = $1 WHERE id = $2`, currentProfile, newOwnerID)
+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'public', owner_id = $1 WHERE id = $2`, newOwnerID, runtimeID)
+
+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "public-delivery-owner-change")
+ resp, _, _, _, failure, finalizeErr := testHandler.finalizeClaimDeliveryForTestWithRuntime(
+ req, task, runtimeSnapshot, runtimeID, testWorkspaceID,
+ )
+ if finalizeErr != nil {
+ t.Fatalf("finalize delivery: %v", finalizeErr)
+ }
+ if failure != nil {
+ t.Fatalf("delivery failure = %+v, want successful public delivery", failure)
+ }
+ if resp.AuthToken == "" {
+ t.Fatal("successful delivery did not return a task token")
+ }
+
+ var tokenOwnerID string
+ dbfx.QueryRow(t, `SELECT user_id::text FROM task_token WHERE task_id = $1`, taskID).Scan(&tokenOwnerID)
+ if tokenOwnerID != newOwnerID {
+ t.Fatalf("task token user_id = %q, want current runtime owner %q", tokenOwnerID, newOwnerID)
+ }
+ currentOwner, err := testHandler.Queries.GetUser(ctx, parseUUID(newOwnerID))
+ if err != nil {
+ t.Fatalf("load current runtime owner: %v", err)
+ }
+ if resp.RequestingUserName != currentOwner.Name || resp.RequestingUserProfileDescription != currentProfile {
+ t.Fatalf("requesting user = %q/%q, want current owner %q/%q", resp.RequestingUserName, resp.RequestingUserProfileDescription, currentOwner.Name, currentProfile)
+ }
+ if resp.RequestingUserName == claimOwner.Name || strings.Contains(resp.RequestingUserProfileDescription, staleProfile) {
+ t.Fatalf("requesting user leaked stale claim-time owner %q/%q", claimOwner.Name, staleProfile)
+ }
+}
+
+// PUCK-89 blocker 1: if the locked runtime loses its owner after claim, the
+// stale claim-time owner must never be used to mint a task credential.
+func TestFinalizeClaimDelivery_CurrentRuntimeOwnerMissingNeverMintsToken(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Ownerless delivery runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Ownerless delivery agent")
+ taskID := seedQueuedIssueTask(t, ctx, agentID, runtimeID, issueID)
+
+ task, err := testHandler.TaskService.ClaimTaskForRuntime(ctx, parseUUID(runtimeID))
+ if err != nil || task == nil {
+ t.Fatalf("claim task: task=%v err=%v", task, err)
+ }
+ runtimeSnapshot, err := testHandler.Queries.GetAgentRuntimeForWorkspace(ctx, db.GetAgentRuntimeForWorkspaceParams{
+ ID: parseUUID(runtimeID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatalf("load claim-time runtime: %v", err)
+ }
+ if !runtimeSnapshot.OwnerID.Valid {
+ t.Fatal("claim-time runtime owner unexpectedly missing")
+ }
+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'public', owner_id = NULL WHERE id = $1`, runtimeID)
+
+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "ownerless-delivery")
+ resp, _, _, _, failure, finalizeErr := testHandler.finalizeClaimDeliveryForTestWithRuntime(
+ req, task, runtimeSnapshot, runtimeID, testWorkspaceID,
+ )
+ if finalizeErr != nil {
+ t.Fatalf("finalize delivery: %v", finalizeErr)
+ }
+ if failure == nil || !failure.settled {
+ t.Fatalf("delivery failure = %+v, want settled ownerless-runtime failure", failure)
+ }
+ if resp.AuthToken != "" || resp.RemoteMCPDaemonToken != "" {
+ t.Fatalf("ownerless delivery returned credentials %q/%q", resp.AuthToken, resp.RemoteMCPDaemonToken)
+ }
+ var tokenCount int
+ dbfx.QueryRow(t, `SELECT count(*) FROM task_token WHERE task_id = $1`, taskID).Scan(&tokenCount)
+ if tokenCount != 0 {
+ t.Fatalf("task token count = %d, want 0", tokenCount)
+ }
+ var status, errorMessage string
+ dbfx.QueryRow(t, `SELECT status, error FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status, &errorMessage)
+ if status != "failed" || !strings.Contains(errorMessage, "runtime has no owner") {
+ t.Fatalf("task state = %q/%q, want failed ownerless-runtime settlement", status, errorMessage)
+ }
+}
+
+func injectFailTaskSettlementFailure(t *testing.T, ctx context.Context, taskID string) {
+ t.Helper()
+ suffix := strings.ReplaceAll(uuid.NewString(), "-", "")
+ functionName := "puck89_fail_task_" + suffix
+ triggerName := "puck89_fail_task_trg_" + suffix
+ t.Cleanup(func() {
+ testPool.Exec(ctx, fmt.Sprintf("DROP TRIGGER IF EXISTS %s ON agent_task_queue", triggerName))
+ testPool.Exec(ctx, fmt.Sprintf("DROP FUNCTION IF EXISTS %s()", functionName))
+ })
+ if _, err := testPool.Exec(ctx, fmt.Sprintf(`
+CREATE FUNCTION %s() RETURNS trigger LANGUAGE plpgsql AS $fn$
+BEGIN
+ IF NEW.status = 'failed' THEN
+ RAISE EXCEPTION 'injected FailTask settlement failure';
+ END IF;
+ RETURN NEW;
+END
+$fn$;
+`, functionName)); err != nil {
+ t.Fatalf("create FailTask fault function: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, fmt.Sprintf(`
+CREATE TRIGGER %s
+BEFORE UPDATE ON agent_task_queue
+FOR EACH ROW WHEN (OLD.id = '%s'::uuid AND NEW.status = 'failed')
+EXECUTE FUNCTION %s();
+`, triggerName, taskID, functionName)); err != nil {
+ t.Fatalf("create FailTask fault trigger: %v", err)
+ }
+}
+
+func injectRuntimeOwnerFlipAfterClaim(t *testing.T, ctx context.Context, taskID, runtimeID, ownerID string) {
+ t.Helper()
+ suffix := strings.ReplaceAll(uuid.NewString(), "-", "")
+ functionName := "puck89_flip_runtime_owner_" + suffix
+ triggerName := "puck89_flip_runtime_owner_trg_" + suffix
+ t.Cleanup(func() {
+ testPool.Exec(ctx, fmt.Sprintf("DROP TRIGGER IF EXISTS %s ON agent_task_queue", triggerName))
+ testPool.Exec(ctx, fmt.Sprintf("DROP FUNCTION IF EXISTS %s()", functionName))
+ })
+ if _, err := testPool.Exec(ctx, fmt.Sprintf(`
+CREATE FUNCTION %s() RETURNS trigger LANGUAGE plpgsql AS $fn$
+BEGIN
+ UPDATE agent_runtime SET visibility = 'private', owner_id = '%s'::uuid WHERE id = '%s'::uuid;
+ RETURN NEW;
+END
+$fn$;
+`, functionName, ownerID, runtimeID)); err != nil {
+ t.Fatalf("create runtime-owner flip function: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, fmt.Sprintf(`
+CREATE TRIGGER %s
+AFTER UPDATE ON agent_task_queue
+FOR EACH ROW WHEN (OLD.id = '%s'::uuid AND OLD.status = 'queued' AND NEW.status = 'dispatched')
+EXECUTE FUNCTION %s();
+`, triggerName, taskID, functionName)); err != nil {
+ t.Fatalf("create runtime-owner flip trigger: %v", err)
+ }
+}
+
+// PUCK-89 blocker 2: a final authorization rejection whose FailTask
+// settlement fails is an HTTP error, not a successful empty poll. The exact
+// claim is requeued and no token is inserted.
+func TestFinalizeClaimDelivery_SettlementFailureIsUnsettled(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ foreignOwnerID := dbfx.User(t, "Settlement failure owner", "settlement-failure-owner-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, foreignOwnerID, "member")
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Settlement failure runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Settlement failure agent")
+ taskID := seedQueuedIssueTask(t, ctx, agentID, runtimeID, issueID)
+ injectRuntimeOwnerFlipAfterClaim(t, ctx, taskID, runtimeID, foreignOwnerID)
+ injectFailTaskSettlementFailure(t, ctx, taskID)
+
+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "settlement-failure")
+ req = withURLParam(req, "runtimeId", runtimeID)
+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusInternalServerError)
+ if strings.TrimSpace(w.Text()) == `{"task":null}` {
+ t.Fatal("settlement failure was hidden as a successful empty poll")
+ }
+ var tokenCount int
+ dbfx.QueryRow(t, `SELECT count(*) FROM task_token WHERE task_id = $1`, taskID).Scan(&tokenCount)
+ if tokenCount != 0 {
+ t.Fatalf("task token count = %d, want 0", tokenCount)
+ }
+ var status string
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status)
+ if status != "queued" {
+ t.Fatalf("task status = %q, want queued after settlement failure requeue", status)
+ }
+}
+
+// PUCK-89 blocker 1 (batch): a task whose runtime owner changed after the
+// claim-time snapshot must never appear in the batch response; the mismatch is
+// settled and a valid task in the same batch still returns.
+func TestClaimTasksByRuntime_OwnerChangedAfterSnapshotSettlesMismatchReturnsValid(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ newOwnerID := dbfx.User(t, "Batch delivery gate owner", "batch-delivery-gate-owner-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, newOwnerID, "member")
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Batch delivery gate runtime")
+ mismatchAgentID, mismatchIssueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Batch delivery gate mismatch agent")
+ validAgentID, validIssueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Batch delivery gate valid agent")
+ mismatchTaskID := seedQueuedIssueTask(t, ctx, mismatchAgentID, runtimeID, mismatchIssueID)
+ validTaskID := seedQueuedIssueTask(t, ctx, validAgentID, runtimeID, validIssueID)
+
+ // The batch handler resolves runtime snapshots before claiming. Start with a
+ // public runtime so both agents are claimable, then flip its visibility and
+ // owner after the mismatch task is claimed. The valid agent already belongs
+ // to the new owner, so only the stale-snapshot task is rejected at the gate.
+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, runtimeID)
+ dbfx.Exec(t, `UPDATE agent SET owner_id = $1 WHERE id = $2`, newOwnerID, validAgentID)
+ dbfx.Exec(t, `UPDATE agent_task_queue SET priority = 1 WHERE id = $1`, mismatchTaskID)
+ injectRuntimeOwnerFlipAfterClaim(t, ctx, mismatchTaskID, runtimeID, newOwnerID)
+ runtimeSnapshot, err := testHandler.Queries.GetAgentRuntimeForWorkspace(ctx, db.GetAgentRuntimeForWorkspaceParams{
+ ID: parseUUID(runtimeID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatalf("load batch claim-time runtime: %v", err)
+ }
+ if runtimeSnapshot.Visibility != "public" || !runtimeSnapshot.OwnerID.Valid {
+ t.Fatalf("claim-time runtime = %+v, want public runtime with owner", runtimeSnapshot)
+ }
+
+ w := postBatchClaim(t, testWorkspaceID, []string{runtimeID}, 5)
+ if w.Code != http.StatusOK {
+ t.Fatalf("batch claim status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ var resp batchClaimResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode batch claim: %v", err)
+ }
+ for _, got := range resp.Tasks {
+ if got.ID == mismatchTaskID {
+ t.Fatalf("batch returned the mismatched task %s", mismatchTaskID)
+ }
+ }
+ if len(resp.Tasks) != 1 || resp.Tasks[0].ID != validTaskID {
+ t.Fatalf("batch tasks = %+v, want only valid task %s", resp.Tasks, validTaskID)
+ }
+
+ var mismatchStatus, mismatchReason, validStatus string
+ dbfx.QueryRow(t, `SELECT status, failure_reason FROM agent_task_queue WHERE id = $1`, mismatchTaskID).Scan(&mismatchStatus, &mismatchReason)
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, validTaskID).Scan(&validStatus)
+ if mismatchStatus != "failed" || mismatchReason != taskfailure.ReasonRuntimeAccessDenied.String() {
+ t.Fatalf("mismatch task state = %q/%q, want failed/%s", mismatchStatus, mismatchReason, taskfailure.ReasonRuntimeAccessDenied)
+ }
+ if validStatus != "dispatched" {
+ t.Fatalf("valid task status = %q, want dispatched", validStatus)
+ }
+}
diff --git a/server/internal/handler/runtime_access_denied_test.go b/server/internal/handler/runtime_access_denied_test.go
new file mode 100644
index 0000000000..cfb9c4dd50
--- /dev/null
+++ b/server/internal/handler/runtime_access_denied_test.go
@@ -0,0 +1,131 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func createRuntimeAccessDeniedAgent(t *testing.T, ctx context.Context, runtimeID, name string) string {
+ t.Helper()
+ foreignOwnerID := dbfx.User(t, name+" owner", "runtime-access-owner-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, foreignOwnerID, "member")
+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, name)
+ dbfx.Exec(t, `UPDATE agent SET owner_id = $1, visibility = 'workspace', permission_mode = 'public_to' WHERE id = $2`, foreignOwnerID, agentID)
+ dbfx.Exec(t, `
+ INSERT INTO agent_invocation_target (agent_id, target_type, target_id)
+ VALUES ($1, 'workspace', $2)
+ ON CONFLICT (agent_id, target_type, target_id) DO NOTHING
+ `, agentID, testWorkspaceID)
+ return agentID
+}
+
+func TestCreateIssue_RuntimeAccessDeniedLeavesNoticeWithoutTask(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Assignment access denied runtime")
+ agentID := createRuntimeAccessDeniedAgent(t, ctx, runtimeID, "Assignment access denied agent")
+
+ w := testutil.Call(t, testHandler.CreateIssue, newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "assignment access denied issue",
+ "status": "todo",
+ "assignee_type": "agent",
+ "assignee_id": agentID,
+ })).Want(http.StatusCreated)
+ var issue IssueResponse
+ w.JSON(&issue)
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issue.ID) })
+
+ var taskCount int
+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, issue.ID).Scan(&taskCount)
+ if taskCount != 0 {
+ t.Fatalf("assignment created %d task rows, want 0", taskCount)
+ }
+ var notice string
+ dbfx.QueryRow(t, `
+ SELECT content FROM comment
+ WHERE issue_id = $1 AND author_type = 'system' AND type = 'system'
+ ORDER BY created_at DESC LIMIT 1
+ `, issue.ID).Scan(&notice)
+ if !strings.Contains(notice, "public") || !strings.Contains(notice, "rebind/copy") {
+ t.Fatalf("assignment notice = %q, want both recovery paths", notice)
+ }
+}
+
+func TestSendChatMessage_RuntimeAccessDeniedReturnsStructuredConflict(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Chat access denied runtime")
+ agentID := createRuntimeAccessDeniedAgent(t, ctx, runtimeID, "Chat access denied agent")
+ sessionID := createHandlerTestChatSession(t, agentID)
+
+ req := newRequest(http.MethodPost, "/api/chat/sessions/"+sessionID+"/messages", map[string]any{"content": "please help"})
+ req = withURLParam(req, "sessionId", sessionID)
+ req = withChatTestWorkspaceCtx(t, req)
+ w := testutil.Call(t, testHandler.SendChatMessage, req).Want(http.StatusConflict)
+ var body struct {
+ ReasonCode string `json:"reason_code"`
+ }
+ w.JSON(&body)
+ if body.ReasonCode != string(ReasonRuntimeAccessDenied) {
+ t.Fatalf("reason_code = %q, want %s", body.ReasonCode, ReasonRuntimeAccessDenied)
+ }
+ var taskCount int
+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id = $1`, sessionID).Scan(&taskCount)
+ if taskCount != 0 {
+ t.Fatalf("blocked chat created %d task rows, want 0", taskCount)
+ }
+}
+
+func TestCommentMention_RuntimeAccessDeniedReportsTargetAndNotice(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Mention access denied runtime")
+ agentID := createRuntimeAccessDeniedAgent(t, ctx, runtimeID, "Mention access denied agent")
+ issueID := createMentionFixtureIssue(t, ctx, "mention access denied issue")
+
+ req := newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{
+ "content": "[@Agent](mention://agent/" + agentID + ") please help",
+ })
+ req = withURLParam(req, "id", issueID)
+ w := testutil.Call(t, testHandler.CreateComment, req).WantOneOf(http.StatusOK, http.StatusCreated)
+ var body struct {
+ TriggerOutcomes []struct {
+ TargetID string `json:"target_id"`
+ Status string `json:"status"`
+ ReasonCode string `json:"reason_code"`
+ } `json:"trigger_outcomes"`
+ }
+ w.JSON(&body)
+ found := false
+ for _, outcome := range body.TriggerOutcomes {
+ if outcome.TargetID == agentID {
+ found = true
+ if outcome.Status != string(DispatchBlocked) || outcome.ReasonCode != string(ReasonRuntimeAccessDenied) {
+ t.Fatalf("target outcome = %+v, want blocked/runtime_access_denied", outcome)
+ }
+ }
+ }
+ if !found {
+ t.Fatalf("no blocked outcome for agent %s: %s", agentID, w.Body.String())
+ }
+ var notice string
+ dbfx.QueryRow(t, `
+ SELECT content FROM comment
+ WHERE issue_id = $1 AND author_type = 'system' AND type = 'system'
+ ORDER BY created_at DESC LIMIT 1
+ `, issueID).Scan(&notice)
+ if !strings.Contains(notice, "public") || !strings.Contains(notice, "rebind/copy") {
+ t.Fatalf("mention notice = %q, want both recovery paths", notice)
+ }
+}
diff --git a/server/internal/service/agent_ready.go b/server/internal/service/agent_ready.go
index 975ca45f33..b65f722105 100644
--- a/server/internal/service/agent_ready.go
+++ b/server/internal/service/agent_ready.go
@@ -102,7 +102,8 @@ const runtimeOfflineCodeDshProfile = "dsh_profile"
// response for the user to read.
func RuntimeBlockedNeedsNotice(code dispatch.ReasonCode) bool {
return code == dispatch.ReasonRuntimeUnusable ||
- code == dispatch.ReasonRuntimeProfileMissing
+ code == dispatch.ReasonRuntimeProfileMissing ||
+ code == dispatch.ReasonRuntimeAccessDenied
}
// AgentReadiness reports whether an agent can accept new work right now, and
@@ -147,12 +148,19 @@ func AgentReadiness(ctx context.Context, lookup RuntimeLookup, agent db.Agent) (
if err != nil {
return AgentVerdict{}, err
}
- return runtimeVerdict(rt), nil
+ return runtimeVerdict(rt, agent), nil
}
-// runtimeVerdict is the half of the decision that depends only on the runtime
-// row, split out so every branch is testable without a database.
-func runtimeVerdict(rt db.AgentRuntime) AgentVerdict {
+// runtimeVerdict combines runtime health with the ownership binding that
+// determines whether this agent can execute there.
+func runtimeVerdict(rt db.AgentRuntime, agent db.Agent) AgentVerdict {
+ if rt.Visibility == "private" && rt.OwnerID.Valid && (!agent.OwnerID.Valid || agent.OwnerID != rt.OwnerID) {
+ return AgentVerdict{
+ Availability: AgentBlocked,
+ Reason: dispatch.ReasonRuntimeAccessDenied,
+ Detail: "agent owner does not match private runtime owner",
+ }
+ }
if rt.Status == "online" {
return AgentVerdict{Availability: AgentAvailable}
}
@@ -259,6 +267,12 @@ func RuntimeUnusableNotice(agentName string, verdict AgentVerdict) string {
if name == "" {
name = "The assigned agent"
}
+ if verdict.Reason == dispatch.ReasonRuntimeAccessDenied {
+ return fmt.Sprintf(
+ "%s cannot run on this private runtime, so this trigger was not queued. Make the runtime's machine public, or rebind/copy the agent to a runtime its owner can use.",
+ name,
+ )
+ }
if verdict.Reason == dispatch.ReasonRuntimeProfileMissing {
return runtimeProfileMissingNotice(name)
}
diff --git a/server/internal/service/reason_code_test.go b/server/internal/service/reason_code_test.go
index f6e1e08ef5..d4491c23bc 100644
--- a/server/internal/service/reason_code_test.go
+++ b/server/internal/service/reason_code_test.go
@@ -52,13 +52,54 @@ func TestAgentReadinessVerdict(t *testing.T) {
t.Errorf("archived agent: got %+v, want blocked/target_unavailable", got)
}
- // The runtime half.
- if got := runtimeVerdict(db.AgentRuntime{Status: "online"}); !got.Ready() {
+ // The runtime half. A private runtime with an owner admits only an agent
+ // owned by that same member; ownerless agents are blocked for new work.
+ ownerA := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}
+ ownerB := pgtype.UUID{Bytes: [16]byte{3}, Valid: true}
+ if got := runtimeVerdict(db.AgentRuntime{Status: "online"}, db.Agent{OwnerID: ownerA}); !got.Ready() {
t.Errorf("online runtime: got %+v, want ready", got)
}
+ for name, tc := range map[string]struct {
+ runtime db.AgentRuntime
+ agent db.Agent
+ blocked bool
+ reason dispatch.ReasonCode
+ }{
+ "private mismatch": {
+ runtime: db.AgentRuntime{Status: "online", Visibility: "private", OwnerID: ownerA},
+ agent: db.Agent{OwnerID: ownerB},
+ blocked: true,
+ reason: dispatch.ReasonRuntimeAccessDenied,
+ },
+ "private ownerless agent": {
+ runtime: db.AgentRuntime{Status: "online", Visibility: "private", OwnerID: ownerA},
+ agent: db.Agent{},
+ blocked: true,
+ reason: dispatch.ReasonRuntimeAccessDenied,
+ },
+ "private same owner": {
+ runtime: db.AgentRuntime{Status: "online", Visibility: "private", OwnerID: ownerA},
+ agent: db.Agent{OwnerID: ownerA},
+ },
+ "public mismatch": {
+ runtime: db.AgentRuntime{Status: "online", Visibility: "public", OwnerID: ownerA},
+ agent: db.Agent{OwnerID: ownerB},
+ },
+ "ownerless runtime": {
+ runtime: db.AgentRuntime{Status: "online", Visibility: "private"},
+ agent: db.Agent{OwnerID: ownerB},
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ got := runtimeVerdict(tc.runtime, tc.agent)
+ if got.Blocked() != tc.blocked || (tc.blocked && got.Reason != tc.reason) {
+ t.Fatalf("got %+v, want blocked=%v reason=%q", got, tc.blocked, tc.reason)
+ }
+ })
+ }
// Offline with no explanation is the sleeping-laptop case: work waits for it,
// so this must NOT be blocked.
- offline := runtimeVerdict(db.AgentRuntime{Status: "offline"})
+ offline := runtimeVerdict(db.AgentRuntime{Status: "offline"}, db.Agent{OwnerID: ownerA})
if offline.Blocked() || offline.Reason != dispatch.ReasonRuntimeOffline {
t.Errorf("plain offline runtime: got %+v, want waitable/runtime_offline", offline)
}
@@ -68,7 +109,7 @@ func TestAgentReadinessVerdict(t *testing.T) {
unusable := runtimeVerdict(db.AgentRuntime{
Status: "offline",
Metadata: []byte(`{"offline_reason":{"code":"not_executable","detail":"agent CLI is not executable","repair":{"package":"@anthropic-ai/claude-code","command":"cd '/pkg' && node install.cjs"}}}`),
- })
+ }, db.Agent{OwnerID: ownerA})
if !unusable.Blocked() || unusable.Reason != dispatch.ReasonRuntimeUnusable {
t.Fatalf("unusable runtime: got %+v, want blocked/runtime_unusable", unusable)
}
@@ -83,7 +124,7 @@ func TestAgentReadinessVerdict(t *testing.T) {
profile := runtimeVerdict(db.AgentRuntime{
Status: "offline",
Metadata: []byte(`{"offline_reason":{"code":"dsh_profile","detail":"the Multica runtime profile is not installed","repair":{"package":"DeepSeek Harness runtime profile"}}}`),
- })
+ }, db.Agent{OwnerID: ownerA})
if !profile.Blocked() || profile.Reason != dispatch.ReasonRuntimeProfileMissing {
t.Fatalf("missing DSH profile: got %+v, want blocked/runtime_profile_missing", profile)
}
@@ -120,14 +161,14 @@ func TestAgentReadinessVerdict(t *testing.T) {
}
// The one exception is an install the daemon is running right now: that wait
// DOES end by itself, so the work queues instead of being refused.
- fresh := runtimeVerdict(installingRow(time.Now()))
+ fresh := runtimeVerdict(installingRow(time.Now()), db.Agent{OwnerID: ownerA})
if fresh.Blocked() {
t.Errorf("install in flight: got %+v, want the waitable verdict", fresh)
}
if fresh.Reason != dispatch.ReasonRuntimeOffline {
t.Errorf("install in flight: reason = %q, want %q", fresh.Reason, dispatch.ReasonRuntimeOffline)
}
- stale := runtimeVerdict(installingRow(time.Now().Add(-runtimeInstallClaimWindow - time.Minute)))
+ stale := runtimeVerdict(installingRow(time.Now().Add(-runtimeInstallClaimWindow - time.Minute)), db.Agent{OwnerID: ownerA})
if !stale.Blocked() || stale.Reason != dispatch.ReasonRuntimeProfileMissing {
t.Fatalf("stale install claim: got %+v, want blocked/runtime_profile_missing", stale)
}
@@ -136,7 +177,7 @@ func TestAgentReadinessVerdict(t *testing.T) {
unbounded := runtimeVerdict(db.AgentRuntime{
Status: "offline",
Metadata: []byte(`{"offline_reason":{"code":"dsh_profile","installing":true}}`),
- })
+ }, db.Agent{OwnerID: ownerA})
if !unbounded.Blocked() {
t.Errorf("install claim with no updated_at: got %+v, want blocked", unbounded)
}
@@ -148,7 +189,7 @@ func TestAgentReadinessVerdict(t *testing.T) {
"malformed": `{"offline_reason":`,
"empty": ``,
} {
- got := runtimeVerdict(db.AgentRuntime{Status: "offline", Metadata: []byte(metadata)})
+ got := runtimeVerdict(db.AgentRuntime{Status: "offline", Metadata: []byte(metadata)}, db.Agent{OwnerID: ownerA})
if got.Blocked() {
t.Errorf("%s: got %+v, want the plain offline verdict", name, got)
}
@@ -185,4 +226,9 @@ func TestRuntimeUnusableNotice(t *testing.T) {
if !strings.Contains(withoutRepair, "Reinstall") {
t.Errorf("notice must still say what to do:\n%s", withoutRepair)
}
+
+ accessDenied := RuntimeUnusableNotice("Mika", AgentVerdict{Reason: dispatch.ReasonRuntimeAccessDenied})
+ if !strings.Contains(accessDenied, "public") || !strings.Contains(accessDenied, "rebind/copy") {
+ t.Errorf("access-denied notice must include both recovery paths:\n%s", accessDenied)
+ }
}
diff --git a/server/internal/service/runtime_claim_access_test.go b/server/internal/service/runtime_claim_access_test.go
index dcf587b070..17f82b4535 100644
--- a/server/internal/service/runtime_claim_access_test.go
+++ b/server/internal/service/runtime_claim_access_test.go
@@ -102,7 +102,7 @@ func TestRuntimeAccessGatesQueuedTaskClaims(t *testing.T) {
ownerlessAgent bool
wantClaim bool
}{
- {name: "private runtime rejects foreign agent", visibility: "private", wantClaim: false, matchingBinding: true},
+ {name: "private runtime routes foreign agent to handler", visibility: "private", wantClaim: true, matchingBinding: true},
{name: "private runtime accepts owner agent", visibility: "private", sameOwner: true, matchingBinding: true, wantClaim: true},
{name: "private runtime routes ownerless agent to handler", visibility: "private", sameOwner: true, matchingBinding: true, ownerlessAgent: true, wantClaim: true},
{name: "public runtime accepts foreign agent", visibility: "public", wantClaim: true, matchingBinding: true},
@@ -266,6 +266,40 @@ func TestClaimTaskRejectsMismatchedAgentRuntime(t *testing.T) {
}
}
+func TestClaimTaskForRuntimeKeepsOwnerlessPrivateAgentClaimable(t *testing.T) {
+ ctx := context.Background()
+ fixture := newRuntimeClaimAccessFixture(t, "private", true, true, "queued")
+ if _, err := fixture.pool.Exec(ctx, `UPDATE agent SET owner_id = NULL WHERE id = $1`, fixture.agentID); err != nil {
+ t.Fatalf("clear agent owner: %v", err)
+ }
+ svc := NewTaskService(db.New(fixture.pool), fixture.pool, nil, events.New())
+
+ claimed, err := svc.ClaimTaskForRuntime(ctx, fixture.runtimeID)
+ if err != nil {
+ t.Fatalf("claim task: %v", err)
+ }
+ if claimed == nil || util.UUIDToString(claimed.ID) != fixture.taskID {
+ t.Fatalf("claimed task = %+v, want %s", claimed, fixture.taskID)
+ }
+}
+
+func TestClaimTasksForRuntimesKeepsOwnerlessPrivateAgentClaimable(t *testing.T) {
+ ctx := context.Background()
+ fixture := newRuntimeClaimAccessFixture(t, "private", true, true, "queued")
+ if _, err := fixture.pool.Exec(ctx, `UPDATE agent SET owner_id = NULL WHERE id = $1`, fixture.agentID); err != nil {
+ t.Fatalf("clear agent owner: %v", err)
+ }
+ svc := NewTaskService(db.New(fixture.pool), fixture.pool, nil, events.New())
+
+ claimed, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{fixture.runtimeID}, 1)
+ if err != nil {
+ t.Fatalf("claim tasks: %v", err)
+ }
+ if len(claimed) != 1 || util.UUIDToString(claimed[0].ID) != fixture.taskID {
+ t.Fatalf("claimed tasks = %+v, want task %s", claimed, fixture.taskID)
+ }
+}
+
func TestClaimTaskUsesCurrentAgentRuntimeWhenRuntimeIDIsOmitted(t *testing.T) {
ctx := context.Background()
fixture := newRuntimeClaimAccessFixture(t, "public", true, true, "queued")
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 53eb0b693d..92810814e5 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -3735,6 +3735,19 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
return claimed, nil
}
+// ErrClaimDeliveryAuthz signals that the final delivery gate rejected the
+// claimed task: the current agent/runtime authorization no longer holds at the
+// delivery boundary. The task is settled by the caller through the existing
+// FailTask path; no claim payload is dispatched.
+type ClaimDeliveryAuthzError struct {
+ Reason string
+ Detail string
+}
+
+func (e *ClaimDeliveryAuthzError) Error() string {
+ return "claim delivery authorization failed: " + e.Reason + ": " + e.Detail
+}
+
// FinalizeTaskClaim atomically persists the task-scoped agent token, an
// optional short-lived daemon token used by the Remote MCP broker, the
// comparable issue state this payload was built from, and, for a comment-backed
@@ -3749,12 +3762,24 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
// rather than a wrong "unchanged" (MUL-7344). Unlike the comment receipt it is
// NOT gated on the task being comment-backed: an assignment run that recorded
// no snapshot leaves the following comment-triggered run with no baseline.
+//
+// The optional authorize closure runs INSIDE the same transaction, after the
+// gate has re-read the current runtime row under a FOR UPDATE row lock. That
+// makes the authorization decision and the task-token/daemon-token writes one
+// atomic unit: a concurrent runtime re-registration that would change owner_id
+// blocks until the gate commits, so the owner the gate authorized against is
+// the owner the tokens were minted for — no stale-snapshot delivery window.
+// The closure receives the in-transaction token params so it can normalize
+// identity fields from the locked rows before the token is inserted. It
+// returns a *ClaimDeliveryAuthzError to reject delivery (every other error
+// rolls the claim back like any other finalize failure).
func (s *TaskService) FinalizeTaskClaim(
ctx context.Context,
task db.AgentTaskQueue,
token db.CreateTaskTokenParams,
deliveredCommentIDs []pgtype.UUID,
recordCommentReceipt bool,
+ authorize func(qtx *db.Queries, token *db.CreateTaskTokenParams) error,
issueSnapshot []byte,
daemonTokens ...db.CreateDaemonTokenParams,
) ([]pgtype.UUID, error) {
@@ -3763,6 +3788,11 @@ func (s *TaskService) FinalizeTaskClaim(
}
receipt := task.DeliveredCommentIds
err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ if authorize != nil {
+ if err := authorize(qtx, &token); err != nil {
+ return fmt.Errorf("authorize claim delivery: %w", err)
+ }
+ }
if _, err := qtx.CreateTaskToken(ctx, token); err != nil {
return fmt.Errorf("create task token: %w", err)
}
diff --git a/server/internal/service/task_finalize_failure_test.go b/server/internal/service/task_finalize_failure_test.go
index 36620ad1c7..f625ebedf8 100644
--- a/server/internal/service/task_finalize_failure_test.go
+++ b/server/internal/service/task_finalize_failure_test.go
@@ -43,7 +43,7 @@ func TestFinalizeTaskClaimFailureRollsBackTokenThenRequeue(t *testing.T) {
WorkspaceID: util.MustParseUUID(workspaceID),
UserID: util.MustParseUUID(userID),
ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},
- }, []pgtype.UUID{bogus}, true, nil)
+ }, []pgtype.UUID{bogus}, true, nil, nil)
if ferr == nil {
t.Fatal("expected FinalizeTaskClaim to fail for an out-of-plan delivery receipt")
}
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index f0a7cacad7..8b31e59e25 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -1544,21 +1544,13 @@ WHERE id = (
WHERE a.id = atq.agent_id
-- A task's persisted runtime is not authority after an agent rebind.
AND a.runtime_id = atq.runtime_id
- -- Private runtimes only execute their owner's agents. Ownerless
- -- runtime/agent rows remain claimable only so the handler can
- -- settle them explicitly before daemon delivery; filtering them
- -- here would leave every task silently queued until the TTL.
- -- Public runtimes remain shareable across agent owners.
+ -- Queued private-runtime rows are claimable so the handler can
+ -- settle an owner mismatch through the existing FailTask path
+ -- before daemon delivery. Public runtimes remain shareable across
+ -- agent owners; dispatched reclaim keeps its owner fence below.
AND (
r.visibility = 'public'
- OR (
- r.visibility = 'private'
- AND (
- r.owner_id IS NULL
- OR a.owner_id IS NULL
- OR r.owner_id = a.owner_id
- )
- )
+ OR r.visibility = 'private'
)
AND r.status = 'online'
AND COALESCE(r.last_seen_at, r.updated_at) >=
@@ -6009,14 +6001,7 @@ WHERE atq.runtime_id = $1
AND a.runtime_id = atq.runtime_id
AND (
r.visibility = 'public'
- OR (
- r.visibility = 'private'
- AND (
- r.owner_id IS NULL
- OR a.owner_id IS NULL
- OR r.owner_id = a.owner_id
- )
- )
+ OR r.visibility = 'private'
)
)
ORDER BY atq.priority DESC, atq.created_at ASC
@@ -6123,14 +6108,7 @@ WHERE atq.runtime_id = ANY($1::uuid[])
AND a.runtime_id = atq.runtime_id
AND (
r.visibility = 'public'
- OR (
- r.visibility = 'private'
- AND (
- r.owner_id IS NULL
- OR a.owner_id IS NULL
- OR r.owner_id = a.owner_id
- )
- )
+ OR r.visibility = 'private'
)
)
ORDER BY atq.priority DESC, atq.created_at ASC
@@ -7651,7 +7629,8 @@ WHERE id = (
AND atq.dispatched_at < now() - make_interval(secs => $3::double precision)
AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())
AND EXISTS (
- -- Keep this authorization fence in sync with ClaimAgentTask.
+ -- Keep the dispatched-reclaim owner fence intentionally stricter
+ -- than the queued claim carve-out below.
SELECT 1
FROM agent a
JOIN agent_runtime r ON r.id = atq.runtime_id
@@ -7775,7 +7754,8 @@ WHERE id IN (
AND atq.dispatched_at < now() - make_interval(secs => $3::double precision)
AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())
AND EXISTS (
- -- Keep this authorization fence in sync with ClaimAgentTask.
+ -- Keep the dispatched-reclaim owner fence intentionally stricter
+ -- than the queued claim carve-out below.
SELECT 1
FROM agent a
JOIN agent_runtime r ON r.id = atq.runtime_id
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 953dc368b6..440426fd7e 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -766,21 +766,13 @@ WHERE id = (
WHERE a.id = atq.agent_id
-- A task's persisted runtime is not authority after an agent rebind.
AND a.runtime_id = atq.runtime_id
- -- Private runtimes only execute their owner's agents. Ownerless
- -- runtime/agent rows remain claimable only so the handler can
- -- settle them explicitly before daemon delivery; filtering them
- -- here would leave every task silently queued until the TTL.
- -- Public runtimes remain shareable across agent owners.
+ -- Queued private-runtime rows are claimable so the handler can
+ -- settle an owner mismatch through the existing FailTask path
+ -- before daemon delivery. Public runtimes remain shareable across
+ -- agent owners; dispatched reclaim keeps its owner fence below.
AND (
r.visibility = 'public'
- OR (
- r.visibility = 'private'
- AND (
- r.owner_id IS NULL
- OR a.owner_id IS NULL
- OR r.owner_id = a.owner_id
- )
- )
+ OR r.visibility = 'private'
)
AND r.status = 'online'
AND COALESCE(r.last_seen_at, r.updated_at) >=
@@ -885,7 +877,8 @@ WHERE id = (
AND atq.dispatched_at < now() - make_interval(secs => @claim_recovery_secs::double precision)
AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())
AND EXISTS (
- -- Keep this authorization fence in sync with ClaimAgentTask.
+ -- Keep the dispatched-reclaim owner fence intentionally stricter
+ -- than the queued claim carve-out below.
SELECT 1
FROM agent a
JOIN agent_runtime r ON r.id = atq.runtime_id
@@ -931,7 +924,8 @@ WHERE id IN (
AND atq.dispatched_at < now() - make_interval(secs => @claim_recovery_secs::double precision)
AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())
AND EXISTS (
- -- Keep this authorization fence in sync with ClaimAgentTask.
+ -- Keep the dispatched-reclaim owner fence intentionally stricter
+ -- than the queued claim carve-out below.
SELECT 1
FROM agent a
JOIN agent_runtime r ON r.id = atq.runtime_id
@@ -2293,14 +2287,7 @@ WHERE atq.runtime_id = $1
AND a.runtime_id = atq.runtime_id
AND (
r.visibility = 'public'
- OR (
- r.visibility = 'private'
- AND (
- r.owner_id IS NULL
- OR a.owner_id IS NULL
- OR r.owner_id = a.owner_id
- )
- )
+ OR r.visibility = 'private'
)
)
ORDER BY atq.priority DESC, atq.created_at ASC;
@@ -2420,14 +2407,7 @@ WHERE atq.runtime_id = ANY(@runtime_ids::uuid[])
AND a.runtime_id = atq.runtime_id
AND (
r.visibility = 'public'
- OR (
- r.visibility = 'private'
- AND (
- r.owner_id IS NULL
- OR a.owner_id IS NULL
- OR r.owner_id = a.owner_id
- )
- )
+ OR r.visibility = 'private'
)
)
ORDER BY atq.priority DESC, atq.created_at ASC;
diff --git a/server/pkg/taskfailure/failure.go b/server/pkg/taskfailure/failure.go
index 56d59a8e0d..4e50a0937d 100644
--- a/server/pkg/taskfailure/failure.go
+++ b/server/pkg/taskfailure/failure.go
@@ -27,7 +27,7 @@
// runtime_recovery, timeout, iteration_limit, agent_blocked,
// api_invalid_request, skill_bundle_unavailable,
// runtime_cli_timeout, environment_prepare_failed,
-// invalid_task_identity
+// invalid_task_identity, runtime_access_denied
//
// - 14 agent-side values (with `agent_error.` prefix) produced by
// Classify(rawError) when the agent process surfaced an error string.
@@ -176,6 +176,22 @@ const (
// only repeat an isolation failure.
ReasonInvalidTaskIdentity Reason = "invalid_task_identity"
+ // ReasonRuntimeAccessDenied: the daemon refused a claimed task because
+ // a private runtime does not authorize the task's agent — the runtime
+ // owner and the agent owner differ, a private owned runtime was paired
+ // with an ownerless agent, or the runtime owner needed for
+ // authorization was missing at the delivery gate. The agent process is
+ // never launched. Unlike ReasonInvalidTaskIdentity the task's persisted
+ // identity is intact; what fails is ownership authorization. Permanent
+ // and non-retryable: retrying the same runtime/agent pair reproduces
+ // the denial, so recovery is user configuration (make the runtime
+ // public, or rebind the agent to a runtime its owner may use), not
+ // another attempt. Written by the daemon claim settlement paths in
+ // handler/daemon.go. Shares the runtime_access_denied wire value with
+ // dispatch.ReasonRuntimeAccessDenied so admission blocks and persisted
+ // settlement failures surface the same recovery guidance.
+ ReasonRuntimeAccessDenied Reason = "runtime_access_denied"
+
// Agent process side: failure surfaced by the agent CLI / SDK as
// an error string. Classify(rawError) is responsible for picking
// the right sub-reason from the string. IsAgentError returns true
@@ -251,7 +267,7 @@ const (
ReasonAgentUnknown Reason = "agent_error.unknown"
)
-// allReasons is the canonical ordered list of the 26 reasons. Order is
+// allReasons is the canonical ordered list of the 27 reasons. Order is
// stable so callers (e.g. Prometheus collectors that pre-warm series via
// AllReasons) can build deterministic label sets across restarts.
//
@@ -274,6 +290,7 @@ var allReasons = []Reason{
ReasonRuntimeCLITimeout,
ReasonEnvironmentPrepareFailed,
ReasonInvalidTaskIdentity,
+ ReasonRuntimeAccessDenied,
// Agent process side: provider errors.
ReasonAgentProviderAuthOrAccess,