gateway: add /steer, /goal, /subgoal, and /queue chat commands
Implement session-scoped goal/subgoal/steer/queue state management with thread-safe access and prompt injection for standing goals. Commands: - /steer <text> — queue a message to inject after the next tool call - /goal [text|draft|show|pause|resume|clear|status|wait|unwait] - /subgoal [text|remove N|clear] - /queue (aliases /q, /bg, /btw, /background) [text|remove N|clear] Architecture: - SessionState in internal/gateway holds per-session goals, subgoals, steer queue, wait flag, and background queue - Goals are injected into the system prompt via BuildGoalPrompt() - Steer messages are consumed between agent tool-calling steps via a MaxSteps=1 loop in the daemon's respond closure - Commands route through the existing gateway.Router with not-configured guards when State is nil Closes: archie-core-alm.1
This commit is contained in:
1 parent
d92ac87c25
commit
6f549fe0a1
7 files changed
+1481
-33
No files matched your search
+139
-30
@@ -99,6 +99,42 @@ func chatGenerateOptions(
|
||||
}, nil
|
||||
}
|
||||
|
||||
// appendStepMessages appends the assistant turn and tool-result
|
||||
// messages for a single generation step to msgs so the next call
|
||||
// has the complete conversation history.
|
||||
func appendStepMessages(msgs []chat.Message, step core.StepResult) []chat.Message {
|
||||
// Build assistant message with tool calls.
|
||||
var toolCalls []chat.ToolCall
|
||||
for _, tc := range step.ToolCalls {
|
||||
toolCalls = append(toolCalls, chat.ToolCall{
|
||||
ID: tc.ToolCallID,
|
||||
Name: tc.ToolName,
|
||||
Arguments: tc.Input,
|
||||
})
|
||||
}
|
||||
msgs = append(msgs, chat.Message{
|
||||
Role: chat.RoleAssistant,
|
||||
Content: step.Text,
|
||||
Parts: step.Parts,
|
||||
ToolCalls: toolCalls,
|
||||
})
|
||||
|
||||
// Build one tool-result message per tool execution.
|
||||
for _, tr := range step.ToolResults {
|
||||
content := tr.Output
|
||||
if tr.Error != "" {
|
||||
content = tr.Error
|
||||
}
|
||||
msgs = append(msgs, chat.Message{
|
||||
Role: chat.RoleTool,
|
||||
Content: content,
|
||||
ToolCallID: tr.ToolCallID,
|
||||
Name: tr.ToolName,
|
||||
})
|
||||
}
|
||||
return msgs
|
||||
}
|
||||
|
||||
func configuredMCPProvider(server config.MCPServer) (toolprovider.Engine, error) {
|
||||
name := strings.TrimSpace(server.Name)
|
||||
if name == "" {
|
||||
@@ -362,6 +398,11 @@ func run() int {
|
||||
sessionStore = gateway.NewSessionStoreMemory(cfg.BotUser)
|
||||
}
|
||||
|
||||
// Session-scoped state for /goal, /steer, /subgoal, and /queue
|
||||
// commands. Created before the LLM responder so it is in scope
|
||||
// for the chat loop; wired into the router afterward.
|
||||
sessionState := gateway.NewSessionState()
|
||||
|
||||
// Build an LLM responder from the runtime. Gateway-local commands
|
||||
// (/status, /model, /spawn) are handled directly; all
|
||||
// other messages are routed through the LLM with conversation
|
||||
@@ -420,6 +461,14 @@ func run() int {
|
||||
SessionID: sessionKey,
|
||||
Now: time.Now(),
|
||||
})
|
||||
// Inject standing goal and subgoals into the system
|
||||
// prompt when set via /goal. The goal prompt is
|
||||
// appended so it overrides nothing in the base
|
||||
// prompt; the instruction-precedence hierarchy
|
||||
// already ranks user requests above conventions.
|
||||
if goalPrompt := sessionState.BuildGoalPrompt(); goalPrompt != "" {
|
||||
systemPrompt += "\n\n" + goalPrompt
|
||||
}
|
||||
view.Messages = append(
|
||||
[]gateway.CompressedMessage{{Role: "system", Content: systemPrompt}},
|
||||
view.Messages...,
|
||||
@@ -443,40 +492,99 @@ func run() int {
|
||||
|
||||
options.Messages = messages
|
||||
|
||||
// Run one model-call-plus-tool-execution at a time
|
||||
// so /steer messages can be injected between steps.
|
||||
// Each call to Chat/ChatStream processes exactly
|
||||
// one step; the loop here manages the full
|
||||
// conversation state by appending the model's
|
||||
// response and tool results after each iteration.
|
||||
options.MaxSteps = 1
|
||||
|
||||
var text string
|
||||
if onDelta == nil {
|
||||
result, err := llm.Chat(ctx, chatModel, options)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("llm chat: %w", err)
|
||||
}
|
||||
text = result.Text
|
||||
} else {
|
||||
stream, err := llm.ChatStream(ctx, chatModel, options)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("llm chat stream: %w", err)
|
||||
}
|
||||
// Consume FullStream, not TextStream. Per the ai-sdk
|
||||
// channel contract FullStream is authoritative and MUST
|
||||
// be drained until close: its writes are synchronous, so
|
||||
// leaving it unread stalls the producer and deadlocks the
|
||||
// whole turn. TextStream is a best-effort view that drops
|
||||
// deltas when it is not being read, so it cannot be used
|
||||
// to reconstruct the reply either.
|
||||
var sb strings.Builder
|
||||
for part := range stream.FullStream {
|
||||
if part.Type != core.StreamPartTextDelta || part.TextDelta == "" {
|
||||
continue
|
||||
for {
|
||||
if onDelta == nil {
|
||||
result, err := llm.Chat(ctx, chatModel, options)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("llm chat: %w", err)
|
||||
}
|
||||
text = result.Text
|
||||
|
||||
// Append the steps to messages so the next
|
||||
// call has the full conversation history.
|
||||
for _, step := range result.Steps {
|
||||
options.Messages = appendStepMessages(options.Messages, step)
|
||||
}
|
||||
|
||||
// No tool calls in the final step means
|
||||
// the model finished.
|
||||
if result.FinishReason != core.FinishReasonToolCalls {
|
||||
break
|
||||
}
|
||||
} else {
|
||||
stream, err := llm.ChatStream(ctx, chatModel, options)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("llm chat stream: %w", err)
|
||||
}
|
||||
// Consume FullStream, not TextStream. Per the
|
||||
// ai-sdk channel contract FullStream is
|
||||
// authoritative and MUST be drained until
|
||||
// close.
|
||||
var sb strings.Builder
|
||||
var stepText strings.Builder
|
||||
var stepToolCalls []core.ToolCall
|
||||
var stepToolResults []core.ToolResult
|
||||
var stepParts chat.Parts
|
||||
for part := range stream.FullStream {
|
||||
switch part.Type {
|
||||
case core.StreamPartTextDelta:
|
||||
if part.TextDelta != "" {
|
||||
sb.WriteString(part.TextDelta)
|
||||
stepText.WriteString(part.TextDelta)
|
||||
onDelta(part.TextDelta)
|
||||
}
|
||||
case core.StreamPartToolCall:
|
||||
if part.ToolCall != nil {
|
||||
stepToolCalls = append(stepToolCalls, *part.ToolCall)
|
||||
}
|
||||
case core.StreamPartToolResult:
|
||||
if part.ToolResult != nil {
|
||||
stepToolResults = append(stepToolResults, *part.ToolResult)
|
||||
}
|
||||
case core.StreamPartFinishStep:
|
||||
if part.StepResult != nil {
|
||||
stepParts = part.StepResult.Parts
|
||||
}
|
||||
}
|
||||
}
|
||||
reason, err := stream.FinishReason()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("llm chat stream: %w", err)
|
||||
}
|
||||
text = sb.String()
|
||||
|
||||
// Append the step to the conversation.
|
||||
options.Messages = appendStepMessages(options.Messages, core.StepResult{
|
||||
Text: stepText.String(),
|
||||
Parts: stepParts,
|
||||
ToolCalls: stepToolCalls,
|
||||
ToolResults: stepToolResults,
|
||||
})
|
||||
|
||||
// No more tool calls — done.
|
||||
if len(stepToolCalls) == 0 && reason != core.FinishReasonToolCalls {
|
||||
break
|
||||
}
|
||||
sb.WriteString(part.TextDelta)
|
||||
onDelta(part.TextDelta)
|
||||
}
|
||||
// Resolves once the producer completes, so a mid-stream
|
||||
// failure surfaces here rather than a truncated reply
|
||||
// passing as a short but complete one.
|
||||
if _, err := stream.FinishReason(); err != nil {
|
||||
return "", fmt.Errorf("llm chat stream: %w", err)
|
||||
|
||||
// Check for pending /steer messages. Inject after
|
||||
// every tool-execution step so guidance arrives
|
||||
// at the earliest safe point.
|
||||
if steerText, ok := sessionState.PollSteer(); ok {
|
||||
options.Messages = append(options.Messages, chat.Message{
|
||||
Role: chat.RoleUser,
|
||||
Content: "[STEER] " + steerText,
|
||||
})
|
||||
}
|
||||
text = sb.String()
|
||||
}
|
||||
|
||||
// Persist the response.
|
||||
@@ -501,6 +609,7 @@ func run() int {
|
||||
router := gateway.NewRouter(st, llmResponder, "telegram")
|
||||
router.LLMStream = llmStream
|
||||
router.Models = chatModels
|
||||
router.State = sessionState
|
||||
configureTaskCommands(router, chatTasks, chatController, defaultChatIdentity)
|
||||
startGateways = append(startGateways, func() {
|
||||
go func() {
|
||||
|
||||
@@ -26,6 +26,11 @@ var gatewayCommandSpecs = []commandSpec{
|
||||
{Command: "model", Description: "Show the model selector or switch directly", Usage: "/model [provider/model]"},
|
||||
{Command: "spawn", Description: "Create a tracked task", Usage: "/spawn [identity=name] [repo=owner/name] [workflow=name] <title>"},
|
||||
{Command: "cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel [identity=name] <task-id>"},
|
||||
{Command: "goal", Description: "Manage standing goals", Usage: "/goal [text|draft|show|pause|resume|clear|status|wait|unwait]"},
|
||||
{Command: "subgoal", Description: "Manage subgoals under the current goal", Usage: "/subgoal [text|remove N|clear]"},
|
||||
{Command: "steer", Description: "Queue a message to inject after the next tool call", Usage: "/steer <message>"},
|
||||
{Command: "queue", Description: "Manage a background task queue", Usage: "/queue [text|remove N|clear]"},
|
||||
{Command: "q", Description: "Alias for /queue", Usage: "/q [text|remove N|clear]"},
|
||||
{Command: "restart", Description: "Reload Archie and its configuration", Usage: "/restart"},
|
||||
{Command: "help", Description: "See what Archie can do", Usage: "/help"},
|
||||
}
|
||||
|
||||
@@ -161,7 +161,13 @@ func TestVersionReportsBothComponents(t *testing.T) {
|
||||
// dangerous and should not be discoverable by casual chat users. Commands in
|
||||
// this set may still be executable if typed explicitly — they just shouldn't
|
||||
// appear on Telegram's discoverability surfaces.
|
||||
var telegramHiddenCommands = map[string]bool{"approve": true}
|
||||
var telegramHiddenCommands = map[string]bool{
|
||||
"approve": true, // dangerous command, intentionally hidden
|
||||
"bg": true, // alias for /queue
|
||||
"background": true, // alias for /queue
|
||||
"btw": true, // alias for /queue
|
||||
"q": true, // alias for /queue
|
||||
}
|
||||
|
||||
func TestPublishedCommandsMatchExecutableCommandSurface(t *testing.T) {
|
||||
executable := make(map[string]bool)
|
||||
|
||||
+212
-2
@@ -145,7 +145,13 @@ type Router struct {
|
||||
// used to scope /approve and /cancel authorization -- a task
|
||||
// spawned under one identity cannot be controlled from another's
|
||||
// chat session.
|
||||
Identity string
|
||||
Identity string
|
||||
// State holds per-session goal, subgoal, steer, and queue state.
|
||||
// When nil, /goal, /steer, /subgoal, and /queue return
|
||||
// "not configured". The daemon wires one SessionState per router
|
||||
// (one per gateway). Multi-identity deployments that need
|
||||
// per-identity state should provide separate routers.
|
||||
State *SessionState
|
||||
gatewayName string
|
||||
}
|
||||
|
||||
@@ -178,6 +184,14 @@ func (r *Router) Route(ctx context.Context, msg Message) (string, error) {
|
||||
return r.handleApprove(ctx, restAfter(text, cmd, r.gatewayName))
|
||||
case "/cancel":
|
||||
return r.handleCancel(ctx, restAfter(text, cmd, r.gatewayName))
|
||||
case "/steer":
|
||||
return r.handleSteer(ctx, restAfter(text, cmd, r.gatewayName))
|
||||
case "/goal":
|
||||
return r.handleGoal(ctx, restAfter(text, cmd, r.gatewayName))
|
||||
case "/subgoal":
|
||||
return r.handleSubgoal(ctx, restAfter(text, cmd, r.gatewayName))
|
||||
case "/queue", "/q", "/background", "/bg", "/btw":
|
||||
return r.handleQueue(ctx, restAfter(text, cmd, r.gatewayName))
|
||||
default:
|
||||
if strings.HasPrefix(cmd, "/") {
|
||||
return fmt.Sprintf("Unknown command %s. Try /help.", cmd), nil
|
||||
@@ -210,7 +224,7 @@ func (r *Router) RouteStream(ctx context.Context, msg Message, onDelta func(stri
|
||||
return r.LLMStream(ctx, msg, onDelta)
|
||||
}
|
||||
|
||||
var localCommands = []string{"/status", "/model", "/spawn", "/approve", "/cancel"}
|
||||
var localCommands = []string{"/status", "/model", "/spawn", "/approve", "/cancel", "/steer", "/goal", "/subgoal", "/queue", "/q", "/background", "/bg", "/btw"}
|
||||
|
||||
// LocalCommands returns the command names Route answers from local state.
|
||||
// Gateways use this to verify that their published command surfaces match
|
||||
@@ -379,6 +393,202 @@ func parseTaskControl(rest, defaultIdentity string) (identity, taskID string) {
|
||||
return identity, fields[0]
|
||||
}
|
||||
|
||||
// ── /steer ────────────────────────────────────────────────────────
|
||||
|
||||
func (r *Router) handleSteer(ctx context.Context, rest string) (string, error) {
|
||||
if r.State == nil {
|
||||
return "Steering is not configured.", nil
|
||||
}
|
||||
rest = strings.TrimSpace(rest)
|
||||
if rest == "" {
|
||||
if text, ok := r.State.PeekSteer(); ok {
|
||||
return fmt.Sprintf("Pending steer: %s", text), nil
|
||||
}
|
||||
return "No steer pending. Usage: /steer <message> — inject after next tool call.", nil
|
||||
}
|
||||
r.State.SetSteer(rest)
|
||||
return fmt.Sprintf("Steer queued: %s", rest), nil
|
||||
}
|
||||
|
||||
// ── /goal ──────────────────────────────────────────────────────────
|
||||
|
||||
func (r *Router) handleGoal(ctx context.Context, rest string) (string, error) {
|
||||
if r.State == nil {
|
||||
return "Goals are not configured.", nil
|
||||
}
|
||||
rest = strings.TrimSpace(rest)
|
||||
if rest == "" || rest == "show" {
|
||||
return r.goalShow(), nil
|
||||
}
|
||||
|
||||
subcmd, _ := splitFirst(rest)
|
||||
switch subcmd {
|
||||
case "draft":
|
||||
return "Send a message describing what you want the goal to be, and I'll suggest one. Or use /goal <text> to set it directly.", nil
|
||||
case "pause":
|
||||
if !r.State.PauseGoal() {
|
||||
return "No goal to pause.", nil
|
||||
}
|
||||
return "Goal paused.", nil
|
||||
case "resume":
|
||||
if !r.State.ResumeGoal() {
|
||||
return "No goal to resume.", nil
|
||||
}
|
||||
return "Goal resumed.", nil
|
||||
case "clear":
|
||||
r.State.ClearGoal()
|
||||
return "Goal and subgoals cleared.", nil
|
||||
case "status":
|
||||
return r.goalStatus(), nil
|
||||
case "wait":
|
||||
if !r.State.HasGoal() {
|
||||
return "No goal to wait on.", nil
|
||||
}
|
||||
r.State.SetWait()
|
||||
return "Goal wait flag set. I'll pause new work toward the goal until /goal unwait.", nil
|
||||
case "unwait":
|
||||
r.State.ClearWait()
|
||||
return "Goal wait flag cleared. I may resume work toward the goal.", nil
|
||||
default:
|
||||
// Treat as goal text.
|
||||
r.State.SetGoal(rest, false)
|
||||
return fmt.Sprintf("Goal set: %s", rest), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) goalShow() string {
|
||||
goals := r.State.Goals()
|
||||
if len(goals) == 0 {
|
||||
return "No goal set. Use /goal <text> to set one."
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("🎯 **Goal**")
|
||||
if goals[0].Status == GoalPaused {
|
||||
b.WriteString(" (paused)")
|
||||
}
|
||||
b.WriteString("\n")
|
||||
b.WriteString(goals[0].Text)
|
||||
|
||||
subgoals := r.State.Subgoals()
|
||||
if len(subgoals) > 0 {
|
||||
b.WriteString("\n\n**Subgoals**\n")
|
||||
for i, sg := range subgoals {
|
||||
fmt.Fprintf(&b, "%d. %s\n", i+1, sg.Text)
|
||||
}
|
||||
}
|
||||
|
||||
if r.State.IsWaiting() {
|
||||
b.WriteString("\n⏸️ Waiting — use /goal unwait to resume.")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (r *Router) goalStatus() string {
|
||||
goals := r.State.Goals()
|
||||
if len(goals) == 0 {
|
||||
return "No goal."
|
||||
}
|
||||
status := string(goals[0].Status)
|
||||
if r.State.IsWaiting() {
|
||||
status += ", waiting"
|
||||
}
|
||||
sgCount := len(r.State.Subgoals())
|
||||
return fmt.Sprintf("Goal: %s (%d subgoals)", status, sgCount)
|
||||
}
|
||||
|
||||
// ── /subgoal ───────────────────────────────────────────────────────
|
||||
|
||||
func (r *Router) handleSubgoal(ctx context.Context, rest string) (string, error) {
|
||||
if r.State == nil {
|
||||
return "Subgoals are not configured.", nil
|
||||
}
|
||||
rest = strings.TrimSpace(rest)
|
||||
if rest == "" || rest == "show" {
|
||||
subgoals := r.State.Subgoals()
|
||||
if len(subgoals) == 0 {
|
||||
return "No subgoals. Use /subgoal <text> to add one.", nil
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("**Subgoals**\n")
|
||||
for i, sg := range subgoals {
|
||||
fmt.Fprintf(&b, "%d. %s\n", i+1, sg.Text)
|
||||
}
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
subcmd, arg := splitFirst(rest)
|
||||
switch subcmd {
|
||||
case "remove":
|
||||
n, err := strconv.Atoi(arg)
|
||||
if err != nil || n < 1 {
|
||||
return "Usage: /subgoal remove <N>", nil
|
||||
}
|
||||
if !r.State.RemoveSubgoal(n) {
|
||||
return fmt.Sprintf("No subgoal at position %d.", n), nil
|
||||
}
|
||||
return fmt.Sprintf("Subgoal %d removed.", n), nil
|
||||
case "clear":
|
||||
r.State.ClearSubgoals()
|
||||
return "Subgoals cleared.", nil
|
||||
default:
|
||||
if !r.State.AddSubgoal(rest) {
|
||||
return "No goal set. Use /goal <text> first.", nil
|
||||
}
|
||||
return fmt.Sprintf("Subgoal added: %s", rest), nil
|
||||
}
|
||||
}
|
||||
|
||||
// ── /queue (aliases /q, /background, /bg, /btw) ────────────────────
|
||||
|
||||
func (r *Router) handleQueue(ctx context.Context, rest string) (string, error) {
|
||||
if r.State == nil {
|
||||
return "Queue is not configured.", nil
|
||||
}
|
||||
rest = strings.TrimSpace(rest)
|
||||
if rest == "" || rest == "show" {
|
||||
entries := r.State.QueueEntries()
|
||||
if len(entries) == 0 {
|
||||
return "Queue is empty. Use /queue <text> to add an item.", nil
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("**Queue**\n")
|
||||
for i, e := range entries {
|
||||
fmt.Fprintf(&b, "%d. %s\n", i+1, e.Text)
|
||||
}
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
subcmd, arg := splitFirst(rest)
|
||||
switch subcmd {
|
||||
case "remove":
|
||||
n, err := strconv.Atoi(arg)
|
||||
if err != nil || n < 1 {
|
||||
return "Usage: /queue remove <N>", nil
|
||||
}
|
||||
if !r.State.RemoveFromQueue(n) {
|
||||
return fmt.Sprintf("No queue item at position %d.", n), nil
|
||||
}
|
||||
return fmt.Sprintf("Queue item %d removed.", n), nil
|
||||
case "clear":
|
||||
r.State.ClearQueue()
|
||||
return "Queue cleared.", nil
|
||||
default:
|
||||
r.State.AddToQueue(rest)
|
||||
return fmt.Sprintf("Queued: %s", rest), nil
|
||||
}
|
||||
}
|
||||
|
||||
// splitFirst splits s on the first whitespace and returns the first
|
||||
// field and the remainder.
|
||||
func splitFirst(s string) (first, rest string) {
|
||||
s = strings.TrimSpace(s)
|
||||
before, after, ok := strings.Cut(s, " ")
|
||||
if !ok {
|
||||
return s, ""
|
||||
}
|
||||
return before, strings.TrimSpace(after)
|
||||
}
|
||||
|
||||
func (r *Router) handleStatus(ctx context.Context) (string, error) {
|
||||
if r.Store == nil {
|
||||
return "store not configured", nil
|
||||
|
||||
@@ -616,3 +616,506 @@ func TestRouteCancelNotConfigured(t *testing.T) {
|
||||
t.Errorf("reply = %q, want 'not configured'", reply)
|
||||
}
|
||||
}
|
||||
|
||||
// -- /steer tests --
|
||||
|
||||
func routerWithState() *Router {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
r.State = NewSessionState()
|
||||
return r
|
||||
}
|
||||
|
||||
func TestRouteSteerQueuesMessage(t *testing.T) {
|
||||
r := routerWithState()
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/steer check the logs"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "Steer queued") {
|
||||
t.Errorf("reply = %q, want confirmation", reply)
|
||||
}
|
||||
if text, ok := r.State.PollSteer(); !ok || text != "check the logs" {
|
||||
t.Errorf("PollSteer() = (%q, %v), want (check the logs, true)", text, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteSteerShowsPending(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.SetSteer("pending steer")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/steer"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "Pending steer") || !strings.Contains(reply, "pending steer") {
|
||||
t.Errorf("reply = %q, want pending steer message", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteSteerEmpty(t *testing.T) {
|
||||
r := routerWithState()
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/steer"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "No steer pending") {
|
||||
t.Errorf("reply = %q, want usage message", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteSteerNotConfigured(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/steer do x"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "not configured") {
|
||||
t.Errorf("reply = %q, want 'not configured'", reply)
|
||||
}
|
||||
}
|
||||
|
||||
// -- /goal tests --
|
||||
|
||||
func TestRouteGoalSet(t *testing.T) {
|
||||
r := routerWithState()
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/goal ship the feature"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "Goal set") || !strings.Contains(reply, "ship the feature") {
|
||||
t.Errorf("reply = %q, want goal set confirmation", reply)
|
||||
}
|
||||
goals := r.State.Goals()
|
||||
if len(goals) != 1 || goals[0].Text != "ship the feature" {
|
||||
t.Errorf("Goals() = %+v, want [ship the feature]", goals)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteGoalShow(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.SetGoal("do the thing", false)
|
||||
r.State.AddSubgoal("step one")
|
||||
r.State.AddSubgoal("step two")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/goal"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "do the thing") {
|
||||
t.Error("reply missing goal text")
|
||||
}
|
||||
if !strings.Contains(reply, "step one") {
|
||||
t.Error("reply missing subgoal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteGoalShowEmpty(t *testing.T) {
|
||||
r := routerWithState()
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/goal"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "No goal set") {
|
||||
t.Errorf("reply = %q, want 'No goal set'", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteGoalPauseResume(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.SetGoal("work", false)
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/goal pause"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "Goal paused") {
|
||||
t.Errorf("reply = %q, want Goal paused", reply)
|
||||
}
|
||||
|
||||
reply, err = r.Route(context.Background(), Message{Text: "/goal resume"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "Goal resumed") {
|
||||
t.Errorf("reply = %q, want Goal resumed", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteGoalPauseWithoutGoal(t *testing.T) {
|
||||
r := routerWithState()
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/goal pause"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "No goal to pause") {
|
||||
t.Errorf("reply = %q, want 'No goal to pause'", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteGoalClear(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.SetGoal("x", false)
|
||||
r.State.AddSubgoal("y")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/goal clear"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "cleared") {
|
||||
t.Errorf("reply = %q, want cleared", reply)
|
||||
}
|
||||
if r.State.HasGoal() {
|
||||
t.Error("HasGoal() = true after /goal clear")
|
||||
}
|
||||
if len(r.State.Subgoals()) != 0 {
|
||||
t.Error("subgoals not cleared")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteGoalStatus(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.SetGoal("g", false)
|
||||
r.State.AddSubgoal("sg")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/goal status"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "Goal:") || !strings.Contains(reply, "1 subgoal") {
|
||||
t.Errorf("reply = %q, want status line", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteGoalWaitUnwait(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.SetGoal("g", false)
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/goal wait"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "wait flag set") {
|
||||
t.Errorf("reply = %q, want wait flag set", reply)
|
||||
}
|
||||
if !r.State.IsWaiting() {
|
||||
t.Error("IsWaiting() = false after /goal wait")
|
||||
}
|
||||
|
||||
reply, err = r.Route(context.Background(), Message{Text: "/goal unwait"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "wait flag cleared") {
|
||||
t.Errorf("reply = %q, want wait flag cleared", reply)
|
||||
}
|
||||
if r.State.IsWaiting() {
|
||||
t.Error("IsWaiting() = true after /goal unwait")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteGoalWaitWithoutGoal(t *testing.T) {
|
||||
r := routerWithState()
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/goal wait"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "No goal to wait") {
|
||||
t.Errorf("reply = %q, want 'No goal to wait'", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteGoalNotConfigured(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/goal show"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "not configured") {
|
||||
t.Errorf("reply = %q, want 'not configured'", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteGoalDraft(t *testing.T) {
|
||||
r := routerWithState()
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/goal draft"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "I'll suggest one") {
|
||||
t.Errorf("reply = %q, want draft prompt", reply)
|
||||
}
|
||||
}
|
||||
|
||||
// -- /subgoal tests --
|
||||
|
||||
func TestRouteSubgoalAdd(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.SetGoal("goal", false)
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/subgoal write tests"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "Subgoal added") || !strings.Contains(reply, "write tests") {
|
||||
t.Errorf("reply = %q, want confirmation", reply)
|
||||
}
|
||||
if len(r.State.Subgoals()) != 1 || r.State.Subgoals()[0].Text != "write tests" {
|
||||
t.Error("subgoal not stored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteSubgoalAddWithoutGoal(t *testing.T) {
|
||||
r := routerWithState()
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/subgoal do x"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "No goal set") {
|
||||
t.Errorf("reply = %q, want 'No goal set'", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteSubgoalShow(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.SetGoal("g", false)
|
||||
r.State.AddSubgoal("a")
|
||||
r.State.AddSubgoal("b")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/subgoal"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "a") || !strings.Contains(reply, "b") {
|
||||
t.Errorf("reply = %q, want subgoals a and b", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteSubgoalShowEmpty(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.SetGoal("g", false)
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/subgoal"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "No subgoals") {
|
||||
t.Errorf("reply = %q, want 'No subgoals'", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteSubgoalRemove(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.SetGoal("g", false)
|
||||
r.State.AddSubgoal("a")
|
||||
r.State.AddSubgoal("b")
|
||||
r.State.AddSubgoal("c")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/subgoal remove 2"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "removed") {
|
||||
t.Errorf("reply = %q, want removed", reply)
|
||||
}
|
||||
sgs := r.State.Subgoals()
|
||||
if len(sgs) != 2 || sgs[0].Text != "a" || sgs[1].Text != "c" {
|
||||
t.Errorf("Subgoals() = %+v, want [a, c]", sgs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteSubgoalRemoveOutOfRange(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.SetGoal("g", false)
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/subgoal remove 5"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "No subgoal at position") {
|
||||
t.Errorf("reply = %q, want 'No subgoal at position'", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteSubgoalClear(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.SetGoal("g", false)
|
||||
r.State.AddSubgoal("a")
|
||||
r.State.AddSubgoal("b")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/subgoal clear"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "cleared") {
|
||||
t.Errorf("reply = %q, want cleared", reply)
|
||||
}
|
||||
if len(r.State.Subgoals()) != 0 {
|
||||
t.Error("Subgoals not cleared")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteSubgoalNotConfigured(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/subgoal add x"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "not configured") {
|
||||
t.Errorf("reply = %q, want 'not configured'", reply)
|
||||
}
|
||||
}
|
||||
|
||||
// -- /queue tests --
|
||||
|
||||
func TestRouteQueueAdd(t *testing.T) {
|
||||
r := routerWithState()
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/queue review the PR"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "Queued") || !strings.Contains(reply, "review the PR") {
|
||||
t.Errorf("reply = %q, want confirmation", reply)
|
||||
}
|
||||
if n := r.State.QueueLen(); n != 1 {
|
||||
t.Errorf("QueueLen() = %d, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteQueueShow(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.AddToQueue("a")
|
||||
r.State.AddToQueue("b")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/queue"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "a") || !strings.Contains(reply, "b") {
|
||||
t.Errorf("reply = %q, want queue contents", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteQueueShowEmpty(t *testing.T) {
|
||||
r := routerWithState()
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/queue"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "empty") {
|
||||
t.Errorf("reply = %q, want 'empty'", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteQueueRemove(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.AddToQueue("a")
|
||||
r.State.AddToQueue("b")
|
||||
r.State.AddToQueue("c")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/queue remove 2"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "removed") {
|
||||
t.Errorf("reply = %q, want removed", reply)
|
||||
}
|
||||
entries := r.State.QueueEntries()
|
||||
if len(entries) != 2 || entries[0].Text != "a" || entries[1].Text != "c" {
|
||||
t.Errorf("QueueEntries() = %+v, want [a, c]", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteQueueClear(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.AddToQueue("a")
|
||||
r.State.AddToQueue("b")
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/queue clear"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "cleared") {
|
||||
t.Errorf("reply = %q, want cleared", reply)
|
||||
}
|
||||
if n := r.State.QueueLen(); n != 0 {
|
||||
t.Errorf("QueueLen() = %d, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteQueueAliases(t *testing.T) {
|
||||
for _, cmd := range []string{"/q add this", "/background add this", "/bg add this", "/btw add this"} {
|
||||
t.Run(cmd, func(t *testing.T) {
|
||||
r := routerWithState()
|
||||
reply, err := r.Route(context.Background(), Message{Text: cmd})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "Queued") {
|
||||
t.Errorf("alias %q reply = %q, want Queued", cmd, reply)
|
||||
}
|
||||
if n := r.State.QueueLen(); n != 1 {
|
||||
t.Errorf("QueueLen() = %d, want 1", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteQueueNotConfigured(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test-gw")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/queue show"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "not configured") {
|
||||
t.Errorf("reply = %q, want 'not configured'", reply)
|
||||
}
|
||||
}
|
||||
|
||||
// -- /goal show includes subgoals and wait status --
|
||||
|
||||
func TestRouteGoalShowWithWait(t *testing.T) {
|
||||
r := routerWithState()
|
||||
r.State.SetGoal("big goal", false)
|
||||
r.State.SetWait()
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/goal"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
}
|
||||
if !strings.Contains(reply, "Waiting") {
|
||||
t.Errorf("reply = %q, want Waiting indicator", reply)
|
||||
}
|
||||
}
|
||||
|
||||
// -- LocalCommands includes the new commands --
|
||||
|
||||
func TestLocalCommandsIncludesNewCommands(t *testing.T) {
|
||||
cmds := LocalCommands()
|
||||
want := []string{"/steer", "/goal", "/subgoal", "/queue", "/q", "/background", "/bg", "/btw"}
|
||||
for _, w := range want {
|
||||
found := slices.Contains(cmds, w)
|
||||
if !found {
|
||||
t.Errorf("LocalCommands() missing %q", w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitFirst(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
wantFirst string
|
||||
wantRest string
|
||||
}{
|
||||
{"show", "show", ""},
|
||||
{"remove 2", "remove", "2"},
|
||||
{"add do the thing", "add", "do the thing"},
|
||||
{" pause ", "pause", ""},
|
||||
{"", "", ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
first, rest := splitFirst(tt.input)
|
||||
if first != tt.wantFirst || rest != tt.wantRest {
|
||||
t.Errorf("splitFirst(%q) = (%q, %q), want (%q, %q)",
|
||||
tt.input, first, rest, tt.wantFirst, tt.wantRest)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// GoalStatus is the operational state of a goal.
|
||||
type GoalStatus string
|
||||
|
||||
const (
|
||||
GoalActive GoalStatus = "active"
|
||||
GoalPaused GoalStatus = "paused"
|
||||
)
|
||||
|
||||
// Goal is a standing objective for a session.
|
||||
type Goal struct {
|
||||
Text string `json:"text"`
|
||||
Status GoalStatus `json:"status"`
|
||||
}
|
||||
|
||||
// Subgoal is a child objective under a goal.
|
||||
type Subgoal struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// QueueEntry is a single item in the session's background queue.
|
||||
type QueueEntry struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// SessionState holds per-session control state for goal, steer, and
|
||||
// queue commands. All access is guarded by the embedded mutex.
|
||||
type SessionState struct {
|
||||
mu sync.Mutex
|
||||
|
||||
// Goal management
|
||||
goals []Goal
|
||||
subgoals []Subgoal
|
||||
waiting bool // /goal wait flag
|
||||
|
||||
// Steer injection
|
||||
steerText string
|
||||
|
||||
// Background queue
|
||||
queue []QueueEntry
|
||||
}
|
||||
|
||||
// NewSessionState returns an empty, usable SessionState.
|
||||
func NewSessionState() *SessionState {
|
||||
return &SessionState{}
|
||||
}
|
||||
|
||||
// ── Goal operations ──────────────────────────────────────────────────
|
||||
|
||||
// SetGoal replaces the current goal. If there is an existing goal with
|
||||
// subgoals, subgoals are preserved unless clearSubgoals is true.
|
||||
func (s *SessionState) SetGoal(text string, clearSubgoals bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.goals) == 0 {
|
||||
s.goals = []Goal{{Text: text, Status: GoalActive}}
|
||||
return
|
||||
}
|
||||
s.goals[0] = Goal{Text: text, Status: GoalActive}
|
||||
if clearSubgoals {
|
||||
s.subgoals = nil
|
||||
}
|
||||
}
|
||||
|
||||
// Goals returns a snapshot of current goals.
|
||||
func (s *SessionState) Goals() []Goal {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]Goal, len(s.goals))
|
||||
copy(out, s.goals)
|
||||
return out
|
||||
}
|
||||
|
||||
// PauseGoal marks the first goal as paused.
|
||||
func (s *SessionState) PauseGoal() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.goals) == 0 {
|
||||
return false
|
||||
}
|
||||
s.goals[0].Status = GoalPaused
|
||||
return true
|
||||
}
|
||||
|
||||
// ResumeGoal marks the first goal as active.
|
||||
func (s *SessionState) ResumeGoal() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.goals) == 0 {
|
||||
return false
|
||||
}
|
||||
s.goals[0].Status = GoalActive
|
||||
return true
|
||||
}
|
||||
|
||||
// ClearGoal removes all goals and subgoals.
|
||||
func (s *SessionState) ClearGoal() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.goals = nil
|
||||
s.subgoals = nil
|
||||
s.waiting = false
|
||||
}
|
||||
|
||||
// HasGoal reports whether a goal is set.
|
||||
func (s *SessionState) HasGoal() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return len(s.goals) > 0
|
||||
}
|
||||
|
||||
// ── Subgoal operations ───────────────────────────────────────────────
|
||||
|
||||
// AddSubgoal appends a subgoal.
|
||||
func (s *SessionState) AddSubgoal(text string) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.goals) == 0 {
|
||||
return false
|
||||
}
|
||||
s.subgoals = append(s.subgoals, Subgoal{Text: text})
|
||||
return true
|
||||
}
|
||||
|
||||
// Subgoals returns a snapshot of current subgoals.
|
||||
func (s *SessionState) Subgoals() []Subgoal {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]Subgoal, len(s.subgoals))
|
||||
copy(out, s.subgoals)
|
||||
return out
|
||||
}
|
||||
|
||||
// RemoveSubgoal removes the subgoal at the given 1-indexed position.
|
||||
// Returns false if the index is out of range.
|
||||
func (s *SessionState) RemoveSubgoal(n int) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
idx := n - 1
|
||||
if idx < 0 || idx >= len(s.subgoals) {
|
||||
return false
|
||||
}
|
||||
s.subgoals = append(s.subgoals[:idx], s.subgoals[idx+1:]...)
|
||||
return true
|
||||
}
|
||||
|
||||
// ClearSubgoals removes all subgoals.
|
||||
func (s *SessionState) ClearSubgoals() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.subgoals = nil
|
||||
}
|
||||
|
||||
// ── Wait operations ──────────────────────────────────────────────────
|
||||
|
||||
// SetWait sets the wait flag.
|
||||
func (s *SessionState) SetWait() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.waiting = true
|
||||
}
|
||||
|
||||
// ClearWait clears the wait flag.
|
||||
func (s *SessionState) ClearWait() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.waiting = false
|
||||
}
|
||||
|
||||
// IsWaiting reports the wait flag.
|
||||
func (s *SessionState) IsWaiting() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.waiting
|
||||
}
|
||||
|
||||
// ── Steer operations ─────────────────────────────────────────────────
|
||||
|
||||
// SetSteer stores a pending steer message. The previous steer (if not yet
|
||||
// consumed) is replaced.
|
||||
func (s *SessionState) SetSteer(text string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.steerText = text
|
||||
}
|
||||
|
||||
// PollSteer returns and clears any pending steer message. The second
|
||||
// return value is false when no steer was pending.
|
||||
func (s *SessionState) PollSteer() (string, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.steerText == "" {
|
||||
return "", false
|
||||
}
|
||||
text := s.steerText
|
||||
s.steerText = ""
|
||||
return text, true
|
||||
}
|
||||
|
||||
// PeekSteer returns the pending steer message without consuming it.
|
||||
func (s *SessionState) PeekSteer() (string, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.steerText == "" {
|
||||
return "", false
|
||||
}
|
||||
return s.steerText, true
|
||||
}
|
||||
|
||||
// HasPendingSteer reports whether a steer message is waiting.
|
||||
func (s *SessionState) HasPendingSteer() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.steerText != ""
|
||||
}
|
||||
|
||||
// ── Queue operations ─────────────────────────────────────────────────
|
||||
|
||||
// AddToQueue appends an entry to the queue.
|
||||
func (s *SessionState) AddToQueue(text string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.queue = append(s.queue, QueueEntry{Text: text})
|
||||
}
|
||||
|
||||
// QueueEntries returns a snapshot of the queue.
|
||||
func (s *SessionState) QueueEntries() []QueueEntry {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]QueueEntry, len(s.queue))
|
||||
copy(out, s.queue)
|
||||
return out
|
||||
}
|
||||
|
||||
// RemoveFromQueue removes the entry at the given 1-indexed position.
|
||||
// Returns false if the index is out of range.
|
||||
func (s *SessionState) RemoveFromQueue(n int) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
idx := n - 1
|
||||
if idx < 0 || idx >= len(s.queue) {
|
||||
return false
|
||||
}
|
||||
s.queue = append(s.queue[:idx], s.queue[idx+1:]...)
|
||||
return true
|
||||
}
|
||||
|
||||
// ClearQueue removes all queue entries.
|
||||
func (s *SessionState) ClearQueue() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.queue = nil
|
||||
}
|
||||
|
||||
// QueueLen returns the number of queue entries.
|
||||
func (s *SessionState) QueueLen() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return len(s.queue)
|
||||
}
|
||||
|
||||
// ── Prompt rendering ─────────────────────────────────────────────────
|
||||
|
||||
// BuildGoalPrompt returns a string suitable for injecting into the system
|
||||
// prompt. Returns empty string when no goal is set.
|
||||
func (s *SessionState) BuildGoalPrompt() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.goals) == 0 {
|
||||
return ""
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("<standing_goal")
|
||||
if s.goals[0].Status == GoalPaused {
|
||||
b.WriteString(` status="paused"`)
|
||||
}
|
||||
if s.waiting {
|
||||
b.WriteString(` wait="true"`)
|
||||
}
|
||||
b.WriteString(">\n")
|
||||
b.WriteString(s.goals[0].Text)
|
||||
b.WriteString("\n")
|
||||
|
||||
if len(s.subgoals) > 0 {
|
||||
b.WriteString("\nSubgoals:\n")
|
||||
for i, sg := range s.subgoals {
|
||||
fmt.Fprintf(&b, "%d. %s\n", i+1, sg.Text)
|
||||
}
|
||||
}
|
||||
b.WriteString("</standing_goal>")
|
||||
|
||||
if s.waiting && s.goals[0].Status == GoalActive {
|
||||
b.WriteString("\n\nThe goal has a wait flag set. Do not begin new work toward the goal unless the user explicitly asks you to proceed. Continue responding to other requests normally.")
|
||||
}
|
||||
if s.goals[0].Status == GoalPaused {
|
||||
b.WriteString("\n\nThe goal is paused. Do not work toward it unless the user explicitly resumes it.")
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSessionStateGoalLifecycle(t *testing.T) {
|
||||
s := NewSessionState()
|
||||
|
||||
if s.HasGoal() {
|
||||
t.Error("new state should have no goal")
|
||||
}
|
||||
if g := s.Goals(); len(g) != 0 {
|
||||
t.Errorf("Goals() = %d, want 0", len(g))
|
||||
}
|
||||
|
||||
s.SetGoal("ship the thing", true)
|
||||
if !s.HasGoal() {
|
||||
t.Error("HasGoal() = false after SetGoal")
|
||||
}
|
||||
goals := s.Goals()
|
||||
if len(goals) != 1 || goals[0].Text != "ship the thing" || goals[0].Status != GoalActive {
|
||||
t.Errorf("Goals() = %+v, want active goal", goals)
|
||||
}
|
||||
|
||||
s.PauseGoal()
|
||||
goals = s.Goals()
|
||||
if goals[0].Status != GoalPaused {
|
||||
t.Errorf("status = %s, want paused", goals[0].Status)
|
||||
}
|
||||
|
||||
s.ResumeGoal()
|
||||
goals = s.Goals()
|
||||
if goals[0].Status != GoalActive {
|
||||
t.Errorf("status = %s, want active after resume", goals[0].Status)
|
||||
}
|
||||
|
||||
s.ClearGoal()
|
||||
if s.HasGoal() {
|
||||
t.Error("HasGoal() = true after ClearGoal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPauseResumeWithoutGoalIsNoop(t *testing.T) {
|
||||
s := NewSessionState()
|
||||
if s.PauseGoal() {
|
||||
t.Error("PauseGoal() without goal should return false")
|
||||
}
|
||||
if s.ResumeGoal() {
|
||||
t.Error("ResumeGoal() without goal should return false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStateSubgoals(t *testing.T) {
|
||||
s := NewSessionState()
|
||||
|
||||
// Cannot add subgoal without a goal
|
||||
if s.AddSubgoal("do thing 1") {
|
||||
t.Error("AddSubgoal() without goal should return false")
|
||||
}
|
||||
|
||||
s.SetGoal("ship", true)
|
||||
if !s.AddSubgoal("sub-a") {
|
||||
t.Error("AddSubgoal() should succeed with goal present")
|
||||
}
|
||||
s.AddSubgoal("sub-b")
|
||||
s.AddSubgoal("sub-c")
|
||||
|
||||
sgs := s.Subgoals()
|
||||
if len(sgs) != 3 {
|
||||
t.Fatalf("Subgoals() = %d, want 3", len(sgs))
|
||||
}
|
||||
|
||||
// Remove subgoal at position 2 (sub-b)
|
||||
if !s.RemoveSubgoal(2) {
|
||||
t.Error("RemoveSubgoal(2) should succeed")
|
||||
}
|
||||
sgs = s.Subgoals()
|
||||
if len(sgs) != 2 || sgs[0].Text != "sub-a" || sgs[1].Text != "sub-c" {
|
||||
t.Errorf("Subgoals() = %+v, want [sub-a, sub-c]", sgs)
|
||||
}
|
||||
|
||||
// Out of range
|
||||
if s.RemoveSubgoal(10) {
|
||||
t.Error("RemoveSubgoal(10) should return false")
|
||||
}
|
||||
if s.RemoveSubgoal(0) {
|
||||
t.Error("RemoveSubgoal(0) should return false")
|
||||
}
|
||||
|
||||
s.ClearSubgoals()
|
||||
if len(s.Subgoals()) != 0 {
|
||||
t.Error("Subgoals() not empty after ClearSubgoals")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStateSetGoalPreservesSubgoalsByDefault(t *testing.T) {
|
||||
s := NewSessionState()
|
||||
s.SetGoal("goal-a", false)
|
||||
s.AddSubgoal("sg-1")
|
||||
s.AddSubgoal("sg-2")
|
||||
|
||||
s.SetGoal("goal-b", false) // no clear
|
||||
sgs := s.Subgoals()
|
||||
if len(sgs) != 2 {
|
||||
t.Errorf("subgoals = %d after SetGoal without clear, want 2", len(sgs))
|
||||
}
|
||||
|
||||
s.SetGoal("goal-c", true) // clear
|
||||
sgs = s.Subgoals()
|
||||
if len(sgs) != 0 {
|
||||
t.Errorf("subgoals = %d after SetGoal with clear, want 0", len(sgs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStateWait(t *testing.T) {
|
||||
s := NewSessionState()
|
||||
if s.IsWaiting() {
|
||||
t.Error("IsWaiting() = true on new state")
|
||||
}
|
||||
s.SetWait()
|
||||
if !s.IsWaiting() {
|
||||
t.Error("IsWaiting() = false after SetWait")
|
||||
}
|
||||
s.ClearWait()
|
||||
if s.IsWaiting() {
|
||||
t.Error("IsWaiting() = true after ClearWait")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStateSteer(t *testing.T) {
|
||||
s := NewSessionState()
|
||||
|
||||
if s.HasPendingSteer() {
|
||||
t.Error("HasPendingSteer() = true on new state")
|
||||
}
|
||||
if _, ok := s.PollSteer(); ok {
|
||||
t.Error("PollSteer() should return false on empty")
|
||||
}
|
||||
|
||||
s.SetSteer("do the thing")
|
||||
if !s.HasPendingSteer() {
|
||||
t.Error("HasPendingSteer() = false after SetSteer")
|
||||
}
|
||||
if text, ok := s.PeekSteer(); !ok || text != "do the thing" {
|
||||
t.Errorf("PeekSteer() = (%q, %v), want (do the thing, true)", text, ok)
|
||||
}
|
||||
// Peek doesn't consume
|
||||
if !s.HasPendingSteer() {
|
||||
t.Error("PeekSteer should not consume")
|
||||
}
|
||||
|
||||
text, ok := s.PollSteer()
|
||||
if !ok || text != "do the thing" {
|
||||
t.Errorf("PollSteer() = (%q, %v), want (do the thing, true)", text, ok)
|
||||
}
|
||||
if s.HasPendingSteer() {
|
||||
t.Error("HasPendingSteer() = true after PollSteer")
|
||||
}
|
||||
|
||||
// Second set replaces
|
||||
s.SetSteer("first")
|
||||
s.SetSteer("second")
|
||||
text, _ = s.PollSteer()
|
||||
if text != "second" {
|
||||
t.Errorf("second SetSteer should replace: got %q", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStateQueue(t *testing.T) {
|
||||
s := NewSessionState()
|
||||
|
||||
if n := s.QueueLen(); n != 0 {
|
||||
t.Errorf("QueueLen() = %d, want 0", n)
|
||||
}
|
||||
|
||||
s.AddToQueue("item-a")
|
||||
s.AddToQueue("item-b")
|
||||
s.AddToQueue("item-c")
|
||||
|
||||
if n := s.QueueLen(); n != 3 {
|
||||
t.Errorf("QueueLen() = %d, want 3", n)
|
||||
}
|
||||
|
||||
entries := s.QueueEntries()
|
||||
if len(entries) != 3 {
|
||||
t.Fatalf("QueueEntries() = %d, want 3", len(entries))
|
||||
}
|
||||
|
||||
if !s.RemoveFromQueue(2) {
|
||||
t.Error("RemoveFromQueue(2) should succeed")
|
||||
}
|
||||
entries = s.QueueEntries()
|
||||
if len(entries) != 2 || entries[0].Text != "item-a" || entries[1].Text != "item-c" {
|
||||
t.Errorf("QueueEntries() = %+v, want [item-a, item-c]", entries)
|
||||
}
|
||||
|
||||
s.ClearQueue()
|
||||
if n := s.QueueLen(); n != 0 {
|
||||
t.Errorf("QueueLen() = %d after clear, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionStateClearGoalResetsWait(t *testing.T) {
|
||||
s := NewSessionState()
|
||||
s.SetGoal("g", false)
|
||||
s.SetWait()
|
||||
|
||||
s.ClearGoal()
|
||||
if s.IsWaiting() {
|
||||
t.Error("ClearGoal should reset wait flag")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildGoalPromptEmpty(t *testing.T) {
|
||||
s := NewSessionState()
|
||||
if p := s.BuildGoalPrompt(); p != "" {
|
||||
t.Errorf("BuildGoalPrompt() = %q, want empty", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildGoalPromptActive(t *testing.T) {
|
||||
s := NewSessionState()
|
||||
s.SetGoal("build the API", false)
|
||||
s.AddSubgoal("add auth")
|
||||
s.AddSubgoal("add rate limiting")
|
||||
|
||||
p := s.BuildGoalPrompt()
|
||||
if p == "" {
|
||||
t.Fatal("BuildGoalPrompt() returned empty")
|
||||
}
|
||||
if !strings.Contains(p, "build the API") {
|
||||
t.Error("prompt missing goal text")
|
||||
}
|
||||
if !strings.Contains(p, "add auth") {
|
||||
t.Error("prompt missing subgoal")
|
||||
}
|
||||
if !strings.Contains(p, "add rate limiting") {
|
||||
t.Error("prompt missing subgoal")
|
||||
}
|
||||
if !strings.Contains(p, "standing_goal") {
|
||||
t.Error("prompt missing standing_goal tag")
|
||||
}
|
||||
// Active goal should not mention pause/wait
|
||||
if strings.Contains(p, "paused") {
|
||||
t.Error("active goal should not mention paused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildGoalPromptPaused(t *testing.T) {
|
||||
s := NewSessionState()
|
||||
s.SetGoal("refactor", false)
|
||||
s.PauseGoal()
|
||||
|
||||
p := s.BuildGoalPrompt()
|
||||
if !strings.Contains(p, `status="paused"`) {
|
||||
t.Error("prompt missing paused status attribute")
|
||||
}
|
||||
if !strings.Contains(p, "paused") {
|
||||
t.Error("prompt should mention goal is paused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildGoalPromptWaiting(t *testing.T) {
|
||||
s := NewSessionState()
|
||||
s.SetGoal("write docs", false)
|
||||
s.SetWait()
|
||||
|
||||
p := s.BuildGoalPrompt()
|
||||
if !strings.Contains(p, `wait="true"`) {
|
||||
t.Error("prompt missing wait attribute")
|
||||
}
|
||||
if !strings.Contains(p, "wait flag") {
|
||||
t.Error("prompt should mention wait flag")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildGoalPromptConcurrency(t *testing.T) {
|
||||
// Verify that concurrent access to BuildGoalPrompt and mutations
|
||||
// does not race. Run with -race.
|
||||
s := NewSessionState()
|
||||
s.SetGoal("concurrent goal", false)
|
||||
s.AddSubgoal("sg-1")
|
||||
s.AddSubgoal("sg-2")
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for i := range 100 {
|
||||
s.SetSteer("steer " + string(rune('a'+i%26)))
|
||||
s.SetWait()
|
||||
s.ClearWait()
|
||||
s.AddToQueue("q")
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
|
||||
for range 1000 {
|
||||
p := s.BuildGoalPrompt()
|
||||
if p == "" {
|
||||
t.Error("BuildGoalPrompt returned empty during concurrent access")
|
||||
break
|
||||
}
|
||||
s.PollSteer()
|
||||
s.QueueEntries()
|
||||
}
|
||||
<-done
|
||||
}
|
||||
Reference in new issue
Block a user