From 6d148b9e9e9d9dc0060a4138bd86389e779955ea Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Fri, 27 Nov 2026 18:32:21 +0530 Subject: [PATCH 01/13] feat(core): add session-store backed todo core tool Add a native core todo tool to Kit for structured task tracking during complex multi-step workflows. - Implement fantasy.AgentTool in internal/core/todo.go for managing task checklists. - Back task persistence to Kit's native JSONL session store via session.ExtensionDataEntry. - Enhance TreeManager.GetExtensionData so extension data survives conversation compactions. - Wire sessionTodoStore into pkg/kit during turn generation and background jobs. - Export NewTodoTool, WithTodoStore, TodoStore, and TodoItem in pkg/kit/tools.go. - Add unit and integration tests covering read/write cycles, status validation, and session reloads. Closes #282 --- internal/core/todo.go | 292 ++++++++++++++++++++++++ internal/core/todo_test.go | 210 +++++++++++++++++ internal/core/tools.go | 14 +- internal/session/extension_data_test.go | 57 +++++ internal/session/tree_manager.go | 29 ++- pkg/kit/jobs.go | 3 + pkg/kit/kit.go | 3 + pkg/kit/session_todo_store.go | 50 ++++ pkg/kit/todo_test.go | 127 +++++++++++ pkg/kit/tools.go | 14 +- www/pages/sdk/api-reference.md | 4 + 11 files changed, 800 insertions(+), 3 deletions(-) create mode 100644 internal/core/todo.go create mode 100644 internal/core/todo_test.go create mode 100644 internal/session/extension_data_test.go create mode 100644 pkg/kit/session_todo_store.go create mode 100644 pkg/kit/todo_test.go diff --git a/internal/core/todo.go b/internal/core/todo.go new file mode 100644 index 000000000..dd1876b00 --- /dev/null +++ b/internal/core/todo.go @@ -0,0 +1,292 @@ +package core + +import ( + "context" + "fmt" + "strings" + "sync" + + "charm.land/fantasy" +) + +// Todo status values. +const ( + TodoStatusPending = "pending" + TodoStatusInProgress = "in_progress" + TodoStatusCompleted = "completed" + TodoStatusCancelled = "cancelled" +) + +// Todo priority values. +const ( + TodoPriorityLow = "low" + TodoPriorityMedium = "medium" + TodoPriorityHigh = "high" +) + +// TodoItem represents a single task in a structured checklist. +type TodoItem struct { + ID string `json:"id"` + Content string `json:"content"` + Status string `json:"status"` + Priority string `json:"priority,omitempty"` +} + +// TodoStore provides storage and retrieval for todo items. +type TodoStore interface { + GetTodos(ctx context.Context) ([]TodoItem, error) + SaveTodos(ctx context.Context, todos []TodoItem) error +} + +type memoryTodoStore struct { + mu sync.RWMutex + todos []TodoItem +} + +// NewMemoryTodoStore returns a thread-safe in-memory TodoStore. +func NewMemoryTodoStore() TodoStore { + return &memoryTodoStore{} +} + +func (s *memoryTodoStore) GetTodos(ctx context.Context) ([]TodoItem, error) { + s.mu.RLock() + defer s.mu.RUnlock() + res := make([]TodoItem, len(s.todos)) + copy(res, s.todos) + return res, nil +} + +func (s *memoryTodoStore) SaveTodos(ctx context.Context, todos []TodoItem) error { + s.mu.Lock() + defer s.mu.Unlock() + s.todos = make([]TodoItem, len(todos)) + copy(s.todos, todos) + return nil +} + +type todoStoreKey struct{} + +// ContextWithTodoStore stores the TodoStore in ctx for use by the todo tool. +func ContextWithTodoStore(ctx context.Context, store TodoStore) context.Context { + return context.WithValue(ctx, todoStoreKey{}, store) +} + +func todoStoreFromContext(ctx context.Context) TodoStore { + if s, ok := ctx.Value(todoStoreKey{}).(TodoStore); ok { + return s + } + return nil +} + +type todoArgs struct { + Action string `json:"action,omitempty"` + Todos *[]TodoItem `json:"todos,omitempty"` +} + +// NewTodoTool creates the todo core tool for managing structured task checklists. +func NewTodoTool(opts ...ToolOption) fantasy.AgentTool { + cfg := ApplyOptions(opts) + defaultStore := cfg.TodoStore + if defaultStore == nil { + defaultStore = NewMemoryTodoStore() + } + + return &coreTool{ + info: fantasy.ToolInfo{ + Name: "todo", + Description: `Track and manage structured task checklists for complex multi-step workflows. + +Use this tool to plan multi-step tasks, track progress, and maintain focus across long workflows. +- To view existing tasks: call with no arguments or {"action": "read"}. +- To update or replace tasks: call with {"todos": [...]}. Each task must have: + - id: unique string identifier (e.g. "1", "2") + - content: clear description of the step + - status: "pending", "in_progress", "completed", or "cancelled" + - priority: optional "high", "medium", or "low" (default: "medium") + +Tasks are persisted in the session store and survive context compaction and session restarts.`, + Parameters: map[string]any{ + "action": map[string]any{ + "type": "string", + "enum": []string{"read", "write"}, + "description": "Optional action. If 'todos' is provided, 'write' is assumed. Defaults to 'read'.", + }, + "todos": map[string]any{ + "type": "array", + "description": "The updated list of todo items.", + "items": map[string]any{ + "type": "object", + "properties": map[string]any{ + "id": map[string]any{ + "type": "string", + "description": "Unique identifier for the task.", + }, + "content": map[string]any{ + "type": "string", + "description": "Detailed description of the task.", + }, + "status": map[string]any{ + "type": "string", + "enum": []string{"pending", "in_progress", "completed", "cancelled"}, + "description": "Current status of the task.", + }, + "priority": map[string]any{ + "type": "string", + "enum": []string{"high", "medium", "low"}, + "description": "Priority level of the task.", + }, + }, + "required": []string{"content", "status"}, + }, + }, + }, + Required: []string{}, + Parallel: false, + }, + handler: func(ctx context.Context, call fantasy.ToolCall) (fantasy.ToolResponse, error) { + return executeTodo(ctx, call, defaultStore) + }, + } +} + +func executeTodo(ctx context.Context, call fantasy.ToolCall, defaultStore TodoStore) (fantasy.ToolResponse, error) { + if err := ctx.Err(); err != nil { + return fantasy.ToolResponse{}, err + } + + store := todoStoreFromContext(ctx) + if store == nil { + store = defaultStore + } + + var args todoArgs + if err := parseArgs(call.Input, &args); err != nil { + return fantasy.NewTextErrorResponse(fmt.Sprintf("invalid arguments: %v", err)), nil + } + + // If todos are provided, treat as write action. + if args.Todos != nil { + items := *args.Todos + if len(items) == 0 { + if err := store.SaveTodos(ctx, []TodoItem{}); err != nil { + return fantasy.NewTextErrorResponse(fmt.Sprintf("failed to save todos: %v", err)), nil + } + return fantasy.NewTextResponse("Todos cleared."), nil + } + + normalized := make([]TodoItem, len(items)) + for i, item := range items { + content := strings.TrimSpace(item.Content) + if content == "" { + return fantasy.NewTextErrorResponse(fmt.Sprintf("item %d: content cannot be empty", i+1)), nil + } + + status := strings.ToLower(strings.TrimSpace(item.Status)) + switch status { + case "done": + status = TodoStatusCompleted + case "in-progress": + status = TodoStatusInProgress + case TodoStatusPending, TodoStatusInProgress, TodoStatusCompleted, TodoStatusCancelled: + // valid + case "": + status = TodoStatusPending + default: + return fantasy.NewTextErrorResponse(fmt.Sprintf("item %d: invalid status %q (must be pending, in_progress, completed, or cancelled)", i+1, item.Status)), nil + } + + priority := strings.ToLower(strings.TrimSpace(item.Priority)) + switch priority { + case TodoPriorityHigh, TodoPriorityMedium, TodoPriorityLow: + // valid + default: + priority = TodoPriorityMedium + } + + id := strings.TrimSpace(item.ID) + if id == "" { + id = fmt.Sprintf("%d", i+1) + } + + normalized[i] = TodoItem{ + ID: id, + Content: content, + Status: status, + Priority: priority, + } + } + + if err := store.SaveTodos(ctx, normalized); err != nil { + return fantasy.NewTextErrorResponse(fmt.Sprintf("failed to save todos: %v", err)), nil + } + + return fantasy.NewTextResponse(FormatTodoList(normalized)), nil + } + + if args.Action == "write" { + return fantasy.NewTextErrorResponse("action 'write' requires 'todos' list"), nil + } + + // Read action + todos, err := store.GetTodos(ctx) + if err != nil { + return fantasy.NewTextErrorResponse(fmt.Sprintf("failed to read todos: %v", err)), nil + } + + if len(todos) == 0 { + return fantasy.NewTextResponse("No todos found. Call todo with a list of tasks in \"todos\" to create some."), nil + } + + return fantasy.NewTextResponse(FormatTodoList(todos)), nil +} + +// FormatTodoList renders a list of TodoItems into a formatted human-readable checklist. +func FormatTodoList(todos []TodoItem) string { + if len(todos) == 0 { + return "No todos found." + } + + var completed, inProgress, cancelled int + for _, t := range todos { + switch t.Status { + case TodoStatusCompleted: + completed++ + case TodoStatusInProgress: + inProgress++ + case TodoStatusCancelled: + cancelled++ + } + } + + var sb strings.Builder + fmt.Fprintf(&sb, "Todos (%d/%d completed", completed, len(todos)) + if inProgress > 0 { + fmt.Fprintf(&sb, ", %d in progress", inProgress) + } + if cancelled > 0 { + fmt.Fprintf(&sb, ", %d cancelled", cancelled) + } + sb.WriteString("):\n") + + for _, t := range todos { + var marker string + switch t.Status { + case TodoStatusCompleted: + marker = "[x]" + case TodoStatusInProgress: + marker = "[~]" + case TodoStatusCancelled: + marker = "[-]" + default: + marker = "[ ]" + } + + prio := "" + if t.Priority != "" && t.Priority != TodoPriorityMedium { + prio = fmt.Sprintf(" [%s]", t.Priority) + } + fmt.Fprintf(&sb, "%s %s: %s%s\n", marker, t.ID, t.Content, prio) + } + + return strings.TrimRight(sb.String(), "\n") +} diff --git a/internal/core/todo_test.go b/internal/core/todo_test.go new file mode 100644 index 000000000..8223af1b9 --- /dev/null +++ b/internal/core/todo_test.go @@ -0,0 +1,210 @@ +package core + +import ( + "context" + "strings" + "sync" + "testing" + + "charm.land/fantasy" +) + +func runTodo(t *testing.T, tool fantasy.AgentTool, ctx context.Context, input string) fantasy.ToolResponse { + t.Helper() + resp, err := tool.Run(ctx, fantasy.ToolCall{ID: "call_todo", Name: "todo", Input: input}) + if err != nil { + t.Fatalf("unexpected error running todo tool: %v", err) + } + return resp +} + +func TestTodoTool_EmptyRead(t *testing.T) { + tool := NewTodoTool() + resp := runTodo(t, tool, context.Background(), `{}`) + if resp.IsError { + t.Fatalf("expected success, got error: %s", resp.Content) + } + if !strings.Contains(resp.Content, "No todos found") { + t.Errorf("expected 'No todos found', got %q", resp.Content) + } +} + +func TestTodoTool_WriteAndRead(t *testing.T) { + tool := NewTodoTool() + ctx := context.Background() + + input := `{ + "todos": [ + {"id": "1", "content": "Explore codebase", "status": "completed", "priority": "high"}, + {"id": "2", "content": "Implement core tool", "status": "in_progress", "priority": "medium"}, + {"id": "3", "content": "Write unit tests", "status": "pending", "priority": "low"} + ] + }` + + resp := runTodo(t, tool, ctx, input) + if resp.IsError { + t.Fatalf("expected success, got error: %s", resp.Content) + } + + expectedParts := []string{ + "Todos (1/3 completed, 1 in progress):", + "[x] 1: Explore codebase [high]", + "[~] 2: Implement core tool", + "[ ] 3: Write unit tests [low]", + } + for _, part := range expectedParts { + if !strings.Contains(resp.Content, part) { + t.Errorf("expected response to contain %q, got:\n%s", part, resp.Content) + } + } + + // Read back with empty input + readResp := runTodo(t, tool, ctx, `{}`) + if readResp.IsError { + t.Fatalf("read failed: %s", readResp.Content) + } + if readResp.Content != resp.Content { + t.Errorf("read response does not match write response.\nGot:\n%s\nWant:\n%s", readResp.Content, resp.Content) + } + + // Read back with explicit action: read + readResp2 := runTodo(t, tool, ctx, `{"action":"read"}`) + if readResp2.Content != resp.Content { + t.Errorf("action:read response does not match.\nGot:\n%s\nWant:\n%s", readResp2.Content, resp.Content) + } +} + +func TestTodoTool_ClearTodos(t *testing.T) { + tool := NewTodoTool() + ctx := context.Background() + + // Add a todo + _ = runTodo(t, tool, ctx, `{"todos":[{"content":"step 1","status":"pending"}]}`) + + // Clear todos + clearResp := runTodo(t, tool, ctx, `{"todos":[]}`) + if clearResp.IsError { + t.Fatalf("clear failed: %s", clearResp.Content) + } + if !strings.Contains(clearResp.Content, "Todos cleared") { + t.Errorf("expected 'Todos cleared', got %q", clearResp.Content) + } + + // Verify empty read + readResp := runTodo(t, tool, ctx, `{}`) + if !strings.Contains(readResp.Content, "No todos found") { + t.Errorf("expected 'No todos found', got %q", readResp.Content) + } +} + +func TestTodoTool_ValidationAndNormalization(t *testing.T) { + tool := NewTodoTool() + ctx := context.Background() + + tests := []struct { + name string + input string + wantError bool + contains string + }{ + { + name: "empty content", + input: `{"todos":[{"content":"","status":"pending"}]}`, + wantError: true, + contains: "content cannot be empty", + }, + { + name: "invalid status", + input: `{"todos":[{"content":"task","status":"unknown"}]}`, + wantError: true, + contains: "invalid status", + }, + { + name: "action write without todos", + input: `{"action":"write"}`, + wantError: true, + contains: "action 'write' requires 'todos' list", + }, + { + name: "normalize done and in-progress, auto-assign ID", + input: `{"todos":[{"content":"task 1","status":"done"},{"content":"task 2","status":"in-progress"}]}`, + wantError: false, + contains: "[x] 1: task 1\n[~] 2: task 2", + }, + { + name: "cancelled status", + input: `{"todos":[{"id":"1","content":"cancelled task","status":"cancelled"}]}`, + wantError: false, + contains: "[-] 1: cancelled task", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resp := runTodo(t, tool, ctx, tt.input) + if tt.wantError { + if !resp.IsError { + t.Fatalf("expected error response, got success: %s", resp.Content) + } + if !strings.Contains(resp.Content, tt.contains) { + t.Errorf("expected error to contain %q, got %q", tt.contains, resp.Content) + } + } else { + if resp.IsError { + t.Fatalf("unexpected error: %s", resp.Content) + } + if !strings.Contains(resp.Content, tt.contains) { + t.Errorf("expected response to contain %q, got:\n%s", tt.contains, resp.Content) + } + } + }) + } +} + +func TestTodoTool_ContextStoreOverride(t *testing.T) { + defaultStore := NewMemoryTodoStore() + _ = defaultStore.SaveTodos(context.Background(), []TodoItem{ + {ID: "default", Content: "from default store", Status: TodoStatusPending}, + }) + + customStore := NewMemoryTodoStore() + _ = customStore.SaveTodos(context.Background(), []TodoItem{ + {ID: "custom", Content: "from custom store", Status: TodoStatusCompleted}, + }) + + tool := NewTodoTool(WithTodoStore(defaultStore)) + + // Without context override: reads default store + resp1 := runTodo(t, tool, context.Background(), `{}`) + if !strings.Contains(resp1.Content, "from default store") { + t.Errorf("expected default store content, got %s", resp1.Content) + } + + // With context override: reads custom store + ctxWithCustom := ContextWithTodoStore(context.Background(), customStore) + resp2 := runTodo(t, tool, ctxWithCustom, `{}`) + if !strings.Contains(resp2.Content, "from custom store") { + t.Errorf("expected custom store content, got %s", resp2.Content) + } +} + +func TestMemoryTodoStore_Concurrency(t *testing.T) { + store := NewMemoryTodoStore() + ctx := context.Background() + + var wg sync.WaitGroup + for i := 0; i < 50; i++ { + wg.Add(2) + go func(idx int) { + defer wg.Done() + _ = store.SaveTodos(ctx, []TodoItem{ + {ID: "1", Content: "concurrent task", Status: TodoStatusInProgress}, + }) + }(i) + go func() { + defer wg.Done() + _, _ = store.GetTodos(ctx) + }() + } + wg.Wait() +} diff --git a/internal/core/tools.go b/internal/core/tools.go index 2508ee6ca..272973968 100644 --- a/internal/core/tools.go +++ b/internal/core/tools.go @@ -52,6 +52,15 @@ type ToolConfig struct { // CodeMode configures the code mode tool. Nil uses the defaults. Only // the code mode tool consumes this. CodeMode *CodeModeConfig + // TodoStore provides storage for the todo tool. Nil uses an in-memory store. + TodoStore TodoStore +} + +// WithTodoStore sets the TodoStore for the todo tool. +func WithTodoStore(store TodoStore) ToolOption { + return func(c *ToolConfig) { + c.TodoStore = store + } } // WithImageLimits bounds the images the read tool attaches to a message. A @@ -185,6 +194,7 @@ var coreTools = map[string]initTool{ "jobs_get": NewJobsGetTool, "jobs_cancel": NewJobsCancelTool, "jobs_wait": NewJobsWaitTool, + "todo": NewTodoTool, CodeModeToolName: NewCodeModeTool, } @@ -200,13 +210,14 @@ func DefaultCoreToolNames() []string { } // CodingTools returns the default set of core tools for a coding agent: -// shell, read, write, edit. +// shell, read, write, edit, todo. func CodingTools(opts ...ToolOption) []fantasy.AgentTool { return []fantasy.AgentTool{ NewShellTool(opts...), NewReadTool(opts...), NewWriteTool(opts...), NewEditTool(opts...), + NewTodoTool(opts...), } } @@ -236,6 +247,7 @@ func SubagentTools(opts ...ToolOption) []fantasy.AgentTool { NewJobsGetTool(opts...), NewJobsCancelTool(opts...), NewJobsWaitTool(opts...), + NewTodoTool(opts...), } } diff --git a/internal/session/extension_data_test.go b/internal/session/extension_data_test.go new file mode 100644 index 000000000..b6e20087f --- /dev/null +++ b/internal/session/extension_data_test.go @@ -0,0 +1,57 @@ +package session + +import ( + "testing" +) + +func TestTreeManager_ExtensionDataSurvivesCompaction(t *testing.T) { + tm := InMemoryTreeSession(t.TempDir()) + + // Append initial extension data before compaction + extID, err := tm.AppendExtensionData("todo", `[{"id":"1","content":"task 1","status":"pending"}]`) + if err != nil { + t.Fatalf("AppendExtensionData failed: %v", err) + } + if extID == "" { + t.Fatal("expected non-empty extension data entry ID") + } + + // Verify it can be retrieved on current branch + entries := tm.GetExtensionData("todo") + if len(entries) != 1 { + t.Fatalf("expected 1 entry, got %d", len(entries)) + } + if entries[0].Data != `[{"id":"1","content":"task 1","status":"pending"}]` { + t.Errorf("unexpected data: %s", entries[0].Data) + } + + // Perform compaction + _, err = tm.AppendCompaction("Conversation summary", "", 1000, 200, 5, nil, nil) + if err != nil { + t.Fatalf("AppendCompaction failed: %v", err) + } + + // Verify extension data is STILL retrievable post-compaction! + postCompactionEntries := tm.GetExtensionData("todo") + if len(postCompactionEntries) != 1 { + t.Fatalf("expected 1 entry post-compaction, got %d", len(postCompactionEntries)) + } + if postCompactionEntries[0].Data != `[{"id":"1","content":"task 1","status":"pending"}]` { + t.Errorf("unexpected data post-compaction: %s", postCompactionEntries[0].Data) + } + + // Now append a new extension data entry on the post-compaction branch + _, err = tm.AppendExtensionData("todo", `[{"id":"1","content":"task 1","status":"completed"}]`) + if err != nil { + t.Fatalf("AppendExtensionData failed: %v", err) + } + + // Should now see the new entry on the active branch + updatedEntries := tm.GetExtensionData("todo") + if len(updatedEntries) != 1 { + t.Fatalf("expected 1 entry on post-compaction branch, got %d", len(updatedEntries)) + } + if updatedEntries[0].Data != `[{"id":"1","content":"task 1","status":"completed"}]` { + t.Errorf("unexpected data: %s", updatedEntries[0].Data) + } +} diff --git a/internal/session/tree_manager.go b/internal/session/tree_manager.go index 54826db98..0194816ea 100644 --- a/internal/session/tree_manager.go +++ b/internal/session/tree_manager.go @@ -954,7 +954,10 @@ func (tm *TreeManager) AppendCompaction(summary, firstKeptEntryID string, tokens // GetExtensionData returns all extension data entries matching the given type, // walking the current branch from root to leaf. If extType is empty, all -// extension data entries on the branch are returned. +// extension data entries on the branch are returned. If the current branch has +// a compaction entry and no matching entries were found on the post-compaction +// branch, earlier entries are checked so persistent extension state survives +// compaction. func (tm *TreeManager) GetExtensionData(extType string) []*ExtensionDataEntry { tm.mu.RLock() defer tm.mu.RUnlock() @@ -972,6 +975,30 @@ func (tm *TreeManager) GetExtensionData(extType string) []*ExtensionDataEntry { } } } + if len(results) > 0 { + return results + } + + // Check if this branch is preceded by compaction. If so, inspect + // historical entries so extension data survives compaction. + hasCompaction := false + for _, entry := range branch { + if _, ok := entry.(*CompactionEntry); ok { + hasCompaction = true + break + } + } + if !hasCompaction { + return nil + } + + for _, entry := range tm.entries { + if e, ok := entry.(*ExtensionDataEntry); ok { + if extType == "" || e.ExtType == extType { + results = append(results, e) + } + } + } return results } diff --git a/pkg/kit/jobs.go b/pkg/kit/jobs.go index 76320af76..5c299aeb5 100644 --- a/pkg/kit/jobs.go +++ b/pkg/kit/jobs.go @@ -223,6 +223,9 @@ func (s *turnJobService) Start(ctx context.Context, kind string, work func(conte detached = agent.ContextWithSteerCh(detached, nil) detached = agent.ContextWithSteerConsumed(detached, nil) detached = core.WithJobService(detached, s) + if s.kit != nil && s.kit.session != nil { + detached = core.ContextWithTodoStore(detached, newSessionTodoStore(s.kit.session)) + } // The manager owns lifetime cancellation. Keep values separate so cancelling // the work-local context on return cannot mark successful work cancelled. jobCtx := jobValueContext{Context: state.lifetime, values: detached} diff --git a/pkg/kit/kit.go b/pkg/kit/kit.go index bc58d81fa..6087410df 100644 --- a/pkg/kit/kit.go +++ b/pkg/kit/kit.go @@ -2887,6 +2887,9 @@ func (m *Kit) Subagent(ctx context.Context, cfg SubagentConfig) (*SubagentResult // single code path so callback wiring is never duplicated. func (m *Kit) generate(ctx context.Context, messages []fantasy.Message) (*agent.GenerateWithLoopResult, error) { ctx = core.WithJobService(ctx, &turnJobService{kit: m}) + if m.session != nil { + ctx = core.ContextWithTodoStore(ctx, newSessionTodoStore(m.session)) + } // Capture the per-turn stream collector (set by runTurn) so streamed // deltas are recorded into TurnResult.Stream in emit order. collector := streamCollectorFromContext(ctx) diff --git a/pkg/kit/session_todo_store.go b/pkg/kit/session_todo_store.go new file mode 100644 index 000000000..c91704d05 --- /dev/null +++ b/pkg/kit/session_todo_store.go @@ -0,0 +1,50 @@ +package kit + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/mark3labs/kit/internal/core" +) + +// sessionTodoStore adapts SessionManager's ExtensionData storage to core.TodoStore. +type sessionTodoStore struct { + session SessionManager +} + +func newSessionTodoStore(sm SessionManager) core.TodoStore { + return &sessionTodoStore{session: sm} +} + +func (s *sessionTodoStore) GetTodos(ctx context.Context) ([]core.TodoItem, error) { + if s.session == nil { + return nil, nil + } + entries := s.session.GetExtensionData("todo") + if len(entries) == 0 { + return nil, nil + } + // Use the latest entry on the branch + latest := entries[len(entries)-1] + var items []core.TodoItem + if err := json.Unmarshal([]byte(latest.Data), &items); err != nil { + return nil, fmt.Errorf("unmarshal session todos: %w", err) + } + return items, nil +} + +func (s *sessionTodoStore) SaveTodos(ctx context.Context, todos []core.TodoItem) error { + if s.session == nil { + return nil + } + data, err := json.Marshal(todos) + if err != nil { + return fmt.Errorf("marshal session todos: %w", err) + } + _, err = s.session.AppendExtensionData("todo", string(data)) + if err != nil { + return fmt.Errorf("append session todo extension data: %w", err) + } + return nil +} diff --git a/pkg/kit/todo_test.go b/pkg/kit/todo_test.go new file mode 100644 index 000000000..96a9aa007 --- /dev/null +++ b/pkg/kit/todo_test.go @@ -0,0 +1,127 @@ +package kit + +import ( + "context" + "strings" + "testing" + + "charm.land/fantasy" + "github.com/mark3labs/kit/internal/core" + "github.com/mark3labs/kit/internal/session" +) + +func runKitTodo(t *testing.T, tool Tool, ctx context.Context, input string) fantasy.ToolResponse { + t.Helper() + resp, err := tool.Run(ctx, fantasy.ToolCall{ID: "call_todo", Name: "todo", Input: input}) + if err != nil { + t.Fatalf("unexpected error running todo tool: %v", err) + } + return resp +} + +func TestSessionTodoStore_SaveAndGet(t *testing.T) { + tm := session.InMemoryTreeSession(t.TempDir()) + sm := NewTreeManagerAdapter(tm) + store := newSessionTodoStore(sm) + + ctx := context.Background() + + // Initial get on empty session + todos, err := store.GetTodos(ctx) + if err != nil { + t.Fatalf("GetTodos failed: %v", err) + } + if len(todos) != 0 { + t.Fatalf("expected 0 todos, got %d", len(todos)) + } + + // Save todos + items := []core.TodoItem{ + {ID: "1", Content: "Task 1", Status: core.TodoStatusCompleted, Priority: core.TodoPriorityHigh}, + {ID: "2", Content: "Task 2", Status: core.TodoStatusInProgress, Priority: core.TodoPriorityMedium}, + } + if err := store.SaveTodos(ctx, items); err != nil { + t.Fatalf("SaveTodos failed: %v", err) + } + + // Read back + retrieved, err := store.GetTodos(ctx) + if err != nil { + t.Fatalf("GetTodos after save failed: %v", err) + } + if len(retrieved) != 2 { + t.Fatalf("expected 2 todos, got %d", len(retrieved)) + } + if retrieved[0].Content != "Task 1" || retrieved[0].Status != core.TodoStatusCompleted { + t.Errorf("unexpected first item: %+v", retrieved[0]) + } + if retrieved[1].Content != "Task 2" || retrieved[1].Status != core.TodoStatusInProgress { + t.Errorf("unexpected second item: %+v", retrieved[1]) + } +} + +func TestTodo_PersistsAcrossSessionRestartAndCompaction(t *testing.T) { + tempDir := t.TempDir() + + // 1. Create a persistent tree session + tm, err := session.CreateTreeSession(tempDir) + if err != nil { + t.Fatalf("CreateTreeSession failed: %v", err) + } + sessionPath := tm.GetFilePath() + sm := NewTreeManagerAdapter(tm) + + todoTool := NewTodoTool() + ctx := core.ContextWithTodoStore(context.Background(), newSessionTodoStore(sm)) + + // Write tasks using the tool + input := `{"todos":[{"id":"task-1","content":"Design architecture","status":"completed"},{"id":"task-2","content":"Write tests","status":"in_progress"}]}` + resp := runKitTodo(t, todoTool, ctx, input) + if resp.IsError { + t.Fatalf("todo tool write failed: %s", resp.Content) + } + + if !strings.Contains(resp.Content, "[x] task-1: Design architecture") { + t.Errorf("expected completed task-1, got: %s", resp.Content) + } + + // Trigger compaction on this session + _, err = tm.AppendCompaction("Compacted earlier messages", "", 500, 100, 4, nil, nil) + if err != nil { + t.Fatalf("AppendCompaction failed: %v", err) + } + + // Verify todos still exist immediately after compaction + compactionRead := runKitTodo(t, todoTool, ctx, `{}`) + if !strings.Contains(compactionRead.Content, "[x] task-1: Design architecture") { + t.Errorf("expected todos to survive compaction, got: %s", compactionRead.Content) + } + + // 2. Close session + if err := tm.Close(); err != nil { + t.Fatalf("Close failed: %v", err) + } + + // 3. Re-open session from disk (simulating restart / resume) + reopenedTM, err := session.OpenTreeSession(sessionPath) + if err != nil { + t.Fatalf("OpenTreeSession failed: %v", err) + } + defer reopenedTM.Close() + + reopenedSM := NewTreeManagerAdapter(reopenedTM) + reopenedCtx := core.ContextWithTodoStore(context.Background(), newSessionTodoStore(reopenedSM)) + + // Read todos with reopened session + resumedRead := runKitTodo(t, todoTool, reopenedCtx, `{}`) + if resumedRead.IsError { + t.Fatalf("resumed read failed: %s", resumedRead.Content) + } + + if !strings.Contains(resumedRead.Content, "[x] task-1: Design architecture") { + t.Errorf("expected resumed read to contain task-1, got: %s", resumedRead.Content) + } + if !strings.Contains(resumedRead.Content, "[~] task-2: Write tests") { + t.Errorf("expected resumed read to contain task-2, got: %s", resumedRead.Content) + } +} diff --git a/pkg/kit/tools.go b/pkg/kit/tools.go index af266f7f3..7368b1a62 100644 --- a/pkg/kit/tools.go +++ b/pkg/kit/tools.go @@ -66,6 +66,15 @@ var WithFileSystem = core.WithFileSystem // [CommandRunner] instead of local child processes. var WithCommandRunner = core.WithCommandRunner +// TodoStore provides storage and retrieval for todo items. +type TodoStore = core.TodoStore + +// TodoItem represents a single task in a structured checklist. +type TodoItem = core.TodoItem + +// WithTodoStore sets the [TodoStore] for the todo tool. +var WithTodoStore = core.WithTodoStore + // --- Core Tool Validation --- // processes a list of tool names, if disableCoreTools is true, return an // empty list. Otherwise if coreTools is not empty, it will return a list of @@ -449,6 +458,9 @@ func NewFindTool(opts ...ToolOption) Tool { return core.NewFindTool(opts...) } // NewLsTool creates a directory listing tool. func NewLsTool(opts ...ToolOption) Tool { return core.NewLsTool(opts...) } +// NewTodoTool creates a todo list management tool. +func NewTodoTool(opts ...ToolOption) Tool { return core.NewTodoTool(opts...) } + // --- Tool bundles --- func ListAllCoreToolNames() []string { return core.ListAllCoreToolNames() } @@ -459,7 +471,7 @@ func DefaultCoreToolNames() []string { return core.DefaultCoreToolNames() } func AllTools(opts ...ToolOption) []Tool { return core.AllTools(opts...) } // CodingTools returns the default set of core tools for a coding agent: -// shell, read, write, edit. +// shell, read, write, edit, todo. func CodingTools(opts ...ToolOption) []Tool { return core.CodingTools(opts...) } // ReadOnlyTools returns tools for read-only exploration: diff --git a/www/pages/sdk/api-reference.md b/www/pages/sdk/api-reference.md index f6469070f..52cc50176 100644 --- a/www/pages/sdk/api-reference.md +++ b/www/pages/sdk/api-reference.md @@ -790,11 +790,14 @@ Types for a custom `LLMLanguageModel` that a `ProviderFactory` returns: - [`NewRawTool`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#NewRawTool) — NewRawTool is the schema-driven counterpart to [NewTool]. - [`NewReadTool`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#NewReadTool) — NewReadTool creates a file-reading tool. - [`NewShellTool`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#NewShellTool) — NewShellTool creates the shell command execution tool. +- [`NewTodoTool`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#NewTodoTool) — NewTodoTool creates a todo list management tool. - [`NewTool`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#NewTool) — NewTool creates a custom [Tool] with automatic JSON schema generation from the TInput struct type. - [`NewWriteTool`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#NewWriteTool) — NewWriteTool creates a file-writing tool. - [`ReadOnlyTools`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#ReadOnlyTools) — ReadOnlyTools returns tools for read-only exploration: read, grep, find, ls. - [`SubagentTools`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#SubagentTools) — SubagentTools returns all core tools except subagent. - [`TextResult`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#TextResult) — TextResult creates a successful text [ToolOutput]. +- [`TodoItem`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#TodoItem) — TodoItem represents a single task in a structured checklist. +- [`TodoStore`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#TodoStore) — TodoStore provides storage and retrieval for todo items. - [`ToolCallIDFromContext`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#ToolCallIDFromContext) — ToolCallIDFromContext extracts the tool call ID from the context. - [`ToolOption`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#ToolOption) — ToolOption configures tool behavior. - [`ToolOutput`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#ToolOutput) — ToolOutput is the return value from custom tool handlers created with [NewTool] or [NewParallelTool]. @@ -804,6 +807,7 @@ Types for a custom `LLMLanguageModel` that a `ProviderFactory` returns: - [`WithShellMaxTimeout`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithShellMaxTimeout) — WithShellMaxTimeout sets the maximum timeout a shell tool call may request. - [`WithShellTimeout`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithShellTimeout) — WithShellTimeout sets the default per-call timeout for the shell tool. - [`WithShell`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithShell) — WithShell sets the shell the shell tool runs command strings through: the shell plus its own leading arguments. +- [`WithTodoStore`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithTodoStore) — WithTodoStore sets the TodoStore for the todo tool. - [`WithWorkDir`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithWorkDir) — WithWorkDir sets the working directory for file-based tools. ## Background jobs From eeca1593e6853c0065ddbab9cf701a504a2dae11 Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Fri, 27 Nov 2026 18:38:36 +0530 Subject: [PATCH 02/13] style(test): fix golangci-lint modernize and errcheck issues --- internal/core/todo_test.go | 2 +- pkg/kit/todo_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/core/todo_test.go b/internal/core/todo_test.go index 8223af1b9..349de0552 100644 --- a/internal/core/todo_test.go +++ b/internal/core/todo_test.go @@ -193,7 +193,7 @@ func TestMemoryTodoStore_Concurrency(t *testing.T) { ctx := context.Background() var wg sync.WaitGroup - for i := 0; i < 50; i++ { + for i := range 50 { wg.Add(2) go func(idx int) { defer wg.Done() diff --git a/pkg/kit/todo_test.go b/pkg/kit/todo_test.go index 96a9aa007..d4ccc2d35 100644 --- a/pkg/kit/todo_test.go +++ b/pkg/kit/todo_test.go @@ -107,7 +107,7 @@ func TestTodo_PersistsAcrossSessionRestartAndCompaction(t *testing.T) { if err != nil { t.Fatalf("OpenTreeSession failed: %v", err) } - defer reopenedTM.Close() + defer func() { _ = reopenedTM.Close() }() reopenedSM := NewTreeManagerAdapter(reopenedTM) reopenedCtx := core.ContextWithTodoStore(context.Background(), newSessionTodoStore(reopenedSM)) From 9f32c9689255b3097123952c03b315b0a0a190ce Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Fri, 27 Nov 2026 18:56:33 +0530 Subject: [PATCH 03/13] fix(core): reject duplicate explicit todo IDs and avoid collision on generated IDs --- internal/core/todo.go | 23 ++++++++++++++++++++++- internal/core/todo_test.go | 12 ++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/internal/core/todo.go b/internal/core/todo.go index dd1876b00..e6cbb01b1 100644 --- a/internal/core/todo.go +++ b/internal/core/todo.go @@ -174,6 +174,19 @@ func executeTodo(ctx context.Context, call fantasy.ToolCall, defaultStore TodoSt return fantasy.NewTextResponse("Todos cleared."), nil } + // Reserve all non-empty explicit IDs and reject duplicate explicit IDs. + usedIDs := make(map[string]bool, len(items)) + for i, item := range items { + id := strings.TrimSpace(item.ID) + if id != "" { + if usedIDs[id] { + return fantasy.NewTextErrorResponse(fmt.Sprintf("item %d: duplicate todo id %q", i+1, id)), nil + } + usedIDs[id] = true + } + } + + nextID := 1 normalized := make([]TodoItem, len(items)) for i, item := range items { content := strings.TrimSpace(item.Content) @@ -205,7 +218,15 @@ func executeTodo(ctx context.Context, call fantasy.ToolCall, defaultStore TodoSt id := strings.TrimSpace(item.ID) if id == "" { - id = fmt.Sprintf("%d", i+1) + for { + cand := fmt.Sprintf("%d", nextID) + nextID++ + if !usedIDs[cand] { + id = cand + usedIDs[id] = true + break + } + } } normalized[i] = TodoItem{ diff --git a/internal/core/todo_test.go b/internal/core/todo_test.go index 349de0552..41e5ee9ed 100644 --- a/internal/core/todo_test.go +++ b/internal/core/todo_test.go @@ -137,6 +137,18 @@ func TestTodoTool_ValidationAndNormalization(t *testing.T) { wantError: false, contains: "[-] 1: cancelled task", }, + { + name: "duplicate explicit ID", + input: `{"todos":[{"id":"task-1","content":"a","status":"pending"},{"id":"task-1","content":"b","status":"pending"}]}`, + wantError: true, + contains: `duplicate todo id "task-1"`, + }, + { + name: "auto-assign avoids collision with explicit ID", + input: `{"todos":[{"id":"1","content":"first","status":"pending"},{"content":"second","status":"pending"}]}`, + wantError: false, + contains: "[ ] 1: first\n[ ] 2: second", + }, } for _, tt := range tests { From e4b81d93397234f530b4e5efc9d33aa3a7b1d629 Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Fri, 27 Nov 2026 19:01:46 +0530 Subject: [PATCH 04/13] fix(session): record branch provenance in CompactionEntry for branch-isolated extension data --- internal/session/entry.go | 34 +++++----- internal/session/extension_data_test.go | 61 +++++++++++++++-- internal/session/tree_manager.go | 87 ++++++++++++++----------- pkg/kit/adapter.go | 19 +++--- pkg/kit/session.go | 19 +++--- 5 files changed, 144 insertions(+), 76 deletions(-) diff --git a/internal/session/entry.go b/internal/session/entry.go index d2a56b9ed..435b5d586 100644 --- a/internal/session/entry.go +++ b/internal/session/entry.go @@ -125,13 +125,14 @@ type ExtensionDataEntry struct { // FirstKeptEntryID when building the LLM context, preserving full history. type CompactionEntry struct { Entry - Summary string `json:"summary"` - FirstKeptEntryID string `json:"first_kept_entry_id"` - TokensBefore int `json:"tokens_before"` - TokensAfter int `json:"tokens_after"` - MessagesRemoved int `json:"messages_removed"` - ReadFiles []string `json:"read_files,omitempty"` - ModifiedFiles []string `json:"modified_files,omitempty"` + Summary string `json:"summary"` + FirstKeptEntryID string `json:"first_kept_entry_id"` + PreCompactionLeafID string `json:"pre_compaction_leaf_id,omitempty"` + TokensBefore int `json:"tokens_before"` + TokensAfter int `json:"tokens_after"` + MessagesRemoved int `json:"messages_removed"` + ReadFiles []string `json:"read_files,omitempty"` + ModifiedFiles []string `json:"modified_files,omitempty"` } // SystemPromptEntry records the system prompt and model used for the session. @@ -234,16 +235,17 @@ func NewExtensionDataEntry(parentID, extType, data string) *ExtensionDataEntry { } // NewCompactionEntry creates a CompactionEntry. -func NewCompactionEntry(parentID, summary, firstKeptEntryID string, tokensBefore, tokensAfter, messagesRemoved int, readFiles, modifiedFiles []string) *CompactionEntry { +func NewCompactionEntry(parentID, summary, firstKeptEntryID, preCompactionLeafID string, tokensBefore, tokensAfter, messagesRemoved int, readFiles, modifiedFiles []string) *CompactionEntry { return &CompactionEntry{ - Entry: NewEntry(EntryTypeCompaction, parentID), - Summary: summary, - FirstKeptEntryID: firstKeptEntryID, - TokensBefore: tokensBefore, - TokensAfter: tokensAfter, - MessagesRemoved: messagesRemoved, - ReadFiles: readFiles, - ModifiedFiles: modifiedFiles, + Entry: NewEntry(EntryTypeCompaction, parentID), + Summary: summary, + FirstKeptEntryID: firstKeptEntryID, + PreCompactionLeafID: preCompactionLeafID, + TokensBefore: tokensBefore, + TokensAfter: tokensAfter, + MessagesRemoved: messagesRemoved, + ReadFiles: readFiles, + ModifiedFiles: modifiedFiles, } } diff --git a/internal/session/extension_data_test.go b/internal/session/extension_data_test.go index b6e20087f..aeb6da445 100644 --- a/internal/session/extension_data_test.go +++ b/internal/session/extension_data_test.go @@ -48,10 +48,63 @@ func TestTreeManager_ExtensionDataSurvivesCompaction(t *testing.T) { // Should now see the new entry on the active branch updatedEntries := tm.GetExtensionData("todo") - if len(updatedEntries) != 1 { - t.Fatalf("expected 1 entry on post-compaction branch, got %d", len(updatedEntries)) + if len(updatedEntries) != 2 { + t.Fatalf("expected 2 entries across history, got %d", len(updatedEntries)) } - if updatedEntries[0].Data != `[{"id":"1","content":"task 1","status":"completed"}]` { - t.Errorf("unexpected data: %s", updatedEntries[0].Data) + if updatedEntries[len(updatedEntries)-1].Data != `[{"id":"1","content":"task 1","status":"completed"}]` { + t.Errorf("unexpected latest data: %s", updatedEntries[len(updatedEntries)-1].Data) + } +} + +func TestTreeManager_ExtensionDataBranchIsolationAcrossCompaction(t *testing.T) { + tm := InMemoryTreeSession(t.TempDir()) + + // Common root extension data + rootID, err := tm.AppendExtensionData("todo", `root`) + if err != nil { + t.Fatalf("root append failed: %v", err) + } + + // Branch A: adds Branch A data, then undergoes compaction + _, err = tm.AppendExtensionData("todo", `branch-a`) + if err != nil { + t.Fatalf("branch A append failed: %v", err) + } + compA, err := tm.AppendCompaction("Branch A summary", "", 500, 100, 2, nil, nil) + if err != nil { + t.Fatalf("branch A compaction failed: %v", err) + } + leafA := compA + + // Branch B: branches from root, adds Branch B data + if err := tm.Branch(rootID); err != nil { + t.Fatalf("branch back to root failed: %v", err) + } + _, err = tm.AppendExtensionData("todo", `branch-b`) + if err != nil { + t.Fatalf("branch B append failed: %v", err) + } + + // Verify Branch B sees only root and branch-b + entriesB := tm.GetExtensionData("todo") + if len(entriesB) != 2 { + t.Fatalf("expected 2 entries on branch B, got %d", len(entriesB)) + } + if entriesB[0].Data != "root" || entriesB[1].Data != "branch-b" { + t.Errorf("unexpected branch B entries: %+v", entriesB) + } + + // Switch to Branch A (post-compaction) + if err := tm.Branch(leafA); err != nil { + t.Fatalf("branch to leafA failed: %v", err) + } + + // Verify Branch A sees ONLY root and branch-a across compaction, NEVER branch-b! + entriesA := tm.GetExtensionData("todo") + if len(entriesA) != 2 { + t.Fatalf("expected 2 entries on branch A across compaction, got %d", len(entriesA)) + } + if entriesA[0].Data != "root" || entriesA[1].Data != "branch-a" { + t.Errorf("unexpected branch A entries (branch B leaked!): %+v", entriesA) } } diff --git a/internal/session/tree_manager.go b/internal/session/tree_manager.go index 0194816ea..77bdcd145 100644 --- a/internal/session/tree_manager.go +++ b/internal/session/tree_manager.go @@ -300,15 +300,20 @@ func (tm *TreeManager) ForkToNewSession(cwd string, targetID string) (*TreeManag if mapped, ok := idMap[e.FirstKeptEntryID]; ok { newFirstKeptID = mapped } + newPreLeafID := e.PreCompactionLeafID + if mapped, ok := idMap[e.PreCompactionLeafID]; ok { + newPreLeafID = mapped + } newEntry = &CompactionEntry{ - Entry: cloneEntry(e.Entry, newID, prevNewID), - Summary: e.Summary, - FirstKeptEntryID: newFirstKeptID, - TokensBefore: e.TokensBefore, - TokensAfter: e.TokensAfter, - MessagesRemoved: e.MessagesRemoved, - ReadFiles: e.ReadFiles, - ModifiedFiles: e.ModifiedFiles, + Entry: cloneEntry(e.Entry, newID, prevNewID), + Summary: e.Summary, + FirstKeptEntryID: newFirstKeptID, + PreCompactionLeafID: newPreLeafID, + TokensBefore: e.TokensBefore, + TokensAfter: e.TokensAfter, + MessagesRemoved: e.MessagesRemoved, + ReadFiles: e.ReadFiles, + ModifiedFiles: e.ModifiedFiles, } } @@ -948,16 +953,13 @@ func (tm *TreeManager) AppendCompaction(summary, firstKeptEntryID string, tokens // The compaction entry has no parent, making it a new "root" for the // post-compaction branch. This ensures old compacted messages are not // traversed when walking from the current leaf. - entry := NewCompactionEntry("", summary, firstKeptEntryID, tokensBefore, tokensAfter, messagesRemoved, readFiles, modifiedFiles) + entry := NewCompactionEntry("", summary, firstKeptEntryID, tm.leafID, tokensBefore, tokensAfter, messagesRemoved, readFiles, modifiedFiles) return tm.commitLeafLocked(entry, entry.ID, "compaction") } // GetExtensionData returns all extension data entries matching the given type, -// walking the current branch from root to leaf. If extType is empty, all -// extension data entries on the branch are returned. If the current branch has -// a compaction entry and no matching entries were found on the post-compaction -// branch, earlier entries are checked so persistent extension state survives -// compaction. +// walking the current branch and its compacted ancestor branches from root to leaf. +// If extType is empty, all extension data entries on the branch are returned. func (tm *TreeManager) GetExtensionData(extType string) []*ExtensionDataEntry { tm.mu.RLock() defer tm.mu.RUnlock() @@ -966,39 +968,48 @@ func (tm *TreeManager) GetExtensionData(extType string) []*ExtensionDataEntry { return nil } - branch := tm.getBranchLocked(tm.leafID) var results []*ExtensionDataEntry - for _, entry := range branch { - if e, ok := entry.(*ExtensionDataEntry); ok { - if extType == "" || e.ExtType == extType { - results = append(results, e) + visitedLeaves := make(map[string]bool) + + currentLeaf := tm.leafID + for currentLeaf != "" && !visitedLeaves[currentLeaf] { + visitedLeaves[currentLeaf] = true + branch := tm.getBranchLocked(currentLeaf) + if len(branch) == 0 { + break + } + + var branchResults []*ExtensionDataEntry + var lastCompaction *CompactionEntry + + for _, entry := range branch { + if e, ok := entry.(*ExtensionDataEntry); ok { + if extType == "" || e.ExtType == extType { + branchResults = append(branchResults, e) + } + } + if c, ok := entry.(*CompactionEntry); ok { + lastCompaction = c } } - } - if len(results) > 0 { - return results - } - // Check if this branch is preceded by compaction. If so, inspect - // historical entries so extension data survives compaction. - hasCompaction := false - for _, entry := range branch { - if _, ok := entry.(*CompactionEntry); ok { - hasCompaction = true - break + if len(branchResults) > 0 { + results = append(branchResults, results...) } - } - if !hasCompaction { - return nil - } - for _, entry := range tm.entries { - if e, ok := entry.(*ExtensionDataEntry); ok { - if extType == "" || e.ExtType == extType { - results = append(results, e) + if lastCompaction != nil { + if lastCompaction.PreCompactionLeafID != "" { + currentLeaf = lastCompaction.PreCompactionLeafID + continue + } + if lastCompaction.FirstKeptEntryID != "" { + currentLeaf = lastCompaction.FirstKeptEntryID + continue } } + break } + return results } diff --git a/pkg/kit/adapter.go b/pkg/kit/adapter.go index a3d2ae9a6..906fc1650 100644 --- a/pkg/kit/adapter.go +++ b/pkg/kit/adapter.go @@ -155,15 +155,16 @@ func (a *treeManagerAdapter) GetLastCompaction() *CompactionEntry { return nil } return &CompactionEntry{ - ID: c.ID, - Summary: c.Summary, - FirstKeptEntryID: c.FirstKeptEntryID, - TokensBefore: c.TokensBefore, - TokensAfter: c.TokensAfter, - MessagesRemoved: c.MessagesRemoved, - ReadFiles: c.ReadFiles, - ModifiedFiles: c.ModifiedFiles, - Timestamp: c.Timestamp, + ID: c.ID, + Summary: c.Summary, + FirstKeptEntryID: c.FirstKeptEntryID, + PreCompactionLeafID: c.PreCompactionLeafID, + TokensBefore: c.TokensBefore, + TokensAfter: c.TokensAfter, + MessagesRemoved: c.MessagesRemoved, + ReadFiles: c.ReadFiles, + ModifiedFiles: c.ModifiedFiles, + Timestamp: c.Timestamp, } } diff --git a/pkg/kit/session.go b/pkg/kit/session.go index 14251e6e3..ed47f0511 100644 --- a/pkg/kit/session.go +++ b/pkg/kit/session.go @@ -166,15 +166,16 @@ const ( // CompactionEntry represents a context compaction/summarization event. type CompactionEntry struct { - ID string - Summary string - FirstKeptEntryID string - TokensBefore int - TokensAfter int - MessagesRemoved int - ReadFiles []string - ModifiedFiles []string - Timestamp time.Time + ID string + Summary string + FirstKeptEntryID string + PreCompactionLeafID string + TokensBefore int + TokensAfter int + MessagesRemoved int + ReadFiles []string + ModifiedFiles []string + Timestamp time.Time } // ExtensionDataEntry represents custom extension data stored in the session. From f0b71c75adc9c95d6d83f98651b7949ee30e5a11 Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Fri, 27 Nov 2026 20:39:51 +0530 Subject: [PATCH 05/13] fix(kit): respect explicit WithTodoStore over session store and document precedence --- internal/core/todo.go | 5 ++-- internal/core/tools.go | 3 +++ pkg/kit/jobs.go | 6 +++-- pkg/kit/kit.go | 33 ++++++++++++++++++++++---- pkg/kit/todo_test.go | 43 ++++++++++++++++++++++++++++++++++ pkg/kit/tools.go | 11 +++++++++ www/pages/sdk/api-reference.md | 2 ++ 7 files changed, 95 insertions(+), 8 deletions(-) diff --git a/internal/core/todo.go b/internal/core/todo.go index e6cbb01b1..7505f0411 100644 --- a/internal/core/todo.go +++ b/internal/core/todo.go @@ -71,7 +71,8 @@ func ContextWithTodoStore(ctx context.Context, store TodoStore) context.Context return context.WithValue(ctx, todoStoreKey{}, store) } -func todoStoreFromContext(ctx context.Context) TodoStore { +// TodoStoreFromContext returns the TodoStore stored in ctx, or nil if none is set. +func TodoStoreFromContext(ctx context.Context) TodoStore { if s, ok := ctx.Value(todoStoreKey{}).(TodoStore); ok { return s } @@ -154,7 +155,7 @@ func executeTodo(ctx context.Context, call fantasy.ToolCall, defaultStore TodoSt return fantasy.ToolResponse{}, err } - store := todoStoreFromContext(ctx) + store := TodoStoreFromContext(ctx) if store == nil { store = defaultStore } diff --git a/internal/core/tools.go b/internal/core/tools.go index 272973968..fc16bda10 100644 --- a/internal/core/tools.go +++ b/internal/core/tools.go @@ -57,6 +57,9 @@ type ToolConfig struct { } // WithTodoStore sets the TodoStore for the todo tool. +// An explicitly configured store takes precedence over default session-backed +// storage. If no store is configured, the tool uses an in-memory store (or +// the store injected into context via ContextWithTodoStore). func WithTodoStore(store TodoStore) ToolOption { return func(c *ToolConfig) { c.TodoStore = store diff --git a/pkg/kit/jobs.go b/pkg/kit/jobs.go index 5c299aeb5..f536a21e6 100644 --- a/pkg/kit/jobs.go +++ b/pkg/kit/jobs.go @@ -223,8 +223,10 @@ func (s *turnJobService) Start(ctx context.Context, kind string, work func(conte detached = agent.ContextWithSteerCh(detached, nil) detached = agent.ContextWithSteerConsumed(detached, nil) detached = core.WithJobService(detached, s) - if s.kit != nil && s.kit.session != nil { - detached = core.ContextWithTodoStore(detached, newSessionTodoStore(s.kit.session)) + if core.TodoStoreFromContext(detached) == nil && s.kit != nil { + if store := s.kit.effectiveTodoStore(); store != nil { + detached = core.ContextWithTodoStore(detached, store) + } } // The manager owns lifetime cancellation. Keep values separate so cancelling // the work-local context on return cannot mark successful work cancelled. diff --git a/pkg/kit/kit.go b/pkg/kit/kit.go index 6087410df..459f081d8 100644 --- a/pkg/kit/kit.go +++ b/pkg/kit/kit.go @@ -79,6 +79,9 @@ type Kit struct { // coreToolOptions is Options.CoreToolOptions, kept so subagents // inherit it. coreToolOptions []ToolOption + // explicitTodoStore is the TodoStore configured via CoreToolOptions.WithTodoStore, + // if any. When non-nil, it takes precedence over session-backed todo storage. + explicitTodoStore core.TodoStore // coreToolList is the resolved list of core tool names this instance // enabled. New always sets it (empty, not nil, when core tools are // disabled); nil means no limit. Subagents built without an explicit @@ -1527,8 +1530,11 @@ type Options struct { // CoreToolOptions are applied to the built-in core tools after the // options Kit derives from its own settings, so they win on conflict. // Use them for tool behavior that has no Options field, such as - // [WithFileSystem] or [WithCommandRunner]. Subagents inherit them. They - // have no effect on tools supplied through Tools. + // [WithFileSystem], [WithCommandRunner], or [WithTodoStore]. A store + // supplied via [WithTodoStore] takes precedence over the default + // session-backed todo store; when none is supplied, the session store is used + // (or an in-memory store if no session is active). Subagents inherit them. + // They have no effect on tools supplied through Tools. CoreToolOptions []ToolOption // ImageMaxEdge caps the width and height, in pixels, of an image the @@ -1935,6 +1941,8 @@ func New(ctx context.Context, opts *Options) (*Kit, error) { return nil, err } + toolCfg := core.ApplyOptions(opts.CoreToolOptions) + k := &Kit{ agent: agentResult.Agent, session: sessionManager, @@ -1944,6 +1952,7 @@ func New(ctx context.Context, opts *Options) (*Kit, error) { shell: append([]string(nil), rc.shell...), workDir: opts.WorkDir, coreToolOptions: append([]ToolOption(nil), opts.CoreToolOptions...), + explicitTodoStore: toolCfg.TodoStore, coreToolList: append([]string{}, rc.toolList...), customTools: append([]Tool(nil), opts.Tools...), events: newEventBus(), @@ -2882,13 +2891,29 @@ func (m *Kit) Subagent(ctx context.Context, cfg SubagentConfig) (*SubagentResult // Shared generation helpers // --------------------------------------------------------------------------- +// effectiveTodoStore returns the TodoStore to use for generation: +// 1. Explicit store from CoreToolOptions.WithTodoStore (highest precedence) +// 2. Session-backed store if a session is active +// 3. nil (tool will fall back to its internal in-memory store) +func (m *Kit) effectiveTodoStore() core.TodoStore { + if m.explicitTodoStore != nil { + return m.explicitTodoStore + } + if m.session != nil { + return newSessionTodoStore(m.session) + } + return nil +} + // generate calls the agent's generation loop with event-emitting handlers. // All prompt modes (Prompt, Steer, FollowUp, PromptWithOptions) share this // single code path so callback wiring is never duplicated. func (m *Kit) generate(ctx context.Context, messages []fantasy.Message) (*agent.GenerateWithLoopResult, error) { ctx = core.WithJobService(ctx, &turnJobService{kit: m}) - if m.session != nil { - ctx = core.ContextWithTodoStore(ctx, newSessionTodoStore(m.session)) + if core.TodoStoreFromContext(ctx) == nil { + if store := m.effectiveTodoStore(); store != nil { + ctx = core.ContextWithTodoStore(ctx, store) + } } // Capture the per-turn stream collector (set by runTurn) so streamed // deltas are recorded into TurnResult.Stream in emit order. diff --git a/pkg/kit/todo_test.go b/pkg/kit/todo_test.go index d4ccc2d35..45a102e88 100644 --- a/pkg/kit/todo_test.go +++ b/pkg/kit/todo_test.go @@ -125,3 +125,46 @@ func TestTodo_PersistsAcrossSessionRestartAndCompaction(t *testing.T) { t.Errorf("expected resumed read to contain task-2, got: %s", resumedRead.Content) } } + +func TestKit_TodoStorePrecedence(t *testing.T) { + // 1. Kit with explicit CoreToolOptions.WithTodoStore + explicitStore := core.NewMemoryTodoStore() + _ = explicitStore.SaveTodos(context.Background(), []core.TodoItem{ + {ID: "explicit-1", Content: "Explicit Store Task", Status: core.TodoStatusPending}, + }) + + k1 := &Kit{ + explicitTodoStore: explicitStore, + session: NewTreeManagerAdapter(session.InMemoryTreeSession(t.TempDir())), + } + + // effectiveTodoStore must return explicitStore, not session store + if got := k1.effectiveTodoStore(); got != explicitStore { + t.Errorf("effectiveTodoStore with explicit store: got %v, want %v", got, explicitStore) + } + + // 2. Kit with NO explicit store, but has session + tm := session.InMemoryTreeSession(t.TempDir()) + sm := NewTreeManagerAdapter(tm) + k2 := &Kit{ + session: sm, + } + + gotStore := k2.effectiveTodoStore() + if gotStore == nil { + t.Fatal("expected non-nil session todo store when session is present") + } + + // 3. Kit with NO explicit store and NO session + k3 := &Kit{} + if got := k3.effectiveTodoStore(); got != nil { + t.Errorf("expected nil effectiveTodoStore when no session and no explicit store, got %v", got) + } + + // 4. Per-turn context override + perTurnStore := core.NewMemoryTodoStore() + ctxWithPerTurn := ContextWithTodoStore(context.Background(), perTurnStore) + if got := TodoStoreFromContext(ctxWithPerTurn); got != perTurnStore { + t.Errorf("TodoStoreFromContext: got %v, want %v", got, perTurnStore) + } +} diff --git a/pkg/kit/tools.go b/pkg/kit/tools.go index 7368b1a62..5a07cb271 100644 --- a/pkg/kit/tools.go +++ b/pkg/kit/tools.go @@ -73,8 +73,19 @@ type TodoStore = core.TodoStore type TodoItem = core.TodoItem // WithTodoStore sets the [TodoStore] for the todo tool. +// When supplied through [Options.CoreToolOptions], this explicit store takes +// precedence over the default session-backed storage. If no explicit store is +// configured, the todo tool persists tasks into the active session store (or +// falls back to an in-memory store when no session is active). A store attached +// to a turn's context via [ContextWithTodoStore] overrides both for that turn. var WithTodoStore = core.WithTodoStore +// ContextWithTodoStore stores the [TodoStore] in ctx for use by the todo tool. +var ContextWithTodoStore = core.ContextWithTodoStore + +// TodoStoreFromContext returns the [TodoStore] stored in ctx, or nil if none is set. +var TodoStoreFromContext = core.TodoStoreFromContext + // --- Core Tool Validation --- // processes a list of tool names, if disableCoreTools is true, return an // empty list. Otherwise if coreTools is not empty, it will return a list of diff --git a/www/pages/sdk/api-reference.md b/www/pages/sdk/api-reference.md index 52cc50176..f690f7815 100644 --- a/www/pages/sdk/api-reference.md +++ b/www/pages/sdk/api-reference.md @@ -774,6 +774,7 @@ Types for a custom `LLMLanguageModel` that a `ProviderFactory` returns: - [`CommandRequest`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#CommandRequest) — CommandRequest describes one command the shell tool wants to run. - [`CommandResult`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#CommandResult) — CommandResult is the outcome of a command run by a [CommandRunner]. - [`CommandRunner`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#CommandRunner) — CommandRunner runs the shell tool's commands somewhere other than a local child process, for example in an editor's terminal. +- [`ContextWithTodoStore`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#ContextWithTodoStore) — ContextWithTodoStore stores the [TodoStore] in ctx for use by the todo tool. - [`DefaultCoreToolNames`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#DefaultCoreToolNames) — DefaultCoreToolNames returns the core tools enabled when none are named. - [`ErrorResult`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#ErrorResult) — ErrorResult creates an error [ToolOutput]. - [`FileSystem`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#FileSystem) — FileSystem reads and writes text files for the read, write and edit tools. @@ -798,6 +799,7 @@ Types for a custom `LLMLanguageModel` that a `ProviderFactory` returns: - [`TextResult`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#TextResult) — TextResult creates a successful text [ToolOutput]. - [`TodoItem`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#TodoItem) — TodoItem represents a single task in a structured checklist. - [`TodoStore`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#TodoStore) — TodoStore provides storage and retrieval for todo items. +- [`TodoStoreFromContext`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#TodoStoreFromContext) — TodoStoreFromContext returns the [TodoStore] stored in ctx, or nil if none is set. - [`ToolCallIDFromContext`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#ToolCallIDFromContext) — ToolCallIDFromContext extracts the tool call ID from the context. - [`ToolOption`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#ToolOption) — ToolOption configures tool behavior. - [`ToolOutput`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#ToolOutput) — ToolOutput is the return value from custom tool handlers created with [NewTool] or [NewParallelTool]. From 2fa8892a815943cb40a4b05e17faedf659037e40 Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Fri, 27 Nov 2026 20:44:26 +0530 Subject: [PATCH 06/13] fix(kit): bind sessionTodoStore to owner branch to reject writes after navigation --- pkg/kit/kit.go | 3 ++- pkg/kit/session_todo_store.go | 32 +++++++++++++++++++--- pkg/kit/todo_test.go | 51 ++++++++++++++++++++++++++++++++--- 3 files changed, 78 insertions(+), 8 deletions(-) diff --git a/pkg/kit/kit.go b/pkg/kit/kit.go index 459f081d8..017c9d03c 100644 --- a/pkg/kit/kit.go +++ b/pkg/kit/kit.go @@ -2900,7 +2900,8 @@ func (m *Kit) effectiveTodoStore() core.TodoStore { return m.explicitTodoStore } if m.session != nil { - return newSessionTodoStore(m.session) + _, branchID := m.jobOwner() + return newSessionTodoStore(m.session, branchID) } return nil } diff --git a/pkg/kit/session_todo_store.go b/pkg/kit/session_todo_store.go index c91704d05..a6ebcd5e8 100644 --- a/pkg/kit/session_todo_store.go +++ b/pkg/kit/session_todo_store.go @@ -8,19 +8,40 @@ import ( "github.com/mark3labs/kit/internal/core" ) -// sessionTodoStore adapts SessionManager's ExtensionData storage to core.TodoStore. +// sessionTodoStore adapts SessionManager's ExtensionData storage to core.TodoStore, +// optionally bound to an owner branch to prevent writes from detached jobs to an +// inactive branch after navigation. type sessionTodoStore struct { - session SessionManager + session SessionManager + ownerBranchID string } -func newSessionTodoStore(sm SessionManager) core.TodoStore { - return &sessionTodoStore{session: sm} +func newSessionTodoStore(sm SessionManager, ownerBranchID string) core.TodoStore { + return &sessionTodoStore{ + session: sm, + ownerBranchID: ownerBranchID, + } +} + +func (s *sessionTodoStore) isBranchActive() bool { + if s.ownerBranchID == "" || s.session == nil { + return true + } + for _, entry := range s.session.GetCurrentBranch() { + if entry.ID == s.ownerBranchID { + return true + } + } + return false } func (s *sessionTodoStore) GetTodos(ctx context.Context) ([]core.TodoItem, error) { if s.session == nil { return nil, nil } + if !s.isBranchActive() { + return nil, fmt.Errorf("cannot read todos: session navigated away from owner branch %q", s.ownerBranchID) + } entries := s.session.GetExtensionData("todo") if len(entries) == 0 { return nil, nil @@ -38,6 +59,9 @@ func (s *sessionTodoStore) SaveTodos(ctx context.Context, todos []core.TodoItem) if s.session == nil { return nil } + if !s.isBranchActive() { + return fmt.Errorf("cannot save todos: session navigated away from owner branch %q", s.ownerBranchID) + } data, err := json.Marshal(todos) if err != nil { return fmt.Errorf("marshal session todos: %w", err) diff --git a/pkg/kit/todo_test.go b/pkg/kit/todo_test.go index 45a102e88..fd942f92e 100644 --- a/pkg/kit/todo_test.go +++ b/pkg/kit/todo_test.go @@ -22,7 +22,7 @@ func runKitTodo(t *testing.T, tool Tool, ctx context.Context, input string) fant func TestSessionTodoStore_SaveAndGet(t *testing.T) { tm := session.InMemoryTreeSession(t.TempDir()) sm := NewTreeManagerAdapter(tm) - store := newSessionTodoStore(sm) + store := newSessionTodoStore(sm, "") ctx := context.Background() @@ -72,7 +72,7 @@ func TestTodo_PersistsAcrossSessionRestartAndCompaction(t *testing.T) { sm := NewTreeManagerAdapter(tm) todoTool := NewTodoTool() - ctx := core.ContextWithTodoStore(context.Background(), newSessionTodoStore(sm)) + ctx := core.ContextWithTodoStore(context.Background(), newSessionTodoStore(sm, "")) // Write tasks using the tool input := `{"todos":[{"id":"task-1","content":"Design architecture","status":"completed"},{"id":"task-2","content":"Write tests","status":"in_progress"}]}` @@ -110,7 +110,7 @@ func TestTodo_PersistsAcrossSessionRestartAndCompaction(t *testing.T) { defer func() { _ = reopenedTM.Close() }() reopenedSM := NewTreeManagerAdapter(reopenedTM) - reopenedCtx := core.ContextWithTodoStore(context.Background(), newSessionTodoStore(reopenedSM)) + reopenedCtx := core.ContextWithTodoStore(context.Background(), newSessionTodoStore(reopenedSM, "")) // Read todos with reopened session resumedRead := runKitTodo(t, todoTool, reopenedCtx, `{}`) @@ -168,3 +168,48 @@ func TestKit_TodoStorePrecedence(t *testing.T) { t.Errorf("TodoStoreFromContext: got %v, want %v", got, perTurnStore) } } + +func TestSessionTodoStore_RejectsNavigatedBranch(t *testing.T) { + tm := session.InMemoryTreeSession(t.TempDir()) + sm := NewTreeManagerAdapter(tm) + + // Append initial message to establish branch 1 + msgID, err := sm.AppendMessage(fantasy.NewUserMessage("branch 1 message")) + if err != nil { + t.Fatalf("AppendMessage failed: %v", err) + } + + // Create store bound to branch 1 + store := newSessionTodoStore(sm, msgID) + ctx := context.Background() + + // Writing on branch 1 must succeed + items := []core.TodoItem{{ID: "1", Content: "Task 1", Status: core.TodoStatusPending}} + if err := store.SaveTodos(ctx, items); err != nil { + t.Fatalf("SaveTodos on owner branch failed: %v", err) + } + + // Navigate away to a different branch + if err := sm.Branch(""); err != nil { + t.Fatalf("Branch failed: %v", err) + } + _, err = sm.AppendMessage(fantasy.NewUserMessage("branch 2 message")) + if err != nil { + t.Fatalf("AppendMessage on branch 2 failed: %v", err) + } + + // Writing from the branch 1 store must be rejected now + err = store.SaveTodos(ctx, []core.TodoItem{{ID: "1", Content: "Task 1", Status: core.TodoStatusCompleted}}) + if err == nil { + t.Fatal("expected SaveTodos to fail after session navigated away from owner branch") + } + if !strings.Contains(err.Error(), "navigated away") { + t.Errorf("expected error to mention 'navigated away', got: %v", err) + } + + // Reading from the branch 1 store must also be rejected + _, err = store.GetTodos(ctx) + if err == nil { + t.Fatal("expected GetTodos to fail after session navigated away from owner branch") + } +} From 70925042a59705c605509b5f19db1d687fd36406 Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Fri, 27 Nov 2026 20:56:06 +0530 Subject: [PATCH 07/13] fix(session): preserve pre-compaction extension history and map PreCompactionLeafID on fork --- internal/session/extension_data_test.go | 82 +++++++++++++++++++++++++ internal/session/tree_manager.go | 45 +++++++++++++- 2 files changed, 124 insertions(+), 3 deletions(-) diff --git a/internal/session/extension_data_test.go b/internal/session/extension_data_test.go index aeb6da445..ecdd5fcfe 100644 --- a/internal/session/extension_data_test.go +++ b/internal/session/extension_data_test.go @@ -2,6 +2,8 @@ package session import ( "testing" + + "github.com/mark3labs/kit/internal/message" ) func TestTreeManager_ExtensionDataSurvivesCompaction(t *testing.T) { @@ -108,3 +110,83 @@ func TestTreeManager_ExtensionDataBranchIsolationAcrossCompaction(t *testing.T) t.Errorf("unexpected branch A entries (branch B leaked!): %+v", entriesA) } } + +func TestTreeManager_ForkCompactedSessionPreservesExtensionData(t *testing.T) { + origDir := t.TempDir() + tm, err := CreateTreeSession(origDir) + if err != nil { + t.Fatalf("CreateTreeSession failed: %v", err) + } + defer func() { _ = tm.Close() }() + + // 1. Append pre-compaction extension data and messages + _, err = tm.AppendExtensionData("todo", `[{"id":"1","content":"task 1","status":"pending"}]`) + if err != nil { + t.Fatalf("AppendExtensionData failed: %v", err) + } + _, err = tm.AppendMessage(message.Message{Role: message.RoleUser, Parts: []message.ContentPart{message.TextContent{Text: "hello"}}}) + if err != nil { + t.Fatalf("AppendMessage failed: %v", err) + } + + // 2. Perform compaction + _, err = tm.AppendCompaction("Compacted conversation", "", 1000, 200, 2, nil, nil) + if err != nil { + t.Fatalf("AppendCompaction failed: %v", err) + } + + // 3. Append post-compaction message + postMsgID, err := tm.AppendMessage(message.Message{Role: message.RoleUser, Parts: []message.ContentPart{message.TextContent{Text: "what next?"}}}) + if err != nil { + t.Fatalf("AppendMessage post-compaction failed: %v", err) + } + + // 4. Fork the session to a new session targeting the post-compaction message + forkDir := t.TempDir() + forked, err := tm.ForkToNewSession(forkDir, postMsgID) + if err != nil { + t.Fatalf("ForkToNewSession failed: %v", err) + } + defer func() { _ = forked.Close() }() + + // 5. Verify forked session has access to the pre-compaction extension data + extEntries := forked.GetExtensionData("todo") + if len(extEntries) != 1 { + t.Fatalf("expected 1 extension entry in forked session, got %d", len(extEntries)) + } + if extEntries[0].Data != `[{"id":"1","content":"task 1","status":"pending"}]` { + t.Errorf("unexpected extension data in fork: %s", extEntries[0].Data) + } + + // 6. Verify that CompactionEntry in the forked session has a valid, existing PreCompactionLeafID in the fork + branch := forked.GetBranch("") + var forkedCompaction *CompactionEntry + for _, e := range branch { + if c, ok := e.(*CompactionEntry); ok { + forkedCompaction = c + break + } + } + if forkedCompaction == nil { + t.Fatal("expected CompactionEntry in forked session branch") + } + if forkedCompaction.PreCompactionLeafID == "" { + t.Fatal("expected non-empty PreCompactionLeafID in forked compaction entry") + } + if forked.GetEntry(forkedCompaction.PreCompactionLeafID) == nil { + t.Fatalf("PreCompactionLeafID %q does not exist in forked session index", forkedCompaction.PreCompactionLeafID) + } + + // 7. Append new extension data in forked session and verify both survive + _, err = forked.AppendExtensionData("todo", `[{"id":"1","content":"task 1","status":"completed"}]`) + if err != nil { + t.Fatalf("AppendExtensionData in fork failed: %v", err) + } + updatedExt := forked.GetExtensionData("todo") + if len(updatedExt) != 2 { + t.Fatalf("expected 2 extension entries in fork after update, got %d", len(updatedExt)) + } + if updatedExt[len(updatedExt)-1].Data != `[{"id":"1","content":"task 1","status":"completed"}]` { + t.Errorf("unexpected latest extension data in fork: %s", updatedExt[len(updatedExt)-1].Data) + } +} diff --git a/internal/session/tree_manager.go b/internal/session/tree_manager.go index 77bdcd145..81ec8e689 100644 --- a/internal/session/tree_manager.go +++ b/internal/session/tree_manager.go @@ -224,6 +224,38 @@ func (tm *TreeManager) ForkToNewSession(cwd string, targetID string) (*TreeManag idMap := make(map[string]string) // old ID -> new ID var prevNewID string + // If the branch contains a compaction entry, its pre-compaction extension + // data is not part of the post-compaction branch path. Copy that historical + // extension data first so that extension state (e.g. todos) survives the fork + // and PreCompactionLeafID resolves to a valid local entry. + allExt := tm.getExtensionDataLocked(targetID, "") + inBranch := make(map[string]bool, len(branch)) + for _, entry := range branch { + if id := tm.EntryID(entry); id != "" { + inBranch[id] = true + } + } + + var preCompLeafID string + var prePrevID string + for _, ext := range allExt { + if !inBranch[ext.ID] { + newID := GenerateEntryID() + idMap[ext.ID] = newID + copied := &ExtensionDataEntry{ + Entry: cloneEntry(ext.Entry, newID, prePrevID), + ExtType: ext.ExtType, + Data: ext.Data, + } + if err := newTm.appendAndPersist(copied); err != nil { + _ = f.Close() + return nil, fmt.Errorf("failed to copy pre-compaction extension entry: %w", err) + } + prePrevID = newID + preCompLeafID = newID + } + } + for _, entry := range branch { oldID := tm.EntryID(entry) newID := GenerateEntryID() @@ -303,9 +335,11 @@ func (tm *TreeManager) ForkToNewSession(cwd string, targetID string) (*TreeManag newPreLeafID := e.PreCompactionLeafID if mapped, ok := idMap[e.PreCompactionLeafID]; ok { newPreLeafID = mapped + } else if preCompLeafID != "" { + newPreLeafID = preCompLeafID } newEntry = &CompactionEntry{ - Entry: cloneEntry(e.Entry, newID, prevNewID), + Entry: cloneEntry(e.Entry, newID, ""), Summary: e.Summary, FirstKeptEntryID: newFirstKeptID, PreCompactionLeafID: newPreLeafID, @@ -963,15 +997,20 @@ func (tm *TreeManager) AppendCompaction(summary, firstKeptEntryID string, tokens func (tm *TreeManager) GetExtensionData(extType string) []*ExtensionDataEntry { tm.mu.RLock() defer tm.mu.RUnlock() + return tm.getExtensionDataLocked(tm.leafID, extType) +} - if tm.leafID == "" { +// getExtensionDataLocked walks the branch ending at leafID and its compacted ancestor branches. +// Caller must hold at least tm.mu.RLock. +func (tm *TreeManager) getExtensionDataLocked(leafID, extType string) []*ExtensionDataEntry { + if leafID == "" { return nil } var results []*ExtensionDataEntry visitedLeaves := make(map[string]bool) - currentLeaf := tm.leafID + currentLeaf := leafID for currentLeaf != "" && !visitedLeaves[currentLeaf] { visitedLeaves[currentLeaf] = true branch := tm.getBranchLocked(currentLeaf) From 9eb3582530fb954a3da8c558d0f9c1e37bb34bfc Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Fri, 27 Nov 2026 21:03:29 +0530 Subject: [PATCH 08/13] fix(core): treat empty todos as read, add explicit action clear, and isolate subagent todo store --- internal/core/todo.go | 24 +++++++++-------- internal/core/todo_test.go | 13 +++++++-- pkg/kit/kit.go | 7 ++++- pkg/kit/todo_test.go | 54 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 84 insertions(+), 14 deletions(-) diff --git a/internal/core/todo.go b/internal/core/todo.go index 7505f0411..94292f85c 100644 --- a/internal/core/todo.go +++ b/internal/core/todo.go @@ -98,19 +98,20 @@ func NewTodoTool(opts ...ToolOption) fantasy.AgentTool { Description: `Track and manage structured task checklists for complex multi-step workflows. Use this tool to plan multi-step tasks, track progress, and maintain focus across long workflows. -- To view existing tasks: call with no arguments or {"action": "read"}. +- To view existing tasks: call with no arguments, {"action": "read"}, or {"todos": []}. - To update or replace tasks: call with {"todos": [...]}. Each task must have: - id: unique string identifier (e.g. "1", "2") - content: clear description of the step - status: "pending", "in_progress", "completed", or "cancelled" - priority: optional "high", "medium", or "low" (default: "medium") +- To clear all tasks: call with {"action": "clear"}. Tasks are persisted in the session store and survive context compaction and session restarts.`, Parameters: map[string]any{ "action": map[string]any{ "type": "string", - "enum": []string{"read", "write"}, - "description": "Optional action. If 'todos' is provided, 'write' is assumed. Defaults to 'read'.", + "enum": []string{"read", "write", "clear"}, + "description": "Optional action. If non-empty 'todos' is provided, 'write' is assumed. 'clear' removes all tasks. Defaults to 'read'.", }, "todos": map[string]any{ "type": "array", @@ -165,15 +166,16 @@ func executeTodo(ctx context.Context, call fantasy.ToolCall, defaultStore TodoSt return fantasy.NewTextErrorResponse(fmt.Sprintf("invalid arguments: %v", err)), nil } - // If todos are provided, treat as write action. - if args.Todos != nil { - items := *args.Todos - if len(items) == 0 { - if err := store.SaveTodos(ctx, []TodoItem{}); err != nil { - return fantasy.NewTextErrorResponse(fmt.Sprintf("failed to save todos: %v", err)), nil - } - return fantasy.NewTextResponse("Todos cleared."), nil + if args.Action == "clear" { + if err := store.SaveTodos(ctx, []TodoItem{}); err != nil { + return fantasy.NewTextErrorResponse(fmt.Sprintf("failed to clear todos: %v", err)), nil } + return fantasy.NewTextResponse("Todos cleared."), nil + } + + // If non-empty todos are provided, treat as write action. + if args.Todos != nil && len(*args.Todos) > 0 { + items := *args.Todos // Reserve all non-empty explicit IDs and reject duplicate explicit IDs. usedIDs := make(map[string]bool, len(items)) diff --git a/internal/core/todo_test.go b/internal/core/todo_test.go index 41e5ee9ed..c9c703ab1 100644 --- a/internal/core/todo_test.go +++ b/internal/core/todo_test.go @@ -81,8 +81,17 @@ func TestTodoTool_ClearTodos(t *testing.T) { // Add a todo _ = runTodo(t, tool, ctx, `{"todos":[{"content":"step 1","status":"pending"}]}`) - // Clear todos - clearResp := runTodo(t, tool, ctx, `{"todos":[]}`) + // Calling with empty todos array {"todos":[]} must leave existing items unchanged + emptyResp := runTodo(t, tool, ctx, `{"todos":[]}`) + if emptyResp.IsError { + t.Fatalf("empty todos call failed: %s", emptyResp.Content) + } + if !strings.Contains(emptyResp.Content, "step 1") { + t.Errorf("expected empty todos to leave existing items unchanged, got: %s", emptyResp.Content) + } + + // Explicit action: "clear" clears todos + clearResp := runTodo(t, tool, ctx, `{"action":"clear"}`) if clearResp.IsError { t.Fatalf("clear failed: %s", clearResp.Content) } diff --git a/pkg/kit/kit.go b/pkg/kit/kit.go index 017c9d03c..0e5db1db3 100644 --- a/pkg/kit/kit.go +++ b/pkg/kit/kit.go @@ -2857,8 +2857,13 @@ func (m *Kit) Subagent(ctx context.Context, cfg SubagentConfig) (*SubagentResult } }) + // Clear any inherited parent TodoStore from the context so the child's + // generate path creates and injects its own session-backed store for its + // own session (or uses its inherited explicit store). + childCtx := core.ContextWithTodoStore(ctx, nil) + // Run the prompt. - result, err := child.PromptResult(ctx, cfg.Prompt) + result, err := child.PromptResult(childCtx, cfg.Prompt) elapsed := time.Since(start) if err != nil { diff --git a/pkg/kit/todo_test.go b/pkg/kit/todo_test.go index fd942f92e..bb487e982 100644 --- a/pkg/kit/todo_test.go +++ b/pkg/kit/todo_test.go @@ -124,6 +124,24 @@ func TestTodo_PersistsAcrossSessionRestartAndCompaction(t *testing.T) { if !strings.Contains(resumedRead.Content, "[~] task-2: Write tests") { t.Errorf("expected resumed read to contain task-2, got: %s", resumedRead.Content) } + + // Calling {"todos":[]} must leave existing items unchanged + emptyTodosResp := runKitTodo(t, todoTool, reopenedCtx, `{"todos":[]}`) + if emptyTodosResp.IsError { + t.Fatalf("empty todos call failed: %s", emptyTodosResp.Content) + } + if !strings.Contains(emptyTodosResp.Content, "[x] task-1: Design architecture") { + t.Errorf("expected empty todos to leave items unchanged, got: %s", emptyTodosResp.Content) + } + + // Explicit action: "clear" removes todos + clearResp := runKitTodo(t, todoTool, reopenedCtx, `{"action":"clear"}`) + if clearResp.IsError { + t.Fatalf("clear call failed: %s", clearResp.Content) + } + if !strings.Contains(clearResp.Content, "Todos cleared") { + t.Errorf("expected 'Todos cleared', got %s", clearResp.Content) + } } func TestKit_TodoStorePrecedence(t *testing.T) { @@ -213,3 +231,39 @@ func TestSessionTodoStore_RejectsNavigatedBranch(t *testing.T) { t.Fatal("expected GetTodos to fail after session navigated away from owner branch") } } + +func TestSubagent_HasOwnSessionTodoStore(t *testing.T) { + parentTM := session.InMemoryTreeSession(t.TempDir()) + parentSM := NewTreeManagerAdapter(parentTM) + parentStore := newSessionTodoStore(parentSM, "") + + ctx := core.ContextWithTodoStore(context.Background(), parentStore) + + // Child context clears parent store + childCtx := core.ContextWithTodoStore(ctx, nil) + if got := core.TodoStoreFromContext(childCtx); got != nil { + t.Fatalf("expected nil TodoStore in child context, got %v", got) + } + + childTM := session.InMemoryTreeSession(t.TempDir()) + childSM := NewTreeManagerAdapter(childTM) + childKit := &Kit{session: childSM} + + childStore := childKit.effectiveTodoStore() + if childStore == nil { + t.Fatal("expected childKit to have its own session todo store") + } + + // Writing to childStore must write to childSM, NOT parentSM + _ = childStore.SaveTodos(childCtx, []core.TodoItem{{ID: "c1", Content: "child task", Status: core.TodoStatusPending}}) + + parentTodos, _ := parentStore.GetTodos(ctx) + if len(parentTodos) != 0 { + t.Errorf("parentStore polluted by child write: %+v", parentTodos) + } + + childTodos, _ := childStore.GetTodos(childCtx) + if len(childTodos) != 1 || childTodos[0].Content != "child task" { + t.Errorf("childStore missing task: %+v", childTodos) + } +} From 2d27aaed242f7484b1fbb4b8866ac07f3c47832f Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Fri, 27 Nov 2026 21:09:34 +0530 Subject: [PATCH 09/13] fix(kit): preserve sessionTodoStore ownership across context compaction --- pkg/kit/session_todo_store.go | 29 ++++++++++++++++- pkg/kit/todo_test.go | 61 +++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 1 deletion(-) diff --git a/pkg/kit/session_todo_store.go b/pkg/kit/session_todo_store.go index a6ebcd5e8..f74f4a416 100644 --- a/pkg/kit/session_todo_store.go +++ b/pkg/kit/session_todo_store.go @@ -27,11 +27,38 @@ func (s *sessionTodoStore) isBranchActive() bool { if s.ownerBranchID == "" || s.session == nil { return true } - for _, entry := range s.session.GetCurrentBranch() { + currentBranch := s.session.GetCurrentBranch() + for _, entry := range currentBranch { if entry.ID == s.ownerBranchID { return true } } + + // If ownerBranchID is not directly on the current branch, check if the + // current branch is a post-compaction continuation of the owner branch. + compaction := s.session.GetLastCompaction() + if compaction == nil { + return false + } + + visited := make(map[string]bool) + currID := compaction.PreCompactionLeafID + if currID == "" { + currID = compaction.FirstKeptEntryID + } + + for currID != "" && !visited[currID] { + if currID == s.ownerBranchID { + return true + } + visited[currID] = true + entry := s.session.GetEntry(currID) + if entry == nil { + break + } + currID = entry.ParentID + } + return false } diff --git a/pkg/kit/todo_test.go b/pkg/kit/todo_test.go index bb487e982..0aa16c050 100644 --- a/pkg/kit/todo_test.go +++ b/pkg/kit/todo_test.go @@ -267,3 +267,64 @@ func TestSubagent_HasOwnSessionTodoStore(t *testing.T) { t.Errorf("childStore missing task: %+v", childTodos) } } + +func TestSessionTodoStore_PreservesOwnershipAcrossCompaction(t *testing.T) { + tm := session.InMemoryTreeSession(t.TempDir()) + sm := NewTreeManagerAdapter(tm) + + // Append initial message to establish branch + msgID, err := sm.AppendMessage(fantasy.NewUserMessage("branch message before compaction")) + if err != nil { + t.Fatalf("AppendMessage failed: %v", err) + } + + // Create store bound to msgID (simulating a job started before compaction) + store := newSessionTodoStore(sm, msgID) + ctx := context.Background() + + // Perform compaction on this branch + _, err = sm.AppendCompaction("Compacted conversation", "", 1000, 200, 2, nil, nil) + if err != nil { + t.Fatalf("AppendCompaction failed: %v", err) + } + + // Append a post-compaction message + _, err = sm.AppendMessage(fantasy.NewUserMessage("branch message after compaction")) + if err != nil { + t.Fatalf("AppendMessage after compaction failed: %v", err) + } + + // Writing from the store bound to pre-compaction msgID must still succeed + // because the session is on a post-compaction continuation of that branch + items := []core.TodoItem{{ID: "1", Content: "Task surviving compaction", Status: core.TodoStatusInProgress}} + if err := store.SaveTodos(ctx, items); err != nil { + t.Fatalf("SaveTodos across compaction failed: %v", err) + } + + // Reading must also succeed + todos, err := store.GetTodos(ctx) + if err != nil { + t.Fatalf("GetTodos across compaction failed: %v", err) + } + if len(todos) != 1 || todos[0].Content != "Task surviving compaction" { + t.Errorf("unexpected todos across compaction: %+v", todos) + } + + // Now branch away to a genuine new branch + if err := sm.Branch(""); err != nil { + t.Fatalf("Branch failed: %v", err) + } + _, err = sm.AppendMessage(fantasy.NewUserMessage("unrelated branch message")) + if err != nil { + t.Fatalf("AppendMessage on unrelated branch failed: %v", err) + } + + // Writing after genuine navigation away must be rejected + err = store.SaveTodos(ctx, []core.TodoItem{{ID: "1", Content: "Should fail", Status: core.TodoStatusCompleted}}) + if err == nil { + t.Fatal("expected SaveTodos to fail after navigating away from owner branch") + } + if !strings.Contains(err.Error(), "navigated away") { + t.Errorf("expected error to mention 'navigated away', got: %v", err) + } +} From 5624f4208f88d5d8752f0361351ff2797ced60ab Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Fri, 27 Nov 2026 21:20:08 +0530 Subject: [PATCH 10/13] fix(kit): use jobScope().leafID for effectiveTodoStore branch binding --- pkg/kit/kit.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/kit/kit.go b/pkg/kit/kit.go index 0e5db1db3..4c2e77da6 100644 --- a/pkg/kit/kit.go +++ b/pkg/kit/kit.go @@ -2905,7 +2905,7 @@ func (m *Kit) effectiveTodoStore() core.TodoStore { return m.explicitTodoStore } if m.session != nil { - _, branchID := m.jobOwner() + branchID := m.jobScope().leafID return newSessionTodoStore(m.session, branchID) } return nil From beb6f8d71e0384ab40bdc86cc7078f1b466b7ee7 Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Fri, 27 Nov 2026 21:49:59 +0530 Subject: [PATCH 11/13] fix(kit): support chained compaction traversal in isBranchActive and populate PreCompactionLeafID on BranchEntry --- pkg/kit/adapter.go | 11 ++++++----- pkg/kit/session.go | 21 +++++++++++---------- pkg/kit/session_todo_store.go | 6 +++++- 3 files changed, 22 insertions(+), 16 deletions(-) diff --git a/pkg/kit/adapter.go b/pkg/kit/adapter.go index 906fc1650..2deea735d 100644 --- a/pkg/kit/adapter.go +++ b/pkg/kit/adapter.go @@ -258,11 +258,12 @@ func (a *treeManagerAdapter) convertEntry(entry any) *BranchEntry { } case *session.CompactionEntry: return &BranchEntry{ - ID: e.ID, - ParentID: e.ParentID, - Type: EntryTypeCompaction, - Content: e.Summary, - Timestamp: e.Timestamp, + ID: e.ID, + ParentID: e.ParentID, + PreCompactionLeafID: e.PreCompactionLeafID, + Type: EntryTypeCompaction, + Content: e.Summary, + Timestamp: e.Timestamp, } case *session.ExtensionDataEntry: return &BranchEntry{ diff --git a/pkg/kit/session.go b/pkg/kit/session.go index ed47f0511..73985ebfb 100644 --- a/pkg/kit/session.go +++ b/pkg/kit/session.go @@ -135,16 +135,17 @@ type BranchEntry struct { // AttemptID identifies generation for an incomplete output entry. AttemptID string // Incomplete marks transcript-only output excluded from model history. - Incomplete bool - ID string - ParentID string - Type EntryType // "message", "branch_summary", "model_change", "compaction", "extension_data" - Role string // for messages: "user", "assistant", "system", "tool" - Content string // text content or summary - Model string // model used (for messages and model_change) - Provider string // provider used - Timestamp time.Time - Children []string // child entry IDs (for tree display) + Incomplete bool + ID string + ParentID string + PreCompactionLeafID string // for compaction entries: leaf ID before compaction + Type EntryType // "message", "branch_summary", "model_change", "compaction", "extension_data" + Role string // for messages: "user", "assistant", "system", "tool" + Content string // text content or summary + Model string // model used (for messages and model_change) + Provider string // provider used + Timestamp time.Time + Children []string // child entry IDs (for tree display) // RawParts contains the full typed content parts for structured access. // Only populated for message entries. diff --git a/pkg/kit/session_todo_store.go b/pkg/kit/session_todo_store.go index f74f4a416..c5372e47f 100644 --- a/pkg/kit/session_todo_store.go +++ b/pkg/kit/session_todo_store.go @@ -56,7 +56,11 @@ func (s *sessionTodoStore) isBranchActive() bool { if entry == nil { break } - currID = entry.ParentID + if entry.Type == EntryTypeCompaction && entry.ParentID == "" && entry.PreCompactionLeafID != "" { + currID = entry.PreCompactionLeafID + } else { + currID = entry.ParentID + } } return false From b3039e96f1587e50c276d9007f8c165fb95a68ad Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Fri, 27 Nov 2026 22:11:34 +0530 Subject: [PATCH 12/13] fix(kit): rebind job todo store to owner branch and propagate CoreToolOptions to subagent --- pkg/kit/jobs.go | 10 ++++++---- pkg/kit/kit.go | 1 + pkg/kit/todo_test.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 4 deletions(-) diff --git a/pkg/kit/jobs.go b/pkg/kit/jobs.go index f536a21e6..fa8c0364f 100644 --- a/pkg/kit/jobs.go +++ b/pkg/kit/jobs.go @@ -223,15 +223,17 @@ func (s *turnJobService) Start(ctx context.Context, kind string, work func(conte detached = agent.ContextWithSteerCh(detached, nil) detached = agent.ContextWithSteerConsumed(detached, nil) detached = core.WithJobService(detached, s) - if core.TodoStoreFromContext(detached) == nil && s.kit != nil { - if store := s.kit.effectiveTodoStore(); store != nil { - detached = core.ContextWithTodoStore(detached, store) + owner := s.kit.jobScope().owner() + if s.kit != nil { + if s.kit.explicitTodoStore != nil { + detached = core.ContextWithTodoStore(detached, s.kit.explicitTodoStore) + } else if s.kit.session != nil { + detached = core.ContextWithTodoStore(detached, newSessionTodoStore(s.kit.session, owner.BranchID)) } } // The manager owns lifetime cancellation. Keep values separate so cancelling // the work-local context on return cannot mark successful work cancelled. jobCtx := jobValueContext{Context: state.lifetime, values: detached} - owner := s.kit.jobScope().owner() job, err := state.manager.Start(jobCtx, kind, owner.SessionID, owner.BranchID, func(ctx context.Context) (string, error) { workCtx, cancel := context.WithCancel(ctx) defer cancel() diff --git a/pkg/kit/kit.go b/pkg/kit/kit.go index 4c2e77da6..c85b515ac 100644 --- a/pkg/kit/kit.go +++ b/pkg/kit/kit.go @@ -2719,6 +2719,7 @@ func (m *Kit) Subagent(ctx context.Context, cfg SubagentConfig) (*SubagentResult Model: model, SystemPrompt: systemPrompt, Tools: tools, + CoreToolOptions: append([]ToolOption(nil), m.coreToolOptions...), NoSession: cfg.NoSession, SessionPath: resumePath, Quiet: true, diff --git a/pkg/kit/todo_test.go b/pkg/kit/todo_test.go index 0aa16c050..af530a286 100644 --- a/pkg/kit/todo_test.go +++ b/pkg/kit/todo_test.go @@ -2,6 +2,7 @@ package kit import ( "context" + "fmt" "strings" "testing" @@ -266,6 +267,47 @@ func TestSubagent_HasOwnSessionTodoStore(t *testing.T) { if len(childTodos) != 1 || childTodos[0].Content != "child task" { t.Errorf("childStore missing task: %+v", childTodos) } + + // Test that an explicit WithTodoStore in parent's coreToolOptions is inherited by the child + explicitStore := core.NewMemoryTodoStore() + childKitExplicit := &Kit{ + coreToolOptions: []ToolOption{WithTodoStore(explicitStore)}, + explicitTodoStore: explicitStore, + session: childSM, + } + if got := childKitExplicit.effectiveTodoStore(); got != explicitStore { + t.Errorf("expected child with explicit store to use it, got %v", got) + } +} + +func TestBackgroundJob_RebindsTodoStoreToOwnerBranch(t *testing.T) { + k := newJobsTestKit(t) + appendTestMessage(t, k, fantasy.NewUserMessage("msg 1")) + appendTestMessage(t, k, fantasy.NewUserMessage("msg 2")) + + jobScope := k.jobScope() + service := &turnJobService{kit: k} + + // Start job with a context that simulates a turn context from an old leaf + turnCtx := core.ContextWithTodoStore(context.Background(), newSessionTodoStore(k.session, "old-leaf")) + + job, err := service.Start(turnCtx, "test", func(ctx context.Context) (string, error) { + store := core.TodoStoreFromContext(ctx) + if store == nil { + return "", fmt.Errorf("expected non-nil store in job context") + } + // Saving todos must succeed because store was rebound to current job owner branch + err := store.SaveTodos(ctx, []core.TodoItem{{ID: "1", Content: "Job task", Status: core.TodoStatusCompleted}}) + return "done", err + }) + if err != nil { + t.Fatalf("Start failed: %v", err) + } + waitJobTest(t, k, job.ID) + + if job.BranchID != jobScope.leafID { + t.Errorf("job.BranchID = %q, want %q", job.BranchID, jobScope.leafID) + } } func TestSessionTodoStore_PreservesOwnershipAcrossCompaction(t *testing.T) { From 4e63ec818be1a065c0c8381cd244858806cd665d Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Mon, 30 Nov 2026 21:03:38 +0530 Subject: [PATCH 13/13] test(kit): assert completed job status in TestBackgroundJob_RebindsTodoStoreToOwnerBranch --- pkg/kit/todo_test.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/pkg/kit/todo_test.go b/pkg/kit/todo_test.go index af530a286..e99e10a94 100644 --- a/pkg/kit/todo_test.go +++ b/pkg/kit/todo_test.go @@ -303,10 +303,13 @@ func TestBackgroundJob_RebindsTodoStoreToOwnerBranch(t *testing.T) { if err != nil { t.Fatalf("Start failed: %v", err) } - waitJobTest(t, k, job.ID) + finished := waitJobTest(t, k, job.ID) + if finished.Status != JobCompleted { + t.Fatalf("job status = %s, want %s (error: %s)", finished.Status, JobCompleted, finished.Error) + } - if job.BranchID != jobScope.leafID { - t.Errorf("job.BranchID = %q, want %q", job.BranchID, jobScope.leafID) + if finished.BranchID != jobScope.leafID { + t.Errorf("job.BranchID = %q, want %q", finished.BranchID, jobScope.leafID) } }