Files
goclaw/internal/tools/team_task_origin_channel_test.go
yatulandClaude Opus 5 305bd7c50d fix(teams): grant a delegated lead read access to its own team (#1537)
* fix(teams): scope team tasks to the delegation origin, not the delivery channel

A delegated run is delivered on the internal "delegate" channel while its real
origin is preserved separately — buildAgentLinkRunRequest is explicit about it:

    // preserves the origin's authorization-bearing identity while keeping
    // delegation on its internal delivery channel.
    Channel:          "delegate",
    WorkspaceChannel: req.Channel,
    WorkspaceChatID:  req.ChatID,

The team tools did not consult that origin, so a task created by a lead reached
through delegate was stamped with the delivery channel. Nothing is registered
for it, so every notification about that task — completion, failure, blocker
escalation, ask_user — was dropped:

    unknown channel for outbound message channel=delegate

The delegatee's first answer still arrived, because it travels back as the
delegation result rather than through a channel; everything the lead said after
the delegation closed was lost. One session produced 16 such drops, including a
blocker escalation the user needed to see.

Add OriginChannelFromCtx / OriginChatIDFromCtx next to the existing workspace
scope propagation helpers, and use them where team scoping and notification
routing are decided: task records, list/search scoping, dispatch fallbacks,
event payloads, escalation tasks, ask_user and leader notifications. The
resolution is the identity when no delegation origin is present, so
non-delegated flows are unchanged.

Deliberately not touched: the channel used in authorization decisions
(checkTeamAccess, requireLead, approve/reject lead bypass). Those ask "how did
this call arrive", not "where should the answer go", and widening them is a
separate question.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(teams): cover delegated-lead completion routing and origin isolation

Triage on #1529 named two gates this PR had not met: regression coverage for
delegated lead task completion, and a guard that unrelated origins cannot
receive the notification. The existing tests only covered what create persists.

TestDelegatedLeadCompletionNotifiesOrigin completes a task raised in a delegated
context and asserts the completion event is addressed to the caller's origin.
Reverting team_event_helpers.go to the delivery channel fails it with
"addressed to delegate/system".

TestCompletionNotificationStaysWithinItsOwnOrigin puts two tasks from different
origins on one board, completes one, and asserts no completion notification
carries the other origin.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(teams): grant a delegated lead read access to its own team

Fixes #1535. Second attempt: the first one set RunRequest.TeamWorkspace on the
delegated run, which loop_context.go rejects outright and deliberately so — that
field also becomes ToolWorkspace, which would displace the exchange outputs
directory. Every delegation then died at setup with "invalid delegation artifact
workspace". This does not go near that field.

The separation the lead needs already exists in the code. A lead addressed
directly resolves its team at loop_context.go:285-321 and gets

    ctx = tools.WithToolTeamWorkspace(ctx, wsDir)
    ctx = tools.WithToolTeamRoot(ctx, teamRoot)

with no WithToolWorkspace call — a read allowance, not an override. Only the
!isArtifactDelegation gate keeps a delegated lead out of it. So the grant is
made inside the artifact branch instead, from the same inputs, and the guard on
req.TeamWorkspace stays exactly as strict as it was.

Both paths are needed. The workspace alone covers only the lead's own chat leaf;
the deliverable in the report sits at teams/<id>/system/review-....md, written by
a member under a different chat scope. buildAllowedPrefixes adds the team root
for reads and not for writes (filesystem.go:366-370), which is precisely the
asymmetry this case wants: the lead reads the team's output, per-chat write
isolation is untouched.

Team ID is deliberately not set. It switches on the workspace interceptor's
write validation, file-change broadcast and task attachment (workspace_
interceptor.go:36,114,203) — none of which a delegated run should trigger, and
none of which reading needs.

Ambiguity is not resolved silently, as triage asked: an agent leading more than
one active team gets nothing. store.GetTeamForAgent would answer in one call but
it is ORDER BY (lead_agent_id = $1) DESC LIMIT 1 and would quietly pick a team.

Hermeticity is unchanged: send_file and message still refuse inside an artifact
run, publication still happens through delegation outputs on completion.

Tests: TestInjectContext_DelegatedLeadReadsTeamWithoutDisplacingOutputs drives
injectContext through the guard that broke the first attempt and pins both
halves — the run is not refused, and ToolWorkspace stays the outputs directory.
Resolution rules, the shared/isolated path shapes, read-not-write on the team
root, and send_file staying blocked are covered alongside.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(teams): pin that the delegated lead resolver does not re-scope by tenant

l.dataDir arrives already tenant-scoped from resolver.go (config.TenantDataDir),
which is why resolveDelegatedLeadTeamRead must not apply TenantLayer itself.
That was carried only by a comment, here and in the sibling branch of
injectContext, and nothing failed if someone added the layer back.

The failure it guards against is quiet: the path stays plausible, it just gains
a second tenant segment — teams/<id> under tenants/<slug>/tenants/<slug> — so
the lead is handed a directory its own tasks never write to, and reads come back
empty rather than denied.

Verified the assertion has teeth by reintroducing the layer: the subtest fails
with "tenant segment appears 2 times". Prompted by #1546 in this same area,
where a contract that lived outside the unit under test went unpinned and the
feature shipped green and did nothing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 21:05:49 +07:00

205 lines
6.5 KiB
Go

package tools
import (
"context"
"strings"
"testing"
"github.com/nextlevelbuilder/goclaw/internal/store"
"github.com/nextlevelbuilder/goclaw/pkg/protocol"
)
// A lead reached through `delegate` runs on the internal "delegate" delivery
// channel, while the real origin is preserved separately. A task must record
// the origin: notifications addressed to the delivery channel have no
// registered handler and are dropped by the outbound dispatcher, so the caller
// never hears about completions, failures or blocker escalations.
func TestCreateRecordsDelegationOriginNotDeliveryChannel(t *testing.T) {
mb, tool, _, _, ctx := newTestTeamSetup()
// Shape the context the way a delegated run is built (buildAgentLinkRunRequest):
// delivery channel is "delegate", origin preserved as the workspace channel/chat.
ctx = WithToolChannel(ctx, "delegate")
ctx = WithToolChatID(ctx, "system")
ctx = WithWorkspaceChannel(ctx, "telegram")
ctx = WithWorkspaceChatID(ctx, "313683273")
ptd := NewPendingTeamDispatch()
ptd.MarkListed()
ctx = WithPendingTeamDispatch(ctx, ptd)
result := tool.Execute(ctx, map[string]any{
"action": "create",
"subject": "Origin routing",
"description": "Task created by a delegated lead",
"assignee": "member-agent",
})
if result.IsError {
t.Fatalf("unexpected error: %s", result.ForLLM)
}
if !strings.Contains(result.ForLLM, "Task created") {
t.Fatalf("expected 'Task created', got: %s", result.ForLLM)
}
mb.taskStore.mu.Lock()
var task *store.TeamTaskData
for _, v := range mb.taskStore.tasks {
task = v
}
mb.taskStore.mu.Unlock()
if task == nil {
t.Fatal("no task was created")
}
if task.Channel != "telegram" {
t.Errorf("task.Channel = %q, want %q — notifications on the delivery channel are dropped", task.Channel, "telegram")
}
if task.ChatID != "313683273" {
t.Errorf("task.ChatID = %q, want %q", task.ChatID, "313683273")
}
}
// Without a delegation origin the resolution is the identity: a task keeps the
// channel and chat of the run that created it.
func TestCreateKeepsOwnChannelWithoutDelegationOrigin(t *testing.T) {
mb, tool, _, _, ctx := newTestTeamSetup()
ptd := NewPendingTeamDispatch()
ptd.MarkListed()
ctx = WithPendingTeamDispatch(ctx, ptd)
result := tool.Execute(ctx, map[string]any{
"action": "create",
"subject": "Direct routing",
"description": "Task created by a lead talking to the user directly",
"assignee": "member-agent",
})
if result.IsError {
t.Fatalf("unexpected error: %s", result.ForLLM)
}
mb.taskStore.mu.Lock()
var task *store.TeamTaskData
for _, v := range mb.taskStore.tasks {
task = v
}
mb.taskStore.mu.Unlock()
if task == nil {
t.Fatal("no task was created")
}
if task.Channel != ChannelDashboard {
t.Errorf("task.Channel = %q, want %q", task.Channel, ChannelDashboard)
}
if task.ChatID != testTeamID.String() {
t.Errorf("task.ChatID = %q, want %q", task.ChatID, testTeamID.String())
}
}
// delegatedCtx shapes a context the way buildAgentLinkRunRequest does: the run is
// delivered on the internal "delegate" channel while the caller's origin is
// preserved as the workspace channel and chat.
func delegatedCtx(ctx context.Context, originChannel, originChat string) context.Context {
ctx = WithToolChannel(ctx, "delegate")
ctx = WithToolChatID(ctx, "system")
ctx = WithWorkspaceChannel(ctx, originChannel)
ctx = WithWorkspaceChatID(ctx, originChat)
ptd := NewPendingTeamDispatch()
ptd.MarkListed()
return WithPendingTeamDispatch(ctx, ptd)
}
func createTaskIn(t *testing.T, tool *TeamTasksTool, ctx context.Context, subject string) string {
t.Helper()
res := tool.Execute(ctx, map[string]any{
"action": "create",
"subject": subject,
"description": "work",
"assignee": "member-agent",
})
if res.IsError {
t.Fatalf("create %q: %s", subject, res.ForLLM)
}
id := res.ForLLM
start := strings.Index(id, "id=")
if start < 0 {
t.Fatalf("no task id in %q", res.ForLLM)
}
id = id[start+3:]
if end := strings.IndexAny(id, ","); end >= 0 {
id = id[:end]
}
return id
}
func completionEvent(t *testing.T, mb *mockBackend, taskID string) protocol.TeamTaskEventPayload {
t.Helper()
mb.mu.Lock()
defer mb.mu.Unlock()
for _, ev := range mb.events {
p, ok := ev.Payload.(protocol.TeamTaskEventPayload)
if ok && ev.Name == protocol.EventTeamTaskCompleted && p.TaskID == taskID {
return p
}
}
t.Fatalf("no completion event for task %s", taskID)
return protocol.TeamTaskEventPayload{}
}
// The notification a delegated lead emits on completion must be addressed to the
// caller's origin. Addressed to the internal "delegate" delivery channel it is
// dropped by the outbound dispatcher and the user never learns the work finished.
func TestDelegatedLeadCompletionNotifiesOrigin(t *testing.T) {
mb, tool, _, _, base := newTestTeamSetup()
ctx := delegatedCtx(base, "telegram", "313683273")
taskID := createTaskIn(t, tool, ctx, "Deliverable")
res := tool.Execute(ctx, map[string]any{
"action": "complete",
"task_id": taskID,
"result": "done",
})
if res.IsError {
t.Fatalf("complete: %s", res.ForLLM)
}
ev := completionEvent(t, mb, taskID)
if ev.Channel != "telegram" || ev.ChatID != "313683273" {
t.Errorf("completion event addressed to %s/%s, want telegram/313683273 — "+
"the delivery channel has no registered handler and the notification is dropped",
ev.Channel, ev.ChatID)
}
}
// Origins must not bleed into each other: completing a task raised from one chat
// must not produce a notification addressed to an unrelated origin sharing the
// same board.
func TestCompletionNotificationStaysWithinItsOwnOrigin(t *testing.T) {
mb, tool, _, _, base := newTestTeamSetup()
ctxA := delegatedCtx(base, "telegram", "chat-A")
ctxB := delegatedCtx(base, "discord", "chat-B")
taskA := createTaskIn(t, tool, ctxA, "Task A")
createTaskIn(t, tool, ctxB, "Task B")
res := tool.Execute(ctxA, map[string]any{"action": "complete", "task_id": taskA, "result": "done"})
if res.IsError {
t.Fatalf("complete: %s", res.ForLLM)
}
if ev := completionEvent(t, mb, taskA); ev.Channel != "telegram" || ev.ChatID != "chat-A" {
t.Errorf("task A announced to %s/%s, want telegram/chat-A", ev.Channel, ev.ChatID)
}
mb.mu.Lock()
defer mb.mu.Unlock()
for _, ev := range mb.events {
p, ok := ev.Payload.(protocol.TeamTaskEventPayload)
if !ok || ev.Name != protocol.EventTeamTaskCompleted {
continue
}
if p.Channel == "discord" || p.ChatID == "chat-B" {
t.Errorf("completing task A produced a notification addressed to the unrelated origin %s/%s",
p.Channel, p.ChatID)
}
}
}