mirror of
https://github.com/tiennm99/goclaw.git
synced 2026-10-12 14:15:00 +00:00
* 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>
297 lines
9.3 KiB
Go
297 lines
9.3 KiB
Go
package tools
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"strings"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/nextlevelbuilder/goclaw/internal/bus"
|
|
"github.com/nextlevelbuilder/goclaw/internal/store"
|
|
"github.com/nextlevelbuilder/goclaw/pkg/protocol"
|
|
)
|
|
|
|
// PostTurnProcessor validates and dispatches pending team tasks after an agent turn.
|
|
type PostTurnProcessor interface {
|
|
ProcessPendingTasks(ctx context.Context, teamID uuid.UUID, taskIDs []uuid.UUID) error
|
|
// DispatchUnblockedTasks finds pending tasks with an owner and dispatches them.
|
|
// Called by the consumer after auto-completing a task to unblock dependent work.
|
|
DispatchUnblockedTasks(ctx context.Context, teamID uuid.UUID)
|
|
}
|
|
|
|
// ProcessPendingTasks validates tasks created during a turn and dispatches unblocked ones.
|
|
// Called by the consumer after an agent turn ends.
|
|
func (m *TeamToolManager) ProcessPendingTasks(ctx context.Context, teamID uuid.UUID, taskIDs []uuid.UUID) error {
|
|
if len(taskIDs) == 0 {
|
|
return nil
|
|
}
|
|
|
|
// Fetch all tasks created in this turn.
|
|
tasks := make([]*store.TeamTaskData, 0, len(taskIDs))
|
|
for _, id := range taskIDs {
|
|
t, err := m.teamStore.GetTask(ctx, id)
|
|
if err != nil {
|
|
slog.Warn("post_turn: cannot fetch task", "task_id", id, "error", err)
|
|
continue
|
|
}
|
|
tasks = append(tasks, t)
|
|
}
|
|
if len(tasks) == 0 {
|
|
return nil
|
|
}
|
|
|
|
// Build lookup: taskID → task (for cycle/ref validation).
|
|
taskMap := make(map[uuid.UUID]*store.TeamTaskData, len(tasks))
|
|
for _, t := range tasks {
|
|
taskMap[t.ID] = t
|
|
}
|
|
|
|
// Validate blocked_by references and detect cycles.
|
|
cycled, invalidRef := validateBlockedBy(taskMap)
|
|
|
|
// Fail tasks with invalid blocked_by references.
|
|
for taskID, badRef := range invalidRef {
|
|
task := taskMap[taskID]
|
|
errMsg := fmt.Sprintf("blocked_by references non-existent task %s", badRef)
|
|
if err := m.teamStore.FailPendingTask(ctx, taskID, teamID, errMsg); err != nil {
|
|
slog.Warn("post_turn: FailPendingTask error", "task_id", taskID, "error", err)
|
|
}
|
|
m.broadcastTeamEvent(ctx, protocol.EventTeamTaskFailed, BuildTaskEventPayload(
|
|
teamID.String(), taskID.String(),
|
|
store.TeamTaskStatusFailed,
|
|
"system", "post_turn",
|
|
))
|
|
slog.Warn("post_turn: task failed — invalid blocked_by",
|
|
"task_id", taskID, "identifier", task.Identifier, "bad_ref", badRef)
|
|
}
|
|
|
|
// Fail cycled tasks and notify leader.
|
|
if len(cycled) > 0 {
|
|
m.failCycledTasks(ctx, teamID, cycled, taskMap)
|
|
}
|
|
|
|
// Fetch team once for lead-agent guard in dispatchTaskToAgent.
|
|
team, err := m.teamStore.GetTeam(ctx, teamID)
|
|
if err != nil || team == nil {
|
|
slog.Warn("post_turn: cannot fetch team", "team_id", teamID, "error", err)
|
|
return fmt.Errorf("cannot fetch team %s: %w", teamID, err)
|
|
}
|
|
|
|
// Dispatch pending assigned tasks (not blocked, not failed).
|
|
for _, task := range tasks {
|
|
if _, isCycled := cycled[task.ID]; isCycled {
|
|
continue
|
|
}
|
|
if _, isInvalid := invalidRef[task.ID]; isInvalid {
|
|
continue
|
|
}
|
|
if task.Status != store.TeamTaskStatusPending || task.OwnerAgentID == nil {
|
|
continue
|
|
}
|
|
// Skip tasks assigned to the lead agent — would cause self-dispatch loop.
|
|
if *task.OwnerAgentID == team.LeadAgentID {
|
|
continue
|
|
}
|
|
if err := m.teamStore.AssignTask(ctx, task.ID, *task.OwnerAgentID, teamID); err != nil {
|
|
slog.Warn("post_turn: assign failed", "task_id", task.ID, "error", err)
|
|
continue
|
|
}
|
|
taskPeerKind := ""
|
|
if pk, ok := task.Metadata[TaskMetaPeerKind].(string); ok {
|
|
taskPeerKind = pk
|
|
}
|
|
taskLocalKey := ""
|
|
if lk, ok := task.Metadata[TaskMetaLocalKey].(string); ok {
|
|
taskLocalKey = lk
|
|
}
|
|
m.broadcastTeamEvent(ctx, protocol.EventTeamTaskDispatched, BuildTaskEventPayload(
|
|
teamID.String(), task.ID.String(),
|
|
store.TeamTaskStatusInProgress,
|
|
"system", "post_turn",
|
|
WithTaskInfo(task.TaskNumber, task.Subject),
|
|
WithOwnerAgentKey(m.agentKeyFromID(ctx, *task.OwnerAgentID)),
|
|
WithChannel(task.Channel),
|
|
WithChatID(task.ChatID),
|
|
WithPeerKind(taskPeerKind),
|
|
WithLocalKey(taskLocalKey),
|
|
))
|
|
// Restore leader's trace context from task metadata (ctx here is the
|
|
// consumer goroutine context which has no trace after the turn ends).
|
|
dispatchCtx := m.restoreTraceContext(ctx, task)
|
|
m.dispatchTaskToAgent(dispatchCtx, task, team, *task.OwnerAgentID)
|
|
}
|
|
|
|
slog.Info("post_turn: processed pending tasks",
|
|
"team_id", teamID,
|
|
"total", len(tasks),
|
|
"dispatched", countPendingAssigned(tasks, cycled, invalidRef),
|
|
)
|
|
return nil
|
|
}
|
|
|
|
// failCycledTasks fails all tasks in the cycle and notifies the leader.
|
|
func (m *TeamToolManager) failCycledTasks(ctx context.Context, teamID uuid.UUID, cycled map[uuid.UUID]bool, taskMap map[uuid.UUID]*store.TeamTaskData) {
|
|
// Build cycle description using task identifiers.
|
|
var ids []string
|
|
for id := range cycled {
|
|
if t := taskMap[id]; t != nil {
|
|
ids = append(ids, t.Identifier)
|
|
}
|
|
}
|
|
cycleDesc := fmt.Sprintf("Circular dependency detected among tasks: %s", strings.Join(ids, " → "))
|
|
|
|
for id := range cycled {
|
|
if err := m.teamStore.FailPendingTask(ctx, id, teamID, cycleDesc); err != nil {
|
|
slog.Warn("post_turn: FailPendingTask (cycle) error", "task_id", id, "error", err)
|
|
}
|
|
m.broadcastTeamEvent(ctx, protocol.EventTeamTaskFailed, BuildTaskEventPayload(
|
|
teamID.String(), id.String(),
|
|
store.TeamTaskStatusFailed,
|
|
"system", "post_turn",
|
|
))
|
|
}
|
|
|
|
// Notify leader via system message.
|
|
m.notifyLeaderCycleError(ctx, teamID, cycleDesc)
|
|
}
|
|
|
|
// notifyLeaderCycleError sends a system message to the leader about cycled tasks.
|
|
// Uses "notification:" sender prefix to go through normal consumer flow (not handleTeammateMessage).
|
|
func (m *TeamToolManager) notifyLeaderCycleError(ctx context.Context, teamID uuid.UUID, cycleDesc string) {
|
|
if m.msgBus == nil {
|
|
return
|
|
}
|
|
team, err := m.teamStore.GetTeam(ctx, teamID)
|
|
if err != nil {
|
|
return
|
|
}
|
|
leadAgent, err := m.cachedGetAgentByID(ctx, team.LeadAgentID)
|
|
if err != nil {
|
|
return
|
|
}
|
|
content := fmt.Sprintf("[System] %s\nPlease recreate these tasks with corrected dependencies.\nUse team_tasks(action=\"list\") to view current task board.", cycleDesc)
|
|
|
|
// Resolve routing: use context channel/chatID if available, fallback to dashboard.
|
|
channel := OriginChannelFromCtx(ctx)
|
|
chatID := OriginChatIDFromCtx(ctx)
|
|
if channel == "" || channel == ChannelSystem || channel == ChannelTeammate {
|
|
channel = "dashboard"
|
|
chatID = teamID.String()
|
|
}
|
|
|
|
m.msgBus.TryPublishInbound(bus.InboundMessage{
|
|
Channel: channel,
|
|
SenderID: "notification:system",
|
|
ChatID: chatID,
|
|
AgentID: leadAgent.AgentKey,
|
|
UserID: team.CreatedBy,
|
|
PeerKind: ToolPeerKindFromCtx(ctx),
|
|
TenantID: store.TenantIDFromContext(ctx),
|
|
Content: content,
|
|
})
|
|
}
|
|
|
|
// validateBlockedBy checks blocked_by references and detects cycles using Kahn's algorithm.
|
|
// Only validates within the batch — out-of-batch blocked_by refs are assumed valid
|
|
// (already validated by executeCreate). Self-blocking is caught as invalid.
|
|
//
|
|
// Note: Cross-turn blocked_by references (tasks from previous turns) work at the DB
|
|
// level via unblockDependentTasks (WHERE $1 = ANY(blocked_by)). Cycle detection here
|
|
// only considers edges within the current batch — cross-turn deps are external.
|
|
//
|
|
// Returns: cycled task IDs, and map of taskID → first invalid blocked_by ref.
|
|
func validateBlockedBy(taskMap map[uuid.UUID]*store.TeamTaskData) (cycled map[uuid.UUID]bool, invalidRef map[uuid.UUID]uuid.UUID) {
|
|
invalidRef = make(map[uuid.UUID]uuid.UUID)
|
|
|
|
// Collect all task IDs in this batch.
|
|
batchIDs := make(map[uuid.UUID]bool, len(taskMap))
|
|
for id := range taskMap {
|
|
batchIDs[id] = true
|
|
}
|
|
|
|
// Check for self-blocking only. Out-of-batch blocked_by refs are valid
|
|
// (tasks from previous turns, already validated by executeCreate).
|
|
for id, task := range taskMap {
|
|
for _, dep := range task.BlockedBy {
|
|
if dep == id {
|
|
invalidRef[id] = dep
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
// Cycle detection via Kahn's algorithm.
|
|
// Only considers edges within the batch — out-of-batch deps are external
|
|
// and don't participate in cycle detection.
|
|
inDegree := make(map[uuid.UUID]int)
|
|
adj := make(map[uuid.UUID][]uuid.UUID) // blocker → dependents
|
|
|
|
for id, task := range taskMap {
|
|
if _, bad := invalidRef[id]; bad {
|
|
continue
|
|
}
|
|
if _, exists := inDegree[id]; !exists {
|
|
inDegree[id] = 0
|
|
}
|
|
for _, dep := range task.BlockedBy {
|
|
if _, bad := invalidRef[dep]; bad {
|
|
continue
|
|
}
|
|
// Only consider edges within the batch for cycle detection.
|
|
if !batchIDs[dep] {
|
|
continue
|
|
}
|
|
adj[dep] = append(adj[dep], id)
|
|
inDegree[id]++
|
|
}
|
|
}
|
|
|
|
// BFS: process nodes with in-degree 0.
|
|
var queue []uuid.UUID
|
|
for id, deg := range inDegree {
|
|
if deg == 0 {
|
|
queue = append(queue, id)
|
|
}
|
|
}
|
|
processed := make(map[uuid.UUID]bool)
|
|
for len(queue) > 0 {
|
|
node := queue[0]
|
|
queue = queue[1:]
|
|
processed[node] = true
|
|
for _, dependent := range adj[node] {
|
|
inDegree[dependent]--
|
|
if inDegree[dependent] == 0 {
|
|
queue = append(queue, dependent)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Any node not processed is part of a cycle.
|
|
cycled = make(map[uuid.UUID]bool)
|
|
for id := range inDegree {
|
|
if !processed[id] {
|
|
cycled[id] = true
|
|
}
|
|
}
|
|
return cycled, invalidRef
|
|
}
|
|
|
|
// countPendingAssigned counts tasks that were eligible for dispatch.
|
|
func countPendingAssigned(tasks []*store.TeamTaskData, cycled map[uuid.UUID]bool, invalidRef map[uuid.UUID]uuid.UUID) int {
|
|
n := 0
|
|
for _, t := range tasks {
|
|
if _, c := cycled[t.ID]; c {
|
|
continue
|
|
}
|
|
if _, i := invalidRef[t.ID]; i {
|
|
continue
|
|
}
|
|
if t.Status == store.TeamTaskStatusPending && t.OwnerAgentID != nil {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|