mirror of
https://github.com/tiennm99/goclaw.git
synced 2026-10-12 10:13:37 +00:00
* feat(delegate): add action=list, scoped to the originating chat Fixes #1545. A delegation result was addressable only by the UUID returned once in a tool result, which the calling model had to carry forward by hand. One mistyped character orphaned a completed, durably stored result with no way back: `get` answers "delegation result not found", and there was nothing else to ask. Observed in production with a 31B-class caller — one flipped character, and separately a splice of the previous delegation's tail onto the next one's prefix. `spawn`, the sibling async mechanism over the same table, has had list/wait/cancel all along; `delegate` had delegate/get. Scope is tenant and calling agent, as get already resolves, plus the origin chat. The chat rather than the session, for three reasons: - It survives a session reset. Deferring long work, clearing the context and coming back to ask for status is ordinary use; a SessionKey predicate would return nothing exactly then — when the handle is most likely already lost. - It keeps chats apart, which is the enumeration boundary #1525 is about: there spawn's list filters on the parent agent key alone and ignores the session, so one chat reads another chat's task text. - It does not carry a conversation between chats. A delegation raised in a team chat stays visible in that team chat and does not surface in someone's DM with the same agent. History stays where it began. In a direct chat that separates users as well, since the chat ID is per person. Group chats deliberately show the group what the group started. get is left as it was, deliberately. #1525 is an enumeration defect — no prior knowledge needed and task text is disclosed. get is access through an unguessable handle, and adding a predicate there would break fetching a result by an ID kept across a reset, which is the very failure this fixes. No schema change: the origin fields are already persisted by createDelegateCompletion. ListByParent is filtered in Go behind a cap of 20, which suits handle recovery; a dedicated predicate would be the next step if this ever needs to page. Tests pin the chat boundary, the session-reset case, refusal when there is no chat to scope to (without querying the store), and the cap. The fake store leaves ListBySession embedded and nil, so a refactor back to session scoping panics rather than passing quietly. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(delegate): list needs its own store query — ListByParent excludes delegations The action shipped in 506ecba4 always returned an empty list. It read through SubagentTaskStore.ListByParent, whose SQL carries AND COALESCE(metadata->>'completion_kind', 'subagent') <> 'delegate' ListBySession carries the same clause. Both serve spawn and filter delegations out on purpose, so no listing in the store could return one — only Get by ID reaches a delegation. The feature was a no-op in production while its unit tests were green, because the fake store returned whatever rows the fixture supplied and never reproduced the predicate that does the damage. Found by running it against a live cluster: an async delegation was created, `get` returned it completed with its result, and `list` reported zero. Adds ListDelegationsByChat to the interface and to both implementations, with the inverse predicate plus origin_chat_id, and points the tool at it. Chat scope and delegate-only selection now live in the query rather than in a Go filter over whatever the store happened to return; an empty chat yields no rows instead of falling back to everything. Tests are where the fix matters most: - internal/store/sqlitestore exercises the real SQL. It pins that ListDelegationsByChat returns the chat's delegation, that a spawn in the same chat is not one, that another tenant's identically named chat stays invisible, and — the part that would have caught this — that ListByParent and ListBySession still do not return delegations, so the complementarity is documented rather than assumed. - the tool's fake now panics if ListByParent or ListBySession is called, so a regression to either fails loudly instead of quietly listing nothing, and it applies the chat and kind predicates itself so fixtures behave like the store. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
177 lines
6.3 KiB
Go
177 lines
6.3 KiB
Go
package tools
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/nextlevelbuilder/goclaw/internal/store"
|
|
)
|
|
|
|
// chatScopedTaskStore serves ListDelegationsByChat and records what it was asked
|
|
// for. The embedded interface is nil on purpose, and ListByParent/ListBySession
|
|
// panic outright: both carry "completion_kind <> 'delegate'" in their real SQL
|
|
// and can never return a delegation, so a regression to either must fail loudly
|
|
// here rather than quietly return nothing — which is exactly how the first
|
|
// version of this shipped green and did nothing in production.
|
|
type chatScopedTaskStore struct {
|
|
store.SubagentTaskStore
|
|
rows []store.SubagentTaskData
|
|
listCalls int
|
|
askedAgent uuid.UUID
|
|
askedChat string
|
|
}
|
|
|
|
func (s *chatScopedTaskStore) ListDelegationsByChat(
|
|
_ context.Context, rootAgentID uuid.UUID, chatID string,
|
|
) ([]store.SubagentTaskData, error) {
|
|
s.listCalls++
|
|
s.askedAgent = rootAgentID
|
|
s.askedChat = chatID
|
|
// Stand in for the query's own chat predicate, so the fixtures can carry
|
|
// rows from other chats and this still behaves like the real store.
|
|
var out []store.SubagentTaskData
|
|
for _, r := range s.rows {
|
|
if r.OriginChatID != nil && *r.OriginChatID == chatID &&
|
|
completionKind(r.Metadata) == asyncCompletionKindDelegate {
|
|
out = append(out, r)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (s *chatScopedTaskStore) ListByParent(context.Context, uuid.UUID, string) ([]store.SubagentTaskData, error) {
|
|
panic("delegate list must not use ListByParent: its SQL excludes delegations")
|
|
}
|
|
|
|
func (s *chatScopedTaskStore) ListBySession(context.Context, uuid.UUID, string) ([]store.SubagentTaskData, error) {
|
|
panic("delegate list must not use ListBySession: its SQL excludes delegations")
|
|
}
|
|
|
|
func delegationRow(chatID, sessionKey, target string, created time.Time) store.SubagentTaskData {
|
|
return store.SubagentTaskData{
|
|
BaseModel: store.BaseModel{ID: uuid.New(), CreatedAt: created},
|
|
Status: TaskStatusCompleted,
|
|
SessionKey: &sessionKey,
|
|
OriginChatID: &chatID,
|
|
Metadata: map[string]any{
|
|
asyncCompletionKindKey: asyncCompletionKindDelegate,
|
|
delegateCompletionTargetKey: target,
|
|
},
|
|
}
|
|
}
|
|
|
|
func spawnRow(chatID string) store.SubagentTaskData {
|
|
return store.SubagentTaskData{
|
|
BaseModel: store.BaseModel{ID: uuid.New(), CreatedAt: time.Unix(1, 0)},
|
|
Status: TaskStatusCompleted,
|
|
OriginChatID: &chatID,
|
|
Metadata: map[string]any{asyncCompletionKindKey: asyncCompletionKindSubagent},
|
|
}
|
|
}
|
|
|
|
func listCtx(chatID string) context.Context {
|
|
ctx := store.WithTenantID(context.Background(), uuid.New())
|
|
ctx = store.WithAgentID(ctx, uuid.New())
|
|
return WithToolChatID(ctx, chatID)
|
|
}
|
|
|
|
func decodeList(t *testing.T, res *Result) []map[string]any {
|
|
t.Helper()
|
|
if res == nil || res.IsError {
|
|
t.Fatalf("list result = %#v", res)
|
|
}
|
|
var payload struct {
|
|
Delegations []map[string]any `json:"delegations"`
|
|
Count int `json:"count"`
|
|
}
|
|
if err := json.Unmarshal([]byte(res.ForLLM), &payload); err != nil {
|
|
t.Fatalf("decode %q: %v", res.ForLLM, err)
|
|
}
|
|
if payload.Count != len(payload.Delegations) {
|
|
t.Errorf("count %d disagrees with %d listed", payload.Count, len(payload.Delegations))
|
|
}
|
|
return payload.Delegations
|
|
}
|
|
|
|
func newListTool(rows []store.SubagentTaskData) (*DelegateTool, *chatScopedTaskStore) {
|
|
s := &chatScopedTaskStore{rows: rows}
|
|
tool := NewDelegateTool(nil, noopAgentCRUD{}, nil, nil)
|
|
tool.SetTaskStore(s)
|
|
return tool, s
|
|
}
|
|
|
|
// The chat is the unit of visibility: a delegation started in one chat is not
|
|
// carried into another chat with the same agent, and spawned subagents sharing
|
|
// the table are not delegations.
|
|
func TestDelegateListIsScopedToItsChat(t *testing.T) {
|
|
tool, s := newListTool([]store.SubagentTaskData{
|
|
delegationRow("chat-a", "session-1", "brain", time.Unix(200, 0)),
|
|
delegationRow("chat-b", "session-1", "brain", time.Unix(300, 0)),
|
|
spawnRow("chat-a"),
|
|
})
|
|
got := decodeList(t, tool.executeListCompletions(listCtx("chat-a")))
|
|
if s.askedChat != "chat-a" {
|
|
t.Errorf("store was asked for chat %q, want the caller's chat", s.askedChat)
|
|
}
|
|
if len(got) != 1 {
|
|
t.Fatalf("listed %d entries, want only this chat's delegation: %v", len(got), got)
|
|
}
|
|
if got[0]["agent"] != "brain" || got[0]["status"] != TaskStatusCompleted {
|
|
t.Errorf("entry = %v", got[0])
|
|
}
|
|
if got[0]["delegation_id"] == "" || got[0]["created_at"] == "" {
|
|
t.Errorf("entry is missing the fields needed to re-acquire a handle: %v", got[0])
|
|
}
|
|
}
|
|
|
|
// The case the whole action exists for. Deferring long work, clearing the
|
|
// session and coming back to ask for status is ordinary use; scoping by session
|
|
// key would return nothing exactly then.
|
|
func TestDelegateListSurvivesSessionReset(t *testing.T) {
|
|
tool, _ := newListTool([]store.SubagentTaskData{
|
|
delegationRow("chat-a", "session-before-reset", "brain", time.Unix(100, 0)),
|
|
})
|
|
|
|
// Same chat, a session that did not exist when the delegation was created.
|
|
ctx := WithToolSessionKey(listCtx("chat-a"), "session-after-reset")
|
|
got := decodeList(t, tool.executeListCompletions(ctx))
|
|
if len(got) != 1 {
|
|
t.Fatalf("listed %d entries after a session reset; the delegation is still "+
|
|
"in this chat and must remain recoverable", len(got))
|
|
}
|
|
}
|
|
|
|
// Without a chat there is nothing to scope to, and listing everything this agent
|
|
// ever did would cross the boundary the predicate exists to draw.
|
|
func TestDelegateListRefusesWithoutChat(t *testing.T) {
|
|
tool, s := newListTool([]store.SubagentTaskData{
|
|
delegationRow("chat-a", "session-1", "brain", time.Unix(100, 0)),
|
|
})
|
|
|
|
ctx := store.WithAgentID(store.WithTenantID(context.Background(), uuid.New()), uuid.New())
|
|
res := tool.executeListCompletions(ctx)
|
|
if res == nil || !res.IsError {
|
|
t.Fatalf("list without a chat returned %#v", res)
|
|
}
|
|
if s.listCalls != 0 {
|
|
t.Errorf("store was queried %d times despite having no chat to scope to", s.listCalls)
|
|
}
|
|
}
|
|
|
|
func TestDelegateListStopsAtItsLimit(t *testing.T) {
|
|
rows := make([]store.SubagentTaskData, 0, delegateListLimit+5)
|
|
for i := range delegateListLimit + 5 {
|
|
rows = append(rows, delegationRow("chat-a", "session-1", fmt.Sprintf("agent-%d", i), time.Unix(int64(i), 0)))
|
|
}
|
|
tool, _ := newListTool(rows)
|
|
|
|
if got := decodeList(t, tool.executeListCompletions(listCtx("chat-a"))); len(got) != delegateListLimit {
|
|
t.Fatalf("listed %d entries, want the cap of %d", len(got), delegateListLimit)
|
|
}
|
|
}
|