clean up of the codebase

This commit is contained in:
ari committed 2026-11-01 13:01:54 -05:00
1 parent 7822529a38
commit 0ac61b4ece
52 files changed
+2545 -2274

No files matched your search

File diff suppressed because it is too large. Load diff
+249
View File
@@ -0,0 +1,249 @@
package bot
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/slack-go/slack"
"slackerbot/internal/acp"
"slackerbot/internal/manager"
"slackerbot/internal/model"
"slackerbot/internal/state"
"slackerbot/internal/testutil"
"slackerbot/internal/testutil/clustertest"
)
func TestOwnership(t *testing.T) {
dm := incoming{user: "U42", channel: "D9", dm: true}
if id, kind := dm.owner(); id != "U42" || kind != model.OwnerUser {
t.Fatalf("DM should be owned by the user, got %s %s", id, kind)
}
ch := incoming{user: "U42", channel: "C7"}
if id, kind := ch.owner(); id != "C7" || kind != model.OwnerChannel {
t.Fatalf("channel message should be owned by the channel, got %s %s", id, kind)
}
other := incoming{user: "U99", channel: "C7"}
a, ka := ch.owner()
b, kb := other.owner()
if model.MachineName(a, ka) != model.MachineName(b, kb) || model.MachineName(a, ka) != "c-c7" {
t.Fatal("two people in one channel should share a container")
}
if model.MachineName("U42", model.OwnerUser) != "u-u42" || !model.IsOurs("u-u42") || !model.IsOurs("c-c7") || model.IsOurs("web") {
t.Fatal("machine naming is off")
}
}
func TestTitle(t *testing.T) {
if got := title(" fix the build\nplease"); got != "fix the build" {
t.Fatal(got)
}
if got := title(strings.Repeat("é", 80)); !strings.HasSuffix(got, "…") || len([]rune(got)) != 61 {
t.Fatal(got)
}
}
type fakeSlack struct {
mu sync.Mutex
msgs map[string]string
order []string
n int
}
func (f *fakeSlack) handler(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
f.mu.Lock()
defer f.mu.Unlock()
ts := r.Form.Get("ts")
if strings.HasSuffix(r.URL.Path, "chat.postMessage") {
f.n++
ts = "ts" + string(rune('0'+f.n))
f.order = append(f.order, ts)
}
f.msgs[ts] = r.Form.Get("text")
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "channel": "D1", "ts": ts, "text": f.msgs[ts]})
}
func TestStreamerSplitsLongReplies(t *testing.T) {
f := &fakeSlack{msgs: map[string]string{"ph": ""}, order: []string{"ph"}}
srv := httptest.NewServer(http.HandlerFunc(f.handler))
defer srv.Close()
api := slack.New("xoxb-test", slack.OptionAPIURL(srv.URL+"/"))
st := NewStreamer(api, "D1", "root", "ph")
line := strings.Repeat("x", 99) + "\n"
for i := 0; i < 80; i++ {
st.Update(acp.Update{Kind: "agent_message_chunk", Text: line})
}
st.Finish("end_turn", nil)
f.mu.Lock()
defer f.mu.Unlock()
if len(f.order) != 3 {
t.Fatalf("want 3 messages, got %d", len(f.order))
}
var all strings.Builder
for _, ts := range f.order {
if len(f.msgs[ts]) > slackMsgLimit {
t.Fatalf("message %s too long: %d", ts, len(f.msgs[ts]))
}
all.WriteString(f.msgs[ts])
}
if all.Len() != 8000 {
t.Fatalf("text lost or duplicated: %d chars", all.Len())
}
}
func TestMoveTarget(t *testing.T) {
b := &Bot{}
for in, want := range map[string]string{"": "", "auto": "", "Slave-1": "slave-1", "to node-b": "node-b"} {
if got, ok := b.moveTarget(in); !ok || got != want {
t.Fatalf("move %q = %q %v, want %q", in, got, ok, want)
}
}
if _, ok := b.moveTarget("the files into the build folder"); ok {
t.Fatal("a normal sentence should go to the agent")
}
}
type slackLog struct {
mu sync.Mutex
n int
text map[string]string
under map[string]string
order []string
}
func (s *slackLog) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
s.mu.Lock()
defer s.mu.Unlock()
ts := r.Form.Get("ts")
if strings.HasSuffix(r.URL.Path, "chat.postMessage") {
s.n++
ts = fmt.Sprintf("%d.0", s.n)
s.order = append(s.order, ts)
s.under[ts] = r.Form.Get("thread_ts")
}
if !strings.HasSuffix(r.URL.Path, "chat.getPermalink") {
s.text[ts] = r.Form.Get("text")
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "channel": "C1", "ts": ts, "permalink": "https://slack.example/" + ts})
}
func TestEveryMoveStartsAnAnnouncedThread(t *testing.T) {
c := clustertest.New(t)
c.AddOwner(t, testutil.HomeData(), false)
log := &slackLog{text: map[string]string{}, under: map[string]string{}}
srv := httptest.NewServer(log)
defer srv.Close()
b := &Bot{cfg: c.Cfg, store: c.Store, mgr: c.Mgr, api: slack.New("xoxb", slack.OptionAPIURL(srv.URL+"/")),
acps: map[string]*acp.ACP{}, busy: map[string]int{}}
b.moveFor(c.Ctx, "C1", "C1", "slave-1", "<@U1>", "100.0")
if _, err := c.Mgr.Migrate(c.Ctx, "C1", manager.MoveOptions{Target: "master"}); err != nil {
t.Fatal(err)
}
b.runMove(c.Ctx, "C1", "C1", manager.MoveOptions{}, "auto process (master was full), for <@U2>'s message", nil)
log.mu.Lock()
defer log.mu.Unlock()
var roots []string
for _, ts := range log.order {
if log.under[ts] == "" {
roots = append(roots, ts)
}
}
linked := 0
for ts, parent := range log.under {
if parent == "100.0" && strings.Contains(log.text[ts], "Follow the move here") {
linked++
}
}
if linked != 1 {
t.Fatalf("the thread where the move started should get one link to the move thread, got %d", linked)
}
if len(roots) != 2 {
t.Fatalf("want one new top-level message per move, got %d", len(roots))
}
checks := []string{"started by <@U1>: master → slave-1", "started by auto process (master was full), for <@U2>'s message"}
for i, root := range roots {
if !strings.Contains(log.text[root], checks[i]) || !strings.Contains(log.text[root], ":white_check_mark: done") {
t.Fatalf("root %d = %q", i, log.text[root])
}
replies := 0
for ts, parent := range log.under {
if parent == root {
replies++
if !strings.Contains(log.text[ts], "Moved from") {
t.Fatalf("progress reply = %q", log.text[ts])
}
}
}
if replies != 1 {
t.Fatalf("want progress in one thread reply, got %d", replies)
}
}
}
func TestManageCommandsInSlack(t *testing.T) {
log := &slackLog{text: map[string]string{}, under: map[string]string{}}
srv := httptest.NewServer(log)
defer srv.Close()
store, _ := state.Open(filepath.Join(t.TempDir(), "state.json"))
store.SeedPermissions(model.PermissionsConfig{Managers: []string{"UBOSS"}, Default: map[string][]string{"UBOSS": {"all"}}})
b := &Bot{store: store, api: slack.New("xoxb", slack.OptionAPIURL(srv.URL+"/"))}
ctx := context.Background()
say := func(user, text string) string {
m := incoming{user: user, channel: "C1", ts: "1.0", text: text}
if !b.command(ctx, m) {
return "(went to the agent)"
}
log.mu.Lock()
defer log.mu.Unlock()
return log.text[log.order[len(log.order)-1]]
}
if got := say("UANA", "grant <@UANA> all"); !strings.Contains(got, ":lock:") {
t.Fatalf("non-managers can't grant: %q", got)
}
if got := say("UBOSS", "grant <@UANA> move manage"); !strings.Contains(got, "<@UANA> can now: move, manage") {
t.Fatalf("manager grant: %q", got)
}
if got := say("UANA", "grant <@UCAL> scale"); !strings.Contains(got, "<@UCAL> can now: scale") {
t.Fatalf("channel manager grant: %q", got)
}
if got := say("UANA", "grant default <@UCAL> all"); !strings.Contains(got, ":lock:") {
t.Fatalf("channel managers can't touch the default list: %q", got)
}
if got := say("UANA", "managers add <@UCAL>"); !strings.Contains(got, ":lock:") {
t.Fatalf("only user managers add managers: %q", got)
}
if got := say("UBOSS", "managers remove <@UBOSS>"); !strings.Contains(got, "nobody able to manage") {
t.Fatalf("last manager guard: %q", got)
}
if got := say("UBOSS", "dm storage off"); !strings.Contains(got, "now turned off") {
t.Fatalf("dm toggle: %q", got)
}
if store.Permissions().Allowed(model.OwnerUser, "D1", "UX", model.ActStorage) {
t.Fatal("dm toggle not saved")
}
if got := say("UANA", "grant me access to the repo"); got != "(went to the agent)" {
t.Fatalf("plain sentence: %q", got)
}
if got := say("UANA", "permissions reset"); !strings.Contains(got, "default super-user list again") {
t.Fatalf("reset: %q", got)
}
if store.Permissions().Allowed(model.OwnerChannel, "C1", "UCAL", model.ActScale) {
t.Fatal("reset should drop the channel's own list")
}
}
+188
View File
@@ -0,0 +1,188 @@
package bot
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"slackerbot/internal/commands"
"slackerbot/internal/model"
)
func mentions(users []string) string {
out := make([]string, len(users))
for i, u := range users {
out[i] = "<@" + u + ">"
}
return strings.Join(out, ", ")
}
func actionList(actions []model.Action) string {
if len(actions) == 0 {
return "nothing"
}
names := make([]string, len(actions))
for i, a := range actions {
names[i] = string(a)
}
return strings.Join(names, ", ")
}
// manageCommand handles permission changes. It returns false if the message
// isn't one of these commands, so it goes to the agent.
func (b *Bot) manageCommand(ctx context.Context, m incoming, verb, args string) bool {
_, kind := m.owner()
p := b.store.Permissions()
reply := func(text string) bool {
b.say(ctx, m.channel, "", text)
return true
}
denied := func(global bool) bool {
who := "user managers"
if !global {
who = "user managers and people with *manage* permission here"
}
names := make([]string, len(p.Managers))
for i, u := range p.Managers {
names[i] = b.displayName(ctx, u)
}
return reply(fmt.Sprintf(":lock: Only %s can do that. User managers: %s.", who, strings.Join(names, ", ")))
}
update := func(change func(p *model.PermissionsConfig) error) error {
return b.store.UpdatePermissions(change)
}
switch verb {
case "grant", "revoke":
g, err := commands.ParseGrant(args)
if errors.Is(err, commands.ErrNotCommand) {
return false
}
if err != nil {
return reply(":warning: " + err.Error() + ". Try `grant @alice move scale` or `revoke @alice`.")
}
channel := m.channel
if g.ToDefault {
channel = ""
if !p.IsManager(m.user) {
return denied(true)
}
} else {
if kind == model.OwnerUser {
return reply("DMs don't have a super-user list. User managers can switch DM permissions with `dm <permission> on|off`.")
}
if !p.CanManage(channel, m.user) {
return denied(false)
}
}
if verb == "grant" && len(g.Actions) == 0 {
return reply(":warning: Say what to grant, like `grant @alice move scale` (or `all`, or `manage`).")
}
if slices.Contains(g.Actions, model.ActManage) && !g.ToDefault && !p.CanManage(channel, m.user) {
return denied(false)
}
err = update(func(p *model.PermissionsConfig) error {
if verb == "grant" {
p.Grant(channel, g.Users, g.Actions)
} else {
p.Revoke(channel, g.Users, g.Actions)
}
return nil
})
if err != nil {
return reply(":warning: " + err.Error())
}
where := "in this channel"
if g.ToDefault {
where = "in every channel that uses the default list"
}
after := b.store.Permissions()
var lines []string
for _, u := range g.Users {
var actions []model.Action
if g.ToDefault {
list := after.Default
for _, a := range model.GrantActions {
if model.Grants(list[u], a) {
actions = append(actions, a)
}
}
} else {
actions = after.ActionsFor(channel, u)
}
lines = append(lines, fmt.Sprintf("• <@%s> can now: %s", u, actionList(actions)))
}
return reply(fmt.Sprintf("Done, %s:\n%s", where, strings.Join(lines, "\n")))
case "dm":
words := strings.Fields(strings.ToLower(args))
if len(words) != 2 || !slices.Contains(model.AllActions, model.Action(words[0])) {
return false
}
on, ok := commands.ParseToggle(words[1])
if !ok {
return false
}
if !p.IsManager(m.user) {
return denied(true)
}
if err := update(func(p *model.PermissionsConfig) error { p.DM[words[0]] = on; return nil }); err != nil {
return reply(":warning: " + err.Error())
}
state := "turned off"
if on {
state = "allowed"
}
return reply(fmt.Sprintf("Done. Changing *%s* on your own DM container is now %s for everyone.", words[0], state))
case "managers":
words := strings.Fields(args)
if len(words) == 0 {
return reply("*User managers:* " + mentions(p.Managers))
}
op := strings.ToLower(words[0])
g, err := commands.ParseGrant(strings.Join(words[1:], " "))
if (op != "add" && op != "remove") || err != nil || len(g.Actions) > 0 {
return false
}
if !p.IsManager(m.user) {
return denied(true)
}
err = update(func(p *model.PermissionsConfig) error {
if op == "add" {
p.AddManagers(g.Users)
return nil
}
return p.RemoveManagers(g.Users)
})
if errors.Is(err, model.ErrLastManager) {
return reply(":warning: That would leave nobody able to manage permissions. Add someone else first.")
}
if err != nil {
return reply(":warning: " + err.Error())
}
verbText := "are now user managers"
if op == "remove" {
verbText = "are no longer user managers"
}
return reply(fmt.Sprintf("Done. %s %s.", mentions(g.Users), verbText))
case "permissions":
if strings.ToLower(args) != "reset" {
return false
}
if kind == model.OwnerUser {
return reply("DMs don't have a super-user list to reset.")
}
if !p.CanManage(m.channel, m.user) {
return denied(false)
}
if err := update(func(p *model.PermissionsConfig) error { delete(p.Channels, m.channel); return nil }); err != nil {
return reply(":warning: " + err.Error())
}
return reply("Done. This channel uses the default super-user list again.")
}
return false
}
+150
View File
@@ -0,0 +1,150 @@
package bot
import (
"context"
"log"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/slack-go/slack"
"slackerbot/internal/acp"
)
const (
slackMsgLimit = 3500
flushEvery = 1500 * time.Millisecond // under Slack's edit rate limit
)
type Streamer struct {
api *slack.Client
channel string
thread string
mu sync.Mutex
full strings.Builder
dirty bool
// Only the flush loop touches these.
ts string
offset int
quit chan struct{}
done chan struct{}
}
func NewStreamer(api *slack.Client, channel, thread, placeholderTS string) *Streamer {
s := &Streamer{api: api, channel: channel, thread: thread, ts: placeholderTS,
quit: make(chan struct{}), done: make(chan struct{})}
go s.loop()
return s
}
func (s *Streamer) Update(u acp.Update) {
s.mu.Lock()
defer s.mu.Unlock()
switch u.Kind {
case "agent_message_chunk":
s.full.WriteString(u.Text)
case "tool_call":
if u.Title == "" {
return
}
if t := s.full.String(); t != "" && !strings.HasSuffix(t, "\n") {
s.full.WriteString("\n")
}
s.full.WriteString("> :wrench: " + u.Title + "\n")
default:
return
}
s.dirty = true
}
func (s *Streamer) Finish(stopReason string, err error) {
close(s.quit)
<-s.done
s.mu.Lock()
note := ""
switch {
case err != nil:
note = ":warning: " + err.Error()
case stopReason == "max_tokens", stopReason == "max_turn_requests":
note = "_(stopped: hit the agent's length limit. Reply to keep going.)_"
case stopReason == "refusal":
note = "_(the agent declined this one)_"
case stopReason == "cancelled":
note = "_(cancelled)_"
}
if note != "" {
if s.full.Len() > 0 {
s.full.WriteString("\n\n")
}
s.full.WriteString(note)
}
if s.full.Len() == 0 {
s.full.WriteString("_(no reply)_")
}
s.dirty = true
s.mu.Unlock()
s.flush()
}
func (s *Streamer) loop() {
defer close(s.done)
t := time.NewTicker(flushEvery)
defer t.Stop()
for {
select {
case <-s.quit:
return
case <-t.C:
s.flush()
}
}
}
func (s *Streamer) flush() {
s.mu.Lock()
if !s.dirty {
s.mu.Unlock()
return
}
s.dirty = false
text := s.full.String()[s.offset:]
s.mu.Unlock()
ctx := context.Background()
for len(text) > slackMsgLimit {
cut := strings.LastIndex(text[:slackMsgLimit], "\n")
if cut < slackMsgLimit/2 {
cut = slackMsgLimit
for cut > 0 && !utf8.RuneStart(text[cut]) {
cut--
}
}
s.edit(ctx, text[:cut])
_, ts, err := s.api.PostMessageContext(ctx, s.channel,
slack.MsgOptionText("…", false), slack.MsgOptionTS(s.thread))
if err != nil {
log.Printf("slack post: %v", err)
return
}
s.ts = ts
s.offset += cut
text = text[cut:]
}
s.edit(ctx, text)
}
func (s *Streamer) edit(ctx context.Context, text string) {
if strings.TrimSpace(text) == "" {
text = "…"
}
if _, _, _, err := s.api.UpdateMessageContext(ctx, s.channel, s.ts, slack.MsgOptionText(text, false)); err != nil {
log.Printf("slack update: %v", err)
}
}