Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(runtimes): delete Agent Builder carriers with their custom runtime profile (MUL-8443) (#9797)
Bohan Jiang2fa08f70f3d3
diff --git a/server/internal/handler/agent_builder.go b/server/internal/handler/agent_builder.goindex 23ec934197..3b0ed868a8 100644--- a/server/internal/handler/agent_builder.go+++ b/server/internal/handler/agent_builder.go@@ -16,6 +16,10 @@ import ("github.com/multica-ai/multica/server/pkg/dbid")+// agentBuilderSystemKeyPrefix marks the hidden execution carrier behind an+// AI agent-creation flow. The suffix is the flow id.+const agentBuilderSystemKeyPrefix = "agent_builder:"+const agentBuilderInstructions = `You are Multica Agent Builder. Help the user design one practical AI agent through a short conversation.Your job is to propose and refine configuration, never to create resources yourself. Ask only questions that materially change behavior. Prefer making a reasonable draft immediately, then ask at most two focused questions per turn.diff --git a/server/internal/handler/runtime_blocking_agents.go b/server/internal/handler/runtime_blocking_agents.goindex cf8db3f2df..0f3da5ed13 100644--- a/server/internal/handler/runtime_blocking_agents.go+++ b/server/internal/handler/runtime_blocking_agents.go@@ -9,21 +9,21 @@ import (db "github.com/multica-ai/multica/server/pkg/db/generated")-// agentBuilderSystemKeyPrefix marks the hidden execution carrier behind an-// unfinished AI agent-creation flow. The suffix is the flow id.-const agentBuilderSystemKeyPrefix = "agent_builder:"--// A runtime or profile delete is refused while agents are still bound. Telling-// the user to "reassign or archive them" is only true for agents they can-// actually reach: the archive endpoint rejects anything carrying a system_key-// outright, and a builder carrier is not in the agent list at all. Naming one-// remedy for every blocker therefore hands some users an instruction that-// cannot be carried out — the same class of defect this whole change set exists-// to remove, so the refusals classify their blockers instead.+// A runtime or profile delete is refused while user agents are still bound.+// Telling the user to "reassign or archive them" is only true for agents they+// can actually reach: the archive endpoint rejects anything carrying a+// system_key outright. Naming one remedy for every blocker therefore hands some+// users an instruction that cannot be carried out — the same class of defect+// this whole change set exists to remove, so the refusals classify their+// blockers instead.+//+// Hidden kind='system' agents (the Agent Builder carriers) are never blockers:+// both delete guards list kind='user' only, and TeardownRuntime deletes the+// carriers with their runtime (GH #9762).//// system_key, not kind, is the discriminator. Mika is deliberately kind='user'// (it must stay visible and assignable) while still being product-owned and-// unarchivable; builder carriers are kind='system'.+// unarchivable.type blockingAgentClass intconst (@@ -34,9 +34,6 @@ const (// takes runtime_id for it like any other manageable agent. Those two halves// have to be stated separately or the remedy is wrong in one direction.blockingAgentMika- // blockingAgentBuilderCarrier is the hidden carrier behind an unfinished- // Agent Builder flow. It is released through that session, not the agent list.- blockingAgentBuilderCarrier// blockingAgentOtherSystem is any future product-owned agent. Unarchivable// like the rest, with no remedy this code can name specifically.blockingAgentOtherSystem@@ -50,7 +47,6 @@ const (const (blockingAgentClassKeyUser = "user"blockingAgentClassKeyMika = "mika"- blockingAgentClassKeyBuilder = "agent_builder"blockingAgentClassKeyOtherSystem = "other_system")@@ -65,8 +61,6 @@ func blockingAgentClassFromKey(key string) blockingAgentClass {return blockingAgentUsercase blockingAgentClassKeyMika:return blockingAgentMika- case blockingAgentClassKeyBuilder:- return blockingAgentBuilderCarrierdefault:return blockingAgentOtherSystem}@@ -77,14 +71,10 @@ func classifyBlockingAgent(systemKey pgtype.Text) blockingAgentClass {if !systemKey.Valid || key == "" {return blockingAgentUser}- switch {- case key == service.MikaSystemKey:+ if key == service.MikaSystemKey {return blockingAgentMika- case strings.HasPrefix(key, agentBuilderSystemKeyPrefix):- return blockingAgentBuilderCarrier- default:- return blockingAgentOtherSystem}+ return blockingAgentOtherSystem}// blockingAgentLabel renders one blocker for a refusal sentence. Product-owned@@ -92,8 +82,6 @@ func classifyBlockingAgent(systemKey pgtype.Text) blockingAgentClass {// does not apply to them.func blockingAgentLabel(name, runtimeName, runtimeStatus string, class blockingAgentClass) string {switch class {- case blockingAgentBuilderCarrier:- return fmt.Sprintf("an unfinished Agent Builder session on %q (%s)", runtimeName, runtimeStatus)case blockingAgentMika, blockingAgentOtherSystem:return fmt.Sprintf("%q on %q (%s, built into Multica)", name, runtimeName, runtimeStatus)default:@@ -121,7 +109,6 @@ func blockingAgentRemedies(classes map[blockingAgentClass]bool, scope blockingAg// blockers listed beside them, which is exactly the instruction they cannot// follow. When both are present the clause names which ones it applies to.mixed := classes[blockingAgentMika] ||- classes[blockingAgentBuilderCarrier] ||classes[blockingAgentOtherSystem]var out []string@@ -130,15 +117,6 @@ func blockingAgentRemedies(classes map[blockingAgentClass]bool, scope blockingAg} else if classes[blockingAgentUser] {out = append(out, "Reassign or archive them first.")}- if classes[blockingAgentBuilderCarrier] {- // Addressed to the creator, not to whoever hit this error. Builder- // sessions are creator-scoped: ListAgentBuilderSessions returns 200 but- // omits other members' sessions, and switch/discard go through- // loadChatSessionForUser and return 403. So an admin who is not the- // creator cannot even see the session to act on it, and telling them to- // reopen it would be another instruction that cannot be carried out.- out = append(out, "The unfinished Agent Builder session(s) here are hidden from the agent list, and only their creator can open them — ask the member who started the session to switch its runtime or discard it; another admin cannot do that for them.")- }if classes[blockingAgentMika] {// Mika is unarchivable but NOT immovable: UpdateAgent takes runtime_id// for it like any other agent an admin can manage (the only system_keydiff --git a/server/internal/handler/runtime_delete_guidance_test.go b/server/internal/handler/runtime_delete_guidance_test.goindex 2a5e57ef88..0b8b662250 100644--- a/server/internal/handler/runtime_delete_guidance_test.go+++ b/server/internal/handler/runtime_delete_guidance_test.go@@ -385,38 +385,10 @@ func TestDeleteRuntimeProfile_MikaBlockerGetsItsOwnRemedy(t *testing.T) {}}-// A builder carrier is hidden from the agent list entirely, so neither-// "reassign" nor "archive" is reachable. The way out is its Builder session.-func TestDeleteRuntimeProfile_BuilderCarrierBlockerPointsAtItsSession(t *testing.T) {- if testHandler == nil {- t.Skip("database not available")- }- ctx := context.Background()-- profileID := insertRuntimeProfileFixture(t, ctx, "Builder Held Profile", "codex", "builder-held")- runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "BUILDER-HOST", "codex")- createSystemFixtureAgent(t, ctx, runtimeID,- ".multica-agent-builder-flow1", "system", "agent_builder:flow1")-- body := deleteProfileExpectingConflict(t, ctx, profileID)- msg := conflictMessage(t, body)-- if strings.Contains(msg, "can be reassigned or archived") || strings.Contains(msg, "Reassign or archive them first.") {- t.Fatalf("a builder carrier is not in the agent list; refusal must not say so: %s", msg)- }- if !strings.Contains(msg, "Agent Builder session") {- t.Fatalf("refusal must point at the Builder session, got: %s", msg)- }-- agents, _ := body["active_agents"].([]any)- entry, _ := agents[0].(map[string]any)- if got, _ := entry["system_key"].(string); got != "agent_builder:flow1" {- t.Fatalf("system_key = %q", got)- }-}--// With both kinds present each needs its own clause: the user agent is-// actionable, the carrier is not, and collapsing them loses one or the other.+// With both an ordinary agent and Mika present each needs its own clause: the+// user agent is archivable, Mika is not, and collapsing them loses one or the+// other. A hidden builder carrier on the same runtime is not a blocker at all+// (GH #9762), so it must not be counted, named, or given a remedy.func TestDeleteRuntimeProfile_MixedBlockersGiveEachItsOwnRemedy(t *testing.T) {if testHandler == nil {t.Skip("database not available")@@ -435,15 +407,24 @@ func TestDeleteRuntimeProfile_MixedBlockersGiveEachItsOwnRemedy(t *testing.T) {for _, want := range []string{"not marked as built into Multica can be reassigned or archived",- "Agent Builder session","Mika is built into Multica, so it cannot be archived",} {if !strings.Contains(msg, want) {t.Fatalf("mixed refusal missing %q, got: %s", want, msg)}}- if got, _ := body["active_agent_count"].(float64); int(got) != 3 {- t.Fatalf("active_agent_count = %v, want 3", got)+ if strings.Contains(msg, "Agent Builder") || strings.Contains(msg, "multica-agent-builder") {+ t.Fatalf("a builder carrier is not a blocker and must not appear in the refusal: %s", msg)+ }+ if got, _ := body["active_agent_count"].(float64); int(got) != 2 {+ t.Fatalf("active_agent_count = %v, want 2 (the carrier does not count)", got)+ }+ agents, _ := body["active_agents"].([]any)+ for _, a := range agents {+ entry, _ := a.(map[string]any)+ if kind, _ := entry["kind"].(string); kind != "user" {+ t.Fatalf("listed blocker %v has kind %q; only user agents block a profile delete", entry["name"], kind)+ }}}@@ -574,34 +555,16 @@ func TestDeleteRuntimeProfile_RemedyCoversBlockersBeyondTheSample(t *testing.T)}}-// Same boundary for a builder carrier: its remedy is a different surface-// entirely, so losing it past the cap strands the user just as badly.-func TestDeleteRuntimeProfile_BuilderCarrierBeyondTheSampleStillReported(t *testing.T) {- if testHandler == nil {- t.Skip("database not available")- }- ctx := context.Background()-- profileID := insertRuntimeProfileFixture(t, ctx, "Beyond Sample Builder", "codex", "beyond-builder")- runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "BEYOND-BUILD-HOST", "codex")- for i := 0; i < maxReportedBlockingAgents; i++ {- _ = createCascadeFixtureAgent(t, ctx, runtimeID, fmt.Sprintf("Agent %03d", i))- }- // "zzz-" sorts last, so the carrier lands past the cap.- createSystemFixtureAgent(t, ctx, runtimeID,- "zzz-multica-agent-builder-flow9", "system", "agent_builder:flow9")-- msg := conflictMessage(t, deleteProfileExpectingConflict(t, ctx, profileID))- if !strings.Contains(msg, "Agent Builder session") {- t.Fatalf("builder carrier is blocker #21 and must still be reported, got: %s", msg)- }-}-// The class mapping exists twice — the SQL CASE in ListActiveAgentsByProfile,// because per-class counts have to cover rows the LIMIT excludes, and// classifyBlockingAgent in Go for the instance path, which reads plain agent// rows. This pins them to each other: if a future system_key is added to one// and not the other, the refusal would name a remedy for the wrong blocker.+//+// It also pins the kind filter both paths share: kind='system' rows — the+// hidden Agent Builder carriers, and anything else that is runtime-local+// infrastructure — never appear, because TeardownRuntime deletes them with the+// runtime instead of leaving them to block it (GH #9762).func TestBlockingAgentClassMatchesSQLClassification(t *testing.T) {if testHandler == nil {t.Skip("database not available")@@ -613,14 +576,10 @@ func TestBlockingAgentClassMatchesSQLClassification(t *testing.T) {_ = createCascadeFixtureAgent(t, ctx, runtimeID, "Pin Ordinary")createSystemFixtureAgent(t, ctx, runtimeID, "Pin Mika", "user", "mika")+ createSystemFixtureAgent(t, ctx, runtimeID, "Pin Future", "user", "some_future_facility")+ // Excluded by kind, whatever their system_key says.createSystemFixtureAgent(t, ctx, runtimeID, "Pin Builder", "system", "agent_builder:pinflow")- createSystemFixtureAgent(t, ctx, runtimeID, "Pin Future", "system", "some_future_facility")- // Near misses for the builder prefix. '_' is a single-character wildcard in- // SQL LIKE, so a LIKE-based CASE classifies both of these as carriers while- // Go's HasPrefix does not — and the refusal would then send the user to an- // Agent Builder session that does not exist.- createSystemFixtureAgent(t, ctx, runtimeID, "Pin Dash", "system", "agent-builder:not-a-carrier")- createSystemFixtureAgent(t, ctx, runtimeID, "Pin Wildcard", "system", "agentXbuilder:not-a-carrier")+ createSystemFixtureAgent(t, ctx, runtimeID, "Pin System Future", "system", "some_system_facility")rows, err := testHandler.Queries.ListActiveAgentsByProfile(ctx, db.ListActiveAgentsByProfileParams{ProfileID: parseUUID(profileID),@@ -630,11 +589,14 @@ func TestBlockingAgentClassMatchesSQLClassification(t *testing.T) {if err != nil {t.Fatalf("list blockers: %v", err)}- if len(rows) != 6 {- t.Fatalf("expected 6 blockers, got %d", len(rows))+ if len(rows) != 3 {+ t.Fatalf("expected 3 blockers (kind='system' rows excluded), got %d", len(rows))}for _, row := range rows {+ if row.Kind != "user" {+ t.Fatalf("%q has kind %q; only user agents block a profile delete", row.Name, row.Kind)+ }fromSQL := blockingAgentClassFromKey(row.BlockerClass)fromGo := classifyBlockingAgent(row.SystemKey)if fromSQL != fromGo {@@ -645,6 +607,9 @@ func TestBlockingAgentClassMatchesSQLClassification(t *testing.T) {// And the per-class counts have to agree with the rows they summarise.summary := rows[0]+ if summary.TotalCount != int64(len(rows)) {+ t.Fatalf("total_count = %d, rows = %d", summary.TotalCount, len(rows))+ }for _, tc := range []struct {name stringgot int64@@ -652,7 +617,6 @@ func TestBlockingAgentClassMatchesSQLClassification(t *testing.T) {}{{"user", summary.UserCount, blockingAgentUser},{"mika", summary.MikaCount, blockingAgentMika},- {"agent_builder", summary.AgentBuilderCount, blockingAgentBuilderCarrier},{"other_system", summary.OtherSystemCount, blockingAgentOtherSystem},} {var want int64@@ -730,10 +694,13 @@ func TestDeleteAgentRuntime_OfflineInstanceWithUnfinishedTaskDoesNotPromiseClean}// Builder sessions are creator-scoped reads, so an admin who is not the-// creator gets 403 from list, switch and discard alike. Telling that admin to-// reopen the session is another instruction they cannot carry out.-// Regression contributed by review.-func TestDeleteRuntimeProfile_BuilderRemedyAddressesTheSessionCreator(t *testing.T) {+// creator cannot list, switch or discard another member's Builder. When that+// carrier blocked the profile delete, the admin was stuck with no action they+// could take (GH #9762). It no longer blocks: the delete goes through and takes+// the carrier, its session and its saved draft with it. Losing another member's+// half-finished draft is the accepted cost — its runtime is gone, so it could+// not run again anyway.+func TestDeleteRuntimeProfile_OtherMembersBuilderDraftDoesNotBlock(t *testing.T) {if testHandler == nil {t.Skip("database not available")}@@ -754,29 +721,156 @@ func TestDeleteRuntimeProfile_BuilderRemedyAddressesTheSessionCreator(t *testingdbfx.Exec(t, `INSERT INTO agent_builder_draft (chat_session_id, workspace_id, draft) VALUES ($1, $2, '{"name":"Saved draft"}'::jsonb)`, session.SessionID, testWorkspaceID)t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM agent_builder_draft WHERE chat_session_id=$1`, session.SessionID)+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id=$1`, session.BuilderAgentID)})- msg := conflictMessage(t, deleteProfileExpectingConflict(t, ctx, profileID))- w = httptest.NewRecorder()- testHandler.ListAgentBuilderSessions(w, newRequest("GET", "/api/agent-builder/sessions", nil))- if w.Code != http.StatusOK {- t.Fatalf("list: %d %s", w.Code, w.Body.String())- }- if strings.Contains(w.Body.String(), session.SessionID) {- t.Fatal("other member's private session unexpectedly visible")- }++ // The admin really cannot reach it, which is why it must not block them.w = switchBuilderRuntime(t, session.SessionID, runtimeID)if w.Code != http.StatusForbidden {t.Fatalf("switch: %d %s", w.Code, w.Body.String())}- w = httptest.NewRecorder()- r := withURLParam(newRequest("DELETE", "/api/chat/sessions/"+session.SessionID, nil), "sessionId", session.SessionID)- testHandler.DeleteChatSession(w, withChatTestWorkspaceCtx(t, r))- if w.Code != http.StatusForbidden {- t.Fatalf("discard: %d %s", w.Code, w.Body.String())++ w = deleteProfile(t, profileID)+ if w.Code != http.StatusNoContent {+ t.Fatalf("expected 204, got %d: %s", w.Code, w.Body.String())}- if strings.Contains(msg, "reopen the session") && !strings.Contains(msg, "creator") && !strings.Contains(msg, "owner") {- t.Fatalf("admin cannot see, switch, or discard the member's Builder, but guidance tells the admin to reopen it: %s", msg)+ assertBuilderSessionGone(t, ctx, session)+ assertProfileGone(t, ctx, profileID, runtimeID)+}++// deleteProfile runs the profile delete as the fixture admin and returns the+// raw response.+func deleteProfile(t *testing.T, profileID string) *httptest.ResponseRecorder {+ t.Helper()+ w := httptest.NewRecorder()+ req := newRequest("DELETE", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles/"+profileID, nil)+ req = withURLParams(req, "id", testWorkspaceID, "profileId", profileID)+ h := *testHandler+ h.DaemonRuntimeGone = &recordingRuntimeGoneNotifier{}+ h.DeleteRuntimeProfile(w, req)+ return w+}++// assertBuilderSessionGone checks that a Builder's carrier and everything+// hanging off it without a foreign key were removed in the same delete.+func assertBuilderSessionGone(t *testing.T, ctx context.Context, session CreateAgentBuilderSessionResponse) {+ t.Helper()+ for _, c := range []struct {+ what, query, id string+ }{+ {"carrier agent", `SELECT count(*) FROM agent WHERE id = $1`, session.BuilderAgentID},+ {"chat session", `SELECT count(*) FROM chat_session WHERE id = $1`, session.SessionID},+ {"chat messages", `SELECT count(*) FROM chat_message WHERE chat_session_id = $1`, session.SessionID},+ {"builder draft", `SELECT count(*) FROM agent_builder_draft WHERE chat_session_id = $1`, session.SessionID},+ {"chat draft restores", `SELECT count(*) FROM chat_draft_restore WHERE chat_session_id = $1`, session.SessionID},+ {"carrier tasks", `SELECT count(*) FROM agent_task_queue WHERE agent_id = $1`, session.BuilderAgentID},+ } {+ var n int+ if err := testPool.QueryRow(ctx, c.query, c.id).Scan(&n); err != nil {+ t.Fatalf("count %s: %v", c.what, err)+ }+ if n != 0 {+ t.Fatalf("%s: %d row(s) left behind after the profile delete", c.what, n)+ }+ }+}++func assertProfileGone(t *testing.T, ctx context.Context, profileID, runtimeID string) {+ t.Helper()+ var profiles, runtimes int+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM runtime_profile WHERE id = $1`, profileID).Scan(&profiles); err != nil {+ t.Fatalf("count profile: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&runtimes); err != nil {+ t.Fatalf("count runtime: %v", err)+ }+ if profiles != 0 || runtimes != 0 {+ t.Fatalf("profile rows = %d, runtime rows = %d after a successful delete; want 0/0", profiles, runtimes)+ }+}++// GH #9762. The two ways a Builder carrier is left behind with no surface that+// can release it, neither of which may block the profile delete any more:+//+// - finished: the agent was created and the studio archived the session+// (archiveAfterCreate). The carrier stays active and the archived session+// drops out of the Builder list.+// - untouched: the flow was opened and left before any message or saved+// draft, so the Builder list never showed it.+//+// A queued Builder turn rides along on the finished one, so the delete also+// has to cancel and remove in-flight carrier work rather than refuse on it.+func TestDeleteRuntimeProfile_DeletesLeftoverBuilderCarriers(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ profileID := insertRuntimeProfileFixture(t, ctx, "Builder Leftover Profile", "codex", "builder-leftover")+ runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "BUILDER-LEFTOVER-HOST", "codex")++ newSession := func() CreateAgentBuilderSessionResponse {+ t.Helper()+ w := httptest.NewRecorder()+ testHandler.CreateAgentBuilderSession(w, newRequest(http.MethodPost, "/api/agent-builder/sessions", map[string]any{+ "runtime_id": runtimeID,+ }))+ if w.Code != http.StatusCreated {+ t.Fatalf("create builder: %d %s", w.Code, w.Body.String())+ }+ var s CreateAgentBuilderSessionResponse+ if err := json.Unmarshal(w.Body.Bytes(), &s); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_builder_draft WHERE chat_session_id=$1`, s.SessionID)+ testPool.Exec(context.Background(), `DELETE FROM chat_draft_restore WHERE chat_session_id=$1`, s.SessionID)+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id=$1`, s.BuilderAgentID)+ })+ return s+ }++ finished := newSession()+ insertChatMessage(t, finished.SessionID, "user", "make me a release agent")+ insertChatMessage(t, finished.SessionID, "assistant", "here is the draft")+ dbfx.Exec(t, `INSERT INTO agent_builder_draft (chat_session_id, workspace_id, draft) VALUES ($1, $2, '{"name":"Release"}'::jsonb)`, finished.SessionID, testWorkspaceID)+ dbfx.Task(t, finished.BuilderAgentID, testutil.Cols{+ "runtime_id": runtimeID, "chat_session_id": finished.SessionID, "status": "queued",+ })+ req := newRequest("PATCH", "/api/chat/sessions/"+finished.SessionID+"/archive", map[string]any{"archived": true})+ req = withChatTestWorkspaceCtx(t, withURLParam(req, "sessionId", finished.SessionID))+ w := httptest.NewRecorder()+ testHandler.SetChatSessionArchived(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("archive builder session: %d %s", w.Code, w.Body.String())+ }++ untouched := newSession()++ // Precondition: both are exactly the reported shape — an active carrier+ // whose session the creator cannot get back to.+ var activeCarriers int+ if err := testPool.QueryRow(ctx, `+ SELECT count(*) FROM agent WHERE id = ANY($1::uuid[]) AND archived_at IS NULL+ `, []string{finished.BuilderAgentID, untouched.BuilderAgentID}).Scan(&activeCarriers); err != nil {+ t.Fatal(err)+ }+ if activeCarriers != 2 {+ t.Fatalf("expected both carriers still active, got %d", activeCarriers)+ }+ for _, s := range listBuilderSessions(t).Sessions {+ if s.SessionID == finished.SessionID || s.SessionID == untouched.SessionID {+ t.Fatalf("session %s is listed; the regression needs it unreachable", s.SessionID)+ }+ }++ w = deleteProfile(t, profileID)+ if w.Code != http.StatusNoContent {+ t.Fatalf("expected 204, got %d: %s", w.Code, w.Body.String())}+ assertBuilderSessionGone(t, ctx, finished)+ assertBuilderSessionGone(t, ctx, untouched)+ assertProfileGone(t, ctx, profileID, runtimeID)}// Forces the archive path's task-cancellation transaction to fail, which isdiff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.goindex c2c6600ef7..ccce9f2ca4 100644--- a/server/internal/handler/runtime_profile.go+++ b/server/internal/handler/runtime_profile.go@@ -399,10 +399,9 @@ func profileDeleteBlockedByAgents(profileName string, agents []db.ListActiveAgentotal := summary.TotalCountclasses := map[blockingAgentClass]bool{- blockingAgentUser: summary.UserCount > 0,- blockingAgentMika: summary.MikaCount > 0,- blockingAgentBuilderCarrier: summary.AgentBuilderCount > 0,- blockingAgentOtherSystem: summary.OtherSystemCount > 0,+ blockingAgentUser: summary.UserCount > 0,+ blockingAgentMika: summary.MikaCount > 0,+ blockingAgentOtherSystem: summary.OtherSystemCount > 0,}named := make([]string, 0, maxNamedBlockingAgents)@@ -468,8 +467,10 @@ func profileDeleteBlockedByAgents(profileName string, agents []db.ListActiveAgen// DeleteRuntimeProfile removes a profile and, in the same transaction, the// agent_runtime instance rows registered against it. Migration 120 dropped the// DB ON DELETE CASCADE, so this app-layer cleanup is what prevents orphaned-// runtime rows. Refuses (409) while active agents are still bound to the-// profile's runtimes. Admin-gated by the router.+// runtime rows. Refuses (409) while active user agents are still bound to the+// profile's runtimes. Hidden Agent Builder carriers do not block: the teardown+// deletes them with their sessions, as the single-runtime delete already does+// (GH #9762). Admin-gated by the router.func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {wsID := strings.TrimSpace(chi.URLParam(r, "id"))member, ok := h.requireWorkspaceMember(w, r, wsID, "workspace not found")@@ -488,10 +489,11 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {// The profile-delete cascade must run the SAME teardown the runtime-delete// path uses for each one: agent.runtime_id is ON DELETE RESTRICT, so an// agent still pointing at one of these rows would turn a bare delete into a- // 500. Active agents are refused (409); everything else is unbound rather- // than destroyed, exactly as in service.TeardownRuntime.- // Guard: refuse while any active (non-archived) agent is bound to one of- // the profile's runtimes. Keep this a 409 — the profile is the thing that+ // 500. Active user agents are refused (409); archived user agents are+ // unbound rather than destroyed, and system agents (Builder carriers) are+ // deleted, exactly as in service.TeardownRuntime.+ // Guard: refuse while any active (non-archived) user agent is bound to one+ // of the profile's runtimes. Keep this a 409 — the profile is the thing that// defines those runtimes, so the user should retire the agents or move them// deliberately instead of having them silently unbound in bulk.tx, err := h.TxStarter.Begin(r.Context())diff --git a/server/pkg/db/generated/runtime_profile.sql.go b/server/pkg/db/generated/runtime_profile.sql.goindex d3a72d2e21..e5e12c1412 100644--- a/server/pkg/db/generated/runtime_profile.sql.go+++ b/server/pkg/db/generated/runtime_profile.sql.go@@ -211,17 +211,12 @@ WITH blockers AS (CASEWHEN a.system_key IS NULL OR btrim(a.system_key) = '' THEN 'user'WHEN btrim(a.system_key) = 'mika' THEN 'mika'- -- starts_with, not LIKE: '_' is a single-character wildcard in- -- LIKE, so 'agent_builder:%' also matches 'agent-builder:x' and- -- 'agentXbuilder:x'. Those would be classified here as carriers- -- and by the Go side as other_system, and the refusal would send- -- the user to an Agent Builder session that does not exist.- WHEN starts_with(btrim(a.system_key), 'agent_builder:') THEN 'agent_builder'ELSE 'other_system'END AS blocker_classFROM agent aJOIN agent_runtime ar ON ar.id = a.runtime_id- WHERE ar.profile_id = $1 AND ar.workspace_id = $2 AND a.archived_at IS NULL+ WHERE ar.profile_id = $1 AND ar.workspace_id = $2+ AND a.archived_at IS NULL AND a.kind = 'user')SELECTid,@@ -236,7 +231,6 @@ SELECTcount(*) OVER () AS total_count,count(*) FILTER (WHERE blocker_class = 'user') OVER () AS user_count,count(*) FILTER (WHERE blocker_class = 'mika') OVER () AS mika_count,- count(*) FILTER (WHERE blocker_class = 'agent_builder') OVER () AS agent_builder_count,count(*) FILTER (WHERE blocker_class = 'other_system') OVER () AS other_system_countFROM blockersORDER BY runtime_name ASC, name ASC@@ -262,7 +256,6 @@ type ListActiveAgentsByProfileRow struct {TotalCount int64 `json:"total_count"`UserCount int64 `json:"user_count"`MikaCount int64 `json:"mika_count"`- AgentBuilderCount int64 `json:"agent_builder_count"`OtherSystemCount int64 `json:"other_system_count"`}@@ -276,14 +269,18 @@ type ListActiveAgentsByProfileRow struct {// the user was trying to clean up, and a bare count gives them no way to tell// (GH #8456). Carrying the runtime is what lets the message say which machine.//-// Deliberately not filtered by kind: it defines when deletion is refused, and-// narrowing it to user agents here would let a profile with a bound builder-// carrier through, whereupon TeardownRuntime would hard-delete that carrier.+// User agents only (kind = 'user'), the same set ListActiveAgentsByRuntime+// guards the single-runtime delete with. System agents are the hidden Agent+// Builder carriers: runtime-local infrastructure that TeardownRuntime deletes+// together with their sessions, drafts and pending restores. Counting them here+// made a profile undeletable whenever an AI agent-creation flow had ever run on+// one of its runtimes, because a carrier outlives its session (archiving the+// session after the agent is created leaves the carrier active) and the session+// is then hidden from every surface that could release it (GH #9762).//// system_key rides along because it, not kind, decides what the user can// actually do about a blocker. Mika is kind='user' with system_key='mika' and-// can be neither archived nor moved; a builder carrier is kind='system' and is-// released by its Builder session, not from the agent list.+// can be moved but not archived.//// Bounded on purpose. The caller only needs to know that blockers exist, name a// few, and report how many there are — it never needs every row. This runs@@ -326,7 +323,6 @@ func (q *Queries) ListActiveAgentsByProfile(ctx context.Context, arg ListActiveA&i.TotalCount,&i.UserCount,&i.MikaCount,- &i.AgentBuilderCount,&i.OtherSystemCount,); err != nil {return nil, errdiff --git a/server/pkg/db/queries/runtime_profile.sql b/server/pkg/db/queries/runtime_profile.sqlindex e6a86e591b..0636bac425 100644--- a/server/pkg/db/queries/runtime_profile.sql+++ b/server/pkg/db/queries/runtime_profile.sql@@ -93,14 +93,18 @@ RETURNING id, workspace_id, owner_id, daemon_id, provider;-- the user was trying to clean up, and a bare count gives them no way to tell-- (GH #8456). Carrying the runtime is what lets the message say which machine.----- Deliberately not filtered by kind: it defines when deletion is refused, and--- narrowing it to user agents here would let a profile with a bound builder--- carrier through, whereupon TeardownRuntime would hard-delete that carrier.+-- User agents only (kind = 'user'), the same set ListActiveAgentsByRuntime+-- guards the single-runtime delete with. System agents are the hidden Agent+-- Builder carriers: runtime-local infrastructure that TeardownRuntime deletes+-- together with their sessions, drafts and pending restores. Counting them here+-- made a profile undeletable whenever an AI agent-creation flow had ever run on+-- one of its runtimes, because a carrier outlives its session (archiving the+-- session after the agent is created leaves the carrier active) and the session+-- is then hidden from every surface that could release it (GH #9762).---- system_key rides along because it, not kind, decides what the user can-- actually do about a blocker. Mika is kind='user' with system_key='mika' and--- can be neither archived nor moved; a builder carrier is kind='system' and is--- released by its Builder session, not from the agent list.+-- can be moved but not archived.---- Bounded on purpose. The caller only needs to know that blockers exist, name a-- few, and report how many there are — it never needs every row. This runs@@ -134,17 +138,12 @@ WITH blockers AS (CASEWHEN a.system_key IS NULL OR btrim(a.system_key) = '' THEN 'user'WHEN btrim(a.system_key) = 'mika' THEN 'mika'- -- starts_with, not LIKE: '_' is a single-character wildcard in- -- LIKE, so 'agent_builder:%' also matches 'agent-builder:x' and- -- 'agentXbuilder:x'. Those would be classified here as carriers- -- and by the Go side as other_system, and the refusal would send- -- the user to an Agent Builder session that does not exist.- WHEN starts_with(btrim(a.system_key), 'agent_builder:') THEN 'agent_builder'ELSE 'other_system'END AS blocker_classFROM agent aJOIN agent_runtime ar ON ar.id = a.runtime_id- WHERE ar.profile_id = $1 AND ar.workspace_id = $2 AND a.archived_at IS NULL+ WHERE ar.profile_id = $1 AND ar.workspace_id = $2+ AND a.archived_at IS NULL AND a.kind = 'user')SELECTid,@@ -159,7 +158,6 @@ SELECTcount(*) OVER () AS total_count,count(*) FILTER (WHERE blocker_class = 'user') OVER () AS user_count,count(*) FILTER (WHERE blocker_class = 'mika') OVER () AS mika_count,- count(*) FILTER (WHERE blocker_class = 'agent_builder') OVER () AS agent_builder_count,count(*) FILTER (WHERE blocker_class = 'other_system') OVER () AS other_system_countFROM blockersORDER BY runtime_name ASC, name ASC