Files
goclaw/internal/tools/team_tasks_mutations.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

319 lines
11 KiB
Go

package tools
import (
"context"
"fmt"
"log/slog"
"path/filepath"
"github.com/google/uuid"
"github.com/nextlevelbuilder/goclaw/internal/store"
"github.com/nextlevelbuilder/goclaw/pkg/protocol"
)
// resolveTeamAndTask is the common preamble for task mutation actions:
// resolve team context + parse task ID from args.
func (t *TeamTasksTool) resolveTeamAndTask(ctx context.Context, args map[string]any) (*store.TeamData, uuid.UUID, uuid.UUID, error) {
team, agentID, err := t.manager.ResolveTeam(ctx)
if err != nil {
return nil, uuid.Nil, uuid.Nil, err
}
taskID, err := resolveTaskID(ctx, args)
if err != nil {
return nil, uuid.Nil, uuid.Nil, err
}
return team, agentID, taskID, nil
}
func (t *TeamTasksTool) executeComment(ctx context.Context, args map[string]any) *Result {
team, agentID, taskID, err := t.resolveTeamAndTask(ctx, args)
if err != nil {
return ErrorResult(err.Error())
}
text, _ := args["text"].(string)
if text == "" {
return ErrorResult("text is required for comment action")
}
if len(text) > 10000 {
return ErrorResult("comment text too long (max 10000 chars)")
}
// Verify task belongs to team.
task, err := t.manager.Store().GetTask(ctx, taskID)
if err != nil {
return ErrorResult("task not found: " + err.Error())
}
if task.TeamID != team.ID {
return ErrorResult("task does not belong to your team")
}
commentType, _ := args["type"].(string)
if commentType != "blocker" {
commentType = "note"
}
if err := t.manager.Store().AddTaskComment(ctx, &store.TeamTaskCommentData{
TaskID: taskID,
AgentID: &agentID,
Content: text,
CommentType: commentType,
}); err != nil {
return ErrorResult("failed to add comment: " + err.Error())
}
t.manager.BroadcastTeamEvent(ctx, protocol.EventTeamTaskCommented, BuildTaskEventPayload(
team.ID.String(), taskID.String(),
"",
"agent", t.manager.AgentKeyFromID(ctx, agentID),
WithTaskInfo(task.TaskNumber, task.Subject),
WithCommentText(truncatePreview(text, 500)),
WithContextInfo(ctx),
))
// Record action flag after successful store operation.
recordTaskAction(ctx, func(f *TaskActionFlags) {
f.Commented = true
if commentType == "blocker" {
f.Escalated = true
}
})
// Blocker escalation: auto-fail task + notify leader.
if commentType == "blocker" {
return t.handleBlockerComment(ctx, team, task, taskID, agentID, text)
}
isLead := agentID == team.LeadAgentID
msg := fmt.Sprintf("Comment added to task #%d \"%s\" (id: %s).", task.TaskNumber, task.Subject, taskID)
switch {
case isLead && task.Status == store.TeamTaskStatusInProgress:
msg += " Note: the assignee is currently working and won't see this comment during execution. To redirect, wait for completion then use retry action with this task_id."
case isLead && task.Status == store.TeamTaskStatusCompleted:
msg += " Task is completed. Use retry action with this task_id to reopen and re-dispatch with your feedback."
case isLead && task.Status == store.TeamTaskStatusFailed:
msg += " Task failed. Use retry action with this task_id to re-dispatch with your feedback."
case !isLead && task.OwnerAgentID != nil && *task.OwnerAgentID == agentID:
msg += " Your comment will be included in the task report sent to the leader. Continue working on the task."
}
return NewResult(msg)
}
func (t *TeamTasksTool) executeProgress(ctx context.Context, args map[string]any) *Result {
team, agentID, taskID, err := t.resolveTeamAndTask(ctx, args)
if err != nil {
return ErrorResult(err.Error())
}
percent := 0
if p, ok := args["percent"].(float64); ok {
percent = int(p)
}
if percent < 0 || percent > 100 {
return ErrorResult("percent must be 0-100")
}
step, _ := args["text"].(string)
// Verify ownership.
task, err := t.manager.Store().GetTask(ctx, taskID)
if err != nil {
return ErrorResult("task not found: " + err.Error())
}
if task.TeamID != team.ID {
return ErrorResult("task does not belong to your team")
}
if task.OwnerAgentID == nil || *task.OwnerAgentID != agentID {
return ErrorResult("only the assigned task owner can update progress. As team lead, task results arrive automatically when members complete their work.")
}
// Early exit: task already terminal — skip DB write entirely.
// Reuses the task fetched above so no extra query needed.
switch task.Status {
case store.TeamTaskStatusCompleted, store.TeamTaskStatusFailed, store.TeamTaskStatusCancelled:
return SilentResult(fmt.Sprintf("Task already %s — progress update skipped.", task.Status))
}
// Prevent progress regression — keep the higher value.
if percent < task.ProgressPercent {
percent = task.ProgressPercent
}
if err := t.manager.Store().UpdateTaskProgress(ctx, taskID, team.ID, percent, step); err != nil {
// Status may have changed between GetTask and UpdateTaskProgress (race with completeTask).
// Fast path: check in-memory turn flags before hitting DB again.
if flags := TaskActionFlagsFromCtx(ctx); flags != nil && flags.Completed {
return SilentResult("Task already completed — progress update skipped.")
}
// Slow path: re-query for stale recovery (pending) or concurrent status change.
if current, getErr := t.manager.Store().GetTask(ctx, taskID); getErr == nil && current != nil {
switch current.Status {
case store.TeamTaskStatusCompleted, store.TeamTaskStatusFailed, store.TeamTaskStatusCancelled:
return SilentResult(fmt.Sprintf("Task already %s — progress update skipped.", current.Status))
case store.TeamTaskStatusPending:
// Task was reset by stale recovery — re-assign and retry once.
if t.manager.Store().AssignTask(ctx, taskID, agentID, team.ID) == nil {
if t.manager.Store().UpdateTaskProgress(ctx, taskID, team.ID, percent, step) == nil {
slog.Info("executeProgress: re-assigned stale-recovered task", "task_id", taskID)
recordTaskAction(ctx, func(f *TaskActionFlags) { f.Progressed = true })
return SilentResult(fmt.Sprintf("Progress updated: %d%% %s", percent, step))
}
}
}
}
return ErrorResult("failed to update progress: " + err.Error())
}
// Record action flag after successful store operation.
recordTaskAction(ctx, func(f *TaskActionFlags) { f.Progressed = true })
ownerKey := ""
if task.OwnerAgentID != nil {
ownerKey = t.manager.AgentKeyFromID(ctx, *task.OwnerAgentID)
}
t.manager.BroadcastTeamEvent(ctx, protocol.EventTeamTaskProgress, BuildTaskEventPayload(
team.ID.String(), taskID.String(),
store.TeamTaskStatusInProgress,
"", "",
WithTaskInfo(task.TaskNumber, task.Subject),
WithOwnerAgentKey(ownerKey),
WithProgress(percent, step),
WithContextInfo(ctx),
))
return SilentResult(fmt.Sprintf("Progress updated: %d%% %s", percent, step))
}
func (t *TeamTasksTool) executeAttach(ctx context.Context, args map[string]any) *Result {
team, agentID, taskID, err := t.resolveTeamAndTask(ctx, args)
if err != nil {
return ErrorResult(err.Error())
}
filePath, _ := args["path"].(string)
if filePath == "" {
return ErrorResult("path is required for attach action")
}
// Resolve to absolute path within team workspace.
if !filepath.IsAbs(filePath) {
if ws := ToolTeamWorkspaceFromCtx(ctx); ws != "" {
filePath = filepath.Join(ws, filePath)
}
}
filePath = filepath.Clean(filePath)
// Verify task belongs to team.
task, err := t.manager.Store().GetTask(ctx, taskID)
if err != nil {
return ErrorResult("task not found: " + err.Error())
}
if task.TeamID != team.ID {
return ErrorResult("task does not belong to your team")
}
chatID := OriginChatIDFromCtx(ctx)
if err := t.manager.Store().AttachFileToTask(ctx, &store.TeamTaskAttachmentData{
TaskID: taskID,
TeamID: team.ID,
ChatID: chatID,
Path: filePath,
CreatedByAgentID: &agentID,
}); err != nil {
return ErrorResult("failed to attach file: " + err.Error())
}
t.manager.BroadcastTeamEvent(ctx, protocol.EventTeamTaskAttachmentAdded, BuildTaskEventPayload(
team.ID.String(), taskID.String(),
"",
"agent", t.manager.AgentKeyFromID(ctx, agentID),
WithTaskInfo(task.TaskNumber, task.Subject),
WithContextInfo(ctx),
))
return NewResult(fmt.Sprintf("File attached to task #%d \"%s\" (id: %s).", task.TaskNumber, task.Subject, taskID))
}
func (t *TeamTasksTool) executeUpdate(ctx context.Context, args map[string]any) *Result {
team, agentID, taskID, err := t.resolveTeamAndTask(ctx, args)
if err != nil {
return ErrorResult(err.Error())
}
if err := t.manager.RequireLead(ctx, team, agentID); err != nil {
return ErrorResult(err.Error())
}
// Verify task belongs to this team (prevent cross-team update).
task, err := t.manager.Store().GetTask(ctx, taskID)
if err != nil {
return ErrorResult("task not found: " + err.Error())
}
if task.TeamID != team.ID {
return ErrorResult("task does not belong to your team")
}
updates := map[string]any{}
if desc, ok := args["description"].(string); ok {
updates["description"] = desc
}
if subj, ok := args["subject"].(string); ok && subj != "" {
updates["subject"] = subj
}
if raw, ok := args["blocked_by"].([]any); ok {
var blockedBy []uuid.UUID
for _, v := range raw {
if s, ok := v.(string); ok {
id, err := uuid.Parse(s)
if err != nil {
return ErrorResult(fmt.Sprintf("blocked_by contains invalid task ID %q — must be a real task UUID.", s))
}
blockedBy = append(blockedBy, id)
}
}
// Batch-validate all blocker tasks in one query.
if len(blockedBy) > 0 {
depTasks, err := t.manager.Store().GetTasksByIDs(ctx, blockedBy)
if err != nil {
return ErrorResult("failed to validate blocked_by: " + err.Error())
}
depMap := make(map[uuid.UUID]*store.TeamTaskData, len(depTasks))
for i := range depTasks {
depMap[depTasks[i].ID] = &depTasks[i]
}
for _, id := range blockedBy {
dt, ok := depMap[id]
if !ok {
return ErrorResult(fmt.Sprintf("blocked_by task %s not found", id))
}
if dt.TeamID != team.ID {
return ErrorResult(fmt.Sprintf("blocked_by task %s belongs to a different team", id))
}
switch dt.Status {
case store.TeamTaskStatusCompleted, store.TeamTaskStatusCancelled, store.TeamTaskStatusFailed:
return ErrorResult(fmt.Sprintf(
"blocked_by task %s (%s) is already %s. "+
"Remove it from blocked_by — finished tasks cannot block new work.",
id, dt.Subject, dt.Status))
}
}
}
updates["blocked_by"] = blockedBy
}
if len(updates) == 0 {
return ErrorResult("no updates provided (set description, subject, or blocked_by)")
}
if err := t.manager.Store().UpdateTask(ctx, taskID, updates); err != nil {
return ErrorResult("failed to update task: " + err.Error())
}
t.manager.BroadcastTeamEvent(ctx, protocol.EventTeamTaskUpdated, BuildTaskEventPayload(
team.ID.String(), taskID.String(),
task.Status,
"agent", t.manager.AgentKeyFromID(ctx, agentID),
WithSubject(task.Subject),
WithContextInfo(ctx),
))
return NewResult(fmt.Sprintf("Task #%d \"%s\" updated (id: %s).", task.TaskNumber, task.Subject, taskID))
}