Merge branch 'worktree-agent-a717651aa412e3b7c'

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 01:00:02 +00:00
60 changed files with 4265 additions and 222 deletions
+210
View File
@@ -0,0 +1,210 @@
package server
import (
"context"
"errors"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf16"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Scoped chat search ("find in chat"): every occurrence of a query in one
// chat's message text, newest message first, paged. A client uses it to count
// and reach matches in history it has not loaded yet.
const (
// scopedChatPageMessages is how many messages one broker read returns.
scopedChatPageMessages = 200
// scopedChatMaxMessages bounds the messages one scoped request reads;
// a longer history continues through NextCursor.
scopedChatMaxMessages = 2000
)
// scopedChatBudget bounds how long one scoped request reads history before it
// replies with what it found and a cursor. A variable so a test can shorten it.
var scopedChatBudget = 2 * time.Second
// scopedChatSession returns the session id a chat search's Scope names, or ""
// when the request is not scoped.
func scopedChatSession(req protocol.SearchRequest) string {
scope := strings.TrimSpace(req.Scope)
if scope == "" {
return ""
}
return strings.TrimPrefix(scope, "chat:")
}
// scopedCursor is where a scoped search resumes: the broker's history cursor
// for a page (empty for the newest) and how many of that page's newest
// messages were already searched. It travels as "<skip>|<history cursor>"; a
// cursor without the separator is a chat_messages next_cursor.
type scopedCursor struct {
history string
skip int
}
func parseScopedCursor(value string) scopedCursor {
skip, history, found := strings.Cut(value, "|")
if !found {
return scopedCursor{history: value}
}
n, err := strconv.Atoi(skip)
if err != nil || n < 0 {
return scopedCursor{history: history}
}
return scopedCursor{history: history, skip: n}
}
func (c scopedCursor) String() string { return strconv.Itoa(c.skip) + "|" + c.history }
// searchChatScoped answers a scoped chat search. Results hold one hit per
// occurrence; a message's occurrences are never split across replies, so a
// reply may exceed the cap by one message's worth.
func searchChatScoped(ctx context.Context, req protocol.SearchRequest, broker chatBroker) (*protocol.SearchResponse, error) {
sessionID := scopedChatSession(req)
if !validChatSessionID(sessionID) {
return nil, errors.New("a valid chat session id is required in scope chat:<id>")
}
if broker == nil {
return nil, errors.New("chat is not configured on this server")
}
response := &protocol.SearchResponse{
Query: req.Query,
Kind: protocol.SearchKindChat,
Results: []protocol.SearchResult{},
Cap: chatSearchLimit(req.Limit),
ScanBoundBytes: protocol.SearchMaxScanBytes,
}
// Find matches the query as typed, spaces included, like the client's
// own matching of the loaded transcript.
query := []rune(req.Query)
if strings.TrimSpace(req.Query) == "" {
return response, nil
}
ctx, cancel := context.WithTimeout(ctx, scopedChatBudget)
defer cancel()
cursor := parseScopedCursor(req.Cursor)
for {
page, err := broker.Messages(ctx, sessionID, scopedChatPageMessages, cursor.history)
if err != nil {
if ctx.Err() != nil && response.ScannedMessages > 0 {
// Out of time: what was found stands; the client continues.
response.Truncated = true
response.NextCursor = cursor.String()
return response, nil
}
return nil, err
}
messages := page.Messages
for index := len(messages) - 1 - cursor.skip; index >= 0; index-- {
message := messages[index]
response.Results = append(response.Results, scopedMessageHits(sessionID, message, query, req.CaseSensitive)...)
response.ScannedMessages++
cursor.skip++
done := index == 0 && (!page.HasMore || page.NextCursor == "")
if done {
return response, nil
}
if len(response.Results) >= response.Cap ||
response.ScannedMessages >= scopedChatMaxMessages || ctx.Err() != nil {
response.Truncated = true
if index == 0 {
cursor = scopedCursor{history: page.NextCursor}
}
response.NextCursor = cursor.String()
return response, nil
}
}
if !page.HasMore || page.NextCursor == "" {
return response, nil
}
cursor = scopedCursor{history: page.NextCursor}
}
}
// scopedMessageHits is one hit per occurrence of query in message's text parts.
func scopedMessageHits(sessionID string, message protocol.ChatMessage, query []rune, caseSensitive bool) []protocol.SearchResult {
var hits []protocol.SearchResult
for partIndex, part := range message.Parts {
if part.Type != protocol.ChatPartText || part.Text == "" {
continue
}
for _, match := range runeMatches([]rune(part.Text), query, caseSensitive) {
hits = append(hits, protocol.SearchResult{
Kind: protocol.SearchKindChat,
Target: protocol.SearchChatTarget(sessionID),
Score: chatScoreMessage,
MatchedField: "message",
Chat: &protocol.SearchChat{
SessionID: sessionID,
MessageID: message.ID,
Role: message.Role,
Snippet: protocol.SearchSnippet(part.Text, string(query)),
Part: partIndex,
Offset: match.offset,
Length: match.length,
},
})
}
}
return hits
}
type runeMatch struct{ offset, length int }
// runeMatches finds the non-overlapping occurrences of query in text, folding
// case unless caseSensitive, and reports each in UTF-16 code units.
func runeMatches(text, query []rune, caseSensitive bool) []runeMatch {
if len(query) == 0 || len(query) > len(text) {
return nil
}
var matches []runeMatch
units := 0 // UTF-16 units before text[i]
for i := 0; i <= len(text)-len(query); {
if runesEqual(text[i:i+len(query)], query, caseSensitive) {
length := utf16Len(text[i : i+len(query)])
matches = append(matches, runeMatch{offset: units, length: length})
units += length
i += len(query)
continue
}
units += utf16.RuneLen(text[i])
i++
}
return matches
}
func runesEqual(a, b []rune, caseSensitive bool) bool {
for i := range a {
if a[i] == b[i] {
continue
}
if caseSensitive || !foldEqual(a[i], b[i]) {
return false
}
}
return true
}
func foldEqual(a, b rune) bool {
if unicode.ToLower(a) == unicode.ToLower(b) {
return true
}
for folded := unicode.SimpleFold(a); folded != a; folded = unicode.SimpleFold(folded) {
if folded == b {
return true
}
}
return false
}
func utf16Len(runes []rune) int {
n := 0
for _, r := range runes {
n += utf16.RuneLen(r)
}
return n
}
+147
View File
@@ -0,0 +1,147 @@
package server
import (
"context"
"fmt"
"strconv"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// scopedHistoryChat serves one session's history oldest first in pages of the
// requested size; a cursor is the index one past the page's oldest message.
type scopedHistoryChat struct {
*fakeChat
messages []protocol.ChatMessage
}
func (c *scopedHistoryChat) Messages(_ context.Context, _ string, limit int, cursor string) (protocol.ChatHistoryPage, error) {
end := len(c.messages)
if cursor != "" {
n, err := strconv.Atoi(cursor)
if err != nil {
return protocol.ChatHistoryPage{}, err
}
end = n
}
start := max(end-limit, 0)
page := protocol.ChatHistoryPage{Messages: c.messages[start:end]}
if start > 0 {
page.HasMore = true
page.NextCursor = strconv.Itoa(start)
}
return page, nil
}
func pagedHistory(n int) []protocol.ChatMessage {
messages := make([]protocol.ChatMessage, n)
for i := range messages {
text := fmt.Sprintf("message %d", i)
if i%10 == 0 {
text = fmt.Sprintf("Needle %d and needle again", i)
}
messages[i] = chatText(fmt.Sprintf("m%d", i), protocol.ChatRoleAssistant, text)
}
return messages
}
func TestScopedChatSearchReturnsEveryOccurrenceNewestFirst(t *testing.T) {
broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)}
response, err := searchChatScoped(context.Background(), protocol.SearchRequest{
Query: "needle", Kind: protocol.SearchKindChat, Scope: protocol.SearchChatScope("ses_a"), Limit: 200,
}, broker)
if err != nil {
t.Fatal(err)
}
if len(response.Results) != 90 || response.NextCursor != "" || response.Truncated {
t.Fatalf("results=%d cursor=%q truncated=%v", len(response.Results), response.NextCursor, response.Truncated)
}
first := response.Results[0].Chat
if first.MessageID != "m440" || first.Offset != 0 || first.Length != 6 {
t.Fatalf("first hit = %+v", first)
}
second := response.Results[1].Chat
if second.MessageID != "m440" || second.Offset != len("Needle 440 and ") {
t.Fatalf("second hit = %+v", second)
}
if last := response.Results[89].Chat; last.MessageID != "m0" {
t.Fatalf("last hit = %+v", last)
}
}
func TestScopedChatSearchPagesThroughCursor(t *testing.T) {
broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)}
request := protocol.SearchRequest{Query: "needle", Kind: protocol.SearchKindChat, Scope: "chat:ses_a", Limit: 7}
var ids []string
for pages := 0; ; pages++ {
if pages > 50 {
t.Fatal("cursor never ended")
}
response, err := searchChatScoped(context.Background(), request, broker)
if err != nil {
t.Fatal(err)
}
for _, hit := range response.Results {
ids = append(ids, hit.Chat.MessageID)
}
if response.NextCursor == "" {
break
}
request.Cursor = response.NextCursor
}
if len(ids) != 90 {
t.Fatalf("hits across pages = %d", len(ids))
}
seen := map[string]int{}
for _, id := range ids {
seen[id]++
}
if len(seen) != 45 || seen["m0"] != 2 || seen["m440"] != 2 {
t.Fatalf("each needle message twice, got %v", seen)
}
}
func TestScopedChatSearchStartsAtHistoryCursorAndMatchesCase(t *testing.T) {
broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)}
response, err := searchChatScoped(context.Background(), protocol.SearchRequest{
Query: "Needle", Kind: protocol.SearchKindChat, Scope: "chat:ses_a", Cursor: "250", CaseSensitive: true,
}, broker)
if err != nil {
t.Fatal(err)
}
if len(response.Results) != 25 || response.Results[0].Chat.MessageID != "m240" {
t.Fatalf("results=%d first=%+v", len(response.Results), response.Results[0].Chat)
}
}
func TestScopedChatSearchCountsUTF16Offsets(t *testing.T) {
matches := runeMatches([]rune("😀 Ünïcode ünïcode"), []rune("ÜNÏ"), false)
if len(matches) != 2 || matches[0].offset != 3 || matches[1].offset != 11 || matches[0].length != 3 {
t.Fatalf("matches = %+v", matches)
}
if got := runeMatches([]rune("aaaa"), []rune("aa"), true); len(got) != 2 {
t.Fatalf("overlapping matches counted: %+v", got)
}
}
func TestScopedChatSearchRejectsAnInvalidScope(t *testing.T) {
broker := &scopedHistoryChat{fakeChat: scriptedChat()}
if _, err := searchChatScoped(context.Background(), protocol.SearchRequest{Query: "x", Scope: "chat:../etc"}, broker); err == nil {
t.Fatal("invalid scope accepted")
}
}
func TestScopedChatSearchOverTheSocket(t *testing.T) {
broker := &transcriptChat{fakeChat: scriptedChat(), pages: map[string][]protocol.ChatMessage{}}
ctx, conn := chatSearchFixture(t, broker)
writeChat(t, ctx, conn, protocol.Message{Type: protocol.Search, ID: "scoped", Search: &protocol.SearchRequest{
Query: "flaky", Kind: protocol.SearchKindChat, Scope: "chat:ses_text",
}})
reply := readReply(t, ctx, conn, "scoped")
// transcriptChat refuses any page size but the global search's, so the
// scoped search's own read comes back as an error reply.
if reply.Type != protocol.Error {
t.Fatalf("reply = %+v", reply)
}
}
+7
View File
@@ -40,6 +40,13 @@ func isChatSearch(request protocol.Message) bool {
// chatSearchReply answers one kind=chat search request.
func chatSearchReply(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry) protocol.Message {
if scopedChatSession(*request.Search) != "" {
response, err := searchChatScoped(ctx, *request.Search, broker)
if err != nil {
return protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}
}
return protocol.Message{Type: protocol.SearchResults, ID: request.ID, SearchResults: response}
}
if registry == nil {
return protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat search unavailable: operator session registry is not configured on this server"}
}
+11 -3
View File
@@ -286,8 +286,11 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
// A chat search runs beside the read loop so its transcript readback
// never delays the run search sent with it; a newer one cancels the
// previous, whose reply the client would discard as stale anyway.
// A newer chat search replaces an older one of the same mode: the
// chat list's search and a find-in-chat search never cancel each other.
cancelChatSearch := func() {}
defer func() { cancelChatSearch() }()
cancelScopedChatSearch := func() {}
defer func() { cancelChatSearch(); cancelScopedChatSearch() }()
// Keystrokes and sizes take their own lane (terminal_lane.go), so
// they never wait behind a slow request read before them. The lane
// is drained before the deferred detaches above run.
@@ -313,9 +316,14 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
continue
}
if isChatSearch(request) {
cancelChatSearch()
searchCtx, cancel := context.WithCancel(connCtx)
cancelChatSearch = cancel
if scopedChatSession(*request.Search) != "" {
cancelScopedChatSearch()
cancelScopedChatSearch = cancel
} else {
cancelChatSearch()
cancelChatSearch = cancel
}
go func(request protocol.Message) {
defer cancel()
_ = write(chatSearchReply(searchCtx, request, options.Chat, registry))