Skip to content
Prev Previous commit
Next Next commit
fix(team): preserve restricted coordination and settle panicked turns
  • Loading branch information
SivanCola committed Nov 3, 2026
commit 166262cf405143ec908e262937281648aca5499f
12 changes: 10 additions & 2 deletions internal/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -1685,7 +1685,7 @@ func (a *Agent) readOnlyExecutionBlock(ctx context.Context, visible tool.Tool, r
if readOnlyExecutionMCPDestructive(visible) {
return block("execute a destructive MCP capability")
}
if h, ok := visible.(tool.ReadOnlyExecutionHostMutation); ok && h.ReadOnlyExecutionHostMutation() && !readOnlyExecutionAllowsMCPStartup(visible) {
if h, ok := visible.(tool.ReadOnlyExecutionHostMutation); ok && h.ReadOnlyExecutionHostMutation() && !readOnlyExecutionAllowsMCPStartup(visible) && !a.readOnlyCeilingAllowsTeamCoordination(ctx, visible) {
return block("start or mutate a host capability")
}
return toolOutcome{}, false
Expand Down Expand Up @@ -1737,7 +1737,7 @@ func (a *Agent) readOnlyExecutionBlock(ctx context.Context, visible tool.Tool, r
if readOnlyExecutionMCPDestructive(resolved.Target) {
return block("execute a destructive MCP capability")
}
if h, ok := resolved.Target.(tool.ReadOnlyExecutionHostMutation); ok && h.ReadOnlyExecutionHostMutation() && !readOnlyExecutionAllowsMCPStartup(resolved.Target) {
if h, ok := resolved.Target.(tool.ReadOnlyExecutionHostMutation); ok && h.ReadOnlyExecutionHostMutation() && !readOnlyExecutionAllowsMCPStartup(resolved.Target) && !a.readOnlyCeilingAllowsTeamCoordination(ctx, resolved.Target) {
return block("start or mutate a host capability")
}
return toolOutcome{}, false
Expand All @@ -1746,6 +1746,14 @@ func (a *Agent) readOnlyExecutionBlock(ctx context.Context, visible tool.Tool, r
}
}

func (a *Agent) readOnlyCeilingAllowsTeamCoordination(ctx context.Context, t tool.Tool) bool {
if a.readOnlyExecution || SubagentDepth(ctx) > 0 || tool.ExecutionCeiling(ctx) != "read-only" || !t.ReadOnly() {
return false
}
coordination, ok := t.(tool.ReadOnlyTeamCoordination)
return ok && coordination.ReadOnlyTeamCoordination()
}

func readOnlyExecutionMCPDestructive(t tool.Tool) bool {
return mcpDestructiveHint(t)
}
Expand Down
90 changes: 90 additions & 0 deletions internal/agent/team_coordination_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package agent

import (
"context"
"testing"

"deepzora/internal/event"
"deepzora/internal/provider"
"deepzora/internal/tool"
"deepzora/internal/tool/builtin"
)

type ceilingTeamDirectory struct {
tool.TeamDirectory
calls int
ceiling string
}

func (d *ceilingTeamDirectory) record(ctx context.Context) {
d.calls++
d.ceiling = tool.ExecutionCeiling(ctx)
}
func (d *ceilingTeamDirectory) MessageAgent(ctx context.Context, _ tool.TeamMessage) (tool.TeamReceipt, error) {
d.record(ctx)
return tool.TeamReceipt{Exchange: "reply", ToName: "Ben"}, nil
}
func (d *ceilingTeamDirectory) PassTurn(ctx context.Context) error { d.record(ctx); return nil }
func (d *ceilingTeamDirectory) HandTurn(ctx context.Context, _ []string) error {
d.record(ctx)
return nil
}
func (d *ceilingTeamDirectory) PostToGroup(ctx context.Context, _, _ string, _ []string) error {
d.record(ctx)
return nil
}

func TestReadOnlyTeamCeilingAllowsOnlyTopLevelCoordination(t *testing.T) {
for _, tc := range []struct {
name, args string
allowed bool
}{
{"message_agent", `{"to":"ben","message":"read this"}`, true},
{"pass_turn", `{}`, true},
{"hand_turn", `{"to":["ben"]}`, true},
{"post_to_group", `{"group":"launch","message":"read this"}`, true},
{"create_agent", `{"name":"new"}`, false},
{"update_agent", `{"agent":"ben","instructions":"change"}`, false},
{"stop_agent", `{"agent":"ben"}`, false},
} {
for _, proxy := range []bool{false, true} {
for _, identity := range []string{"member", "child", "strict-reader"} {
t.Run(tc.name+"/"+identity+map[bool]string{false: "/direct", true: "/proxy"}[proxy], func(t *testing.T) {
d := &ceilingTeamDirectory{}
link := &tool.TeamLink{}
link.Bind(d)
reg := tool.NewRegistry()
var target tool.Tool
for _, v := range builtin.TeamTools(link) {
reg.Add(v)
if v.Name() == tc.name {
target = v
}
}
if target == nil {
t.Fatal("tool missing")
}
call := provider.ToolCall{ID: "coordination", Name: tc.name, Arguments: tc.args}
if proxy {
reg.Add(readOnlyBoundaryProxy{resolved: tool.ResolvedCall{ProxyAction: "call", Target: target, TargetName: tc.name, Args: []byte(tc.args), ReadOnly: target.ReadOnly()}})
call.Name = "use_capability"
}
a := New(nil, reg, NewSession("sys"), Options{ReadOnlyExecution: identity == "strict-reader"}, event.Discard)
ctx := tool.WithExecutionCeiling(t.Context(), "read-only")
if identity == "child" {
ctx = WithSubagentDepth(ctx, 1)
}
out := a.executeOne(ctx, &a.turn, call)
allowed := identity == "member" && tc.allowed
if allowed {
if out.blocked || d.calls != 1 || d.ceiling != "read-only" {
t.Fatalf("coordination blocked or widened: %+v calls=%d ceiling=%s", out, d.calls, d.ceiling)
}
} else if !out.blocked || d.calls != 0 {
t.Fatalf("restricted tool executed: %+v calls=%d", out, d.calls)
}
})
}
}
}
}
92 changes: 92 additions & 0 deletions internal/control/team_panic_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package control

import (
"context"
"testing"
"time"

"deepzora/internal/event"
"deepzora/internal/sessioninbox"
"deepzora/internal/team"
"deepzora/internal/teamroster"
)

func TestTeamPanicSettlesMessageReplyAndGroupTurn(t *testing.T) {
for _, kind := range []team.DeliveryKind{team.DeliverMessage, team.DeliverReply, team.DeliverGroupTurn} {
t.Run(string(kind), func(t *testing.T) {
c, svc, store, chief, ada := teamControllerFixture(t, &fakeTurnRunner{}, nil)
x, _, err := store.OpenExchange(t.Context(), teamroster.Exchange{From: chief, To: ada, ReplyTo: teamroster.ReplyToUser}, "read")
if err != nil {
t.Fatal(err)
}
extra := map[string]string{team.ExtraKind: string(kind), team.ExtraExchange: x.ID, team.ExtraCeiling: "read-only"}
childID, groupID := "", ""
if kind == team.DeliverReply {
child, _, err := store.OpenExchange(t.Context(), teamroster.Exchange{From: ada, To: chief, Parent: x.ID, ReplyTo: teamroster.ReplyToSender}, "child")
if err != nil {
t.Fatal(err)
}
if _, err := store.SetExchangeState(t.Context(), child.ID, teamroster.ExchangeReplied, time.Now()); err != nil {
t.Fatal(err)
}
childID = child.ID
extra[team.ExtraExchange], extra[team.ExtraServing] = child.ID, x.ID
}
if kind == team.DeliverGroupTurn {
_, err := store.Update(t.Context(), func(r *teamroster.Roster) error {
groupID = r.AddGroup(teamroster.Group{Name: "discussion", Mode: teamroster.ModeEveryone, Members: []string{chief, ada}, CreatedBy: teamroster.ByUser}).ID
return nil
})
if err != nil {
t.Fatal(err)
}
c.team.mu.Lock()
c.team.seat = team.Seat{Service: svc, Ref: team.SeatRef{Agent: ada, Group: groupID}}
c.team.mu.Unlock()
if err := store.SaveRound(t.Context(), groupID, teamroster.RoundState{Round: 1, Step: 1, Speaking: &teamroster.Speaking{Slot: teamroster.Slot{Member: ada, Cause: teamroster.CauseUser}, Key: "step-1"}}); err != nil {
t.Fatal(err)
}
extra[team.ExtraStep] = "step-1"
}
started := make(chan struct{})
c.runGuarded(func(ctx context.Context) error {
return c.runTeamInbox(ctx, sessioninbox.PromptEnvelope{Extra: extra}, func(context.Context) error { close(started); panic("runner failure") })
})
select {
case <-started:
case <-time.After(10 * time.Second):
t.Fatal("not started")
}
waitIdle(t, c)
if c.RuntimeStateSnapshot().TurnStatus != event.TurnFailed {
t.Fatal("panic lost failed terminal outcome")
}
if c.effectiveApprovalMode() != ToolApprovalDangerFullAccess || c.currentTeamTurn().ceiling != "" {
t.Fatal("panic leaked turn permission or identity")
}
if kind == team.DeliverGroupTurn {
round, err := store.Round(groupID)
if err != nil || round.Speaking != nil {
t.Fatalf("group stuck: %+v %v", round, err)
}
lines, err := store.Lines(groupID, 0, 0)
if err != nil || len(lines) != 1 || lines[0].Event != teamroster.EventFailed {
t.Fatalf("group failure missing: %+v %v", lines, err)
}
} else {
book, err := store.Exchanges()
if err != nil {
t.Fatal(err)
}
for _, item := range book {
if item.ID == x.ID && item.State != teamroster.ExchangeFailed {
t.Fatalf("panic left parent pending: %+v", item)
}
if item.ID == childID && item.Returned {
t.Fatal("panic pretended to consume reply")
}
}
}
})
}
}
51 changes: 33 additions & 18 deletions internal/control/team_turn.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package control
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"time"
Expand Down Expand Up @@ -95,25 +96,39 @@ func (c *Controller) runTeamInbox(ctx context.Context, env sessioninbox.PromptEn
ctx = sandbox.WithPermissionPreset(ctx, mode)
}
previousID, _ := teamFinalAnswer(c.History())
err = run(ctx)
outcome := team.OutcomeCompleted
code := ""
if ctx.Err() != nil {
outcome, code = team.OutcomeCancelled, "turn.cancelled"
} else if err != nil {
outcome, code = team.OutcomeFailed, "turn.failed"
}
answer := ""
if err == nil {
if id, text := teamFinalAnswer(c.History()); id != previousID {
answer = text
// The outer Controller guard recovers runner panics. Settle the team work
// before that unwind clears its identity, while preserving the original
// panic for the guard's terminal event and diagnostics.
defer func() {
panicValue := recover()
if panicValue != nil {
err = fmt.Errorf("team turn panicked: %v", panicValue)
// A runner that panicked may not have consumed the reply at all.
t.consumed = nil
}
}
settled := svc.Settled(context.Background(), ref, team.Settlement{
Serving: t.serving, Consumed: t.consumed, Steps: t.steps,
Outcome: outcome, Code: code, FinalText: answer,
})
return errors.Join(err, settled)
outcome := team.OutcomeCompleted
code := ""
if ctx.Err() != nil {
outcome, code = team.OutcomeCancelled, "turn.cancelled"
} else if err != nil {
outcome, code = team.OutcomeFailed, "turn.failed"
}
answer := ""
if err == nil {
if id, text := teamFinalAnswer(c.History()); id != previousID {
answer = text
}
}
settled := svc.Settled(context.Background(), ref, team.Settlement{
Serving: t.serving, Consumed: t.consumed, Steps: t.steps,
Outcome: outcome, Code: code, FinalText: answer,
})
err = errors.Join(err, settled)
if panicValue != nil {
panic(panicValue)
}
}()
return run(ctx)
}

func teamFinalAnswer(messages []provider.Message) (string, string) {
Expand Down
8 changes: 8 additions & 0 deletions internal/tool/builtin/team.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ func (t *teamTool) ReadOnlyExecutionHostMutation() bool {
return t.name != "list_agents" && t.name != "read_group"
}

func (t *teamTool) ReadOnlyTeamCoordination() bool {
switch t.name {
case "message_agent", "post_to_group", "pass_turn", "hand_turn":
return true
}
return false
}

func (t *teamTool) Execute(ctx context.Context, args json.RawMessage) (string, error) {
dir, ok := t.link.Directory()
if !ok {
Expand Down
7 changes: 7 additions & 0 deletions internal/tool/team.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ type TeamDirectory interface {
ReadGroup(ctx context.Context, group string, before int64, limit int) (string, error)
}

// ReadOnlyTeamCoordination identifies coordination that preserves the current
// execution ceiling. It is available to a bound, top-level team member, never
// to a task child borrowing that member's identity.
type ReadOnlyTeamCoordination interface {
ReadOnlyTeamCoordination() bool
}

// TeamLink joins the team tools, built with the registry, to the controller
// that exists only afterwards.
type TeamLink struct {
Expand Down