mirror of
https://github.com/tiennm99/goclaw.git
synced 2026-10-12 18:16:09 +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>
230 lines
7.4 KiB
Go
230 lines
7.4 KiB
Go
package tools
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/nextlevelbuilder/goclaw/internal/bus"
|
|
"github.com/nextlevelbuilder/goclaw/internal/store"
|
|
"github.com/nextlevelbuilder/goclaw/pkg/protocol"
|
|
)
|
|
|
|
// broadcastTeamEvent sends a real-time event via the message bus for team activity visibility.
|
|
// Includes tenant_id from context for proper WS event filtering.
|
|
func (m *TeamToolManager) broadcastTeamEvent(ctx context.Context, name string, payload any) {
|
|
if m.msgBus == nil {
|
|
return
|
|
}
|
|
bus.BroadcastForTenant(m.msgBus, name, store.TenantIDFromContext(ctx), payload)
|
|
}
|
|
|
|
func reviewOutboundMessage(task *store.TeamTaskData, content string) bus.OutboundMessage {
|
|
message := bus.OutboundMessage{
|
|
Channel: task.Channel,
|
|
ChatID: task.ChatID,
|
|
Content: content,
|
|
}
|
|
message.Metadata = TaskLocalKeyMetadata(task)
|
|
return message
|
|
}
|
|
|
|
// TaskLocalKeyMetadata extracts local_key from task metadata for Telegram forum topic routing.
|
|
func TaskLocalKeyMetadata(task *store.TeamTaskData) map[string]string {
|
|
if task == nil || task.Metadata == nil {
|
|
return nil
|
|
}
|
|
if localKey, ok := task.Metadata[TaskMetaLocalKey].(string); ok && localKey != "" {
|
|
return map[string]string{TaskMetaLocalKey: localKey}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// resolveTeamRole returns the calling agent's role in the team.
|
|
// Unlike requireLead(), this does NOT bypass for teammate channel —
|
|
// workspace RBAC must respect actual roles even for teammate agents.
|
|
func (m *TeamToolManager) resolveTeamRole(ctx context.Context, team *store.TeamData, agentID uuid.UUID) (string, error) {
|
|
if agentID == team.LeadAgentID {
|
|
return store.TeamRoleLead, nil
|
|
}
|
|
members, err := m.cachedListMembers(ctx, team.ID, agentID)
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to resolve team role: %w", err)
|
|
}
|
|
for _, member := range members {
|
|
if member.AgentID == agentID {
|
|
return member.Role, nil
|
|
}
|
|
}
|
|
return "", fmt.Errorf("agent is not a member of this team")
|
|
}
|
|
|
|
// agentDisplayName returns the display name for an agent key, falling back to empty string.
|
|
func (m *TeamToolManager) agentDisplayName(ctx context.Context, key string) string {
|
|
ag, err := m.cachedGetAgentByKey(ctx, key)
|
|
if err != nil || ag.DisplayName == "" {
|
|
return ""
|
|
}
|
|
return ag.DisplayName
|
|
}
|
|
|
|
// ============================================================
|
|
// TeamToolBackend exported wrappers (helpers layer)
|
|
// ============================================================
|
|
|
|
func (m *TeamToolManager) BroadcastTeamEvent(ctx context.Context, name string, payload any) {
|
|
m.broadcastTeamEvent(ctx, name, payload)
|
|
}
|
|
func (m *TeamToolManager) AgentDisplayName(ctx context.Context, key string) string {
|
|
return m.agentDisplayName(ctx, key)
|
|
}
|
|
func (m *TeamToolManager) FollowupDelayMinutes(team *store.TeamData) int {
|
|
return m.followupDelayMinutes(team)
|
|
}
|
|
func (m *TeamToolManager) FollowupMaxReminders(team *store.TeamData) int {
|
|
return m.followupMaxReminders(team)
|
|
}
|
|
|
|
// ============================================================
|
|
// Version helpers
|
|
// ============================================================
|
|
|
|
|
|
// ============================================================
|
|
// Follow-up settings helpers
|
|
// ============================================================
|
|
|
|
const (
|
|
defaultFollowupDelayMinutes = 30
|
|
defaultFollowupMaxReminders = 0 // 0 = unlimited
|
|
)
|
|
|
|
// followupDelayMinutes returns the team's followup_interval_minutes setting, or the default.
|
|
func (m *TeamToolManager) followupDelayMinutes(team *store.TeamData) int {
|
|
if team == nil || team.Settings == nil {
|
|
return defaultFollowupDelayMinutes
|
|
}
|
|
var settings map[string]any
|
|
if json.Unmarshal(team.Settings, &settings) != nil {
|
|
return defaultFollowupDelayMinutes
|
|
}
|
|
if v, ok := settings["followup_interval_minutes"].(float64); ok && v > 0 {
|
|
return int(v)
|
|
}
|
|
return defaultFollowupDelayMinutes
|
|
}
|
|
|
|
// followupMaxReminders returns the team's followup_max_reminders setting, or the default.
|
|
func (m *TeamToolManager) followupMaxReminders(team *store.TeamData) int {
|
|
if team == nil || team.Settings == nil {
|
|
return defaultFollowupMaxReminders
|
|
}
|
|
var settings map[string]any
|
|
if json.Unmarshal(team.Settings, &settings) != nil {
|
|
return defaultFollowupMaxReminders
|
|
}
|
|
if v, ok := settings["followup_max_reminders"].(float64); ok && v >= 0 {
|
|
return int(v)
|
|
}
|
|
return defaultFollowupMaxReminders
|
|
}
|
|
|
|
// ============================================================
|
|
// Escalation policy
|
|
// ============================================================
|
|
|
|
// EscalationResult indicates how an action should be handled.
|
|
type EscalationResult int
|
|
|
|
const (
|
|
EscalationNone EscalationResult = iota // no escalation configured
|
|
EscalationAuto // LLM chooses (currently: always review)
|
|
EscalationReview // create review task
|
|
EscalationReject // reject outright
|
|
)
|
|
|
|
// checkEscalation parses the team's escalation_mode and escalation_actions settings.
|
|
func (m *TeamToolManager) checkEscalation(team *store.TeamData, action string) EscalationResult {
|
|
if team == nil || team.Settings == nil {
|
|
return EscalationNone
|
|
}
|
|
var settings map[string]any
|
|
if err := json.Unmarshal(team.Settings, &settings); err != nil {
|
|
return EscalationNone
|
|
}
|
|
|
|
mode, _ := settings["escalation_mode"].(string)
|
|
if mode == "" {
|
|
return EscalationNone
|
|
}
|
|
|
|
// Check if action is in escalation_actions list.
|
|
actionsRaw, _ := settings["escalation_actions"].([]any)
|
|
if len(actionsRaw) > 0 {
|
|
found := false
|
|
for _, a := range actionsRaw {
|
|
if s, ok := a.(string); ok && s == action {
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
if !found {
|
|
return EscalationNone
|
|
}
|
|
}
|
|
|
|
switch mode {
|
|
case "auto":
|
|
return EscalationAuto
|
|
case "review":
|
|
return EscalationReview
|
|
case "reject":
|
|
return EscalationReject
|
|
default:
|
|
return EscalationNone
|
|
}
|
|
}
|
|
|
|
// createEscalationTask creates an escalation task and broadcasts the event.
|
|
func (m *TeamToolManager) createEscalationTask(ctx context.Context, team *store.TeamData, agentID uuid.UUID, subject, description string) *Result {
|
|
task := &store.TeamTaskData{
|
|
TeamID: team.ID,
|
|
Subject: subject,
|
|
Description: description,
|
|
Status: store.TeamTaskStatusPending,
|
|
UserID: store.UserIDFromContext(ctx),
|
|
Channel: OriginChannelFromCtx(ctx),
|
|
TaskType: "escalation",
|
|
CreatedByAgentID: &agentID,
|
|
ChatID: OriginChatIDFromCtx(ctx),
|
|
}
|
|
if err := m.teamStore.CreateTask(ctx, task); err != nil {
|
|
return ErrorResult("failed to create escalation task: " + err.Error())
|
|
}
|
|
|
|
m.broadcastTeamEvent(ctx, protocol.EventTeamTaskCreated, BuildTaskEventPayload(
|
|
team.ID.String(), task.ID.String(),
|
|
store.TeamTaskStatusPending,
|
|
"", "",
|
|
WithSubject(subject),
|
|
WithContextInfo(ctx),
|
|
WithTimestamp(task.CreatedAt.UTC().Format("2006-01-02T15:04:05Z")),
|
|
))
|
|
|
|
// Notify channel if possible.
|
|
m.notifyChannelReview(task)
|
|
|
|
return NewResult(fmt.Sprintf("Action requires approval. Escalation task created: %s (id=%s). A human must approve before this action can proceed.", subject, task.Identifier))
|
|
}
|
|
|
|
// notifyChannelReview publishes an outbound message to the origin channel about a pending review.
|
|
func (m *TeamToolManager) notifyChannelReview(task *store.TeamTaskData) {
|
|
if m.msgBus == nil || task.Channel == "" || task.ChatID == "" {
|
|
return
|
|
}
|
|
content := fmt.Sprintf("🔔 Escalation: \"%s\" requires human review (task %s).", task.Subject, task.Identifier)
|
|
m.msgBus.PublishOutbound(reviewOutboundMessage(task, content))
|
|
}
|