feat(daemon): identity-scoped isolation + gateway session titles and /delete

Multi-identity daemon isolation:
- Split runIdentities into per-identity poll loops plus one shared
  maintenance-and-drain loop, so reconcilePRs and storage cleanup run in
  multi-identity mode and the global max_concurrency / per-repo
  serialization holds across identities.
- Make the poll path identity-aware: each identity polls with its own
  forge client, bot user, label, trigger, and ack reaction.
- Make allowConcurrentFor task-based and identity-aware via repoFor.
- Roll back storage mounts when container acquisition fails; log
  Store.Update failures after branch set.

Container-mode RPC identity routing:
- forgerpc/worktreerpc gain identity-scoped subjects (SubjectFor,
  RegisterFor) and identity-carrying clients.
- registerTaskRPCServers registers one server pair per identity (plus
  root), so a container-mode task owned by a non-root identity is served
  by its own forge client and worktree manager.

Gateway/Telegram:
- LLM-proposed session titles generated in the background after turns
  (TitleGenerator + chatTitleGenerator), persisted by the gateway.
- /delete session command with prefix guard and tracker forget.
- Shared session display helpers (shortSessionID, sessionDisplayTitle,
  resolveSessionRef).
This commit is contained in:
sam committed 2026-08-08 01:32:35 +10:00
1 parent 7e896c9411
commit 1081a6c3ed
20 files changed
+1860 -209

No files matched your search

+5 -5
View File
@@ -10,13 +10,13 @@ import (
natsio "github.com/nats-io/nats.go"
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/domain/workflow/skillbuild"
"github.com/samcharles93/archie-core/internal/domain/workflow/wfeval"
"github.com/samcharles93/archie-core/internal/forgerpc"
"github.com/samcharles93/archie-core/internal/storage"
"github.com/samcharles93/archie-core/internal/storerpc"
"github.com/samcharles93/archie-core/internal/taskrun"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/domain/workflow/skillbuild"
"github.com/samcharles93/archie-core/internal/domain/workflow/wfeval"
"github.com/samcharles93/archie-core/internal/worktree"
"github.com/samcharles93/archie-core/internal/worktreerpc"
)
@@ -83,7 +83,7 @@ func runTask(ctx context.Context, req taskrun.Request, nc *natsio.Conn, newRunne
wf := workflow.Route(req.Task, registry)
trees := &hybridTrees{
push: &worktreerpc.Client{Conn: nc, Timeout: rpcTimeout},
push: &worktreerpc.Client{Conn: nc, Timeout: rpcTimeout, Identity: req.Task.Identity},
local: &worktree.Manager{WorkDir: workDir},
owner: req.Task.Owner,
repo: req.Task.Repo,
@@ -115,7 +115,7 @@ func runTask(ctx context.Context, req taskrun.Request, nc *natsio.Conn, newRunne
Task: req.Task,
Repo: req.Repo,
Cfg: req.Cfg.ToConfig(),
Forge: &forgerpc.Client{Conn: nc, Timeout: rpcTimeout},
Forge: &forgerpc.Client{Conn: nc, Timeout: rpcTimeout, Identity: req.Task.Identity},
Store: &storerpc.Client{Conn: nc, Timeout: rpcTimeout},
Trees: trees,
Agent: agent,
+72 -22
View File
@@ -32,6 +32,8 @@ import (
"github.com/samcharles93/archie-core/internal/container"
"github.com/samcharles93/archie-core/internal/daemon"
"github.com/samcharles93/archie-core/internal/domain/curator"
"github.com/samcharles93/archie-core/internal/domain/workflow/skillbuild"
"github.com/samcharles93/archie-core/internal/domain/workflow/wfeval"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/forge"
@@ -59,8 +61,6 @@ import (
memorytoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/memory"
"github.com/samcharles93/archie-core/internal/tools/webfetch"
"github.com/samcharles93/archie-core/internal/webui"
"github.com/samcharles93/archie-core/internal/domain/workflow/skillbuild"
"github.com/samcharles93/archie-core/internal/domain/workflow/wfeval"
"github.com/samcharles93/archie-core/internal/worktree"
"github.com/samcharles93/archie-core/internal/worktreerpc"
)
@@ -478,6 +478,8 @@ func run() int {
Bus: bus, Log: log,
}
webRouter.LLM, webRouter.LLMStream = makeChatLLMResponder("web", webSetup, chatSessionStore, webRouter)
webRouter.Titles = newChatTitleGenerator(webSetup)
webRouter.Log = log
web.Chat = &webui.ChatService{
Router: webRouter, Sessions: chatSessionStore,
Turns: gateway.NewTurns(log),
@@ -683,7 +685,7 @@ func run() int {
log.Error("nats connection unavailable for task RPC", "err", err)
return 1
}
unsubscribe, err := registerTaskRPCServers(coreConn, st, forgeClient, trees, log)
unsubscribe, err := registerTaskRPCServers(coreConn, st, forgeClient, trees, identityRunners, log)
if err != nil {
log.Error("task RPC server registration failed", "err", err)
return 1
@@ -1088,34 +1090,82 @@ func executionProviders(cfg config.Config) map[string]agentexec.Provider {
// registerTaskRPCServers subscribes the storerpc/forgerpc/worktreerpc
// handlers on nc so an archie-agent container (which holds no DB
// connection, forge token, or push credential) can proxy those operations
// back to archied. The returned func unsubscribes all three.
func registerTaskRPCServers(nc *natsio.Conn, st store.TaskStore, forgeClient forge.Forge, trees *worktree.Manager, log *slog.Logger) (unsubscribe func(), err error) {
// back to archied. The returned func unsubscribes all of them.
//
// The store is shared across identities, so storerpc registers once on its
// root subjects. Forge and worktree are identity-scoped: the root servers
// answer the root (identity-less) subjects for single-identity deployments
// and root-owned tasks, and one server pair per identity answers that
// identity's scoped subjects so a container-mode task owned by a non-root
// identity has its RPC calls served by its own forge client and worktree
// manager.
func registerTaskRPCServers(nc *natsio.Conn, st store.TaskStore, forgeClient forge.Forge, trees *worktree.Manager, identities []*daemon.IdentityRunner, log *slog.Logger) (unsubscribe func(), err error) {
unsubs := make([]func(), 0, 3+2*len(identities))
unsubAll := func() {
for _, u := range unsubs {
u()
}
}
storeServer := &storerpc.Server{Store: st, Log: log}
unsubStore, err := storeServer.Register(nc)
u, err := storeServer.Register(nc)
if err != nil {
return nil, fmt.Errorf("register storerpc: %w", err)
}
unsubs = append(unsubs, u)
forgeServer := &forgerpc.Server{Forge: forgeClient, Log: log}
unsubForge, err := forgeServer.Register(nc)
if err != nil {
unsubStore()
return nil, fmt.Errorf("register forgerpc: %w", err)
registerForge := func(fg forge.Forge, identity string) error {
srv := &forgerpc.Server{Forge: fg, Log: log.With("rpc_identity", identity)}
u, err := srv.RegisterFor(nc, identity)
if err != nil {
return fmt.Errorf("register forgerpc%s: %w", identitySuffix(identity), err)
}
unsubs = append(unsubs, u)
return nil
}
registerTrees := func(mgr *worktree.Manager, identity string) error {
srv := &worktreerpc.Server{Trees: mgr, Log: log.With("rpc_identity", identity)}
u, err := srv.RegisterFor(nc, identity)
if err != nil {
return fmt.Errorf("register worktreerpc%s: %w", identitySuffix(identity), err)
}
unsubs = append(unsubs, u)
return nil
}
treesServer := &worktreerpc.Server{Trees: trees, Log: log}
unsubTrees, err := treesServer.Register(nc)
if err != nil {
unsubStore()
unsubForge()
return nil, fmt.Errorf("register worktreerpc: %w", err)
// Root (identity-less) forge and worktree servers.
if err := registerForge(forgeClient, ""); err != nil {
unsubAll()
return nil, err
}
if err := registerTrees(trees, ""); err != nil {
unsubAll()
return nil, err
}
return func() {
unsubStore()
unsubForge()
unsubTrees()
}, nil
// One forge/worktree server pair per identity, on identity-scoped
// subjects.
for _, id := range identities {
if err := registerForge(id.Forge, id.Name); err != nil {
unsubAll()
return nil, err
}
if err := registerTrees(id.Trees, id.Name); err != nil {
unsubAll()
return nil, err
}
}
return unsubAll, nil
}
// identitySuffix renders a log suffix for an identity-scoped registration,
// empty for the root set.
func identitySuffix(identity string) string {
if identity == "" {
return ""
}
return " (" + identity + ")"
}
func configuredNATSToken(cfg config.NATSConfig, getenv func(string) string) (string, error) {
+103 -1
View File
@@ -18,6 +18,7 @@ import (
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/daemon"
"github.com/samcharles93/archie-core/internal/forge"
"github.com/samcharles93/archie-core/internal/forgerpc"
"github.com/samcharles93/archie-core/internal/gateway"
@@ -573,7 +574,7 @@ func TestRegisterTaskRPCServersReachableFromClient(t *testing.T) {
trees := &worktree.Manager{WorkDir: t.TempDir()}
log := slog.New(slog.DiscardHandler)
unsubscribe, err := registerTaskRPCServers(serverConn, st, stubForge{}, trees, log)
unsubscribe, err := registerTaskRPCServers(serverConn, st, stubForge{}, trees, nil, log)
if err != nil {
t.Fatalf("registerTaskRPCServers: %v", err)
}
@@ -612,6 +613,107 @@ func TestRegisterTaskRPCServersReachableFromClient(t *testing.T) {
}
}
// identityForge records which forge instance served a CloseIssue call, so
// tests can prove identity-scoped RPC routing reaches the right forge.
type identityForge struct {
closes int
}
func (*identityForge) Comment(context.Context, string, string, int, string) (int64, error) {
return 1, nil
}
func (f *identityForge) CloseIssue(context.Context, string, string, int, string) error {
f.closes++
return nil
}
func (*identityForge) CreatePR(context.Context, string, string, string, string, string, string) (int, error) {
return 1, nil
}
func (*identityForge) SetStateLabel(context.Context, string, string, int, string, []string) {}
func (*identityForge) LinkBranch(context.Context, string, string, int, string) error { return nil }
func (*identityForge) AcceptInvitations(context.Context) error { panic("unexpected") }
func (*identityForge) AssignedIssues(context.Context, string, string, string) ([]forge.Issue, error) {
panic("unexpected")
}
func (*identityForge) IssuesWithLabel(context.Context, string, string, string) ([]forge.Issue, error) {
panic("unexpected")
}
func (*identityForge) RepliesAfter(context.Context, string, string, int, int64, string) ([]forge.Reply, error) {
panic("unexpected")
}
func (*identityForge) PRState(context.Context, string, string, int) (string, error) {
panic("unexpected")
}
func (*identityForge) CreateIssue(context.Context, string, string, string, string, []string) (int, error) {
panic("unexpected")
}
func (*identityForge) React(context.Context, string, string, int, string) error { panic("unexpected") }
func (*identityForge) VerifyPush(context.Context, string, string) error { panic("unexpected") }
// A container-mode task owned by a non-root identity must have its RPC
// calls served by that identity's own forge client, never the root's.
// Before identity-scoped subjects existed, the single server set was wired
// to the root d.Forge/d.Trees, so one identity's agent could act through
// another identity's credential.
func TestRegisterTaskRPCServersRoutesIdentityScopedCalls(t *testing.T) {
srv := startEmbeddedNATS(t)
serverConn, err := natsio.Connect(srv.ClientURL())
if err != nil {
t.Fatalf("nats connect: %v", err)
}
t.Cleanup(serverConn.Close)
st := store.OpenTest(t)
rootForge := &identityForge{}
archieForge := &identityForge{}
rootTrees := &worktree.Manager{WorkDir: t.TempDir()}
archieTrees := &worktree.Manager{WorkDir: t.TempDir()}
identities := []*daemon.IdentityRunner{
{Name: "archie", Forge: archieForge, Trees: archieTrees},
}
unsubscribe, err := registerTaskRPCServers(serverConn, st, rootForge, rootTrees, identities, slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("registerTaskRPCServers: %v", err)
}
t.Cleanup(unsubscribe)
clientConn, err := natsio.Connect(srv.ClientURL())
if err != nil {
t.Fatalf("nats connect: %v", err)
}
t.Cleanup(clientConn.Close)
ctx := context.Background()
// An identity-scoped client must reach archie's forge, not the root's.
archieClient := &forgerpc.Client{Conn: clientConn, Timeout: 2 * time.Second, Identity: "archie"}
if err := archieClient.CloseIssue(ctx, "acme", "shared", 1, "done"); err != nil {
t.Fatalf("identity-scoped CloseIssue: %v", err)
}
if archieForge.closes != 1 {
t.Fatalf("identity forge closes = %d, want 1", archieForge.closes)
}
if rootForge.closes != 0 {
t.Fatalf("root forge closes = %d, want 0 (identity call leaked to root)", rootForge.closes)
}
// The root (identity-less) client must reach the root forge.
rootClient := &forgerpc.Client{Conn: clientConn, Timeout: 2 * time.Second}
if err := rootClient.CloseIssue(ctx, "acme", "shared", 2, "done"); err != nil {
t.Fatalf("root-scoped CloseIssue: %v", err)
}
if rootForge.closes != 1 {
t.Fatalf("root forge closes = %d, want 1", rootForge.closes)
}
}
func TestConfiguredNATSToken(t *testing.T) {
t.Run("anonymous when token env is not configured", func(t *testing.T) {
token, err := configuredNATSToken(config.NATSConfig{}, func(string) string {
+44
View File
@@ -163,6 +163,8 @@ func buildTelegramRouter(tg *telegram.Gateway, s telegramSetup, sessionStore gat
router.Models = s.ChatModels
router.Updates = s.Updates
router.InitSessions(sessionStore)
router.Titles = newChatTitleGenerator(s)
router.Log = s.Log
configureTaskCommands(router, s.ChatTasks, s.ChatController, s.DefaultChatIdentity)
router.LLM, router.LLMStream = makeChatLLMResponder(tg.Name(), s, sessionStore, router)
@@ -305,3 +307,45 @@ func sendChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, o
}
return sb.String(), nil
}
// chatTitleGenerator proposes session titles through the chat model. It
// is a pure proposal: it persists nothing, so a failed or slow title
// call can never corrupt conversation history or fail the turn. The
// gateway bounds the call with its own timeout; errors leave the session
// untitled and are logged here.
type chatTitleGenerator struct {
log *slog.Logger
llm *runtime.Runtime
chatModels gateway.ModelManager
}
// newChatTitleGenerator wires an LLM-backed title generator for a chat
// setup, or nil when no model is available. Title generation is optional
// everywhere, so every caller tolerates nil.
func newChatTitleGenerator(s telegramSetup) gateway.TitleGenerator {
if s.LLM == nil || s.ChatModels == nil {
return nil
}
return &chatTitleGenerator{log: s.Log, llm: s.LLM, chatModels: s.ChatModels}
}
func (g *chatTitleGenerator) GenerateTitle(ctx context.Context, sessionID, firstMessage string) (string, error) {
messages := []chat.Message{
{Role: chat.RoleSystem, Content: gateway.TitleGenerationSystemPrompt},
{Role: chat.RoleUser, Content: firstMessage},
}
// No tools: a title is a single completion. The active model is read
// at call time so a /model switch applies to titles too.
text, err := sendChatTurn(ctx, g.llm, g.chatModels.ActiveModel(),
core.GenerateOptions{Messages: messages, MaxSteps: 1}, nil)
if err != nil {
if g.log != nil {
g.log.Error("session title generation failed", "session", sessionID, "err", err)
}
return "", fmt.Errorf("generate title for session %s: %w", sessionID, err)
}
if g.log != nil {
g.log.Info("session title generated", "session", sessionID)
}
return text, nil
}
+1
View File
@@ -41,6 +41,7 @@ var gatewayCommandSpecs = []commandSpec{
{Command: "profile", Description: "Show the active identity's profile", Usage: "/profile"},
{Command: "sessions", Description: "List this channel's sessions", Usage: "/sessions"},
{Command: "resume", Description: "Switch to a session by id or unique prefix", Usage: "/resume <session-id>"},
{Command: "delete", Description: "Permanently delete a session and its history", Usage: "/delete <session-id>"},
{Command: "agents", Description: "List tasks currently being worked", Usage: "/agents"},
{Command: "rollback", Description: "Restore a filesystem checkpoint", Usage: "/rollback [number]"},
{Command: "stop", Description: "Terminate a background process", Usage: "/stop <process-name>"},
@@ -102,6 +102,21 @@ func TestTelegramUserFacingCommandCopyDoesNotCallArchieAGateway(t *testing.T) {
}
}
// /delete removes a stored conversation, so it has to appear in the menu
// beside /sessions and /resume: an operator who can list a session and
// switch to it must be able to see how to get rid of it.
func TestSessionManagementCommandsArePublished(t *testing.T) {
found := make(map[string]bool, len(gatewayCommandSpecs))
for _, spec := range gatewayCommandSpecs {
found[spec.Command] = true
}
for _, cmd := range []string{"sessions", "resume", "delete"} {
if !found[cmd] {
t.Errorf("/%s is missing from gatewayCommandSpecs", cmd)
}
}
}
func TestCommandSurfaceUsesOneModelSelectorAndUsefulHelpCopy(t *testing.T) {
for _, spec := range gatewayCommandSpecs {
if spec.Command == "models" {
+118 -110
View File
@@ -18,6 +18,8 @@ import (
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/container"
"github.com/samcharles93/archie-core/internal/domain/curator"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/domain/workflow/skillbuild"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/eventbus"
"github.com/samcharles93/archie-core/internal/events"
@@ -28,8 +30,6 @@ import (
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskrun"
"github.com/samcharles93/archie-core/internal/tools"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/domain/workflow/skillbuild"
"github.com/samcharles93/archie-core/internal/worktree"
)
@@ -217,11 +217,25 @@ func (d *Daemon) Run(ctx context.Context) error {
}
}
// runIdentities starts one goroutine per identity. Each goroutine runs an
// independent poll loop. All identities share the daemon's store, NATS
// connection, container pool, and event bus.
// runIdentities starts one goroutine per identity plus one shared
// maintenance-and-drain loop.
//
// Polling is identity-scoped: each identity goroutine polls only its own
// repos via its own forge client and enqueues under its own name. It never
// drains or reconciles. Maintenance and draining are store-wide, not
// identity-scoped, so they run once in a single shared loop -- that keeps
// the global max_concurrency cap and the per-repo serialization intact
// across identities (N per-identity dispatchers would multiply the cap and
// split the same-repo lock), and it ensures reconcilePRs and storage
// cleanup actually run in multi-identity mode.
func (d *Daemon) runIdentities(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var wg sync.WaitGroup
// One poll loop per identity. Polling is the only identity-scoped
// work; it never executes tasks.
for _, id := range d.Identities {
wg.Add(1)
go func(id *IdentityRunner) {
@@ -233,7 +247,7 @@ func (d *Daemon) runIdentities(ctx context.Context) error {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
d.cycleForIdentity(ctx, id)
d.pollForIdentity(ctx, id)
select {
case <-ctx.Done():
return
@@ -242,27 +256,51 @@ func (d *Daemon) runIdentities(ctx context.Context) error {
}
}(id)
}
// One shared maintenance-and-drain loop.
wg.Go(func() {
ticker := time.NewTicker(d.Cfg.PollInterval.Std())
defer ticker.Stop()
for {
d.maintainAndDrain(ctx)
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
})
wg.Wait()
return ctx.Err()
}
// cycleForIdentity is a single poll-and-drain pass scoped to one identity's
// forge client and repo list.
func (d *Daemon) cycleForIdentity(ctx context.Context, id *IdentityRunner) {
// Poll the identity's repos via its own forge client.
// pollForIdentity polls one identity's repos via its own forge client,
// enqueuing any discovered issues under that identity's name. It never
// drains or reconciles -- those are store-wide and run in the shared
// maintainAndDrain loop.
func (d *Daemon) pollForIdentity(ctx context.Context, id *IdentityRunner) {
cfg := configForIdentity(d.Cfg, id.Cfg)
for _, repo := range id.Repos {
issues := d.pollIssuesWithForge(ctx, id.Forge, repo)
issues := d.pollIssuesWithConfig(ctx, id.Forge, cfg, repo)
for _, is := range issues {
labels := strings.Join(is.Labels, ",")
if d.Tasks != nil {
d.pollNATS(ctx, id.Forge, repo, is, labels, id.Name)
d.pollNATS(ctx, id.Forge, cfg, repo, is, labels, id.Name)
} else {
d.pollSQLite(ctx, id.Forge, repo, is, labels, id.Name)
d.pollSQLite(ctx, id.Forge, cfg, repo, is, labels, id.Name)
}
}
}
// Draining is shared: ClaimNext returns the oldest queued task
// regardless of which identity enqueued it.
}
// maintainAndDrain runs the store-wide passes of a multi-identity cycle:
// storage cleanup, PR reconciliation, then task dispatch. A single shared
// loop runs this so the global concurrency cap and per-repo serialization
// hold across identities.
func (d *Daemon) maintainAndDrain(ctx context.Context) {
d.cleanupExpiredStorage(ctx)
d.reconcilePRs(ctx)
if d.Tasks != nil {
d.drainNATS(ctx)
} else {
@@ -270,21 +308,23 @@ func (d *Daemon) cycleForIdentity(ctx context.Context, id *IdentityRunner) {
}
}
// pollIssuesWithForge is pollIssues using an explicit forge client rather
// than d.Forge -- used by multi-identity poll loops.
func (d *Daemon) pollIssuesWithForge(ctx context.Context, fg forge.Forge, repo config.Repo) []forge.Issue {
switch d.Cfg.Dispatch.Trigger {
// pollIssuesWithConfig discovers work for one repo using the given forge
// client and dispatch config. Single-identity mode passes d.Forge/d.Cfg;
// identity poll loops pass the identity's own forge and configForIdentity,
// so each identity polls with its own bot user, label, and trigger.
func (d *Daemon) pollIssuesWithConfig(ctx context.Context, fg forge.Forge, cfg config.Config, repo config.Repo) []forge.Issue {
switch cfg.Dispatch.Trigger {
case "label":
issues, err := fg.IssuesWithLabel(ctx, repo.Owner, repo.Name, d.Cfg.Label)
issues, err := fg.IssuesWithLabel(ctx, repo.Owner, repo.Name, cfg.Label)
if err != nil {
d.Log.Error("label poll failed", "repo", repo.FullName(), "err", err)
return nil
}
return issues
case "either":
return d.pollEitherWithForge(ctx, fg, repo)
return d.pollEitherWithConfig(ctx, fg, cfg, repo)
default: // "assignee" (default)
issues, err := fg.AssignedIssues(ctx, repo.Owner, repo.Name, d.Cfg.BotUser)
issues, err := fg.AssignedIssues(ctx, repo.Owner, repo.Name, cfg.BotUser)
if err != nil {
d.Log.Error("poll failed", "repo", repo.FullName(), "err", err)
return nil
@@ -293,11 +333,11 @@ func (d *Daemon) pollIssuesWithForge(ctx context.Context, fg forge.Forge, repo c
}
}
func (d *Daemon) pollEitherWithForge(ctx context.Context, fg forge.Forge, repo config.Repo) []forge.Issue {
func (d *Daemon) pollEitherWithConfig(ctx context.Context, fg forge.Forge, cfg config.Config, repo config.Repo) []forge.Issue {
seen := map[int]bool{}
var out []forge.Issue
assigned, err := fg.AssignedIssues(ctx, repo.Owner, repo.Name, d.Cfg.BotUser)
assigned, err := fg.AssignedIssues(ctx, repo.Owner, repo.Name, cfg.BotUser)
if err != nil {
d.Log.Error("assigned poll failed", "repo", repo.FullName(), "err", err)
} else {
@@ -306,7 +346,7 @@ func (d *Daemon) pollEitherWithForge(ctx context.Context, fg forge.Forge, repo c
out = append(out, is)
}
}
labelled, err := fg.IssuesWithLabel(ctx, repo.Owner, repo.Name, d.Cfg.Label)
labelled, err := fg.IssuesWithLabel(ctx, repo.Owner, repo.Name, cfg.Label)
if err != nil {
d.Log.Error("label poll failed", "repo", repo.FullName(), "err", err)
} else {
@@ -351,7 +391,7 @@ func (d *Daemon) cleanupExpiredStorage(ctx context.Context) {
// drainSQLite claims queued tasks from SQLite and dispatches them concurrently.
func (d *Daemon) drainSQLite(ctx context.Context) {
dispatcher := newTaskDispatcher(d.Cfg.Containers.MaxConcurrency, d.allowConcurrentFor)
dispatcher := newTaskDispatcher(d.Cfg.Containers.MaxConcurrency, d.allowConcurrentForTask)
for ctx.Err() == nil {
task, err := d.Store.ClaimNext(ctx)
if err != nil {
@@ -370,7 +410,7 @@ func (d *Daemon) drainSQLite(ctx context.Context) {
// requeued tasks (waiting_human approval, retry-parked) that didn't come
// through a NATS publish.
func (d *Daemon) drainNATS(ctx context.Context) {
dispatcher := newTaskDispatcher(d.Cfg.Containers.MaxConcurrency, d.allowConcurrentFor)
dispatcher := newTaskDispatcher(d.Cfg.Containers.MaxConcurrency, d.allowConcurrentForTask)
for ctx.Err() == nil {
msg, err := d.Tasks.Fetch(ctx)
if err != nil && !errors.Is(err, eventbus.ErrNoMessage) {
@@ -409,7 +449,7 @@ func (d *Daemon) submitNATSTask(ctx context.Context, dispatcher *taskDispatcher,
_ = msg.Ack()
return
}
task := &store.Task{Owner: envelope.Owner, Repo: envelope.Repo}
task := &store.Task{Owner: envelope.Owner, Repo: envelope.Repo, Identity: envelope.Identity}
dispatcher.Submit(ctx, task, func(ctx context.Context, _ *store.Task) {
d.processNATSTask(ctx, msg)
})
@@ -422,20 +462,20 @@ func (d *Daemon) submitNATSTask(ctx context.Context, dispatcher *taskDispatcher,
// entirely -- the global slot limit is the only bound on their concurrency.
type taskDispatcher struct {
slots chan struct{}
allowConcurrent func(owner, repo string) bool
allowConcurrent func(task *store.Task) bool
mu sync.Mutex
repoTail map[string]chan struct{}
wg sync.WaitGroup
}
func newTaskDispatcher(maxConcurrency int, allowConcurrent func(owner, repo string) bool) *taskDispatcher {
func newTaskDispatcher(maxConcurrency int, allowConcurrent func(task *store.Task) bool) *taskDispatcher {
var slots chan struct{}
if maxConcurrency > 0 {
slots = make(chan struct{}, maxConcurrency)
}
if allowConcurrent == nil {
allowConcurrent = func(string, string) bool { return false }
allowConcurrent = func(*store.Task) bool { return false }
}
return &taskDispatcher{
slots: slots,
@@ -452,7 +492,7 @@ func (d *taskDispatcher) Submit(
repo := task.Owner + "/" + task.Repo
var previous, done chan struct{}
if !d.allowConcurrent(task.Owner, task.Repo) {
if !d.allowConcurrent(task) {
done = make(chan struct{})
d.mu.Lock()
previous = d.repoTail[repo]
@@ -492,9 +532,9 @@ func (d *Daemon) poll(ctx context.Context) {
for _, is := range issues {
labels := strings.Join(is.Labels, ",")
if d.Tasks != nil {
d.pollNATS(ctx, d.Forge, repo, is, labels, "")
d.pollNATS(ctx, d.Forge, d.Cfg, repo, is, labels, "")
} else {
d.pollSQLite(ctx, d.Forge, repo, is, labels, "")
d.pollSQLite(ctx, d.Forge, d.Cfg, repo, is, labels, "")
}
}
}
@@ -502,10 +542,11 @@ func (d *Daemon) poll(ctx context.Context) {
// pollSQLite enqueues discovered issues directly into SQLite (existing flow).
// fg is the forge client that discovered is -- d.Forge for the
// single-identity path, or an identity's own client from cycleForIdentity.
// single-identity path, or an identity's own client from pollForIdentity.
// cfg is the dispatch config that owns this poll (root or identity-scoped).
// identity records which identity owns the resulting task; empty for
// single-identity deployments.
func (d *Daemon) pollSQLite(ctx context.Context, fg forge.Forge, repo config.Repo, is forge.Issue, labels, identity string) {
func (d *Daemon) pollSQLite(ctx context.Context, fg forge.Forge, cfg config.Config, repo config.Repo, is forge.Issue, labels, identity string) {
inserted, err := d.Store.EnqueueIssue(ctx,
repo.Owner, repo.Name, is.Number, is.Title, is.Body, labels, identity)
if err != nil {
@@ -513,7 +554,7 @@ func (d *Daemon) pollSQLite(ctx context.Context, fg forge.Forge, repo config.Rep
return
}
if inserted {
d.acknowledge(ctx, fg, repo, is)
d.acknowledge(ctx, fg, cfg, repo, is)
return
}
// Existing tasks are left untouched. Retry and approval are explicit
@@ -521,7 +562,7 @@ func (d *Daemon) pollSQLite(ctx context.Context, fg forge.Forge, repo config.Rep
}
// pollNATS publishes discovered issues to NATS (new flow).
func (d *Daemon) pollNATS(ctx context.Context, fg forge.Forge, repo config.Repo, is forge.Issue, labels, identity string) {
func (d *Daemon) pollNATS(ctx context.Context, fg forge.Forge, cfg config.Config, repo config.Repo, is forge.Issue, labels, identity string) {
// Read-only existence check prevents rediscovering an existing task.
existing, err := d.Store.TaskByIssue(ctx, repo.Owner, repo.Name, is.Number)
if err != nil {
@@ -548,7 +589,7 @@ func (d *Daemon) pollNATS(ctx context.Context, fg forge.Forge, repo config.Repo,
d.Log.Error("task publish failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
return
}
d.acknowledge(ctx, fg, repo, is)
d.acknowledge(ctx, fg, cfg, repo, is)
}
// publishTask validates, encodes and publishes a task envelope. The
@@ -566,10 +607,11 @@ func (d *Daemon) publishTask(ctx context.Context, task workintake.TaskEnvelope)
}
// acknowledge posts the pickup reaction and queued event
// using fg -- the forge client that owns repo (identity-scoped or root).
func (d *Daemon) acknowledge(ctx context.Context, fg forge.Forge, repo config.Repo, is forge.Issue) {
// using fg -- the forge client that owns repo (identity-scoped or root) --
// and the ack reaction from cfg, the dispatch config that owns this poll.
func (d *Daemon) acknowledge(ctx context.Context, fg forge.Forge, cfg config.Config, repo config.Repo, is forge.Issue) {
d.Log.Info("issue queued", "repo", repo.FullName(), "issue", is.Number, "title", is.Title)
if ack := d.Cfg.Dispatch.AckReaction; ack != "" {
if ack := cfg.Dispatch.AckReaction; ack != "" {
if err := fg.React(ctx, repo.Owner, repo.Name, is.Number, ack); err != nil {
d.Log.Warn("ack reaction failed", "issue", is.Number, "err", err)
}
@@ -632,56 +674,11 @@ func (d *Daemon) processNATSTask(ctx context.Context, msg eventbus.Message) {
}
}
// pollIssues discovers work for one repo according to cfg.Dispatch.Trigger.
// pollIssues discovers work for one repo according to the root dispatch
// config, using the root forge client. Identity poll loops use
// pollIssuesWithConfig with their own forge and config instead.
func (d *Daemon) pollIssues(ctx context.Context, repo config.Repo) []forge.Issue {
switch d.Cfg.Dispatch.Trigger {
case "label":
issues, err := d.Forge.IssuesWithLabel(ctx, repo.Owner, repo.Name, d.Cfg.Label)
if err != nil {
d.Log.Error("label poll failed", "repo", repo.FullName(), "err", err)
return nil
}
return issues
case "either":
return d.pollEither(ctx, repo)
default: // "assignee" (default)
issues, err := d.Forge.AssignedIssues(ctx, repo.Owner, repo.Name, d.Cfg.BotUser)
if err != nil {
d.Log.Error("poll failed", "repo", repo.FullName(), "err", err)
return nil
}
return issues
}
}
// pollEither returns the union of assigned and labelled issues, deduped
// by issue number. An issue both assigned and labelled appears once.
func (d *Daemon) pollEither(ctx context.Context, repo config.Repo) []forge.Issue {
seen := map[int]bool{}
var out []forge.Issue
assigned, err := d.Forge.AssignedIssues(ctx, repo.Owner, repo.Name, d.Cfg.BotUser)
if err != nil {
d.Log.Error("assigned poll failed", "repo", repo.FullName(), "err", err)
} else {
for _, is := range assigned {
seen[is.Number] = true
out = append(out, is)
}
}
labelled, err := d.Forge.IssuesWithLabel(ctx, repo.Owner, repo.Name, d.Cfg.Label)
if err != nil {
d.Log.Error("label poll failed", "repo", repo.FullName(), "err", err)
} else {
for _, is := range labelled {
if !seen[is.Number] {
out = append(out, is)
}
}
}
return out
return d.pollIssuesWithConfig(ctx, d.Forge, d.Cfg, repo)
}
// closeResolvedIssue closes the forge issue behind a finished task.
@@ -808,7 +805,9 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) {
return
}
task.Branch = branch
_ = d.Store.Update(ctx, task)
if err := d.Store.Update(ctx, task); err != nil {
d.Log.Warn("task branch not persisted", "task", task.ID, "err", err)
}
// Refuse to run unsandboxed when sandboxing was asked for. Parking is
// recoverable -- fix the image, retry -- whereas running the agent loop
@@ -841,14 +840,11 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) {
// trip instead of running the stage loop here. archie-agent proxies
// Store/Forge/worktree-push calls back to archied over storerpc/
// forgerpc/worktreerpc -- by the time runViaAgent returns, the task's
// terminal state already landed via those calls.
//
// NOTE: the RPC servers registered in cmd/archied (forgerpc/worktreerpc)
// are still wired to the root d.Forge/d.Trees, not per-identity clients
// (see registerTaskRPCServers in main.go). A container-mode task owned
// by a non-root identity will have its RPC calls served by the wrong
// identity's forge/worktree until that registration is made
// identity-aware; the in-process path below is fully identity-scoped.
// terminal state already landed via those calls. The task's identity
// travels in the taskrun request; the agent scopes its forgerpc and
// worktreerpc clients to that identity, and the daemon registered one
// server pair per identity (plus the root pair), so a container-mode
// task is always served by its own forge client and worktree manager.
if d.ContainerPool != nil {
d.runViaAgent(ctx, task, repo)
} else {
@@ -928,6 +924,19 @@ func (d *Daemon) acquireTaskContainer(
ctr, err := d.ContainerPool.Acquire(ctx, mounts, d.containerEnv(task))
if err != nil {
// Roll back the storage we just set up: the mounts were created
// for this task but no container will use them. Leaking them until
// a later TTL sweep is not acceptable on a backend that allocates
// real resources (volumes, NFS leases).
if terr := d.Storage.Teardown(ctx, storage.TaskRef{
WorktreeDir: workDir,
Ecosystem: repo.Ecosystem,
PersistentStorage: repo.PersistentStorage,
Owner: task.Owner,
Repo: task.Repo,
}); terr != nil {
d.Log.Warn("storage teardown after acquire failure failed", "err", terr)
}
park("container acquire failed", err)
return nil, false
}
@@ -1128,14 +1137,13 @@ func (d *Daemon) repoFor(t *store.Task) (config.Repo, bool) {
return config.Repo{}, false
}
// allowConcurrentFor reports whether owner/repo has opted into concurrent
// task dispatch (config.Repo.AllowConcurrent). Unknown repos default to the
// safe, serialized behavior.
func (d *Daemon) allowConcurrentFor(owner, repo string) bool {
for _, r := range d.Cfg.Repos {
if r.Owner == owner && r.Name == repo {
return r.AllowConcurrent
}
}
return false
// allowConcurrentForTask reports whether the task's owning repo has opted
// into concurrent task dispatch (config.Repo.AllowConcurrent). The repo is
// resolved through repoFor, which selects the identity-scoped repo list when
// task.Identity names a configured identity -- so multi-identity concurrency
// policy comes from the identity's own config, not the root daemon's.
// Unknown repos default to the safe, serialized behavior.
func (d *Daemon) allowConcurrentForTask(task *store.Task) bool {
repo, ok := d.repoFor(task)
return ok && repo.AllowConcurrent
}
+152 -6
View File
@@ -167,8 +167,8 @@ func TestTaskDispatcherSerializesTasksForSameRepo(t *testing.T) {
func TestTaskDispatcherRunsConcurrentReposInParallel(t *testing.T) {
t.Parallel()
dispatcher := newTaskDispatcher(3, func(owner, repo string) bool {
return owner == "acme" && repo == "widget"
dispatcher := newTaskDispatcher(3, func(task *store.Task) bool {
return task.Owner == "acme" && task.Repo == "widget"
})
releaseFirst := make(chan struct{})
firstStarted := make(chan struct{})
@@ -235,17 +235,48 @@ func TestDaemonAllowConcurrentForReadsRepoConfig(t *testing.T) {
},
}
if !d.allowConcurrentFor("acme", "widget") {
if !d.allowConcurrentForTask(&store.Task{Owner: "acme", Repo: "widget"}) {
t.Fatal("expected allow_concurrent=true repo to report concurrent-allowed")
}
if d.allowConcurrentFor("acme", "todo") {
if d.allowConcurrentForTask(&store.Task{Owner: "acme", Repo: "todo"}) {
t.Fatal("expected repo without allow_concurrent to report false")
}
if d.allowConcurrentFor("acme", "unknown") {
if d.allowConcurrentForTask(&store.Task{Owner: "acme", Repo: "unknown"}) {
t.Fatal("expected unknown repo to report false")
}
}
// allowConcurrentForTask must resolve the repo from the identity's own
// repo list when the task names an identity -- root Cfg.Repos must not be
// consulted, or an identity-only repo would silently fall back to the
// serialized default and an overlapping identity repo would use the wrong
// policy.
func TestAllowConcurrentForTaskPrefersOwningIdentityRepo(t *testing.T) {
shared := config.Repo{Owner: "acme", Name: "shared"}
d := &Daemon{
Cfg: config.Config{
// Root (legacy) list: shared is NOT opted in.
Repos: []config.Repo{shared},
},
Identities: []*IdentityRunner{
{
Name: "archie",
// The identity's own list opts shared in.
Repos: []config.Repo{{Owner: "acme", Name: "shared", AllowConcurrent: true}},
},
},
}
if !d.allowConcurrentForTask(&store.Task{Owner: "acme", Repo: "shared", Identity: "archie"}) {
t.Fatal("identity-owned task must use the identity's repo allow_concurrent")
}
// A root-owned (identity-less) task must NOT inherit the identity's
// opt-in: it resolves through the root repo list.
if d.allowConcurrentForTask(&store.Task{Owner: "acme", Repo: "shared"}) {
t.Fatal("identity-less task leaked the identity's allow_concurrent")
}
}
func TestContainerEnvIncludesConfiguredNATSCredentials(t *testing.T) {
t.Setenv("ARCHIE_NATS_SECRET", "test-nats-token")
@@ -802,7 +833,7 @@ func TestAcknowledgeUsesOwningIdentityForgeNotRoot(t *testing.T) {
is := forge.Issue{Number: 1, Title: "shared issue"}
// archie's poll cycle acknowledges via its own forge client.
d.acknowledge(ctx, archieFg, repo, is)
d.acknowledge(ctx, archieFg, d.Cfg, repo, is)
if len(archieFg.stateLabels) != 0 {
t.Fatalf("archie forge got %d state label calls, want 0", len(archieFg.stateLabels))
}
@@ -843,6 +874,121 @@ func mustCoreConn(t *testing.T, c *arnats.Client) *natsio.Conn {
return conn
}
// Multi-identity mode must still run the store-wide maintenance passes:
// storage cleanup and PR reconciliation. Before this loop was split into
// per-identity polling plus a single shared maintainAndDrain loop, neither
// ran in multi-identity mode -- merged PRs were never reconciled, tasks
// stayed pr_open forever, and worktrees were never cleaned up.
func TestMaintainAndDrainReconcilesPRsInMultiIdentityMode(t *testing.T) {
d, s, _, archieFg, _ := twoIdentityDaemon(t)
ctx := context.Background()
// A forge-sourced task owned by the "archie" identity whose PR merged.
if _, err := s.EnqueueIssue(ctx, "acme", "shared", 7, "t", "b", "", "archie"); err != nil {
t.Fatal(err)
}
task, err := s.ClaimNext(ctx)
if err != nil || task == nil {
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
}
task.PRNumber = 42
if err := s.Update(ctx, task); err != nil {
t.Fatal(err)
}
if err := s.Transition(ctx, task.ID, store.StatusRunning, store.StatusPROpen, ""); err != nil {
t.Fatal(err)
}
archieFg.prStates = map[int]string{42: "merged"}
d.maintainAndDrain(ctx)
got, err := s.TaskByID(ctx, task.ID)
if err != nil || got == nil {
t.Fatalf("TaskByID = (%+v, %v)", got, err)
}
if got.Status != store.StatusMerged {
t.Fatalf("status = %q, want %q (multi-identity reconcile never ran)", got.Status, store.StatusMerged)
}
if len(archieFg.closedIssues) != 1 {
t.Fatalf("CloseIssue calls = %d, want 1 (issue must be closed on merge)", len(archieFg.closedIssues))
}
}
// The identity poll path must use the identity's own dispatch config --
// its bot user, label, and trigger -- not the root daemon's. An identity
// with a different bot user polling "assignee" would otherwise query for
// issues assigned to the root bot user.
func TestPollIssuesWithConfigUsesIdentityScopedDispatch(t *testing.T) {
fg := &recordingForge{}
d := &Daemon{Cfg: config.Config{}, Log: slog.New(slog.DiscardHandler)}
// Root uses bot_user "root"; the identity uses "winter". Both default
// to the assignee trigger.
rootCfg := config.Config{BotUser: "root", Dispatch: config.Dispatch{Trigger: "assignee"}}
idCfg := config.IdentityConfig{BotUser: "winter", Dispatch: config.Dispatch{Trigger: "assignee"}}
// Root poll queries root's bot user.
_ = d.pollIssuesWithConfig(context.Background(), fg, rootCfg, config.Repo{Owner: "acme", Name: "shared"})
_ = d.pollIssuesWithConfig(context.Background(), fg, configForIdentity(rootCfg, idCfg), config.Repo{Owner: "acme", Name: "shared"})
if got := fg.assigned; len(got) != 2 || got[0] != "root" || got[1] != "winter" {
t.Fatalf("AssignedIssues bot users = %v, want [root winter] (identity dispatch ignored)", got)
}
}
// recordingForge records the bot user/label passed to the discovery calls
// so tests can assert identity-scoped polling. Everything else panics.
type recordingForge struct {
assigned []string
labelled []string
}
func (f *recordingForge) AssignedIssues(_ context.Context, _, _, botUser string) ([]forge.Issue, error) {
f.assigned = append(f.assigned, botUser)
return nil, nil
}
func (f *recordingForge) IssuesWithLabel(_ context.Context, _, _, label string) ([]forge.Issue, error) {
f.labelled = append(f.labelled, label)
return nil, nil
}
func (f *recordingForge) Comment(context.Context, string, string, int, string) (int64, error) {
panic("unexpected call")
}
func (f *recordingForge) SetStateLabel(context.Context, string, string, int, string, []string) {
panic("unexpected call")
}
func (f *recordingForge) AcceptInvitations(context.Context) error { panic("unexpected call") }
func (f *recordingForge) RepliesAfter(context.Context, string, string, int, int64, string) ([]forge.Reply, error) {
panic("unexpected call")
}
func (f *recordingForge) CreatePR(context.Context, string, string, string, string, string, string) (int, error) {
panic("unexpected call")
}
func (f *recordingForge) PRState(context.Context, string, string, int) (string, error) {
panic("unexpected call")
}
func (f *recordingForge) CloseIssue(context.Context, string, string, int, string) error {
panic("unexpected call")
}
func (f *recordingForge) CreateIssue(context.Context, string, string, string, string, []string) (int, error) {
panic("unexpected call")
}
func (f *recordingForge) React(context.Context, string, string, int, string) error {
panic("unexpected call")
}
func (f *recordingForge) VerifyPush(context.Context, string, string) error { panic("unexpected call") }
func (f *recordingForge) LinkBranch(context.Context, string, string, int, string) error {
panic("unexpected call")
}
// A merged PR must close the forge issue.
//
// "Closes #N" was removed from PR bodies in favour of LinkBranch, which is
@@ -14,9 +14,9 @@ import (
"github.com/traefik/yaegi/interp"
"github.com/samcharles93/archie-core/internal/skill"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/domain/workflow/wfextract"
"github.com/samcharles93/archie-core/internal/skill"
"github.com/samcharles93/archie-core/internal/yaegiutil"
)
+38 -12
View File
@@ -22,6 +22,7 @@ import (
"encoding/json"
"fmt"
"log/slog"
"strings"
"time"
"github.com/nats-io/nats.go"
@@ -38,6 +39,19 @@ const (
SubjectSetStateLabel = "archie.forge.set_state_label"
)
// SubjectFor returns the subject for base, scoped to identity when set.
// An empty identity uses the root subject, which is how single-identity
// deployments and agent images that predate identity routing behave. The
// daemon registers one server per identity on these scoped subjects so a
// container-mode task owned by a non-root identity has its RPC calls
// served by that identity's own forge client, not the root's.
func SubjectFor(identity, base string) string {
if identity == "" {
return base
}
return "archie.forge." + identity + "." + strings.TrimPrefix(base, "archie.forge.")
}
type CommentRequest struct {
Owner, Repo string
Number int
@@ -88,15 +102,22 @@ type Server struct {
Log *slog.Logger
}
// Register subscribes all handlers on nc. The returned func
// unsubscribes all of them.
// Register subscribes all handlers on nc under the root (identity-less)
// subjects. RegisterFor(nc, identity) registers the same handlers under
// that identity's scoped subjects; the daemon calls it once per identity
// so container-mode tasks route to their own forge client.
func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) {
return s.RegisterFor(nc, "")
}
// RegisterFor registers all handlers under the subjects scoped to identity.
func (s *Server) RegisterFor(nc *nats.Conn, identity string) (unsubscribe func(), err error) {
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
{Subject: SubjectComment, Handler: s.handleComment},
{Subject: SubjectCloseIssue, Handler: s.handleCloseIssue},
{Subject: SubjectCreatePR, Handler: s.handleCreatePR},
{Subject: SubjectLinkBranch, Handler: s.handleLinkBranch},
{Subject: SubjectSetStateLabel, Handler: s.handleSetStateLabel},
{Subject: SubjectFor(identity, SubjectComment), Handler: s.handleComment},
{Subject: SubjectFor(identity, SubjectCloseIssue), Handler: s.handleCloseIssue},
{Subject: SubjectFor(identity, SubjectCreatePR), Handler: s.handleCreatePR},
{Subject: SubjectFor(identity, SubjectLinkBranch), Handler: s.handleLinkBranch},
{Subject: SubjectFor(identity, SubjectSetStateLabel), Handler: s.handleSetStateLabel},
})
}
@@ -161,10 +182,15 @@ type Client struct {
Conn *nats.Conn
// Timeout bounds each call when ctx has no deadline of its own.
Timeout time.Duration
// Identity scopes this client's calls to one identity's RPC server.
// Empty uses the root subjects (single-identity deployments).
Identity string
}
func (c *Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} }
func (c *Client) subject(base string) string { return SubjectFor(c.Identity, base) }
// Comment and SetStateLabel are not in workflow.Forger, so no current agent
// calls them. They stay as the client half of handlers kept for image skew
// (see the package doc) -- and as the only way to exercise those handlers
@@ -172,7 +198,7 @@ func (c *Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Ti
// untested rather than merely unused.
func (c *Client) Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error) {
req := CommentRequest{Owner: owner, Repo: repo, Number: number, Body: body}
resp, err := natsrpc.Call[CommentResponse](ctx, c.rpc(), SubjectComment, req)
resp, err := natsrpc.Call[CommentResponse](ctx, c.rpc(), c.subject(SubjectComment), req)
if err != nil {
return 0, err
}
@@ -184,7 +210,7 @@ func (c *Client) Comment(ctx context.Context, owner, repo string, number int, bo
func (c *Client) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error {
req := CloseIssueRequest{Owner: owner, Repo: repo, Number: number, Comment: comment}
resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectCloseIssue, req)
resp, err := natsrpc.Call[Response](ctx, c.rpc(), c.subject(SubjectCloseIssue), req)
if err != nil {
return err
}
@@ -193,7 +219,7 @@ func (c *Client) CloseIssue(ctx context.Context, owner, repo string, number int,
func (c *Client) CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error) {
req := CreatePRRequest{Owner: owner, Repo: repo, Title: title, Head: head, Base: base, Body: body}
resp, err := natsrpc.Call[CreatePRResponse](ctx, c.rpc(), SubjectCreatePR, req)
resp, err := natsrpc.Call[CreatePRResponse](ctx, c.rpc(), c.subject(SubjectCreatePR), req)
if err != nil {
return 0, err
}
@@ -205,7 +231,7 @@ func (c *Client) CreatePR(ctx context.Context, owner, repo, title, head, base, b
func (c *Client) LinkBranch(ctx context.Context, owner, repo string, issueNumber int, branch string) error {
req := LinkBranchRequest{Owner: owner, Repo: repo, IssueNumber: issueNumber, Branch: branch}
resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectLinkBranch, req)
resp, err := natsrpc.Call[Response](ctx, c.rpc(), c.subject(SubjectLinkBranch), req)
if err != nil {
return err
}
@@ -216,5 +242,5 @@ func (c *Client) LinkBranch(ctx context.Context, owner, repo string, issueNumber
// the current workflow deliberately never calls it.
func (c *Client) SetStateLabel(ctx context.Context, owner, repo string, number int, label string, knownLabels []string) {
req := SetStateLabelRequest{Owner: owner, Repo: repo, Number: number, Label: label, KnownLabels: knownLabels}
_, _ = natsrpc.Call[Response](ctx, c.rpc(), SubjectSetStateLabel, req)
_, _ = natsrpc.Call[Response](ctx, c.rpc(), c.subject(SubjectSetStateLabel), req)
}
+69
View File
@@ -225,3 +225,72 @@ func TestClientCommentTimesOutWithNoResponder(t *testing.T) {
t.Fatal("expected Comment to time out with no server registered")
}
}
// TestIdentityScopedRoutingIsolatesForges proves the critical fix: an
// identity-scoped client must reach the forge wired to that identity's
// subject, never the root forge. Before identity-scoped subjects existed,
// every container-mode task's RPC was served by the root forge regardless
// of which identity owned the task.
func TestIdentityScopedRoutingIsolatesForges(t *testing.T) {
rootFg := &fakeForge{}
archieFg := &fakeForge{}
srv := startEmbedded(t)
url := srv.ClientURL()
serverConn := connect(t, url)
// Root server on root subjects.
unsubRoot, err := (&Server{Forge: rootFg, Log: slog.New(slog.DiscardHandler)}).Register(serverConn)
if err != nil {
t.Fatalf("register root: %v", err)
}
t.Cleanup(unsubRoot)
// Identity server on archie-scoped subjects.
unsubArch, err := (&Server{Forge: archieFg, Log: slog.New(slog.DiscardHandler)}).RegisterFor(serverConn, "archie")
if err != nil {
t.Fatalf("register archie: %v", err)
}
t.Cleanup(unsubArch)
clientConn := connect(t, url)
ctx := context.Background()
// Identity-scoped call reaches archie's forge only.
archieClient := &Client{Conn: clientConn, Timeout: 2 * time.Second, Identity: "archie"}
if err := archieClient.CloseIssue(ctx, "acme", "widget", 1, "done"); err != nil {
t.Fatalf("identity-scoped CloseIssue: %v", err)
}
if len(archieFg.closes) != 1 {
t.Fatalf("archie forge closes = %d, want 1", len(archieFg.closes))
}
if len(rootFg.closes) != 0 {
t.Fatalf("root forge closes = %d, want 0 (identity call leaked to root)", len(rootFg.closes))
}
// Root (identity-less) call reaches the root forge only.
rootClient := &Client{Conn: clientConn, Timeout: 2 * time.Second}
if err := rootClient.CloseIssue(ctx, "acme", "widget", 2, "done"); err != nil {
t.Fatalf("root-scoped CloseIssue: %v", err)
}
if len(rootFg.closes) != 1 {
t.Fatalf("root forge closes = %d, want 1", len(rootFg.closes))
}
if len(archieFg.closes) != 1 {
t.Fatalf("archie forge closes = %d, want still 1 (root call leaked to identity)", len(archieFg.closes))
}
}
// SubjectFor leaves the root subject unchanged for an empty identity and
// prefixes the identity for a non-empty one -- the root subjects must stay
// byte-identical so single-identity deployments and older agent images keep
// working.
func TestSubjectFor(t *testing.T) {
if got := SubjectFor("", SubjectComment); got != SubjectComment {
t.Fatalf("SubjectFor(\"\", %q) = %q, want unchanged root subject", SubjectComment, got)
}
if got := SubjectFor("archie", SubjectComment); got != "archie.forge.archie.comment" {
t.Fatalf("SubjectFor(\"archie\", %q) = %q", SubjectComment, got)
}
if got := SubjectFor("archie", SubjectCreatePR); got != "archie.forge.archie.create_pr" {
t.Fatalf("SubjectFor(\"archie\", %q) = %q", SubjectCreatePR, got)
}
}
+144 -33
View File
@@ -11,10 +11,12 @@ package gateway
import (
"context"
"fmt"
"log/slog"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/samcharles93/archie-core/internal/releaseupdate"
@@ -252,10 +254,23 @@ type Router struct {
// When set, session lifecycle commands (/new, /branch, /title,
// /undo, /retry, /compress) are available. When nil, those
// commands report "not configured".
Sessions SessionStore
Agents AgentReader // nil = /agents not configured
Sessions SessionStore
Agents AgentReader // nil = /agents not configured
// Titles proposes display titles for untitled sessions (see
// TitleGenerator). Nil disables automatic title generation; when set,
// the router asks for a title after a successful turn on a session
// that still has none, in the background, and persists the result.
Titles TitleGenerator
// Log is the optional logger for the best-effort background title
// path. Nil drops those diagnostics silently; nothing on this path is
// important enough to fail the turn over.
Log *slog.Logger
sessionTracker *sessionTracker
gatewayName string
// titlingMu guards titling, the set of sessions with a title proposal
// in flight (see claimTitleInFlight). Zero value is ready to use.
titlingMu sync.Mutex
titling map[string]struct{}
}
// NewRouter returns a Router. llm is optional -- when nil, non-command
@@ -287,7 +302,11 @@ func (r *Router) Route(ctx context.Context, msg Message) (string, error) {
if r.LLM == nil {
return "I'm running but LLM processing isn't wired yet. Try /status.", nil
}
return r.LLM(ctx, msg)
reply, err := r.LLM(ctx, msg)
if err == nil {
r.maybeAutoTitle(ctx, msg)
}
return reply, err
}
// dispatchLocal handles recognized local commands. Returns (reply,
@@ -335,7 +354,7 @@ func (r *Router) dispatchLocal(ctx context.Context, msg Message, text, cmd strin
reply, err := r.handleProfile()
return reply, true, err
case "/sessions":
reply, err := r.handleSessions(ctx)
reply, err := r.handleSessions(ctx, msg)
return reply, true, err
case "/resume":
reply, err := r.handleResume(ctx, msg, rest)
@@ -401,6 +420,9 @@ func (r *Router) dispatchSessionCommand(ctx context.Context, msg Message, cmd, r
case "/compress", "/compact":
reply, err := r.handleCompress(ctx, msg, rest)
return reply, true, err
case "/delete":
reply, err := r.handleDelete(ctx, msg, rest)
return reply, true, err
}
return "", false, nil
}
@@ -423,7 +445,11 @@ func (r *Router) RouteStream(ctx context.Context, msg Message, onDelta func(stri
if isLocalCommand(cmd) || strings.HasPrefix(cmd, "/") {
return r.Route(ctx, msg)
}
return r.LLMStream(ctx, msg, onDelta)
reply, err := r.LLMStream(ctx, msg, onDelta)
if err == nil {
r.maybeAutoTitle(ctx, msg)
}
return reply, err
}
var localCommands = []string{
@@ -431,7 +457,7 @@ var localCommands = []string{
"/start",
"/new", "/reset", "/topic", "/retry", "/undo",
"/title", "/branch", "/fork", "/compress", "/compact",
"/whoami", "/profile", "/sessions", "/resume", "/agents",
"/whoami", "/profile", "/sessions", "/resume", "/delete", "/agents",
"/personality", "/help", "/version", "/update", "/restart",
}
@@ -465,6 +491,7 @@ var localCommandSpecs = []CommandSpec{
{Command: "/profile", Description: "Show the active identity profile", Usage: "/profile"},
{Command: "/sessions", Description: "List this channel's conversations", Usage: "/sessions"},
{Command: "/resume", Description: "Switch to a conversation", Usage: "/resume <session-id>"},
{Command: "/delete", Description: "Delete a conversation and its history", Usage: "/delete <session-id>"},
{Command: "/agents", Description: "List tasks currently being worked", Usage: "/agents"},
{Command: "/personality", Description: "Choose a communication style", Usage: "/personality [name]"},
{Command: "/help", Description: "See what Archie can do", Usage: "/help"},
@@ -731,7 +758,7 @@ func (r *Router) handleProfile() (string, error) {
return strings.TrimSpace(b.String()), nil
}
func (r *Router) handleSessions(ctx context.Context) (string, error) {
func (r *Router) handleSessions(ctx context.Context, msg Message) (string, error) {
if r.Sessions == nil {
return "Session management is not configured.", nil
}
@@ -739,20 +766,115 @@ func (r *Router) handleSessions(ctx context.Context) (string, error) {
if err != nil {
return "", fmt.Errorf("list sessions: %w", err)
}
active := ""
if r.sessionTracker != nil {
active = r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)
}
return renderSessionList(sessions, active, time.Now()), nil
}
// renderSessionList formats sessions (already newest-first) as the
// /sessions reply: a count header, then one numbered, column-aligned row
// per session carrying an 8-character id prefix, its title, and a
// recency suffix. The active session (matched by ID) is marked.
func renderSessionList(sessions []SessionContext, active string, now time.Time) string {
if len(sessions) == 0 {
return "No sessions.", nil
return "No sessions."
}
var b strings.Builder
b.WriteString("Sessions:\n")
maxTitle := 0
for _, s := range sessions {
prefix := s.SessionID[:min(8, len(s.SessionID))]
title := s.Title
if title == "" {
title = "(untitled)"
if l := len([]rune(sessionDisplayTitle(s))); l > maxTitle {
maxTitle = l
}
fmt.Fprintf(&b, " %s — %s\n", prefix, title)
}
return strings.TrimSpace(b.String()), nil
numW := len(strconv.Itoa(len(sessions)))
var b strings.Builder
fmt.Fprintf(&b, "Sessions (%d):\n", len(sessions))
for i, s := range sessions {
meta := relativeAge(sessionRecency(s), now)
if s.SessionID == active {
meta = "active · " + meta
}
fmt.Fprintf(&b, " %*d. %s %-*s · %s\n",
numW, i+1, shortSessionID(s.SessionID), maxTitle+1, sessionDisplayTitle(s), meta)
}
return strings.TrimSpace(b.String())
}
// shortSessionIDLen is how much of a session ID the chat surfaces show. It
// is also the shorthand /resume and /delete are given back, so every
// listing must truncate to the same width.
const shortSessionIDLen = 8
// shortSessionID renders the abbreviated form of a session ID used
// wherever a session is listed.
//
// Truncation is on a rune boundary: slicing bytes could split a
// multi-byte channel-ID-derived session key mid-rune and emit invalid
// UTF-8. UUID keys are ASCII, so this only differs for the exotic cases --
// where it must stay well-formed.
func shortSessionID(id string) string {
if r := []rune(id); len(r) > shortSessionIDLen {
return string(r[:shortSessionIDLen])
}
return id
}
// resolveSessionRef resolves an operator-supplied session reference
// against a session list, the way /resume and /delete both accept one.
//
// An exact ID wins outright -- a full ID names one session unambiguously
// even when it is also the prefix of a longer one -- otherwise the
// reference must be a prefix of exactly one session. It returns (nil,
// false) when nothing matches and (nil, true) when more than one session
// shares the prefix.
func resolveSessionRef(sessions []SessionContext, ref string) (match *SessionContext, ambiguous bool) {
for i, s := range sessions {
if s.SessionID == ref {
return &sessions[i], false
}
}
var found *SessionContext
for i, s := range sessions {
if !strings.HasPrefix(s.SessionID, ref) {
continue
}
if found != nil {
return nil, true
}
found = &sessions[i]
}
return found, false
}
// sessionDisplayTitle is the title a session is shown under, falling
// back to the standard placeholder when none has been set or generated.
func sessionDisplayTitle(sc SessionContext) string {
if sc.Title != "" {
return sc.Title
}
return "(untitled)"
}
// relativeAge renders an instant as a short human age ("5m ago") for
// session listings. The zero time renders as an empty string.
func relativeAge(t, now time.Time) string {
if t.IsZero() {
return ""
}
d := now.Sub(t)
switch {
case d < time.Minute:
return "just now"
case d < time.Hour:
return fmt.Sprintf("%dm ago", int(d.Minutes()))
case d < 24*time.Hour:
return fmt.Sprintf("%dh ago", int(d.Hours()))
case d < 7*24*time.Hour:
return fmt.Sprintf("%dd ago", int(d.Hours()/24))
default:
return t.Format("Jan 2")
}
}
// handleResume switches the active session for the current channel+thread
@@ -769,25 +891,14 @@ func (r *Router) handleResume(ctx context.Context, msg Message, arg string) (str
if err != nil {
return "", fmt.Errorf("list sessions: %w", err)
}
for _, s := range sessions {
if s.SessionID == arg {
return r.resumeSession(msg, s), nil
}
}
var matches []SessionContext
for _, s := range sessions {
if strings.HasPrefix(s.SessionID, arg) {
matches = append(matches, s)
}
}
switch len(matches) {
case 0:
return fmt.Sprintf("No session matching %q.", arg), nil
case 1:
return r.resumeSession(msg, matches[0]), nil
default:
match, ambiguous := resolveSessionRef(sessions, arg)
switch {
case ambiguous:
return fmt.Sprintf("Multiple sessions match %q; be more specific.", arg), nil
case match == nil:
return fmt.Sprintf("No session matching %q.", arg), nil
}
return r.resumeSession(msg, *match), nil
}
func (r *Router) resumeSession(msg Message, s SessionContext) string {
+20
View File
@@ -892,3 +892,23 @@ func TestLocalCommandsIncludesNewCommands(t *testing.T) {
}
}
}
// The two command surfaces must describe the same set: /help lists the
// names, adapters publish the specs, and a command in one but not the
// other is either undiscoverable or advertised without an implementation.
func TestLocalCommandSpecsAndCommandsAgree(t *testing.T) {
names := LocalCommands()
specs := LocalCommandSpecs()
specified := make(map[string]bool, len(specs))
for _, s := range specs {
specified[s.Command] = true
if !slices.Contains(names, s.Command) {
t.Errorf("LocalCommandSpecs() advertises %s, which Route does not handle", s.Command)
}
}
for _, name := range names {
if !specified[name] {
t.Errorf("LocalCommandSpecs() is missing %s", name)
}
}
}
+31 -13
View File
@@ -3,6 +3,7 @@ package gateway
import (
"context"
"fmt"
"maps"
"strconv"
"strings"
"sync"
@@ -211,6 +212,28 @@ func (t *sessionTracker) flattenTopic(channelID, threadID string) {
t.active[sessionTrackerKey(channelID, "")] = current
}
// forget drops every channel+thread whose active session is sessionID.
//
// It is the counterpart to deleting a session from the store. resolve
// treats a cached entry as authoritative and never checks that the session
// still exists, so a pointer left behind here would make every later
// message in that chat persist under an ID the store no longer knows --
// history written to a session nothing can list, resume or delete.
//
// One session can be active under more than one key (a flat chat and a
// thread that /resume'd the same session), so every entry is swept, not
// just the one the command was typed in.
func (t *sessionTracker) forget(sessionID string) {
// An empty ID is a prefix of nothing and a value of everything a
// poisoned map would hold; sweeping on it would clear unrelated chats.
if sessionID == "" {
return
}
t.mu.Lock()
defer t.mu.Unlock()
maps.DeleteFunc(t.active, func(_, id string) bool { return id == sessionID })
}
// getActive returns the current session ID for a channel+thread.
func (t *sessionTracker) getActive(channelID, threadID string) string {
t.mu.RLock()
@@ -333,12 +356,7 @@ func (r *Router) topicListSessions(ctx context.Context, msg Message) (string, er
if s.SessionID == active {
marker = "*"
}
prefix := s.SessionID[:min(8, len(s.SessionID))]
title := s.Title
if title == "" {
title = "(untitled)"
}
fmt.Fprintf(&b, " %s %s — %s", marker, prefix, title)
fmt.Fprintf(&b, " %s %s — %s", marker, shortSessionID(s.SessionID), sessionDisplayTitle(s))
if s.BranchName != "" {
fmt.Fprintf(&b, " [branch: %s]", s.BranchName)
}
@@ -355,12 +373,8 @@ func (r *Router) topicSwitchSession(ctx context.Context, msg Message, rest strin
for _, s := range sessions {
if len(s.SessionID) >= len(rest) && s.SessionID[:len(rest)] == rest {
r.sessionTracker.setActive(msg.ChannelID, msg.ThreadID, s.SessionID)
prefix := s.SessionID[:min(8, len(s.SessionID))]
title := s.Title
if title == "" {
title = "(untitled)"
}
return fmt.Sprintf("Switched to session %s: %s", prefix, title), nil
return fmt.Sprintf("Switched to session %s: %s",
shortSessionID(s.SessionID), sessionDisplayTitle(s)), nil
}
}
return fmt.Sprintf("No session found matching %q. Use /topic to list available sessions.", rest), nil
@@ -406,7 +420,11 @@ func (r *Router) handleRetry(ctx context.Context, msg Message) (string, error) {
lastUserMsg := msgs[0]
lastUserMsg.ChannelID = msg.ChannelID
lastUserMsg.ThreadID = msg.ThreadID
return r.LLM(ctx, lastUserMsg)
reply, err := r.LLM(ctx, lastUserMsg)
if err == nil {
r.maybeAutoTitle(ctx, lastUserMsg)
}
return reply, err
}
// handleUndo removes the last N messages (default 1) from the session
+76
View File
@@ -0,0 +1,76 @@
package gateway
import (
"context"
"fmt"
"strings"
)
// minDeleteRefLen is the shortest prefix /delete will act on.
//
// /resume resolves a session on any unique prefix, because resuming the
// wrong conversation is undone by resuming the right one. Deleting one is
// not undoable, so a reference short enough to be a typo is refused even
// when it happens to match exactly one session today -- the same keystroke
// would hit a different session tomorrow. A full ID always works: the
// guard applies to prefix matching, not to naming a session outright.
const minDeleteRefLen = 4
// handleDelete permanently removes a session and its history.
//
// It is the only way to retire a conversation from chat: /new starts a
// fresh one and leaves the old session listed by /sessions forever, so
// without this the list only ever grows.
func (r *Router) handleDelete(ctx context.Context, msg Message, rest string) (string, error) {
ref := strings.TrimSpace(rest)
if ref == "" {
// No bare form. Deleting "the current conversation" on an
// unqualified command is one keystroke away from destroying a
// history nobody meant to touch; the session must be named.
return "Usage: /delete <session-id> — permanently removes a conversation and its history. Run /sessions to see the ids.", nil
}
if r.Sessions == nil {
return "Session management is not configured.", nil
}
sessions, err := r.Sessions.List(ctx)
if err != nil {
return "", fmt.Errorf("list sessions: %w", err)
}
target, ambiguous := resolveSessionRef(sessions, ref)
switch {
case ambiguous:
return fmt.Sprintf("Multiple sessions match %q; be more specific.", ref), nil
case target == nil:
return fmt.Sprintf("No session matching %q.", ref), nil
case target.SessionID != ref && len([]rune(ref)) < minDeleteRefLen:
return fmt.Sprintf(
"Refusing to delete on %d characters — this cannot be undone. "+
"Give at least %d characters of the session id, or its full id.",
len([]rune(ref)), minDeleteRefLen), nil
}
// Read the active session before the delete, so the reply can say
// whether the operator just ended the conversation they are in.
active := ""
if r.sessionTracker != nil {
active = r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)
}
if err := r.Sessions.Delete(ctx, target.SessionID); err != nil {
return "", fmt.Errorf("delete session: %w", err)
}
// Only after the store has actually let go of it: a failed delete
// leaves the session live, and dropping the tracker entry then would
// strand the operator's conversation for no reason.
if r.sessionTracker != nil {
r.sessionTracker.forget(target.SessionID)
}
reply := fmt.Sprintf("Deleted session %s (%s) and its history.",
shortSessionID(target.SessionID), sessionDisplayTitle(*target))
if target.SessionID == active {
reply += " The next message starts a new conversation."
}
return reply, nil
}
+330
View File
@@ -0,0 +1,330 @@
package gateway
import (
"context"
"errors"
"strings"
"testing"
)
// deleteFailingStore is a session store whose Delete always fails, used to
// prove the command surfaces a store failure instead of reporting success.
type deleteFailingStore struct {
*fakeSessionStore
err error
}
func (d *deleteFailingStore) Delete(context.Context, string) error { return d.err }
// newDeleteRouter returns a router wired to a fresh in-memory store,
// plus that store, so tests can assert on what survived the command.
func newDeleteRouter(t *testing.T) (*Router, *fakeSessionStore) {
t.Helper()
store := newFakeSessionStore()
r := NewRouter(nil, nil, "test-gw")
r.InitSessions(store)
return r, store
}
// seedSession stores a session on channelID and returns its ID.
func seedSession(t *testing.T, r *Router, store *fakeSessionStore, id, channelID, title string) string {
t.Helper()
sc := SessionContext{
SessionID: id,
Source: SessionSource{
Platform: r.gatewayName,
BotUser: r.Identity,
ChannelID: channelID,
},
Title: title,
}
if err := store.Save(context.Background(), sc); err != nil {
t.Fatalf("seed session %s: %v", id, err)
}
return id
}
func TestRouteDeleteNotConfigured(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
reply, err := r.Route(context.Background(), Message{Text: "/delete abc-123"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "not configured") {
t.Errorf("reply = %q, want 'not configured'", reply)
}
}
func TestRouteDeleteNoArgExplainsUsageAndDeletesNothing(t *testing.T) {
r, store := newDeleteRouter(t)
seedSession(t, r, store, "abc-123", "chan-1", "Work")
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "Usage") {
t.Errorf("reply = %q, want usage", reply)
}
if got, _ := store.Get(context.Background(), "abc-123"); got == nil {
t.Error("bare /delete removed a session")
}
}
func TestRouteDeleteRejectsUnknownReference(t *testing.T) {
r, store := newDeleteRouter(t)
seedSession(t, r, store, "abc-123", "chan-1", "Work")
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete zzzz"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "No session matching") {
t.Errorf("reply = %q, want 'No session matching'", reply)
}
if got, _ := store.Get(context.Background(), "abc-123"); got == nil {
t.Error("a non-matching reference removed a session")
}
}
func TestRouteDeleteRejectsAmbiguousReference(t *testing.T) {
r, store := newDeleteRouter(t)
seedSession(t, r, store, "abcd-123", "chan-1", "One")
seedSession(t, r, store, "abcd-456", "chan-1", "Two")
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete abcd"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "Multiple sessions") {
t.Errorf("reply = %q, want 'Multiple sessions'", reply)
}
for _, id := range []string{"abcd-123", "abcd-456"} {
if got, _ := store.Get(context.Background(), id); got == nil {
t.Errorf("ambiguous reference deleted %s", id)
}
}
}
// A prefix short enough to be a typo must not destroy a conversation, even
// when it happens to match exactly one session. /resume has no such guard
// because resuming the wrong session is undone by resuming the right one.
func TestRouteDeleteRejectsShortPrefixEvenWhenUnique(t *testing.T) {
r, store := newDeleteRouter(t)
seedSession(t, r, store, "abc-123", "chan-1", "Work")
for _, ref := range []string{"a", "ab", "abc"} {
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete " + ref})
if err != nil {
t.Fatalf("Route %q: %v", ref, err)
}
if !strings.Contains(reply, "characters") {
t.Errorf("/delete %s = %q, want a reply asking for more characters", ref, reply)
}
if got, _ := store.Get(context.Background(), "abc-123"); got == nil {
t.Fatalf("/delete %s deleted the session on a short prefix", ref)
}
}
}
// The length guard applies to prefix matching only: a session whose whole
// ID is short is still deletable by naming it in full.
func TestRouteDeleteAcceptsShortExactID(t *testing.T) {
r, store := newDeleteRouter(t)
seedSession(t, r, store, "abc", "chan-1", "Work")
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete abc"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "Deleted session") {
t.Errorf("reply = %q, want 'Deleted session'", reply)
}
if got, _ := store.Get(context.Background(), "abc"); got != nil {
t.Error("exact short ID was not deleted")
}
}
// An exact ID wins over a prefix that also matches other sessions, matching
// how /resume resolves a reference.
func TestRouteDeleteExactIDBeatsAmbiguousPrefix(t *testing.T) {
r, store := newDeleteRouter(t)
seedSession(t, r, store, "abcd-123", "chan-1", "One")
seedSession(t, r, store, "abcd-123-extra", "chan-1", "Two")
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete abcd-123"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "Deleted session") {
t.Fatalf("reply = %q, want 'Deleted session'", reply)
}
if got, _ := store.Get(context.Background(), "abcd-123"); got != nil {
t.Error("the exactly named session survived")
}
if got, _ := store.Get(context.Background(), "abcd-123-extra"); got == nil {
t.Error("the session sharing the prefix was deleted too")
}
}
func TestRouteDeleteRemovesSessionAndItsHistory(t *testing.T) {
r, store := newDeleteRouter(t)
id := seedSession(t, r, store, "abcd-123", "chan-1", "Work")
for _, text := range []string{"first", "second"} {
if err := store.SaveMessage(context.Background(), id, Message{From: "sam", Text: text}); err != nil {
t.Fatalf("seed message: %v", err)
}
}
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete " + id})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "Deleted session") || !strings.Contains(reply, "Work") {
t.Errorf("reply = %q, want the deleted session's title", reply)
}
if got, _ := store.Get(context.Background(), id); got != nil {
t.Error("session survived /delete")
}
count, err := store.MessageCount(context.Background(), id)
if err != nil {
t.Fatalf("MessageCount: %v", err)
}
if count != 0 {
t.Errorf("history left %d messages behind", count)
}
}
// Deleting the session a chat is currently using must clear the tracker
// too: a cached pointer at a deleted session would persist every later
// message under an ID the store no longer knows.
func TestRouteDeleteActiveSessionClearsTracker(t *testing.T) {
r, store := newDeleteRouter(t)
msg := Message{ChannelID: "chan-1"}
if _, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/new Work"}); err != nil {
t.Fatalf("/new: %v", err)
}
id := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)
if id == "" {
t.Fatal("/new did not set an active session")
}
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete " + id})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "new conversation") {
t.Errorf("reply = %q, want a note that the next message starts fresh", reply)
}
if active := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID); active != "" {
t.Errorf("tracker still points at %q after deleting it", active)
}
// The next turn must resolve to a session that exists in the store.
next, err := r.ResolveSessionKey(context.Background(), msg)
if err != nil {
t.Fatalf("ResolveSessionKey: %v", err)
}
if next == id {
t.Errorf("resolved the deleted session %q again", id)
}
if got, _ := store.Get(context.Background(), next); got == nil {
t.Errorf("resolved session %q is not in the store", next)
}
}
// Deleting some other session must leave the current conversation alone.
func TestRouteDeleteOtherSessionKeepsActive(t *testing.T) {
r, store := newDeleteRouter(t)
other := seedSession(t, r, store, "abcd-999", "chan-1", "Old")
if _, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/new Current"}); err != nil {
t.Fatalf("/new: %v", err)
}
active := r.sessionTracker.getActive("chan-1", "")
reply, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete " + other})
if err != nil {
t.Fatalf("Route: %v", err)
}
if strings.Contains(reply, "new conversation") {
t.Errorf("reply = %q, should not claim the active conversation ended", reply)
}
if got := r.sessionTracker.getActive("chan-1", ""); got != active {
t.Errorf("active session = %q, want %q", got, active)
}
}
func TestRouteDeleteReportsStoreFailure(t *testing.T) {
store := newFakeSessionStore()
r := NewRouter(nil, nil, "test-gw")
r.InitSessions(store)
seedSession(t, r, store, "abcd-123", "chan-1", "Work")
r.Sessions = &deleteFailingStore{fakeSessionStore: store, err: errors.New("store unavailable")}
_, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete abcd-123"})
if err == nil {
t.Fatal("expected an error when the store cannot delete")
}
}
func TestRouteDeleteReportsListFailure(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
r.Sessions = &fakeSessionLister{
fakeSessionStore: newFakeSessionStore(),
err: errors.New("store unavailable"),
}
_, err := r.Route(context.Background(), Message{ChannelID: "chan-1", Text: "/delete abcd-123"})
if err == nil {
t.Fatal("expected an error when the store cannot list sessions")
}
}
// forget must clear every channel+thread pointing at the session, not just
// the one the command was typed in: the same session can be active in a
// flat chat and in a thread at once.
func TestSessionTrackerForgetClearsEveryReference(t *testing.T) {
tr := newSessionTracker(newFakeSessionStore())
tr.setActive("chan-1", "", "doomed")
tr.setActive("chan-1", "thread-1", "doomed")
tr.setActive("chan-2", "", "survivor")
tr.forget("doomed")
for _, key := range []struct{ channel, thread string }{{"chan-1", ""}, {"chan-1", "thread-1"}} {
if got := tr.getActive(key.channel, key.thread); got != "" {
t.Errorf("getActive(%q, %q) = %q, want empty", key.channel, key.thread, got)
}
}
if got := tr.getActive("chan-2", ""); got != "survivor" {
t.Errorf("getActive(chan-2) = %q, want survivor", got)
}
}
// An empty argument must not be treated as a session reference: it is a
// prefix of every ID.
func TestSessionTrackerForgetIgnoresEmptyID(t *testing.T) {
tr := newSessionTracker(newFakeSessionStore())
tr.setActive("chan-1", "", "keep-me")
tr.forget("")
if got := tr.getActive("chan-1", ""); got != "keep-me" {
t.Errorf("getActive = %q, want keep-me", got)
}
}
func TestDeleteIsAPublishedLocalCommand(t *testing.T) {
found := false
for _, spec := range LocalCommandSpecs() {
if spec.Command == "/delete" {
found = true
if !strings.Contains(spec.Usage, "<session-id>") {
t.Errorf("/delete usage %q does not name its argument", spec.Usage)
}
}
}
if !found {
t.Error("LocalCommandSpecs() does not advertise /delete")
}
}
+179
View File
@@ -0,0 +1,179 @@
package gateway
import (
"context"
"strings"
"time"
)
// TitleGenerator proposes a display title for an untitled session.
//
// The gateway invokes it asynchronously after a successful turn on a
// session that still has no title, and persists the result itself: the
// generator is a pure proposal and must not write to the session store.
// Returning an empty title declines; returning an error leaves the
// session untitled and is logged by the implementation. The gateway
// bounds the call with a timeout, so implementations need no deadline of
// their own, but must stop promptly when ctx is cancelled.
type TitleGenerator interface {
GenerateTitle(ctx context.Context, sessionID, firstMessage string) (string, error)
}
// TitleGenerationSystemPrompt instructs the model how to propose a
// session title. The title contract (length, shape) is messaging's
// concern, so the prompt lives beside the generator, and the result is
// still normalised by cleanGeneratedTitle before it is persisted.
const TitleGenerationSystemPrompt = `You write short titles for conversation logs.
Given the first user message of a new conversation, write a title for the
conversation. Requirements:
- 3 to 6 words, under 60 characters
- Name the topic, not a summary of the message
- No quotes, no bullet, no trailing period
- Reply with the title only, nothing else`
// maxTitleRunes caps how long a generated session title may be. Titles
// stay short enough to render on one line in a chat bubble.
const maxTitleRunes = 60
// titleGenerationTimeout bounds one title proposal. Titles are cosmetic;
// a stuck model call must not pin a goroutine forever.
const titleGenerationTimeout = 30 * time.Second
// maybeAutoTitle proposes a title for an untitled session after a
// successful turn, without delaying the reply. It runs in the
// background: the title is not worth blocking the turn on, and a failed
// or slow proposal must never fail the conversation.
//
// The triggering message becomes the title source -- the first user
// message the session successfully answered while it still had no
// title. For a fresh session that is its first message; for an older
// session that predates automatic titles, it is the first message
// observed after this code is deployed, i.e. the current topic.
func (r *Router) maybeAutoTitle(ctx context.Context, msg Message) {
if r.Titles == nil || r.sessionTracker == nil {
return
}
sessionID := r.sessionTracker.getActive(msg.ChannelID, msg.ThreadID)
if sessionID == "" || !r.claimTitleInFlight(sessionID) {
return
}
go r.generateTitle(context.WithoutCancel(ctx), sessionID, msg.Text)
}
// generateTitle runs one title proposal to completion: ask the
// generator, then persist the result if the session is still untitled.
func (r *Router) generateTitle(ctx context.Context, sessionID, firstMessage string) {
defer r.releaseTitleInFlight(sessionID)
// A proposal runs outside the turn lane, which is where the repo
// recovers panics for turns; a panic here would take the daemon down
// over a cosmetic title. Contain it: the title is optional, and a
// panic only loses that title.
defer func() {
if p := recover(); p != nil {
if r.Log != nil {
r.Log.Error("session title generation panicked", "session", sessionID, "panic", p)
}
}
}()
gctx, cancel := context.WithTimeout(ctx, titleGenerationTimeout)
defer cancel()
// A title may have landed since the turn (a manual /title, or a
// racing proposal that won the slot earlier and finished first). Ask
// for one only if the session still has none -- the proposal is the
// expensive part and must never run against a titled session.
sc, err := r.sessionTracker.sessions.Get(gctx, sessionID)
if err != nil {
r.debugTitle(sessionID, "session title skipped: read failed", err)
return
}
if sc == nil || sc.Title != "" {
return
}
title, err := r.Titles.GenerateTitle(gctx, sessionID, firstMessage)
if err != nil {
return
}
title = cleanGeneratedTitle(title)
if title == "" {
return
}
// Re-check before writing: a manual /title that lands while the
// proposal is in flight must win over the generated one. The re-read
// closes the multi-second generation window; the residual gap between
// this read and the Save below is a few microseconds and is left open
// deliberately -- closing it would need a store-level compare-and-set
// that a cosmetic path does not justify.
sc, err = r.sessionTracker.sessions.Get(gctx, sessionID)
if err != nil {
r.debugTitle(sessionID, "session title skipped: re-read failed", err)
return
}
if sc == nil || sc.Title != "" {
return
}
sc.Title = title
if err := r.sessionTracker.sessions.Save(gctx, *sc); err != nil {
r.debugTitle(sessionID, "session title not persisted", err)
}
}
// debugTitle reports a best-effort background failure through the
// router's optional logger. Without a logger these are dropped, exactly
// like the session tracker's best-effort touch; with one they are debug
// noise rather than alerts, because a missing title is never a turn
// failure.
func (r *Router) debugTitle(sessionID, msg string, err error) {
if r.Log != nil {
r.Log.Debug(msg, "session", sessionID, "err", err)
}
}
// claimTitleInFlight records that a title proposal is running for
// sessionID, reporting whether this call won the slot. Concurrent turns
// in one untitled session would otherwise each spawn a proposal; only
// the first one does, and the rest skip.
func (r *Router) claimTitleInFlight(sessionID string) bool {
r.titlingMu.Lock()
defer r.titlingMu.Unlock()
if r.titling == nil {
r.titling = make(map[string]struct{})
}
if _, ok := r.titling[sessionID]; ok {
return false
}
r.titling[sessionID] = struct{}{}
return true
}
// releaseTitleInFlight drops the in-flight marker once a proposal has
// finished, so a later turn can try again (the proposal may have failed).
func (r *Router) releaseTitleInFlight(sessionID string) {
r.titlingMu.Lock()
defer r.titlingMu.Unlock()
delete(r.titling, sessionID)
}
// cleanGeneratedTitle normalises a model-proposed title for display. The
// model is told to reply with a bare title, but it may wrap it in
// quotes, trail a period, or include stray whitespace; this turns
// whatever came back into a single trimmed line, and drops anything
// unusable.
func cleanGeneratedTitle(text string) string {
s := strings.Join(strings.Fields(text), " ")
s = strings.TrimSpace(s)
if len(s) >= 2 {
if (s[0] == '"' && s[len(s)-1] == '"') || (s[0] == '\'' && s[len(s)-1] == '\'') {
s = strings.TrimSpace(s[1 : len(s)-1])
}
}
s = strings.TrimSuffix(s, ".")
s = strings.TrimSpace(s)
if r := []rune(s); len(r) > maxTitleRunes {
s = string(r[:maxTitleRunes]) + "…"
}
return s
}
+416
View File
@@ -0,0 +1,416 @@
package gateway
import (
"context"
"errors"
"strings"
"sync"
"testing"
"time"
)
// stubTitleGenerator records calls and answers from a per-session table.
// When block is non-nil, GenerateTitle blocks until the channel closes,
// which tests use to hold a proposal in flight.
type stubTitleGenerator struct {
mu sync.Mutex
calls int
texts []string
sessionIDs []string
titles map[string]string
err error
block chan struct{}
// panicMsg, when set, makes GenerateTitle panic after any block wait.
panicMsg string
}
func (s *stubTitleGenerator) GenerateTitle(_ context.Context, sessionID, firstMessage string) (string, error) {
s.mu.Lock()
s.calls++
s.sessionIDs = append(s.sessionIDs, sessionID)
s.texts = append(s.texts, firstMessage)
s.mu.Unlock()
if s.block != nil {
<-s.block
}
if s.err != nil {
return "", s.err
}
if s.panicMsg != "" {
panic(s.panicMsg)
}
return s.titles[sessionID], nil
}
func (s *stubTitleGenerator) callCount() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.calls
}
func (s *stubTitleGenerator) lastText() string {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.texts) == 0 {
return ""
}
return s.texts[len(s.texts)-1]
}
// llmResponder is a deterministic LLMResponder for turn-path tests.
func llmResponder(reply string) LLMResponder {
return func(context.Context, Message) (string, error) { return reply, nil }
}
// waitForTitle polls the store until sessionID carries the wanted title.
// Title generation is asynchronous, so tests must wait rather than
// assume the reply path finished the write.
func waitForTitle(t *testing.T, store SessionStore, sessionID, want string) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
sc, err := store.Get(context.Background(), sessionID)
if err == nil && sc != nil && sc.Title == want {
return
}
time.Sleep(5 * time.Millisecond)
}
sc, _ := store.Get(context.Background(), sessionID)
var got string
if sc != nil {
got = sc.Title
}
t.Fatalf("title for %s never became %q (got %q)", sessionID, want, got)
}
func TestCleanGeneratedTitle(t *testing.T) {
long := strings.Repeat("x", maxTitleRunes+10)
cases := []struct {
name string
in string
want string
}{
{"plain", "Deploy the NATS worker", "Deploy the NATS worker"},
{"collapses whitespace", " spaced out\t\ntext ", "spaced out text"},
{"strips wrapping double quotes", `"Deploy the worker"`, "Deploy the worker"},
{"strips wrapping single quotes", "'Deploy the worker'", "Deploy the worker"},
{"strips trailing period", "Deploy the worker.", "Deploy the worker"},
{"empty", "", ""},
{"blank", " \n\t ", ""},
{"quote junk only", `""`, ""},
{"truncates long titles", long, strings.Repeat("x", maxTitleRunes) + "…"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := cleanGeneratedTitle(tc.in); got != tc.want {
t.Errorf("cleanGeneratedTitle(%q) = %q, want %q", tc.in, got, tc.want)
}
})
}
}
func TestRelativeAge(t *testing.T) {
now := time.Date(2026, 7, 28, 12, 0, 0, 0, time.UTC)
cases := []struct {
name string
at time.Time
want string
}{
{"just now", now.Add(-30 * time.Second), "just now"},
{"minutes", now.Add(-5 * time.Minute), "5m ago"},
{"hours", now.Add(-2 * time.Hour), "2h ago"},
{"days", now.Add(-3 * 24 * time.Hour), "3d ago"},
{"older dates", now.Add(-10 * 24 * time.Hour), "Jul 18"},
{"zero time", time.Time{}, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := relativeAge(tc.at, now); got != tc.want {
t.Errorf("relativeAge(%v) = %q, want %q", tc.at, got, tc.want)
}
})
}
}
func TestRenderSessionList(t *testing.T) {
now := time.Date(2026, 7, 28, 12, 0, 0, 0, time.UTC)
sessions := []SessionContext{
{
SessionID: "aaaaaaaa-1111-2222-3333-444444444444", Title: "Deploy NATS worker image",
CreatedAt: now.Add(-5 * time.Minute), LastActiveAt: now.Add(-5 * time.Minute),
},
{
SessionID: "bbbbbbbb-1111-2222-3333-444444444444", Title: "Fix telegram redelivery",
CreatedAt: now.Add(-2 * time.Hour), LastActiveAt: now.Add(-2 * time.Hour),
},
{
SessionID: "cccccccc-1111-2222-3333-444444444444",
CreatedAt: now.Add(-3 * 24 * time.Hour), LastActiveAt: now.Add(-3 * 24 * time.Hour),
},
}
got := renderSessionList(sessions, "aaaaaaaa-1111-2222-3333-444444444444", now)
want := "Sessions (3):\n" +
" 1. aaaaaaaa Deploy NATS worker image · active · 5m ago\n" +
" 2. bbbbbbbb Fix telegram redelivery · 2h ago\n" +
" 3. cccccccc (untitled) · 3d ago"
if got != want {
t.Errorf("renderSessionList:\n got:\n%q\nwant:\n%q", got, want)
}
}
func TestRenderSessionListEmpty(t *testing.T) {
if got := renderSessionList(nil, "", time.Now()); got != "No sessions." {
t.Errorf("renderSessionList(nil) = %q, want %q", got, "No sessions.")
}
}
func TestRouteSessionsRenderedList(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
store := NewSessionStoreMemory("test-node")
ctx := context.Background()
now := time.Now()
for _, sc := range []SessionContext{
{
SessionID: "aaaaaaaa-1111-2222-3333-444444444444", Title: "Deploy NATS worker image",
CreatedAt: now.Add(-5 * time.Minute), LastActiveAt: now.Add(-5 * time.Minute),
},
{
SessionID: "bbbbbbbb-1111-2222-3333-444444444444",
CreatedAt: now.Add(-2 * time.Hour), LastActiveAt: now.Add(-2 * time.Hour),
},
} {
if err := store.Save(ctx, sc); err != nil {
t.Fatalf("save session: %v", err)
}
}
r.InitSessions(store)
reply, err := r.Route(ctx, Message{Text: "/sessions"})
if err != nil {
t.Fatalf("Route: %v", err)
}
for _, want := range []string{
"Sessions (2):",
"1. aaaaaaaa Deploy NATS worker image",
"2. bbbbbbbb (untitled)",
"5m ago",
"2h ago",
} {
if !strings.Contains(reply, want) {
t.Errorf("reply = %q, want substring %q", reply, want)
}
}
}
func TestRouteAutoTitlesUntitledSession(t *testing.T) {
r := NewRouter(nil, llmResponder("reply ok"), "test-gw")
store := newFakeSessionStore()
r.InitSessions(store)
gen := &stubTitleGenerator{titles: map[string]string{}}
r.Titles = gen
ctx := context.Background()
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "Deploy the NATS worker"})
if err != nil {
t.Fatalf("resolve: %v", err)
}
gen.titles[sessionID] = "Deploy NATS worker"
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "Deploy the NATS worker"}); err != nil {
t.Fatalf("Route: %v", err)
}
waitForTitle(t, store, sessionID, "Deploy NATS worker")
if n := gen.callCount(); n != 1 {
t.Errorf("generator calls = %d, want 1", n)
}
if got := gen.lastText(); got != "Deploy the NATS worker" {
t.Errorf("title source = %q, want the triggering message", got)
}
}
// waitForTitleIdle waits until no title proposal is in flight. A
// correctly-skipped session never spawns a proposal, so it returns
// immediately; a wrongly-spawned one stays in flight (blocked on the
// stub) and times out. This pins that the background decision ran and
// finished, instead of passing vacuously because nothing ever started.
func waitForTitleIdle(t *testing.T, r *Router) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
r.titlingMu.Lock()
idle := len(r.titling) == 0
r.titlingMu.Unlock()
if idle {
return
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("title proposal still in flight after timeout")
}
func TestRouteDoesNotRetitleTitledSession(t *testing.T) {
r := NewRouter(nil, llmResponder("reply ok"), "test-gw")
store := newFakeSessionStore()
r.InitSessions(store)
gen := &stubTitleGenerator{titles: map[string]string{}}
// Never closed: if a proposal were wrongly spawned against this
// titled session, it would block here and waitForTitleIdle would time
// out -- turning the vacuous "no call" assertion into a hard failure.
gen.block = make(chan struct{})
r.Titles = gen
ctx := context.Background()
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "hello"})
if err != nil {
t.Fatalf("resolve: %v", err)
}
sc, err := store.Get(ctx, sessionID)
if err != nil || sc == nil {
t.Fatalf("get session: %v", err)
}
sc.Title = "Manual title"
if err := store.Save(ctx, *sc); err != nil {
t.Fatalf("save session: %v", err)
}
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "more text"}); err != nil {
t.Fatalf("Route: %v", err)
}
waitForTitleIdle(t, r)
if n := gen.callCount(); n != 0 {
t.Errorf("generator calls = %d, want 0 for a titled session", n)
}
sc, _ = store.Get(ctx, sessionID)
if sc == nil || sc.Title != "Manual title" {
t.Errorf("title = %q, want it untouched", sc.Title)
}
}
func TestRouteAutoTitleErrorKeepsUntitled(t *testing.T) {
r := NewRouter(nil, llmResponder("reply ok"), "test-gw")
store := newFakeSessionStore()
r.InitSessions(store)
gen := &stubTitleGenerator{err: errors.New("model down"), titles: map[string]string{}}
r.Titles = gen
ctx := context.Background()
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy"})
if err != nil {
t.Fatalf("resolve: %v", err)
}
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy"}); err != nil {
t.Fatalf("Route: %v", err)
}
// The proposal is spawned (the session is untitled) and must drain
// after the generator errors, leaving the session untitled.
waitForTitleIdle(t, r)
sc, _ := store.Get(ctx, sessionID)
if sc == nil || sc.Title != "" {
t.Errorf("title = %q, want empty after generator error", sc.Title)
}
}
func TestRouteAutoTitleInFlightGuard(t *testing.T) {
r := NewRouter(nil, llmResponder("reply ok"), "test-gw")
store := newFakeSessionStore()
r.InitSessions(store)
gen := &stubTitleGenerator{titles: map[string]string{}}
gen.block = make(chan struct{})
r.Titles = gen
ctx := context.Background()
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy"})
if err != nil {
t.Fatalf("resolve: %v", err)
}
gen.titles[sessionID] = "Deploy worker"
done := make(chan struct{})
go func() {
defer close(done)
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy"}); err != nil {
t.Errorf("Route 1: %v", err)
}
}()
// Wait until the first proposal is in flight and blocked.
deadline := time.Now().Add(2 * time.Second)
for gen.callCount() < 1 && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
<-done
// A second turn while the first proposal is still blocked must not
// spawn a second call: the guard lets one proposal win the session.
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy again"}); err != nil {
t.Fatalf("Route 2: %v", err)
}
time.Sleep(100 * time.Millisecond)
if n := gen.callCount(); n != 1 {
t.Errorf("generator calls = %d, want 1 (in-flight guard)", n)
}
close(gen.block)
waitForTitle(t, store, sessionID, "Deploy worker")
}
func TestRouteStreamAutoTitlesUntitledSession(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
store := newFakeSessionStore()
r.InitSessions(store)
gen := &stubTitleGenerator{titles: map[string]string{}}
r.Titles = gen
r.LLMStream = func(_ context.Context, _ Message, onDelta func(string)) (string, error) {
onDelta("r")
return "reply ok", nil
}
ctx := context.Background()
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "stream me"})
if err != nil {
t.Fatalf("resolve: %v", err)
}
gen.titles[sessionID] = "Stream topic"
if _, err := r.RouteStream(ctx, Message{ChannelID: "ch", From: "u", Text: "stream me"}, func(string) {}); err != nil {
t.Fatalf("RouteStream: %v", err)
}
waitForTitle(t, store, sessionID, "Stream topic")
}
func TestRouteAutoTitlePanicIsContained(t *testing.T) {
r := NewRouter(nil, llmResponder("reply ok"), "test-gw")
store := newFakeSessionStore()
r.InitSessions(store)
gen := &stubTitleGenerator{titles: map[string]string{}, panicMsg: "boom"}
r.Titles = gen
ctx := context.Background()
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy"})
if err != nil {
t.Fatalf("resolve: %v", err)
}
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy"}); err != nil {
t.Fatalf("Route: %v", err)
}
// If the recover is ever removed, the panic in the background
// goroutine crashes the test process: this test fails loudly.
waitForTitleIdle(t, r)
sc, _ := store.Get(ctx, sessionID)
if sc == nil || sc.Title != "" {
t.Errorf("title = %q, want empty after panicking generator", sc.Title)
}
}
func TestRetryAutoTitlesUntitledSession(t *testing.T) {
r := NewRouter(nil, llmResponder("reply ok"), "test-gw")
store := newFakeSessionStore()
r.InitSessions(store)
gen := &stubTitleGenerator{titles: map[string]string{}}
r.Titles = gen
ctx := context.Background()
sessionID, err := r.ResolveSessionKey(ctx, Message{ChannelID: "ch", From: "u", Text: "deploy the worker"})
if err != nil {
t.Fatalf("resolve: %v", err)
}
gen.titles[sessionID] = "Deploy worker"
if err := store.SaveMessage(ctx, sessionID, Message{From: "u", Text: "deploy the worker"}); err != nil {
t.Fatalf("save user message: %v", err)
}
if err := store.SaveMessage(ctx, sessionID, Message{From: "bot", Text: "sure"}); err != nil {
t.Fatalf("save reply: %v", err)
}
if _, err := r.Route(ctx, Message{ChannelID: "ch", From: "u", Text: "/retry"}); err != nil {
t.Fatalf("Route /retry: %v", err)
}
waitForTitle(t, store, sessionID, "Deploy worker")
if got := gen.lastText(); got != "deploy the worker" {
t.Errorf("title source = %q, want the replayed message", got)
}
}
+32 -6
View File
@@ -15,6 +15,7 @@ import (
"context"
"encoding/json"
"log/slog"
"strings"
"time"
"github.com/nats-io/nats.go"
@@ -28,6 +29,19 @@ const (
SubjectPrepare = "archie.worktree.prepare"
)
// SubjectFor returns the subject for base, scoped to identity when set.
// An empty identity uses the root subject (single-identity deployments and
// agent images that predate identity routing). The daemon registers one
// server per identity on these scoped subjects so a container-mode task
// owned by a non-root identity has its push/prepare calls served by that
// identity's own worktree manager (its own credential and workdir).
func SubjectFor(identity, base string) string {
if identity == "" {
return base
}
return "archie.worktree." + identity + "." + strings.TrimPrefix(base, "archie.worktree.")
}
// PushRequest identifies the task's worktree by owner/repo/issue rather
// than trusting a path from the (sandboxed) agent -- the server resolves
// the directory itself via worktree.Manager.Dir.
@@ -88,12 +102,19 @@ func (s *Server) handlerContext() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), timeout)
}
// Register subscribes the push and prepare handlers on nc. The returned
// func unsubscribes both.
// Register subscribes the push and prepare handlers on nc under the root
// (identity-less) subjects. RegisterFor(nc, identity) registers them under
// that identity's scoped subjects; the daemon calls it once per identity.
func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) {
return s.RegisterFor(nc, "")
}
// RegisterFor registers the push and prepare handlers under the subjects
// scoped to identity.
func (s *Server) RegisterFor(nc *nats.Conn, identity string) (unsubscribe func(), err error) {
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
{Subject: SubjectPush, Handler: s.handlePush},
{Subject: SubjectPrepare, Handler: s.handlePrepare},
{Subject: SubjectFor(identity, SubjectPush), Handler: s.handlePush},
{Subject: SubjectFor(identity, SubjectPrepare), Handler: s.handlePrepare},
})
}
@@ -135,15 +156,20 @@ type Client struct {
Conn *nats.Conn
// Timeout bounds each call when ctx has no deadline of its own.
Timeout time.Duration
// Identity scopes this client's calls to one identity's RPC server.
// Empty uses the root subjects (single-identity deployments).
Identity string
}
func (c *Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} }
func (c *Client) subject(base string) string { return SubjectFor(c.Identity, base) }
// Push requests that archied push branch for owner/repo/issue's worktree
// using its held forge credential.
func (c *Client) Push(ctx context.Context, owner, repo string, issue int, branch string) error {
req := PushRequest{Owner: owner, Repo: repo, Issue: issue, Branch: branch}
resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectPush, req)
resp, err := natsrpc.Call[Response](ctx, c.rpc(), c.subject(SubjectPush), req)
if err != nil {
return err
}
@@ -155,7 +181,7 @@ func (c *Client) Push(ctx context.Context, owner, repo string, issue int, branch
// worktree.Manager.Prepare's signature.
func (c *Client) Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string) (dir, branch string, err error) {
req := PrepareRequest{Owner: owner, Repo: repo, Base: base, Issue: issue, Title: title, Body: body, Labels: labels}
resp, err := natsrpc.Call[PrepareResponse](ctx, c.rpc(), SubjectPrepare, req)
resp, err := natsrpc.Call[PrepareResponse](ctx, c.rpc(), c.subject(SubjectPrepare), req)
if err != nil {
return "", "", err
}
+14
View File
@@ -217,6 +217,20 @@ func TestClientPushTimesOutWithNoResponder(t *testing.T) {
}
}
// SubjectFor leaves the root subject unchanged for an empty identity and
// prefixes the identity for a non-empty one.
func TestSubjectFor(t *testing.T) {
if got := SubjectFor("", SubjectPush); got != SubjectPush {
t.Fatalf("SubjectFor(\"\", %q) = %q, want unchanged root subject", SubjectPush, got)
}
if got := SubjectFor("winter", SubjectPush); got != "archie.worktree.winter.push" {
t.Fatalf("SubjectFor(\"winter\", %q) = %q", SubjectPush, got)
}
if got := SubjectFor("winter", SubjectPrepare); got != "archie.worktree.winter.prepare" {
t.Fatalf("SubjectFor(\"winter\", %q) = %q", SubjectPrepare, got)
}
}
// A handler must impose its own deadline. NATS request/reply carries no
// deadline to the server, and a clone or push now runs in-process via
// go-git, so an unresponsive forge would otherwise wedge the handler