diff --git a/CLAUDE.md b/CLAUDE.md
index a514e84..1f3d17a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -22,6 +22,10 @@ IKE_DATA_FILE=$(mktemp -d)/t.json go run . list # run against a scratch data f
Dependency direction: `cli` → `tui`/`mcpserver` → `store` → `task`. **All business logic lives in `internal/store/ops.go`** (Add/Complete/Restore/Move/Reorder/Rename/Delete/SetQuadrantLabel/Undo/Redo/List/ListArchive); the three frontends must stay thin wrappers over it. `internal/task` is the zero-dependency domain (Task struct, Quadrant 1–4 with default labels, and `Less`/`SortOrder`, the single definition of display order).
+**Every mutating op returns the post-mutation `Data` alongside its own result** — `Add` is `(task.Task, Data, error)`, `Undo` is `(string, Data, error)`. `Mutate` already produces that value, so handing it back costs nothing and spares the caller a second read. Frontends must render the outcome from it (`d.Labels.Of(q)`, `d.List(q)`) rather than calling `Load`/`QuadrantLabels` again: a follow-up read observes a *later* file state, and the helpers that used to do it (`cli.quadrantLabels`, `mcpserver.labelsOf`) both swallowed the error to stay "cosmetic". `SetMCPEnabled` is the deliberate exception — nothing renders from it.
+
+Listing order has exactly one definition each, as pure methods on `Data`: **`d.List(q)`** (active tasks, quadrant then rank then ID) and **`d.ListArchive()`** (newest completion first, unstamped tasks by ID). `Store.List`/`Store.ListArchive` are `Load` plus these; the TUI calls them directly on the data it already holds. The TUI used to reverse `data.Archive` instead, which agrees with `ListArchive` only while every archived task carries a `done_at`. `ListArchive` must keep returning a non-nil empty slice — `ike archive --json` emits `[]`, not `null`.
+
Quadrant headings are user-customizable. `task.Quadrant.Label()` gives the **default** name; `store.Data.Labels` (a sparse `map[Quadrant]string`, only renamed quadrants present) holds overrides, and **`Labels.Of(q)` is the only correct way to render a quadrant name** — it is nil-safe, so `d.Labels.Of(q)` works on a store that has never been renamed. Never print `q.Label()` in a frontend. Clearing a label deletes the map entry rather than storing `""`, so later changes to the defaults still reach users who reset. The quadrant *number* is the stable identifier for classification and scripting; only the display name varies.
Concurrency contract (`internal/store/store.go`): every mutation goes through `Store.Mutate`, which flocks a **sidecar** `tasks.json.lock` (locking the data file itself would break — atomic rename replaces the inode), re-reads fresh inside the lock, applies the change, and writes via temp-file + `os.Rename`. Never write the data file any other way. Completing a task moves it from `tasks` to `archive` with `DoneAt` stamped (`Restore` reverses that); IDs are monotonic via `next_id` and never reused. Deleting skips the archive.
@@ -41,7 +45,13 @@ Undo/redo is snapshot-based, with two stacks in the data file (each capped at `u
Data file version is **2** (ranks + history stacks). `readFile` accepts version 1 and upgrades in memory; the next write persists version 2. A newer version than `currentVersion` is still a hard error. The `redo` field was added within version 2 as `omitempty` rather than bumping again — losing redo history to an older binary is harmless, whereas a bump makes older binaries refuse the file outright.
-The TUI (`internal/tui`) is a single `Model` with a mode enum (normal/input/move/archive); `model.go` holds state + key handling, `view.go` all rendering. It re-renders from `Mutate` results and polls file mtime every 2s to pick up CLI/MCP writes. `archCursor` indexes `archiveList()` (newest first), *not* `data.Archive` — use the helper when acting on the selected archive row.
+The TUI (`internal/tui`) is a single `Model` with a mode enum (normal/input/move/archive); `model.go` holds state + key handling, `view.go` all rendering. It re-renders from the `Data` each op returns and polls file mtime every 2s to pick up CLI/MCP writes. `archCursor` indexes `data.ListArchive()` (newest first), *not* `data.Archive` — use the helper when acting on the selected archive row.
+
+Every mutation goes through **`m.apply(d, err) bool`**, which either shows the error or re-renders, and *returns whether it succeeded*. Set a success status only inside `if m.apply(...)`. Signalling failure through `m.status` and sniffing it afterwards is what let a failed complete/delete/move print "done: …" over its own error while the row stayed on screen (`TestFailedMutationsDoNotReportSuccess`). Enter and leave input mode only via **`enterInput`/`exitInput`**, which set and clear all of `mode`/`editingID`/`labelTarget`/value/placeholder together — setting them field-by-field leaked the quadrant-rename placeholder into the next task edit.
+
+The CLI is **constructed, not registered**: `NewRootCmd(open)` builds the whole tree and every command has a `newXCmd(open) *cobra.Command` constructor, where `open` yields the store (lazily, inside `RunE`, so `ike --help` still works with a broken `IKE_DATA_FILE`). Command bodies wrap in `withStore` and print to `cmd.OutOrStdout()`. Do not go back to `init()` plus a package-level `rootCmd`: that made flag variables process-global and left every `RunE` untestable — `internal/cli` sat at 18.9% coverage with `ike mcp enable|disable` at 0%, i.e. the consent toggle was tested everywhere except where users invoke it. Tests build a tree over a scratch file with `runCLI`.
+
+Store tests are split by concern: `ops_test.go` (tasks, ordering, ranks), `history_test.go` (undo/redo), `labels_test.go`, `mcp_test.go` (the gate), `store_test.go` + `durability_test.go` (the write path). Keep new tests in the matching file rather than growing one past ~1000 lines.
## Gotchas
diff --git a/internal/cli/commands.go b/internal/cli/commands.go
index 88a4f0a..353250e 100644
--- a/internal/cli/commands.go
+++ b/internal/cli/commands.go
@@ -3,7 +3,7 @@ package cli
import (
"encoding/json"
"fmt"
- "os"
+ "io"
"strconv"
"github.com/spf13/cobra"
@@ -20,24 +20,21 @@ func parseID(s string) (int, error) {
return id, nil
}
-func printJSON(v any) error {
- enc := json.NewEncoder(os.Stdout)
- enc.SetIndent("", " ")
- return enc.Encode(v)
-}
-
-// quadrantLabels resolves the display names of the four quadrants. On a read
-// error it returns nil, which still resolves to the built-in defaults — a
-// label lookup should never be the thing that fails a command.
-func quadrantLabels(s *store.Store) store.Labels {
- l, err := s.QuadrantLabels()
+func parseQuadrant(s string) (task.Quadrant, error) {
+ q, err := strconv.Atoi(s)
if err != nil {
- return nil
+ return 0, fmt.Errorf("invalid quadrant %q", s)
}
- return l
+ return task.Quadrant(q), nil
+}
+
+func printJSON(w io.Writer, v any) error {
+ enc := json.NewEncoder(w)
+ enc.SetIndent("", " ")
+ return enc.Encode(v)
}
-func printGrouped(tasks []task.Task, labels store.Labels) {
+func printGrouped(w io.Writer, tasks []task.Task, labels store.Labels) {
byQ := map[task.Quadrant][]task.Task{}
for _, t := range tasks {
byQ[t.Quadrant] = append(byQ[t.Quadrant], t)
@@ -46,162 +43,157 @@ func printGrouped(tasks []task.Task, labels store.Labels) {
if len(byQ[q]) == 0 {
continue
}
- fmt.Printf("%d · %s\n", q, labels.Of(q))
+ fmt.Fprintf(w, "%d · %s\n", q, labels.Of(q))
for _, t := range byQ[q] {
- fmt.Printf(" %3d %s\n", t.ID, t.DisplayTitle())
+ fmt.Fprintf(w, " %3d %s\n", t.ID, t.DisplayTitle())
}
}
}
-func init() {
- var addQuadrant int
- addCmd := &cobra.Command{
+func newAddCmd(open opener) *cobra.Command {
+ var quadrant int
+ cmd := &cobra.Command{
Use: "add
",
Short: "Add a task",
Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- s, err := openStore()
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
+ t, d, err := s.Add(args[0], task.Quadrant(quadrant))
if err != nil {
return err
}
- t, err := s.Add(args[0], task.Quadrant(addQuadrant))
- if err != nil {
- return err
- }
- fmt.Printf("added %d [%s] %s\n", t.ID, quadrantLabels(s).Of(t.Quadrant), t.DisplayTitle())
+ fmt.Fprintf(cmd.OutOrStdout(), "added %d [%s] %s\n",
+ t.ID, d.Labels.Of(t.Quadrant), t.DisplayTitle())
return nil
- },
+ }),
}
- addCmd.Flags().IntVarP(&addQuadrant, "quadrant", "q", 2,
+ cmd.Flags().IntVarP(&quadrant, "quadrant", "q", 2,
"quadrant: 1=urgent+important, 2=important, 3=urgent, 4=neither")
+ return cmd
+}
- var listQuadrant int
- var listJSON bool
- listCmd := &cobra.Command{
+func newListCmd(open opener) *cobra.Command {
+ var quadrant int
+ var asJSON bool
+ cmd := &cobra.Command{
Use: "list",
Short: "List active tasks",
Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, args []string) error {
- s, err := openStore()
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
+ d, err := s.Load()
if err != nil {
return err
}
- tasks, err := s.List(task.Quadrant(listQuadrant))
- if err != nil {
- return err
- }
- if listJSON {
- return printJSON(tasks)
+ tasks := d.List(task.Quadrant(quadrant))
+ out := cmd.OutOrStdout()
+ if asJSON {
+ return printJSON(out, tasks)
}
if len(tasks) == 0 {
- fmt.Println("no active tasks")
+ fmt.Fprintln(out, "no active tasks")
return nil
}
- printGrouped(tasks, quadrantLabels(s))
+ printGrouped(out, tasks, d.QuadrantLabels())
return nil
- },
+ }),
}
- listCmd.Flags().IntVarP(&listQuadrant, "quadrant", "q", 0, "filter to quadrant 1-4 (0 = all)")
- listCmd.Flags().BoolVar(&listJSON, "json", false, "output JSON")
+ cmd.Flags().IntVarP(&quadrant, "quadrant", "q", 0, "filter to quadrant 1-4 (0 = all)")
+ cmd.Flags().BoolVar(&asJSON, "json", false, "output JSON")
+ return cmd
+}
- doneCmd := &cobra.Command{
+func newDoneCmd(open opener) *cobra.Command {
+ return &cobra.Command{
Use: "done ",
Short: "Complete a task (moves it to the archive)",
Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
id, err := parseID(args[0])
if err != nil {
return err
}
- s, err := openStore()
+ t, _, err := s.Complete(id)
if err != nil {
return err
}
- t, err := s.Complete(id)
- if err != nil {
- return err
- }
- fmt.Printf("done %d %s\n", t.ID, t.DisplayTitle())
+ fmt.Fprintf(cmd.OutOrStdout(), "done %d %s\n", t.ID, t.DisplayTitle())
return nil
- },
+ }),
}
+}
- mvCmd := &cobra.Command{
+func newMvCmd(open opener) *cobra.Command {
+ return &cobra.Command{
Use: "mv ",
Short: "Move a task to another quadrant",
Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
id, err := parseID(args[0])
if err != nil {
return err
}
- q, err := strconv.Atoi(args[1])
- if err != nil {
- return fmt.Errorf("invalid quadrant %q", args[1])
- }
- s, err := openStore()
+ q, err := parseQuadrant(args[1])
if err != nil {
return err
}
- t, err := s.Move(id, task.Quadrant(q))
+ t, d, err := s.Move(id, q)
if err != nil {
return err
}
- fmt.Printf("moved %d to %d · %s\n", t.ID, q, quadrantLabels(s).Of(t.Quadrant))
+ fmt.Fprintf(cmd.OutOrStdout(), "moved %d to %d · %s\n",
+ t.ID, t.Quadrant, d.Labels.Of(t.Quadrant))
return nil
- },
+ }),
}
+}
- rmCmd := &cobra.Command{
+func newRmCmd(open opener) *cobra.Command {
+ return &cobra.Command{
Use: "rm ",
Short: "Delete a task permanently (does not archive)",
Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
id, err := parseID(args[0])
if err != nil {
return err
}
- s, err := openStore()
- if err != nil {
- return err
- }
- t, err := s.Delete(id)
+ t, _, err := s.Delete(id)
if err != nil {
return err
}
- fmt.Printf("deleted %d %s\n", t.ID, t.DisplayTitle())
+ fmt.Fprintf(cmd.OutOrStdout(), "deleted %d %s\n", t.ID, t.DisplayTitle())
return nil
- },
+ }),
}
+}
- restoreCmd := &cobra.Command{
+func newRestoreCmd(open opener) *cobra.Command {
+ return &cobra.Command{
Use: "restore ",
Short: "Un-archive a completed task, putting it back in its quadrant",
Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
id, err := parseID(args[0])
if err != nil {
return err
}
- s, err := openStore()
- if err != nil {
- return err
- }
- t, err := s.Restore(id)
+ t, d, err := s.Restore(id)
if err != nil {
return err
}
- fmt.Printf("restored %d to %d · %s %s\n", t.ID, t.Quadrant, quadrantLabels(s).Of(t.Quadrant), t.DisplayTitle())
+ fmt.Fprintf(cmd.OutOrStdout(), "restored %d to %d · %s %s\n",
+ t.ID, t.Quadrant, d.Labels.Of(t.Quadrant), t.DisplayTitle())
return nil
- },
+ }),
}
+}
- reorderCmd := &cobra.Command{
+func newReorderCmd(open opener) *cobra.Command {
+ return &cobra.Command{
Use: "reorder ",
Short: "Move a task up or down within its quadrant",
Args: cobra.ExactArgs(2),
ValidArgs: []string{"up", "down", "top", "bottom"},
- RunE: func(cmd *cobra.Command, args []string) error {
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
id, err := parseID(args[0])
if err != nil {
return err
@@ -220,145 +212,132 @@ func init() {
default:
return fmt.Errorf("invalid direction %q: want up, down, top, or bottom", args[1])
}
- s, err := openStore()
- if err != nil {
- return err
- }
- t, err := s.Reorder(id, delta)
+ t, d, err := s.Reorder(id, delta)
if err != nil {
return err
}
- fmt.Printf("moved %d %s %d · %s\n", t.ID, where, t.Quadrant, quadrantLabels(s).Of(t.Quadrant))
+ fmt.Fprintf(cmd.OutOrStdout(), "moved %d %s %d · %s\n",
+ t.ID, where, t.Quadrant, d.Labels.Of(t.Quadrant))
return nil
- },
+ }),
}
+}
- undoCmd := &cobra.Command{
+func newUndoCmd(open opener) *cobra.Command {
+ return &cobra.Command{
Use: "undo",
Short: "Undo the last change made from any frontend (TUI, CLI, or MCP)",
Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, args []string) error {
- s, err := openStore()
- if err != nil {
- return err
- }
- label, err := s.Undo()
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
+ label, _, err := s.Undo()
if err != nil {
return err
}
- fmt.Printf("undid %s\n", label)
+ fmt.Fprintf(cmd.OutOrStdout(), "undid %s\n", label)
return nil
- },
+ }),
}
+}
- redoCmd := &cobra.Command{
+func newRedoCmd(open opener) *cobra.Command {
+ return &cobra.Command{
Use: "redo",
Short: "Re-apply the last undone change (until the next change discards it)",
Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, args []string) error {
- s, err := openStore()
- if err != nil {
- return err
- }
- label, err := s.Redo()
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
+ label, _, err := s.Redo()
if err != nil {
return err
}
- fmt.Printf("redid %s\n", label)
+ fmt.Fprintf(cmd.OutOrStdout(), "redid %s\n", label)
return nil
- },
+ }),
}
+}
- var labelReset bool
- labelCmd := &cobra.Command{
+func newLabelCmd(open opener) *cobra.Command {
+ var reset bool
+ cmd := &cobra.Command{
Use: "label [quadrant] [name]",
Short: "Show or change the quadrant headings",
Long: "With no arguments, print the four quadrant headings.\n" +
"With a quadrant and a name, rename that quadrant.\n" +
"Pass --reset (or an empty name) to restore the built-in default.",
Args: cobra.MaximumNArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- s, err := openStore()
- if err != nil {
- return err
- }
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
if len(args) == 0 {
- if labelReset {
- return fmt.Errorf("--reset needs a quadrant: ike label <1-4> --reset")
- }
- labels, err := s.QuadrantLabels()
- if err != nil {
- return err
- }
- for q := task.Do; q <= task.Eliminate; q++ {
- marker := ""
- if labels.IsCustom(q) {
- marker = fmt.Sprintf(" (default: %s)", q.Label())
- }
- fmt.Printf("%d · %s%s\n", q, labels.Of(q), marker)
- }
- return nil
+ return printLabels(cmd, s, reset)
}
-
- q, err := strconv.Atoi(args[0])
+ q, err := parseQuadrant(args[0])
if err != nil {
- return fmt.Errorf("invalid quadrant %q", args[0])
+ return err
}
name := ""
if len(args) == 2 {
name = args[1]
}
- if labelReset {
- if name != "" {
- return fmt.Errorf("pass a name or --reset, not both")
- }
- } else if len(args) < 2 {
+ if reset && name != "" {
+ return fmt.Errorf("pass a name or --reset, not both")
+ }
+ if !reset && len(args) < 2 {
return fmt.Errorf("give a name to set, or --reset to restore the default")
}
-
- result, err := s.SetQuadrantLabel(task.Quadrant(q), name)
+ result, _, err := s.SetQuadrantLabel(q, name)
if err != nil {
return err
}
- fmt.Printf("quadrant %d is now %s\n", q, result)
+ fmt.Fprintf(cmd.OutOrStdout(), "quadrant %d is now %s\n", q, result)
return nil
- },
+ }),
+ }
+ cmd.Flags().BoolVar(&reset, "reset", false, "restore the built-in default name")
+ return cmd
+}
+
+// printLabels handles `ike label` with no arguments.
+func printLabels(cmd *cobra.Command, s *store.Store, reset bool) error {
+ if reset {
+ return fmt.Errorf("--reset needs a quadrant: ike label <1-4> --reset")
+ }
+ labels, err := s.QuadrantLabels()
+ if err != nil {
+ return err
}
- labelCmd.Flags().BoolVar(&labelReset, "reset", false, "restore the built-in default name")
+ for q := task.Do; q <= task.Eliminate; q++ {
+ marker := ""
+ if labels.IsCustom(q) {
+ marker = fmt.Sprintf(" (default: %s)", q.Label())
+ }
+ fmt.Fprintf(cmd.OutOrStdout(), "%d · %s%s\n", q, labels.Of(q), marker)
+ }
+ return nil
+}
- var archiveJSON bool
- archiveCmd := &cobra.Command{
+func newArchiveCmd(open opener) *cobra.Command {
+ var asJSON bool
+ cmd := &cobra.Command{
Use: "archive",
Short: "List completed tasks, newest first",
Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, args []string) error {
- s, err := openStore()
- if err != nil {
- return err
- }
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
arch, err := s.ListArchive()
if err != nil {
return err
}
- if archiveJSON {
- return printJSON(arch)
+ out := cmd.OutOrStdout()
+ if asJSON {
+ return printJSON(out, arch)
}
if len(arch) == 0 {
- fmt.Println("archive is empty")
+ fmt.Fprintln(out, "archive is empty")
return nil
}
for _, t := range arch {
- when := ""
- if t.DoneAt != nil {
- when = t.DoneAt.Local().Format("2006-01-02")
- }
- fmt.Printf(" %3d %s %s\n", t.ID, when, t.DisplayTitle())
+ fmt.Fprintln(out, t.ArchiveRow(t.DisplayTitle()))
}
return nil
- },
+ }),
}
- archiveCmd.Flags().BoolVar(&archiveJSON, "json", false, "output JSON")
-
- rootCmd.AddCommand(addCmd, listCmd, doneCmd, mvCmd, rmCmd, archiveCmd,
- restoreCmd, reorderCmd, undoCmd, redoCmd, labelCmd)
+ cmd.Flags().BoolVar(&asJSON, "json", false, "output JSON")
+ return cmd
}
diff --git a/internal/cli/commands_test.go b/internal/cli/commands_test.go
index bb87f2e..3f076de 100644
--- a/internal/cli/commands_test.go
+++ b/internal/cli/commands_test.go
@@ -2,7 +2,6 @@ package cli
import (
"bytes"
- "io"
"os"
"path/filepath"
"strings"
@@ -13,33 +12,33 @@ import (
"github.com/jonascript/ike/internal/task"
)
-// captureStdout runs fn with os.Stdout redirected and returns what it wrote.
-// The print helpers write to os.Stdout directly, which is what `ike list`
-// actually does, so this tests the real output path rather than a stand-in.
-func captureStdout(t *testing.T, fn func()) string {
+// scratch returns a data file path in a fresh temp directory. Nothing here ever
+// touches the real matrix.
+func scratch(t *testing.T) string {
t.Helper()
- r, w, err := os.Pipe()
- if err != nil {
- t.Fatal(err)
- }
- orig := os.Stdout
- os.Stdout = w
- defer func() { os.Stdout = orig }()
+ return filepath.Join(t.TempDir(), "tasks.json")
+}
- done := make(chan string, 1)
- go func() {
- var buf bytes.Buffer
- _, _ = io.Copy(&buf, r)
- done <- buf.String()
- }()
+// runCLI builds the command tree over path and runs it, returning what the
+// command printed. Each call constructs a fresh tree, so flag values cannot
+// leak between invocations the way package-level flag variables did.
+func runCLI(t *testing.T, path string, args ...string) (string, error) {
+ t.Helper()
+ root := NewRootCmd(func() (*store.Store, error) { return store.OpenAt(path), nil })
+ var out, errOut bytes.Buffer
+ root.SetOut(&out)
+ root.SetErr(&errOut)
+ root.SetArgs(args)
+ err := root.Execute()
+ return out.String(), err
+}
- fn()
- if err := w.Close(); err != nil {
- t.Fatal(err)
- }
- out := <-done
- if err := r.Close(); err != nil {
- t.Fatal(err)
+// mustRunCLI runs a command that is expected to succeed.
+func mustRunCLI(t *testing.T, path string, args ...string) string {
+ t.Helper()
+ out, err := runCLI(t, path, args...)
+ if err != nil {
+ t.Fatalf("ike %s: %v", strings.Join(args, " "), err)
}
return out
}
@@ -58,7 +57,6 @@ func TestParseID(t *testing.T) {
{"abc", 0, true},
{"1.5", 0, true},
{"3x", 0, true},
- {" 4", 0, true},
}
for _, c := range cases {
got, err := parseID(c.in)
@@ -69,10 +67,6 @@ func TestParseID(t *testing.T) {
if err == nil && got != c.want {
t.Errorf("parseID(%q) = %d, want %d", c.in, got, c.want)
}
- // The message has to quote the offending input to be useful.
- if err != nil && !strings.Contains(err.Error(), c.in) {
- t.Errorf("parseID(%q) error %q should name the bad input", c.in, err)
- }
}
}
@@ -83,7 +77,8 @@ func TestPrintGrouped(t *testing.T) {
{ID: 2, Title: "hand off", Quadrant: task.Delegate},
{ID: 3, Title: "drop this", Quadrant: task.Eliminate},
}
- got := captureStdout(t, func() { printGrouped(tasks, nil) })
+ var buf bytes.Buffer
+ printGrouped(&buf, tasks, nil)
want := "1 · Do It First\n" +
" 1 ship it\n" +
@@ -93,7 +88,7 @@ func TestPrintGrouped(t *testing.T) {
" 2 hand off\n" +
"4 · Consider Eliminating It\n" +
" 3 drop this\n"
- if got != want {
+ if got := buf.String(); got != want {
t.Errorf("printGrouped output:\n%q\nwant:\n%q", got, want)
}
}
@@ -104,10 +99,11 @@ func TestPrintGroupedSkipsEmptyAndUsesCustomLabels(t *testing.T) {
tasks := []task.Task{{ID: 5, Title: "only one", Quadrant: task.Delegate}}
labels := store.Labels{task.Delegate: "Pass Along"}
- got := captureStdout(t, func() { printGrouped(tasks, labels) })
+ var buf bytes.Buffer
+ printGrouped(&buf, tasks, labels)
want := "3 · Pass Along\n 5 only one\n"
- if got != want {
+ if got := buf.String(); got != want {
t.Errorf("printGrouped output:\n%q\nwant:\n%q", got, want)
}
}
@@ -123,7 +119,9 @@ func TestPrintGroupedNeutralizesEscapeSequences(t *testing.T) {
tasks := []task.Task{{ID: 1, Title: overwrite, Quadrant: task.Do}}
labels := store.Labels{task.Do: "head\x1b[31mer"}
- got := captureStdout(t, func() { printGrouped(tasks, labels) })
+ var buf bytes.Buffer
+ printGrouped(&buf, tasks, labels)
+ got := buf.String()
if strings.ContainsRune(got, 0x1b) {
t.Errorf("output still contains an escape: %q", got)
@@ -152,11 +150,11 @@ func TestPrintJSONKeepsRawTitleEscaped(t *testing.T) {
Quadrant: task.Do,
CreatedAt: time.Unix(0, 0).UTC(),
}}
- got := captureStdout(t, func() {
- if err := printJSON(tasks); err != nil {
- t.Error(err)
- }
- })
+ var buf bytes.Buffer
+ if err := printJSON(&buf, tasks); err != nil {
+ t.Fatal(err)
+ }
+ got := buf.String()
if strings.ContainsRune(got, 0x1b) {
t.Errorf("JSON output should escape the control byte, not emit it: %q", got)
@@ -169,20 +167,294 @@ func TestPrintJSONKeepsRawTitleEscaped(t *testing.T) {
}
}
-// quadrantLabels must never be the reason a command fails: a broken data file
-// should surface from the operation itself, not from resolving a heading.
-func TestQuadrantLabelsFallsBackOnReadError(t *testing.T) {
- path := filepath.Join(t.TempDir(), "tasks.json")
- if err := os.WriteFile(path, []byte("{ not json"), 0o600); err != nil {
+func TestAddAndList(t *testing.T) {
+ p := scratch(t)
+
+ out := mustRunCLI(t, p, "add", "ship v2", "-q", "1")
+ if !strings.Contains(out, "added 1 [Do It First] ship v2") {
+ t.Errorf("add output = %q", out)
+ }
+
+ out = mustRunCLI(t, p, "list")
+ if !strings.Contains(out, "1 · Do It First") || !strings.Contains(out, "ship v2") {
+ t.Errorf("list output = %q", out)
+ }
+}
+
+// The quadrant flag defaults to 2, and a fresh tree per invocation means the
+// value from an earlier `-q 1` cannot bleed into a later call.
+func TestAddQuadrantFlagDoesNotLeakBetweenRuns(t *testing.T) {
+ p := scratch(t)
+ mustRunCLI(t, p, "add", "urgent thing", "-q", "1")
+ mustRunCLI(t, p, "add", "later thing")
+
+ out := mustRunCLI(t, p, "list", "-q", "2")
+ if !strings.Contains(out, "later thing") {
+ t.Errorf("second add should have defaulted to quadrant 2: %q", out)
+ }
+ if strings.Contains(out, "urgent thing") {
+ t.Errorf("quadrant 2 listing should not contain the quadrant 1 task: %q", out)
+ }
+}
+
+// The label a command prints comes from the data its own mutation produced.
+func TestAddPrintsCustomQuadrantLabel(t *testing.T) {
+ p := scratch(t)
+ mustRunCLI(t, p, "label", "1", "Firefighting")
+
+ out := mustRunCLI(t, p, "add", "page duty", "-q", "1")
+ if !strings.Contains(out, "[Firefighting]") {
+ t.Errorf("add should print the custom label: %q", out)
+ }
+}
+
+func TestDoneMovesToArchive(t *testing.T) {
+ p := scratch(t)
+ mustRunCLI(t, p, "add", "ship v2", "-q", "1")
+ mustRunCLI(t, p, "done", "1")
+
+ if out := mustRunCLI(t, p, "list"); !strings.Contains(out, "no active tasks") {
+ t.Errorf("task should have left the active list: %q", out)
+ }
+ if out := mustRunCLI(t, p, "archive"); !strings.Contains(out, "ship v2") {
+ t.Errorf("task should be in the archive: %q", out)
+ }
+}
+
+func TestUndoRedoRoundTrip(t *testing.T) {
+ p := scratch(t)
+ mustRunCLI(t, p, "add", "ship v2", "-q", "1")
+
+ if out := mustRunCLI(t, p, "undo"); !strings.Contains(out, `undid add "ship v2"`) {
+ t.Errorf("undo output = %q", out)
+ }
+ if out := mustRunCLI(t, p, "list"); !strings.Contains(out, "no active tasks") {
+ t.Errorf("undo should have removed the task: %q", out)
+ }
+ if out := mustRunCLI(t, p, "redo"); !strings.Contains(out, `redid add "ship v2"`) {
+ t.Errorf("redo output = %q", out)
+ }
+ if out := mustRunCLI(t, p, "list"); !strings.Contains(out, "ship v2") {
+ t.Errorf("redo should have restored the task: %q", out)
+ }
+}
+
+// An exhausted history stack is an error, not silent success.
+func TestUndoWithNothingToUndo(t *testing.T) {
+ if _, err := runCLI(t, scratch(t), "undo"); err == nil {
+ t.Error("undo on an empty history should fail")
+ }
+}
+
+func TestLabelArgumentValidation(t *testing.T) {
+ cases := []struct {
+ name string
+ args []string
+ want string
+ }{
+ {"reset with no quadrant", []string{"label", "--reset"}, "--reset needs a quadrant"},
+ {"name and reset together", []string{"label", "1", "Nope", "--reset"}, "not both"},
+ {"quadrant with no name", []string{"label", "1"}, "give a name to set"},
+ {"unparseable quadrant", []string{"label", "x", "Name"}, "invalid quadrant"},
+ {"out of range quadrant", []string{"label", "9", "Name"}, "quadrant must be 1-4"},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ _, err := runCLI(t, scratch(t), c.args...)
+ if err == nil {
+ t.Fatalf("ike %s should have failed", strings.Join(c.args, " "))
+ }
+ if !strings.Contains(err.Error(), c.want) {
+ t.Errorf("error = %q, want it to mention %q", err, c.want)
+ }
+ })
+ }
+}
+
+func TestLabelSetAndReset(t *testing.T) {
+ p := scratch(t)
+
+ if out := mustRunCLI(t, p, "label", "3", "Pass Along"); !strings.Contains(out, "quadrant 3 is now Pass Along") {
+ t.Errorf("label set output = %q", out)
+ }
+ out := mustRunCLI(t, p, "label")
+ if !strings.Contains(out, "3 · Pass Along") || !strings.Contains(out, "(default: Delegate It)") {
+ t.Errorf("label listing should mark the custom name: %q", out)
+ }
+
+ mustRunCLI(t, p, "label", "3", "--reset")
+ if out := mustRunCLI(t, p, "label"); strings.Contains(out, "Pass Along") {
+ t.Errorf("reset should have restored the default: %q", out)
+ }
+}
+
+func TestReorderRejectsUnknownDirection(t *testing.T) {
+ p := scratch(t)
+ mustRunCLI(t, p, "add", "ship v2", "-q", "1")
+
+ _, err := runCLI(t, p, "reorder", "1", "sideways")
+ if err == nil || !strings.Contains(err.Error(), "invalid direction") {
+ t.Errorf("error = %v, want an invalid-direction message", err)
+ }
+}
+
+// A data file that cannot be parsed must fail the command outright. Nothing
+// papers over it: the quadrant labels a command prints now come from the same
+// read as the operation, so there is no second, error-swallowing lookup.
+func TestUnreadableDataFileFailsTheCommand(t *testing.T) {
+ p := scratch(t)
+ if err := os.WriteFile(p, []byte("{ not json"), 0o600); err != nil {
t.Fatal(err)
}
+ for _, args := range [][]string{{"list"}, {"add", "x"}, {"label"}, {"archive"}} {
+ if _, err := runCLI(t, p, args...); err == nil {
+ t.Errorf("ike %s on an unparseable file should fail", strings.Join(args, " "))
+ }
+ }
+}
+
+// `ike mcp enable|disable|status` is how a user grants and revokes agent access
+// to their matrix. The store-level gate is covered in internal/store; this pins
+// the commands that drive it.
+func TestMCPEnableDisableStatus(t *testing.T) {
+ p := scratch(t)
+
+ out := mustRunCLI(t, p, "mcp", "status")
+ if !strings.Contains(out, "MCP access: off") {
+ t.Errorf("access must start off: %q", out)
+ }
+ if !strings.Contains(out, p) {
+ t.Errorf("status should name the data file it applies to: %q", out)
+ }
+
+ if out := mustRunCLI(t, p, "mcp", "enable"); !strings.Contains(out, "MCP access is now on") {
+ t.Errorf("enable output = %q", out)
+ }
+ if on, err := store.OpenAt(p).MCPEnabled(); err != nil || !on {
+ t.Errorf("enable should have persisted: on=%v err=%v", on, err)
+ }
+
+ // Re-running reports no change rather than claiming a fresh one.
+ if out := mustRunCLI(t, p, "mcp", "enable"); !strings.Contains(out, "was already on") {
+ t.Errorf("second enable output = %q", out)
+ }
+ if out := mustRunCLI(t, p, "mcp", "status"); !strings.Contains(out, "MCP access: on") {
+ t.Errorf("status after enable = %q", out)
+ }
+
+ if out := mustRunCLI(t, p, "mcp", "disable"); !strings.Contains(out, "MCP access is now off") {
+ t.Errorf("disable output = %q", out)
+ }
+ if on, err := store.OpenAt(p).MCPEnabled(); err != nil || on {
+ t.Errorf("disable should have persisted: on=%v err=%v", on, err)
+ }
+ if out := mustRunCLI(t, p, "mcp", "status"); !strings.Contains(out, "MCP access: off") {
+ t.Errorf("status after disable = %q", out)
+ }
+}
+
+// The server must refuse to start while access is off, and say how to turn it
+// on — the reader is looking at an MCP client's error log.
+func TestMCPServeRefusesWhileDisabled(t *testing.T) {
+ _, err := runCLI(t, scratch(t), "mcp")
+ if err == nil {
+ t.Fatal("ike mcp should refuse to serve while access is off")
+ }
+ if !strings.Contains(err.Error(), "ike mcp enable") {
+ t.Errorf("error should name the command that grants access: %q", err)
+ }
+}
+
+func TestMvRmRestore(t *testing.T) {
+ p := scratch(t)
+ mustRunCLI(t, p, "add", "ship v2", "-q", "1")
+ mustRunCLI(t, p, "add", "drop this", "-q", "1")
- if got := quadrantLabels(store.OpenAt(path)); got != nil {
- t.Errorf("quadrantLabels on an unreadable file = %v, want nil", got)
+ if out := mustRunCLI(t, p, "mv", "1", "3"); !strings.Contains(out, "moved 1 to 3 · Delegate It") {
+ t.Errorf("mv output = %q", out)
}
- // nil still resolves to the built-in defaults.
- var nilLabels store.Labels
- if got, want := nilLabels.Of(task.Do), task.Do.Label(); got != want {
- t.Errorf("nil Labels.Of(Do) = %q, want %q", got, want)
+ if out := mustRunCLI(t, p, "list", "-q", "3"); !strings.Contains(out, "ship v2") {
+ t.Errorf("task should have moved to quadrant 3: %q", out)
+ }
+
+ if out := mustRunCLI(t, p, "rm", "2"); !strings.Contains(out, "deleted 2 drop this") {
+ t.Errorf("rm output = %q", out)
+ }
+ // rm skips the archive entirely, unlike done.
+ if out := mustRunCLI(t, p, "archive"); !strings.Contains(out, "archive is empty") {
+ t.Errorf("rm must not archive: %q", out)
+ }
+
+ mustRunCLI(t, p, "done", "1")
+ if out := mustRunCLI(t, p, "restore", "1"); !strings.Contains(out, "restored 1 to 3 · Delegate It") {
+ t.Errorf("restore output = %q", out)
+ }
+ if out := mustRunCLI(t, p, "list"); !strings.Contains(out, "ship v2") {
+ t.Errorf("restored task should be active again: %q", out)
+ }
+}
+
+func TestMvRejectsBadArguments(t *testing.T) {
+ p := scratch(t)
+ mustRunCLI(t, p, "add", "ship v2", "-q", "1")
+
+ for _, c := range []struct{ args, want []string }{
+ {[]string{"mv", "x", "2"}, []string{"invalid task id"}},
+ {[]string{"mv", "1", "x"}, []string{"invalid quadrant"}},
+ {[]string{"mv", "1", "9"}, []string{"quadrant must be 1-4"}},
+ {[]string{"mv", "99", "2"}, []string{"no active task with id 99"}},
+ } {
+ _, err := runCLI(t, p, c.args...)
+ if err == nil {
+ t.Errorf("ike %s should have failed", strings.Join(c.args, " "))
+ continue
+ }
+ if !strings.Contains(err.Error(), c.want[0]) {
+ t.Errorf("ike %s error = %q, want it to mention %q",
+ strings.Join(c.args, " "), err, c.want[0])
+ }
+ }
+}
+
+func TestReorderDirections(t *testing.T) {
+ p := scratch(t)
+ for _, title := range []string{"first", "second", "third"} {
+ mustRunCLI(t, p, "add", title, "-q", "1")
+ }
+
+ order := func() string {
+ t.Helper()
+ return mustRunCLI(t, p, "list", "-q", "1")
+ }
+ indexOf := func(out, title string) int { return strings.Index(out, title) }
+
+ mustRunCLI(t, p, "reorder", "3", "top")
+ if out := order(); indexOf(out, "third") > indexOf(out, "first") {
+ t.Errorf("`top` should have moved third to the front: %q", out)
+ }
+ mustRunCLI(t, p, "reorder", "3", "bottom")
+ if out := order(); indexOf(out, "third") < indexOf(out, "first") {
+ t.Errorf("`bottom` should have moved third to the end: %q", out)
+ }
+ mustRunCLI(t, p, "reorder", "3", "up")
+ if out := order(); indexOf(out, "third") > indexOf(out, "second") {
+ t.Errorf("`up` should have moved third above second: %q", out)
+ }
+ if out := mustRunCLI(t, p, "reorder", "3", "down"); !strings.Contains(out, "down in 1 · Do It First") {
+ t.Errorf("reorder output = %q", out)
+ }
+}
+
+func TestArchiveJSONAndEmpty(t *testing.T) {
+ p := scratch(t)
+ if out := mustRunCLI(t, p, "archive", "--json"); !strings.Contains(out, "[]") {
+ t.Errorf("empty archive as JSON = %q", out)
+ }
+ mustRunCLI(t, p, "add", "ship v2", "-q", "1")
+ mustRunCLI(t, p, "done", "1")
+
+ out := mustRunCLI(t, p, "archive", "--json")
+ if !strings.Contains(out, `"title": "ship v2"`) || !strings.Contains(out, `"done_at"`) {
+ t.Errorf("archive JSON = %q", out)
}
}
diff --git a/internal/cli/mcp.go b/internal/cli/mcp.go
index 1bb1020..044d118 100644
--- a/internal/cli/mcp.go
+++ b/internal/cli/mcp.go
@@ -9,6 +9,7 @@ import (
"github.com/spf13/cobra"
"github.com/jonascript/ike/internal/mcpserver"
+ "github.com/jonascript/ike/internal/store"
)
// mcpDisabledMsg explains how to switch agent access on. It is worded for the
@@ -18,8 +19,8 @@ const mcpDisabledMsg = "MCP access is off for this matrix.\n" +
" ike mcp enable\n\n" +
"Run `ike mcp status` to see the current setting and which data file it applies to."
-func init() {
- mcpCmd := &cobra.Command{
+func newMCPCmd(open opener) *cobra.Command {
+ cmd := &cobra.Command{
Use: "mcp",
Short: "Serve MCP over stdio so AI agents can manage the matrix",
Long: "Runs an MCP (Model Context Protocol) server on stdin/stdout.\n\n" +
@@ -29,11 +30,7 @@ func init() {
" claude mcp add ike -- ike mcp\n\n" +
"The setting is remembered per data file, and `ike mcp disable` revokes it.",
Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, args []string) error {
- s, err := openStore()
- if err != nil {
- return err
- }
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
enabled, err := s.MCPEnabled()
if err != nil {
return err
@@ -50,9 +47,6 @@ func init() {
//nolint:staticcheck // ST1005: formatted for a human, not a caller.
return errors.New(mcpDisabledMsg)
}
- // stdout carries JSON-RPC; anything human-facing must go to stderr,
- // which cobra already uses for errors.
- //
// ForMCP re-checks the gate on every read and mutation, so
// `ike mcp disable` revokes this session even while it stays
// connected. The check above only covers startup.
@@ -64,72 +58,71 @@ func init() {
return nil
}
return err
- },
+ }),
}
+ cmd.AddCommand(newMCPSetCmd(open, true), newMCPSetCmd(open, false), newMCPStatusCmd(open))
+ return cmd
+}
- enableCmd := &cobra.Command{
- Use: "enable",
- Short: "Allow AI agents to read and manage this matrix over MCP",
- Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, args []string) error { return setMCP(true) },
+// newMCPSetCmd builds `ike mcp enable` or `ike mcp disable`. They differ only
+// in the value they write and the words they print, so they are one function:
+// two near-identical command bodies is how the two drift apart.
+func newMCPSetCmd(open opener, on bool) *cobra.Command {
+ use, short := "disable", "Revoke MCP access to this matrix"
+ if on {
+ use, short = "enable", "Allow AI agents to read and manage this matrix over MCP"
}
-
- disableCmd := &cobra.Command{
- Use: "disable",
- Short: "Revoke MCP access to this matrix",
+ return &cobra.Command{
+ Use: use,
+ Short: short,
Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, args []string) error { return setMCP(false) },
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
+ changed, err := s.SetMCPEnabled(on)
+ if err != nil {
+ return err
+ }
+ out := cmd.OutOrStdout()
+ if !changed {
+ fmt.Fprintf(out, "MCP access was already %s for %s\n", mcpState(on), s.Path())
+ return nil
+ }
+ fmt.Fprintf(out, "MCP access is now %s for %s\n", mcpState(on), s.Path())
+ if on {
+ fmt.Fprintln(out, "Register ike with a client if you have not already:\n\n claude mcp add ike -- ike mcp")
+ }
+ return nil
+ }),
}
+}
- statusCmd := &cobra.Command{
+// newMCPStatusCmd reports the setting. It deliberately uses the ungated store,
+// so it still answers after access has been revoked.
+func newMCPStatusCmd(open opener) *cobra.Command {
+ return &cobra.Command{
Use: "status",
Short: "Show whether MCP access is enabled, and for which data file",
Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, args []string) error {
- s, err := openStore()
- if err != nil {
- return err
- }
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
enabled, err := s.MCPEnabled()
if err != nil {
return err
}
- state, hint := "off", "ike mcp enable"
+ hint := "ike mcp enable"
if enabled {
- state, hint = "on", "ike mcp disable"
+ hint = "ike mcp disable"
}
- fmt.Printf("MCP access: %s\n", state)
- fmt.Printf("data file: %s\n", s.Path())
- fmt.Printf("change it: %s\n", hint)
+ out := cmd.OutOrStdout()
+ fmt.Fprintf(out, "MCP access: %s\n", mcpState(enabled))
+ fmt.Fprintf(out, "data file: %s\n", s.Path())
+ fmt.Fprintf(out, "change it: %s\n", hint)
return nil
- },
+ }),
}
-
- mcpCmd.AddCommand(enableCmd, disableCmd, statusCmd)
- rootCmd.AddCommand(mcpCmd)
}
-// setMCP flips the MCP permission and reports what happened.
-func setMCP(on bool) error {
- s, err := openStore()
- if err != nil {
- return err
- }
- changed, err := s.SetMCPEnabled(on)
- if err != nil {
- return err
- }
- state := "off"
- if on {
- state = "on"
- }
- if !changed {
- fmt.Printf("MCP access was already %s for %s\n", state, s.Path())
- return nil
- }
- fmt.Printf("MCP access is now %s for %s\n", state, s.Path())
+func mcpState(on bool) string {
if on {
- fmt.Println("Register ike with a client if you have not already:\n\n claude mcp add ike -- ike mcp")
+ return "on"
}
- return nil
+ return "off"
}
diff --git a/internal/cli/root.go b/internal/cli/root.go
index c39986c..69bea0d 100644
--- a/internal/cli/root.go
+++ b/internal/cli/root.go
@@ -14,28 +14,60 @@ import (
// version is stamped at build time via -ldflags "-X ...cli.version=...".
var version = "dev"
-var rootCmd = &cobra.Command{
- Use: "ike",
- Short: "ike — an Eisenhower matrix task manager",
- Long: "ike is a terminal Eisenhower matrix: run it bare for the interactive TUI,\nor use subcommands for quick capture and scripting.",
- Version: version,
- SilenceUsage: true,
- RunE: func(cmd *cobra.Command, args []string) error {
- s, err := openStore()
+// opener yields the store a command should act on. It is a parameter rather
+// than a direct call to store.Open so tests can build the command tree over a
+// scratch data file; that is the whole reason the commands are constructed
+// instead of registered from init().
+//
+// It stays lazy — resolved inside RunE, not when the tree is built — so `ike
+// --help` still works when IKE_DATA_FILE is set to something invalid.
+type opener func() (*store.Store, error)
+
+// withStore adapts a command body that needs a store into a cobra RunE, so the
+// bodies start at the part that differs instead of repeating the same three
+// lines of open-and-check.
+func withStore(open opener, run func(*cobra.Command, []string, *store.Store) error) func(*cobra.Command, []string) error {
+ return func(cmd *cobra.Command, args []string) error {
+ s, err := open()
if err != nil {
return err
}
- return tui.Run(s)
- },
+ return run(cmd, args, s)
+ }
}
-func openStore() (*store.Store, error) {
- return store.Open()
+// NewRootCmd builds the whole command tree against open.
+func NewRootCmd(open opener) *cobra.Command {
+ root := &cobra.Command{
+ Use: "ike",
+ Short: "ike — an Eisenhower matrix task manager",
+ Long: "ike is a terminal Eisenhower matrix: run it bare for the interactive TUI,\nor use subcommands for quick capture and scripting.",
+ Version: version,
+ SilenceUsage: true,
+ RunE: withStore(open, func(cmd *cobra.Command, args []string, s *store.Store) error {
+ return tui.Run(s)
+ }),
+ }
+ root.AddCommand(
+ newAddCmd(open),
+ newListCmd(open),
+ newDoneCmd(open),
+ newMvCmd(open),
+ newRmCmd(open),
+ newRestoreCmd(open),
+ newReorderCmd(open),
+ newUndoCmd(open),
+ newRedoCmd(open),
+ newLabelCmd(open),
+ newArchiveCmd(open),
+ newMCPCmd(open),
+ )
+ return root
}
// Execute runs the CLI and exits non-zero on error.
func Execute() {
- if err := rootCmd.Execute(); err != nil {
+ if err := NewRootCmd(store.Open).Execute(); err != nil {
os.Exit(1)
}
}
diff --git a/internal/mcpserver/server.go b/internal/mcpserver/server.go
index 7bb723c..e4b140a 100644
--- a/internal/mcpserver/server.go
+++ b/internal/mcpserver/server.go
@@ -5,6 +5,7 @@ package mcpserver
import (
"context"
"fmt"
+ "time"
"github.com/modelcontextprotocol/go-sdk/mcp"
@@ -25,16 +26,20 @@ type taskOut struct {
Done string `json:"done_at,omitempty" jsonschema:"completion time, only set for archived tasks"`
}
+// Title is deliberately the raw stored title, not DisplayTitle: this output is
+// JSON, and encoding/json escapes control characters itself. Label goes through
+// Labels.Of, which sanitizes — that is the store's render choke point, not a
+// policy chosen here.
func toOut(t task.Task, labels store.Labels) taskOut {
o := taskOut{
ID: t.ID,
Title: t.Title,
Quadrant: int(t.Quadrant),
Label: labels.Of(t.Quadrant),
- Created: t.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
+ Created: t.CreatedAt.Format(time.RFC3339),
}
if t.DoneAt != nil {
- o.Done = t.DoneAt.Format("2006-01-02T15:04:05Z07:00")
+ o.Done = t.DoneAt.Format(time.RFC3339)
}
return o
}
@@ -47,17 +52,6 @@ func toOuts(ts []task.Task, labels store.Labels) []taskOut {
return out
}
-// labelsOf resolves the quadrant headings for tool output. A read failure
-// falls back to the defaults rather than failing the tool call, since the
-// labels are cosmetic.
-func labelsOf(s *store.Store) store.Labels {
- l, err := s.QuadrantLabels()
- if err != nil {
- return nil
- }
- return l
-}
-
type listIn struct {
Quadrant int `json:"quadrant,omitempty" jsonschema:"optional filter, 1-4; omit or 0 for all quadrants"`
}
@@ -126,107 +120,99 @@ func directionDelta(dir string) (int, error) {
return 0, fmt.Errorf("invalid direction %q: want up, down, top, or bottom", dir)
}
+// taskTool registers a tool whose result is a single task. Eight of ike's
+// thirteen tools have that shape and had the same five lines of error plumbing
+// copied into each; op is the only part that differed.
+//
+// The store operation returns the post-mutation data alongside the task, so the
+// quadrant label rendered here comes from the state the change produced — not
+// from a second read that could observe a later one.
+func taskTool[In any](srv *mcp.Server, spec *mcp.Tool, op func(In) (task.Task, store.Data, error)) {
+ mcp.AddTool(srv, spec, func(ctx context.Context, req *mcp.CallToolRequest, in In) (*mcp.CallToolResult, taskOut, error) {
+ t, d, err := op(in)
+ if err != nil {
+ return nil, taskOut{}, err
+ }
+ return nil, toOut(t, d.Labels), nil
+ })
+}
+
+// listTool registers a tool that returns a list of tasks drawn from one read of
+// the store, so the tasks and the labels describing them agree.
+func listTool[In any](srv *mcp.Server, s *store.Store, spec *mcp.Tool, sel func(store.Data, In) []task.Task) {
+ mcp.AddTool(srv, spec, func(ctx context.Context, req *mcp.CallToolRequest, in In) (*mcp.CallToolResult, tasksOut, error) {
+ d, err := s.Load()
+ if err != nil {
+ return nil, tasksOut{}, err
+ }
+ return nil, tasksOut{Tasks: toOuts(sel(d, in), d.Labels)}, nil
+ })
+}
+
// NewServer builds the MCP server around s. version is the ike build version.
func NewServer(s *store.Store, version string) *mcp.Server {
srv := mcp.NewServer(&mcp.Implementation{Name: "ike", Version: version}, nil)
- mcp.AddTool(srv, &mcp.Tool{
+ listTool(srv, s, &mcp.Tool{
Name: "list_tasks",
Description: "List active tasks in the Eisenhower matrix, ordered by quadrant. " + quadrantDoc,
- }, func(ctx context.Context, req *mcp.CallToolRequest, in listIn) (*mcp.CallToolResult, tasksOut, error) {
- ts, err := s.List(task.Quadrant(in.Quadrant))
- if err != nil {
- return nil, tasksOut{}, err
- }
- return nil, tasksOut{Tasks: toOuts(ts, labelsOf(s))}, nil
- })
+ }, func(d store.Data, in listIn) []task.Task { return d.List(task.Quadrant(in.Quadrant)) })
- mcp.AddTool(srv, &mcp.Tool{
+ listTool(srv, s, &mcp.Tool{
+ Name: "list_archive",
+ Description: "List completed (archived) tasks, most recently completed first.",
+ }, func(d store.Data, in emptyIn) []task.Task { return d.ListArchive() })
+
+ taskTool(srv, &mcp.Tool{
Name: "add_task",
Description: "Add a task to the matrix. " + quadrantDoc,
- }, func(ctx context.Context, req *mcp.CallToolRequest, in addIn) (*mcp.CallToolResult, taskOut, error) {
- t, err := s.Add(in.Title, task.Quadrant(in.Quadrant))
- if err != nil {
- return nil, taskOut{}, err
- }
- return nil, toOut(t, labelsOf(s)), nil
+ }, func(in addIn) (task.Task, store.Data, error) {
+ return s.Add(in.Title, task.Quadrant(in.Quadrant))
})
- mcp.AddTool(srv, &mcp.Tool{
+ taskTool(srv, &mcp.Tool{
Name: "complete_task",
Description: "Mark a task done. It moves from the active matrix to the archive.",
- }, func(ctx context.Context, req *mcp.CallToolRequest, in idIn) (*mcp.CallToolResult, taskOut, error) {
- t, err := s.Complete(in.ID)
- if err != nil {
- return nil, taskOut{}, err
- }
- return nil, toOut(t, labelsOf(s)), nil
- })
+ }, func(in idIn) (task.Task, store.Data, error) { return s.Complete(in.ID) })
- mcp.AddTool(srv, &mcp.Tool{
+ taskTool(srv, &mcp.Tool{
Name: "move_task",
Description: "Move a task to a different quadrant. " + quadrantDoc,
- }, func(ctx context.Context, req *mcp.CallToolRequest, in moveIn) (*mcp.CallToolResult, taskOut, error) {
- t, err := s.Move(in.ID, task.Quadrant(in.Quadrant))
- if err != nil {
- return nil, taskOut{}, err
- }
- return nil, toOut(t, labelsOf(s)), nil
+ }, func(in moveIn) (task.Task, store.Data, error) {
+ return s.Move(in.ID, task.Quadrant(in.Quadrant))
})
- mcp.AddTool(srv, &mcp.Tool{
+ taskTool(srv, &mcp.Tool{
Name: "update_task",
Description: "Rename a task (change its title).",
- }, func(ctx context.Context, req *mcp.CallToolRequest, in updateIn) (*mcp.CallToolResult, taskOut, error) {
- t, err := s.Rename(in.ID, in.Title)
- if err != nil {
- return nil, taskOut{}, err
- }
- return nil, toOut(t, labelsOf(s)), nil
- })
+ }, func(in updateIn) (task.Task, store.Data, error) { return s.Rename(in.ID, in.Title) })
- mcp.AddTool(srv, &mcp.Tool{
+ taskTool(srv, &mcp.Tool{
Name: "delete_task",
Description: "Delete an active task permanently. Unlike complete_task, the task is NOT archived. Use for tasks that should never have existed; prefer complete_task for finished work.",
- }, func(ctx context.Context, req *mcp.CallToolRequest, in idIn) (*mcp.CallToolResult, taskOut, error) {
- t, err := s.Delete(in.ID)
- if err != nil {
- return nil, taskOut{}, err
- }
- return nil, toOut(t, labelsOf(s)), nil
- })
+ }, func(in idIn) (task.Task, store.Data, error) { return s.Delete(in.ID) })
- mcp.AddTool(srv, &mcp.Tool{
+ taskTool(srv, &mcp.Tool{
Name: "restore_task",
Description: "Un-archive a completed task: it returns to the active matrix in the quadrant it was completed in, at the bottom, with its completion time cleared.",
- }, func(ctx context.Context, req *mcp.CallToolRequest, in idIn) (*mcp.CallToolResult, taskOut, error) {
- t, err := s.Restore(in.ID)
- if err != nil {
- return nil, taskOut{}, err
- }
- return nil, toOut(t, labelsOf(s)), nil
- })
+ }, func(in idIn) (task.Task, store.Data, error) { return s.Restore(in.ID) })
- mcp.AddTool(srv, &mcp.Tool{
+ taskTool(srv, &mcp.Tool{
Name: "reorder_task",
Description: "Change a task's position within its own quadrant. This does not change which quadrant it is in — use move_task for that.",
- }, func(ctx context.Context, req *mcp.CallToolRequest, in reorderIn) (*mcp.CallToolResult, taskOut, error) {
+ }, func(in reorderIn) (task.Task, store.Data, error) {
delta, err := directionDelta(in.Direction)
if err != nil {
- return nil, taskOut{}, err
- }
- t, err := s.Reorder(in.ID, delta)
- if err != nil {
- return nil, taskOut{}, err
+ return task.Task{}, store.Data{}, err
}
- return nil, toOut(t, labelsOf(s)), nil
+ return s.Reorder(in.ID, delta)
})
mcp.AddTool(srv, &mcp.Tool{
Name: "undo",
Description: "Revert the single most recent change to the matrix, whichever frontend made it. Returns a description of what was undone. Call repeatedly to walk further back, and use redo to re-apply.",
}, func(ctx context.Context, req *mcp.CallToolRequest, in emptyIn) (*mcp.CallToolResult, undoOut, error) {
- label, err := s.Undo()
+ label, _, err := s.Undo()
if err != nil {
return nil, undoOut{}, err
}
@@ -237,7 +223,7 @@ func NewServer(s *store.Store, version string) *mcp.Server {
Name: "redo",
Description: "Re-apply the most recently undone change. Only available until the next change to the matrix, which discards the redo history — so making any edit after an undo permanently gives up the redo.",
}, func(ctx context.Context, req *mcp.CallToolRequest, in emptyIn) (*mcp.CallToolResult, undoOut, error) {
- label, err := s.Redo()
+ label, _, err := s.Redo()
if err != nil {
return nil, undoOut{}, err
}
@@ -265,24 +251,13 @@ func NewServer(s *store.Store, version string) *mcp.Server {
Description: "Rename a quadrant's heading. This changes only the display name — it does not " +
"move tasks or change what the quadrant means. Pass an empty label to restore the default.",
}, func(ctx context.Context, req *mcp.CallToolRequest, in labelIn) (*mcp.CallToolResult, quadrantOut, error) {
- label, err := s.SetQuadrantLabel(task.Quadrant(in.Quadrant), in.Label)
+ label, _, err := s.SetQuadrantLabel(task.Quadrant(in.Quadrant), in.Label)
if err != nil {
return nil, quadrantOut{}, err
}
return nil, quadrantOut{Quadrant: in.Quadrant, Label: label}, nil
})
- mcp.AddTool(srv, &mcp.Tool{
- Name: "list_archive",
- Description: "List completed (archived) tasks, most recently completed first.",
- }, func(ctx context.Context, req *mcp.CallToolRequest, in emptyIn) (*mcp.CallToolResult, tasksOut, error) {
- ts, err := s.ListArchive()
- if err != nil {
- return nil, tasksOut{}, err
- }
- return nil, tasksOut{Tasks: toOuts(ts, labelsOf(s))}, nil
- })
-
return srv
}
diff --git a/internal/mcpserver/server_test.go b/internal/mcpserver/server_test.go
index 3e95610..365c8c7 100644
--- a/internal/mcpserver/server_test.go
+++ b/internal/mcpserver/server_test.go
@@ -237,7 +237,7 @@ func TestRedoInvalidatedByAnotherFrontend(t *testing.T) {
call(t, sess, "undo", map[string]any{})
// A write straight to the store, as the CLI or TUI would make.
- if _, err := s.Add("from another frontend", task.Schedule); err != nil {
+ if _, _, err := s.Add("from another frontend", task.Schedule); err != nil {
t.Fatal(err)
}
if res := call(t, sess, "redo", map[string]any{}); !res.IsError {
diff --git a/internal/store/durability_test.go b/internal/store/durability_test.go
index e33ffed..f66cacd 100644
--- a/internal/store/durability_test.go
+++ b/internal/store/durability_test.go
@@ -18,7 +18,7 @@ func TestDataFileAndDirArePrivate(t *testing.T) {
dir := filepath.Join(t.TempDir(), "ike")
path := filepath.Join(dir, "tasks.json")
s := OpenAt(path)
- if _, err := s.Add("private", task.Do); err != nil {
+ if _, _, err := s.Add("private", task.Do); err != nil {
t.Fatal(err)
}
@@ -45,14 +45,14 @@ func TestWriteTightensPermissionsOfAnOlderFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "tasks.json")
s := OpenAt(path)
- if _, err := s.Add("first", task.Do); err != nil {
+ if _, _, err := s.Add("first", task.Do); err != nil {
t.Fatal(err)
}
if err := os.Chmod(path, 0o644); err != nil {
t.Fatal(err)
}
- if _, err := s.Add("second", task.Do); err != nil {
+ if _, _, err := s.Add("second", task.Do); err != nil {
t.Fatal(err)
}
fi, err := os.Stat(path)
@@ -79,7 +79,7 @@ func TestWriteDoesNotUsePredictableTempName(t *testing.T) {
}
s := OpenAt(path)
- if _, err := s.Add("safe", task.Do); err != nil {
+ if _, _, err := s.Add("safe", task.Do); err != nil {
t.Fatal(err)
}
@@ -108,7 +108,7 @@ func TestWriteKeepsABackupOfThePreviousContents(t *testing.T) {
path := filepath.Join(dir, "tasks.json")
s := OpenAt(path)
- if _, err := s.Add("first", task.Do); err != nil {
+ if _, _, err := s.Add("first", task.Do); err != nil {
t.Fatal(err)
}
// No backup yet: there was nothing to preserve before the first write.
@@ -116,7 +116,7 @@ func TestWriteKeepsABackupOfThePreviousContents(t *testing.T) {
t.Errorf("unexpected backup after the first write: %v", err)
}
- if _, err := s.Add("second", task.Do); err != nil {
+ if _, _, err := s.Add("second", task.Do); err != nil {
t.Fatal(err)
}
bak, err := os.ReadFile(path + ".bak")
@@ -147,7 +147,7 @@ func TestWrittenFileIsCompleteAndParses(t *testing.T) {
path := filepath.Join(dir, "tasks.json")
s := OpenAt(path)
for i := range 25 {
- if _, err := s.Add(strings.Repeat("x", i+1), task.Schedule); err != nil {
+ if _, _, err := s.Add(strings.Repeat("x", i+1), task.Schedule); err != nil {
t.Fatal(err)
}
d, err := s.Load()
@@ -204,7 +204,7 @@ func TestMutateTimesOutInsteadOfHangingForever(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "tasks.json")
s := OpenAt(path)
- if _, err := s.Add("seed", task.Do); err != nil {
+ if _, _, err := s.Add("seed", task.Do); err != nil {
t.Fatal(err)
}
@@ -216,7 +216,7 @@ func TestMutateTimesOutInsteadOfHangingForever(t *testing.T) {
defer func() { _ = held.Unlock() }()
start := time.Now()
- _, err := s.Add("blocked", task.Do)
+ _, _, err := s.Add("blocked", task.Do)
elapsed := time.Since(start)
if err == nil {
@@ -237,7 +237,7 @@ func TestMutateTimesOutInsteadOfHangingForever(t *testing.T) {
if err := held.Unlock(); err != nil {
t.Fatal(err)
}
- if _, err := s.Add("after release", task.Do); err != nil {
+ if _, _, err := s.Add("after release", task.Do); err != nil {
t.Errorf("Add after the lock was released: %v", err)
}
}
diff --git a/internal/store/history_test.go b/internal/store/history_test.go
new file mode 100644
index 0000000..7cd3914
--- /dev/null
+++ b/internal/store/history_test.go
@@ -0,0 +1,383 @@
+package store
+
+import (
+ "path/filepath"
+ "testing"
+
+ "github.com/jonascript/ike/internal/task"
+)
+
+// titles returns the titles of q's tasks in display order.
+
+func TestUndoOfTaskChangeLeavesLabelsAlone(t *testing.T) {
+ s := testStore(t)
+ if _, _, err := s.SetQuadrantLabel(task.Do, "Firefighting"); err != nil {
+ t.Fatal(err)
+ }
+ a, _, _ := s.Add("something", task.Do)
+ if _, _, err := s.Delete(a.ID); err != nil {
+ t.Fatal(err)
+ }
+ // Undoing the delete must not roll the rename back with it.
+ if _, _, err := s.Undo(); err != nil {
+ t.Fatal(err)
+ }
+ labels, _ := s.QuadrantLabels()
+ if labels.Of(task.Do) != "Firefighting" {
+ t.Errorf("label = %q, want the rename to survive an unrelated undo", labels.Of(task.Do))
+ }
+}
+
+func TestUndoCannotReopenRevokedAccess(t *testing.T) {
+ s := testStore(t)
+ if _, err := s.SetMCPEnabled(true); err != nil {
+ t.Fatal(err)
+ }
+ s.Add("a task", task.Do)
+ if _, err := s.SetMCPEnabled(false); err != nil {
+ t.Fatal(err)
+ }
+
+ // No amount of undo or redo may hand access back.
+ for i := 0; i < 5; i++ {
+ if _, _, err := s.Undo(); err != nil {
+ break
+ }
+ if on, _ := s.MCPEnabled(); on {
+ t.Fatalf("undo %d re-enabled revoked MCP access", i)
+ }
+ }
+ for i := 0; i < 5; i++ {
+ if _, _, err := s.Redo(); err != nil {
+ break
+ }
+ if on, _ := s.MCPEnabled(); on {
+ t.Fatalf("redo %d re-enabled revoked MCP access", i)
+ }
+ }
+}
+
+func TestUndoRestoresPreviousState(t *testing.T) {
+ s := testStore(t)
+ a, _, _ := s.Add("keep me", task.Do)
+
+ if _, _, err := s.Complete(a.ID); err != nil {
+ t.Fatal(err)
+ }
+ label, _, err := s.Undo()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if label != `complete "keep me"` {
+ t.Errorf("label = %q, want the complete label", label)
+ }
+ d, _ := s.Load()
+ if len(d.Tasks) != 1 || len(d.Archive) != 0 {
+ t.Fatalf("after undo: %d active, %d archived; want 1 and 0", len(d.Tasks), len(d.Archive))
+ }
+
+ // Undo the add itself.
+ if _, _, err := s.Undo(); err != nil {
+ t.Fatal(err)
+ }
+ d, _ = s.Load()
+ if len(d.Tasks) != 0 {
+ t.Errorf("after second undo: %d active, want 0", len(d.Tasks))
+ }
+}
+
+func TestUndoOfDeleteBringsTaskBack(t *testing.T) {
+ s := testStore(t)
+ a, _, _ := s.Add("oops", task.Do)
+ if _, _, err := s.Delete(a.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := s.Undo(); err != nil {
+ t.Fatal(err)
+ }
+ got := titles(t, s, task.Do)
+ if !equal(got, []string{"oops"}) {
+ t.Errorf("after undoing delete: %v, want [oops]", got)
+ }
+}
+
+func TestUndoDoesNotReuseIDs(t *testing.T) {
+ s := testStore(t)
+ a, _, _ := s.Add("first", task.Do)
+ if _, _, err := s.Undo(); err != nil { // undo the add
+ t.Fatal(err)
+ }
+ b, _, err := s.Add("second", task.Do)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if b.ID == a.ID {
+ t.Errorf("ID %d was reused after undo; IDs must stay monotonic", b.ID)
+ }
+}
+
+func TestUndoEmptyStack(t *testing.T) {
+ s := testStore(t)
+ if _, _, err := s.Undo(); err == nil {
+ t.Error("undo with nothing to undo should error")
+ }
+}
+
+func TestRepeatedUndoWalksBack(t *testing.T) {
+ s := testStore(t)
+ s.Add("a", task.Do)
+ s.Add("b", task.Do)
+ if _, _, err := s.Undo(); err != nil { // undoes add "b"
+ t.Fatal(err)
+ }
+ label, _, err := s.Undo() // must undo add "a", not re-apply add "b"
+ if err != nil {
+ t.Fatal(err)
+ }
+ if label != `add "a"` {
+ t.Errorf("second undo label = %q, want `add \"a\"`", label)
+ }
+ if got := titles(t, s, task.Do); len(got) != 0 {
+ t.Errorf("after two undos: %v, want nothing", got)
+ }
+}
+
+func TestRedoReappliesUndoneChange(t *testing.T) {
+ s := testStore(t)
+ a, _, _ := s.Add("ship it", task.Do)
+ if _, _, err := s.Complete(a.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := s.Undo(); err != nil {
+ t.Fatal(err)
+ }
+ if arch, _ := s.ListArchive(); len(arch) != 0 {
+ t.Fatal("undo should have un-archived the task")
+ }
+
+ label, _, err := s.Redo()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if label != `complete "ship it"` {
+ t.Errorf("redo label = %q, want the complete label", label)
+ }
+ active, _ := s.List(0)
+ arch, _ := s.ListArchive()
+ if len(active) != 0 || len(arch) != 1 {
+ t.Errorf("after redo: active=%d archive=%d, want 0/1", len(active), len(arch))
+ }
+}
+
+func TestRedoRoundTripIsExact(t *testing.T) {
+ s := testStore(t)
+ s.Add("a", task.Do)
+ b, _, _ := s.Add("b", task.Do)
+ s.Add("c", task.Do)
+ if _, _, err := s.Reorder(b.ID, ToTop); err != nil {
+ t.Fatal(err)
+ }
+ want := titles(t, s, task.Do)
+
+ if _, _, err := s.Undo(); err != nil {
+ t.Fatal(err)
+ }
+ if got := titles(t, s, task.Do); equal(got, want) {
+ t.Fatal("undo did not change the order")
+ }
+ if _, _, err := s.Redo(); err != nil {
+ t.Fatal(err)
+ }
+ if got := titles(t, s, task.Do); !equal(got, want) {
+ t.Errorf("after undo+redo: %v, want %v (ordering must survive the round trip)", got, want)
+ }
+}
+
+func TestNewChangeDiscardsRedo(t *testing.T) {
+ s := testStore(t)
+ a, _, _ := s.Add("first", task.Do)
+ if _, _, err := s.Complete(a.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := s.Undo(); err != nil {
+ t.Fatal(err)
+ }
+
+ // Diverging from the undone branch must strand it: redoing the complete
+ // here would clobber the task added below.
+ if _, _, err := s.Add("second", task.Do); err != nil {
+ t.Fatal(err)
+ }
+ d, err := s.Load()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(d.Redo) != 0 {
+ t.Errorf("redo stack = %d entries, want 0 after a new change", len(d.Redo))
+ }
+ if _, _, err := s.Redo(); err == nil {
+ t.Error("redo after a diverging change should error")
+ }
+ if got, want := titles(t, s, task.Do), []string{"first", "second"}; !equal(got, want) {
+ t.Errorf("tasks = %v, want %v", got, want)
+ }
+}
+
+func TestRedoAcrossFrontendsIsDiscardedToo(t *testing.T) {
+ dir := t.TempDir()
+ p := filepath.Join(dir, "tasks.json")
+
+ a, _, err := OpenAt(p).Add("mine", task.Do)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := OpenAt(p).Delete(a.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := OpenAt(p).Undo(); err != nil {
+ t.Fatal(err)
+ }
+ // A different "process" (CLI or MCP agent) writes.
+ if _, _, err := OpenAt(p).Add("theirs", task.Schedule); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := OpenAt(p).Redo(); err == nil {
+ t.Error("a write from another frontend should invalidate redo")
+ }
+}
+
+func TestRedoMultipleSteps(t *testing.T) {
+ s := testStore(t)
+ s.Add("a", task.Do)
+ s.Add("b", task.Do)
+ s.Add("c", task.Do)
+
+ for i := 0; i < 3; i++ {
+ if _, _, err := s.Undo(); err != nil {
+ t.Fatalf("undo %d: %v", i, err)
+ }
+ }
+ if got := titles(t, s, task.Do); len(got) != 0 {
+ t.Fatalf("after three undos: %v, want nothing", got)
+ }
+
+ // Redo must walk forward the same distance. This is what breaks if Redo
+ // clears the redo stack via pushUndo.
+ for i := 0; i < 3; i++ {
+ if _, _, err := s.Redo(); err != nil {
+ t.Fatalf("redo %d: %v", i, err)
+ }
+ }
+ if got, want := titles(t, s, task.Do), []string{"a", "b", "c"}; !equal(got, want) {
+ t.Errorf("after three redos: %v, want %v", got, want)
+ }
+ if _, _, err := s.Redo(); err == nil {
+ t.Error("a fourth redo should error")
+ }
+}
+
+func TestRedoIsUndoable(t *testing.T) {
+ s := testStore(t)
+ a, _, _ := s.Add("wobble", task.Do)
+ s.Delete(a.ID)
+ s.Undo() // task is back
+ if _, _, err := s.Redo(); err != nil {
+ t.Fatal(err)
+ }
+ if got := titles(t, s, task.Do); len(got) != 0 {
+ t.Fatalf("redo should have re-deleted: %v", got)
+ }
+ if _, _, err := s.Undo(); err != nil {
+ t.Fatal(err)
+ }
+ if got, want := titles(t, s, task.Do), []string{"wobble"}; !equal(got, want) {
+ t.Errorf("undo after redo = %v, want %v", got, want)
+ }
+}
+
+func TestRedoEmptyStack(t *testing.T) {
+ s := testStore(t)
+ s.Add("a", task.Do)
+ if _, _, err := s.Redo(); err == nil {
+ t.Error("redo with nothing undone should error")
+ }
+}
+
+func TestRedoStackIsCapped(t *testing.T) {
+ s := testStore(t)
+ for i := 0; i < undoDepth+5; i++ {
+ if _, _, err := s.Add("t", task.Do); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i := 0; i < undoDepth; i++ {
+ if _, _, err := s.Undo(); err != nil {
+ t.Fatalf("undo %d: %v", i, err)
+ }
+ }
+ d, err := s.Load()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(d.Redo) != undoDepth {
+ t.Errorf("redo stack depth = %d, want %d", len(d.Redo), undoDepth)
+ }
+}
+
+func TestUndoStackIsCapped(t *testing.T) {
+ s := testStore(t)
+ for i := 0; i < undoDepth+15; i++ {
+ if _, _, err := s.Add("t", task.Do); err != nil {
+ t.Fatal(err)
+ }
+ }
+ d, err := s.Load()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(d.Undo) != undoDepth {
+ t.Errorf("undo stack depth = %d, want %d", len(d.Undo), undoDepth)
+ }
+}
+
+func TestUndoSurvivesReload(t *testing.T) {
+ dir := t.TempDir()
+ p := filepath.Join(dir, "tasks.json")
+
+ // One "process" makes a change...
+ a, _, err := OpenAt(p).Add("cross-process", task.Do)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := OpenAt(p).Complete(a.ID); err != nil {
+ t.Fatal(err)
+ }
+ // ...and another undoes it.
+ label, _, err := OpenAt(p).Undo()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if label != `complete "cross-process"` {
+ t.Errorf("label = %q", label)
+ }
+ d, _ := OpenAt(p).Load()
+ if len(d.Tasks) != 1 {
+ t.Errorf("undo across processes left %d active tasks, want 1", len(d.Tasks))
+ }
+}
+
+func TestFailedMutationDoesNotRecordUndo(t *testing.T) {
+ s := testStore(t)
+ a, _, _ := s.Add("valid", task.Do)
+ if _, _, err := s.Rename(a.ID, " "); err == nil {
+ t.Fatal("rename to blank should fail")
+ }
+ d, err := s.Load()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(d.Undo) != 1 || UndoLabel(d) != `add "valid"` {
+ t.Errorf("undo stack = %d entries, top %q; a failed rename should not record",
+ len(d.Undo), UndoLabel(d))
+ }
+}
diff --git a/internal/store/labels_test.go b/internal/store/labels_test.go
new file mode 100644
index 0000000..4fc332e
--- /dev/null
+++ b/internal/store/labels_test.go
@@ -0,0 +1,168 @@
+package store
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/jonascript/ike/internal/task"
+)
+
+// titles returns the titles of q's tasks in display order.
+
+func TestQuadrantLabelDefaults(t *testing.T) {
+ s := testStore(t)
+ labels, err := s.QuadrantLabels()
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := map[task.Quadrant]string{
+ task.Do: "Do It First",
+ task.Schedule: "Schedule It",
+ task.Delegate: "Delegate It",
+ task.Eliminate: "Consider Eliminating It",
+ }
+ for q, w := range want {
+ if got := labels.Of(q); got != w {
+ t.Errorf("quadrant %d label = %q, want %q", q, got, w)
+ }
+ if labels.IsCustom(q) {
+ t.Errorf("quadrant %d reported as custom before any rename", q)
+ }
+ }
+}
+
+func TestSetQuadrantLabel(t *testing.T) {
+ s := testStore(t)
+ got, _, err := s.SetQuadrantLabel(task.Do, "Firefighting")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != "Firefighting" {
+ t.Errorf("SetQuadrantLabel returned %q", got)
+ }
+
+ labels, err := s.QuadrantLabels()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if labels.Of(task.Do) != "Firefighting" {
+ t.Errorf("label = %q, want Firefighting", labels.Of(task.Do))
+ }
+ if !labels.IsCustom(task.Do) {
+ t.Error("renamed quadrant should report as custom")
+ }
+ // Renaming one quadrant must not disturb the others.
+ if labels.Of(task.Schedule) != "Schedule It" {
+ t.Errorf("Schedule label = %q, want the default", labels.Of(task.Schedule))
+ }
+}
+
+func TestSetQuadrantLabelResetsOnBlank(t *testing.T) {
+ s := testStore(t)
+ if _, _, err := s.SetQuadrantLabel(task.Eliminate, "Junk"); err != nil {
+ t.Fatal(err)
+ }
+ got, _, err := s.SetQuadrantLabel(task.Eliminate, " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != "Consider Eliminating It" {
+ t.Errorf("reset returned %q, want the default", got)
+ }
+ d, err := s.Load()
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The override is removed, not stored as an empty string.
+ if _, ok := d.Labels[task.Eliminate]; ok {
+ t.Error("reset should delete the override, not blank it")
+ }
+}
+
+func TestSetQuadrantLabelValidates(t *testing.T) {
+ s := testStore(t)
+ if _, _, err := s.SetQuadrantLabel(9, "Nope"); err == nil {
+ t.Error("invalid quadrant should error")
+ }
+ long := strings.Repeat("x", task.MaxLabelLen+1)
+ if _, _, err := s.SetQuadrantLabel(task.Do, long); err == nil {
+ t.Error("over-long label should error")
+ }
+ labels, _ := s.QuadrantLabels()
+ if labels.Of(task.Do) != "Do It First" {
+ t.Errorf("failed rename changed the label to %q", labels.Of(task.Do))
+ }
+}
+
+func TestQuadrantLabelIsUndoable(t *testing.T) {
+ s := testStore(t)
+ if _, _, err := s.SetQuadrantLabel(task.Delegate, "Hand Off"); err != nil {
+ t.Fatal(err)
+ }
+ label, _, err := s.Undo()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(label, "Hand Off") {
+ t.Errorf("undo label = %q, want it to name the rename", label)
+ }
+ labels, _ := s.QuadrantLabels()
+ if labels.Of(task.Delegate) != "Delegate It" {
+ t.Errorf("after undo, label = %q, want the default back", labels.Of(task.Delegate))
+ }
+
+ if _, _, err := s.Redo(); err != nil {
+ t.Fatal(err)
+ }
+ labels, _ = s.QuadrantLabels()
+ if labels.Of(task.Delegate) != "Hand Off" {
+ t.Errorf("after redo, label = %q, want Hand Off", labels.Of(task.Delegate))
+ }
+}
+
+func TestSetSameLabelIsANoOp(t *testing.T) {
+ s := testStore(t)
+ s.Add("anchor", task.Do)
+ if _, _, err := s.SetQuadrantLabel(task.Do, "Do It First"); err != nil {
+ t.Fatal(err)
+ }
+ d, err := s.Load()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if UndoLabel(d) != `add "anchor"` {
+ t.Errorf("undo top = %q; setting the label it already has should not record", UndoLabel(d))
+ }
+}
+
+// Labels.Of is the single choke point every frontend renders a quadrant name
+// through, so it sanitizes. SetQuadrantLabel rejects control characters on the
+// way in; this covers a label that reached the file some other way — an older
+// build, a hand edit, or a synced copy.
+func TestLabelsOfSanitizesUntrustedFile(t *testing.T) {
+ l := Labels{task.Do: "red\x1b[31m", task.Schedule: "two\nlines"}
+
+ got := l.Of(task.Do)
+ if strings.ContainsRune(got, 0x1b) {
+ t.Errorf("Of(Do) = %q, still contains an escape", got)
+ }
+ if !strings.Contains(got, "red") {
+ t.Errorf("Of(Do) = %q, dropped visible text", got)
+ }
+ if got := l.Of(task.Schedule); strings.ContainsRune(got, '\n') {
+ t.Errorf("Of(Schedule) = %q, still contains a newline", got)
+ }
+ // An unrenamed quadrant still falls back to its default.
+ if got, want := l.Of(task.Delegate), task.Delegate.Label(); got != want {
+ t.Errorf("Of(Delegate) = %q, want the default %q", got, want)
+ }
+ // The stored label itself is untouched; only the rendered form changes.
+ if l[task.Do] != "red\x1b[31m" {
+ t.Error("Of must not rewrite the stored label")
+ }
+}
+
+// The gate used to be checked once, before serving. A client that stayed
+// connected therefore kept full access after `ike mcp disable`, while
+// `ike mcp status` reported "off". These pin the data-layer check that closed
+// that window.
diff --git a/internal/store/mcp_test.go b/internal/store/mcp_test.go
new file mode 100644
index 0000000..ffd1f23
--- /dev/null
+++ b/internal/store/mcp_test.go
@@ -0,0 +1,192 @@
+package store
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/jonascript/ike/internal/task"
+)
+
+// titles returns the titles of q's tasks in display order.
+
+func TestMCPDisabledByDefault(t *testing.T) {
+ s := testStore(t)
+ on, err := s.MCPEnabled()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if on {
+ t.Error("a fresh matrix should have MCP access off")
+ }
+ // Adding tasks must not switch it on by side effect.
+ s.Add("a task", task.Do)
+ if on, _ := s.MCPEnabled(); on {
+ t.Error("MCP access turned on by an unrelated write")
+ }
+}
+
+func TestMCPEnabledPersists(t *testing.T) {
+ dir := t.TempDir()
+ p := filepath.Join(dir, "tasks.json")
+
+ changed, err := OpenAt(p).SetMCPEnabled(true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !changed {
+ t.Error("enabling from the default should report a change")
+ }
+ // A separate Store instance, as a later process would see it.
+ if on, _ := OpenAt(p).MCPEnabled(); !on {
+ t.Error("setting did not survive a reload")
+ }
+
+ changed, err = OpenAt(p).SetMCPEnabled(true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if changed {
+ t.Error("enabling twice should report no change")
+ }
+
+ if _, err := OpenAt(p).SetMCPEnabled(false); err != nil {
+ t.Fatal(err)
+ }
+ if on, _ := OpenAt(p).MCPEnabled(); on {
+ t.Error("disable did not stick")
+ }
+}
+
+func TestMCPSettingIsNotUndoable(t *testing.T) {
+ s := testStore(t)
+ s.Add("a task", task.Do)
+ if _, err := s.SetMCPEnabled(true); err != nil {
+ t.Fatal(err)
+ }
+
+ // Undo must reach past the permission change to the task change, and must
+ // not restore the old permission on the way.
+ label, _, err := s.Undo()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if label != `add "a task"` {
+ t.Errorf("undo label = %q; the MCP setting should not occupy an undo slot", label)
+ }
+ if on, _ := s.MCPEnabled(); !on {
+ t.Error("undo switched MCP access back off")
+ }
+}
+
+// The gate used to be checked once, before serving. A client that stayed
+// connected therefore kept full access after `ike mcp disable`, while
+// `ike mcp status` reported "off". These pin the data-layer check that closed
+// that window.
+func TestMCPGateRevokesLiveSession(t *testing.T) {
+ s := testStore(t)
+ if _, err := s.SetMCPEnabled(true); err != nil {
+ t.Fatal(err)
+ }
+
+ // The session a connected client holds.
+ live := s.ForMCP()
+ if _, _, err := live.Add("while enabled", task.Do); err != nil {
+ t.Fatalf("Add with access on: %v", err)
+ }
+ if _, err := live.Load(); err != nil {
+ t.Fatalf("Load with access on: %v", err)
+ }
+
+ // Revoked from another process, on the same file, mid-session.
+ if _, err := s.SetMCPEnabled(false); err != nil {
+ t.Fatal(err)
+ }
+
+ if _, _, err := live.Add("after revoke", task.Do); !errors.Is(err, ErrMCPDisabled) {
+ t.Errorf("Add after revoke: err = %v, want ErrMCPDisabled", err)
+ }
+ if _, err := live.Load(); !errors.Is(err, ErrMCPDisabled) {
+ t.Errorf("Load after revoke: err = %v, want ErrMCPDisabled", err)
+ }
+ if _, _, err := live.Complete(1); !errors.Is(err, ErrMCPDisabled) {
+ t.Errorf("Complete after revoke: err = %v, want ErrMCPDisabled", err)
+ }
+ if _, _, err := live.Delete(1); !errors.Is(err, ErrMCPDisabled) {
+ t.Errorf("Delete after revoke: err = %v, want ErrMCPDisabled", err)
+ }
+ if _, _, err := live.Undo(); !errors.Is(err, ErrMCPDisabled) {
+ t.Errorf("Undo after revoke: err = %v, want ErrMCPDisabled", err)
+ }
+
+ // The revoked mutations must not have landed, and the owner's own access is
+ // unaffected — that is what `ike mcp status` and the TUI keep using.
+ d, err := s.Load()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(d.Tasks) != 1 || d.Tasks[0].Title != "while enabled" {
+ t.Errorf("tasks = %+v, want only the pre-revoke task", d.Tasks)
+ }
+
+ // Re-enabling restores the same session, without reconnecting.
+ if _, err := s.SetMCPEnabled(true); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := live.Load(); err != nil {
+ t.Errorf("Load after re-enable: %v", err)
+ }
+}
+
+// A store that was never marked for MCP use is unaffected by the setting, so
+// the TUI and CLI keep working while agent access is off.
+
+// A store that was never marked for MCP use is unaffected by the setting, so
+// the TUI and CLI keep working while agent access is off.
+func TestGateDoesNotAffectOwnerAccess(t *testing.T) {
+ s := testStore(t)
+ if enabled, err := s.MCPEnabled(); err != nil || enabled {
+ t.Fatalf("MCPEnabled() = %v, %v; want false, nil", enabled, err)
+ }
+ if _, _, err := s.Add("owner task", task.Do); err != nil {
+ t.Errorf("owner Add with MCP off: %v", err)
+ }
+ if _, err := s.Load(); err != nil {
+ t.Errorf("owner Load with MCP off: %v", err)
+ }
+}
+
+func TestMCPErrorsOmitDataFilePath(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "tasks.json")
+ if err := os.WriteFile(path, []byte("{ not json"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ gated := OpenAt(path).ForMCP()
+
+ _, err := gated.Load()
+ if err == nil {
+ t.Fatal("expected a parse error")
+ }
+ if strings.Contains(err.Error(), dir) {
+ t.Errorf("error discloses the data file's directory to the agent: %v", err)
+ }
+ // The file name still appears, so the message stays actionable.
+ if !strings.Contains(err.Error(), "tasks.json") {
+ t.Errorf("error should still name the file: %v", err)
+ }
+
+ // The owner's view keeps the full path, which is what makes a CLI error
+ // useful.
+ if _, err := OpenAt(path).Load(); err == nil || !strings.Contains(err.Error(), dir) {
+ t.Errorf("ungated error should keep the full path: %v", err)
+ }
+}
+
+// Archive order is defined once, in Data.ListArchive, and both `ike archive`
+// and the TUI's archive view render it. The TUI used to reverse the stored
+// slice instead, which agrees only while every archived task carries a
+// completion stamp — a file written by an older build, or hand-edited, need
+// not. This pins the definition that both now share.
diff --git a/internal/store/ops.go b/internal/store/ops.go
index efc3a85..4636131 100644
--- a/internal/store/ops.go
+++ b/internal/store/ops.go
@@ -36,14 +36,21 @@ var (
ErrNothingToRedo = errors.New("nothing to redo")
)
+// Every mutating operation returns the post-mutation Data alongside its own
+// result. Mutate already produces it, so handing it back costs nothing and
+// spares callers a second read: the quadrant labels a frontend needs to render
+// the outcome, and the full state the TUI re-renders from, are both in there.
+// Reading them again would also be a read of a *later* file state, which may
+// no longer be the one the operation produced.
+
// Add creates a new task at the bottom of the given quadrant and returns it.
-func (s *Store) Add(title string, q task.Quadrant) (task.Task, error) {
+func (s *Store) Add(title string, q task.Quadrant) (task.Task, Data, error) {
title = strings.TrimSpace(title)
if err := task.Validate(title, q); err != nil {
- return task.Task{}, err
+ return task.Task{}, Data{}, err
}
var created task.Task
- _, err := s.Mutate(func(d *Data) error {
+ d, err := s.Mutate(func(d *Data) error {
pushUndo(d, fmt.Sprintf("add %q", title))
created = task.Task{
ID: d.NextID,
@@ -56,13 +63,13 @@ func (s *Store) Add(title string, q task.Quadrant) (task.Task, error) {
d.Tasks = append(d.Tasks, created)
return nil
})
- return created, err
+ return created, d, err
}
// Complete moves a task to the archive, stamping DoneAt.
-func (s *Store) Complete(id int) (task.Task, error) {
+func (s *Store) Complete(id int) (task.Task, Data, error) {
var done task.Task
- _, err := s.Mutate(func(d *Data) error {
+ d, err := s.Mutate(func(d *Data) error {
i, err := findTask(d, id)
if err != nil {
return err
@@ -75,15 +82,15 @@ func (s *Store) Complete(id int) (task.Task, error) {
d.Archive = append(d.Archive, done)
return nil
})
- return done, err
+ return done, d, err
}
// Restore moves an archived task back into the active matrix, clearing its
// completion stamp and placing it at the bottom of the quadrant it was
// completed in.
-func (s *Store) Restore(id int) (task.Task, error) {
+func (s *Store) Restore(id int) (task.Task, Data, error) {
var restored task.Task
- _, err := s.Mutate(func(d *Data) error {
+ d, err := s.Mutate(func(d *Data) error {
i, err := findArchived(d, id)
if err != nil {
return err
@@ -96,16 +103,16 @@ func (s *Store) Restore(id int) (task.Task, error) {
d.Tasks = append(d.Tasks, restored)
return nil
})
- return restored, err
+ return restored, d, err
}
// Move changes a task's quadrant, placing it at the bottom of the destination.
-func (s *Store) Move(id int, q task.Quadrant) (task.Task, error) {
+func (s *Store) Move(id int, q task.Quadrant) (task.Task, Data, error) {
if !q.Valid() {
- return task.Task{}, fmt.Errorf("quadrant must be 1-4, got %d", q)
+ return task.Task{}, Data{}, fmt.Errorf("quadrant must be 1-4, got %d", q)
}
var moved task.Task
- _, err := s.Mutate(func(d *Data) error {
+ d, err := s.Mutate(func(d *Data) error {
i, err := findTask(d, id)
if err != nil {
return err
@@ -120,15 +127,15 @@ func (s *Store) Move(id int, q task.Quadrant) (task.Task, error) {
moved = d.Tasks[i]
return nil
})
- return moved, err
+ return moved, d, err
}
// Reorder moves a task within its quadrant by delta positions — negative is
// toward the top, positive toward the bottom — clamped at either end. It
// rewrites the whole quadrant's ranks, so repeated moves never lose precision.
-func (s *Store) Reorder(id int, delta int) (task.Task, error) {
+func (s *Store) Reorder(id int, delta int) (task.Task, Data, error) {
var moved task.Task
- _, err := s.Mutate(func(d *Data) error {
+ d, err := s.Mutate(func(d *Data) error {
i, err := findTask(d, id)
if err != nil {
return err
@@ -151,22 +158,22 @@ func (s *Store) Reorder(id int, delta int) (task.Task, error) {
moved = d.Tasks[i]
return nil
})
- return moved, err
+ return moved, d, err
}
// SetQuadrantLabel renames a quadrant's heading. A blank label clears the
// override, restoring the built-in default. It returns the resulting display
// name.
-func (s *Store) SetQuadrantLabel(q task.Quadrant, label string) (string, error) {
+func (s *Store) SetQuadrantLabel(q task.Quadrant, label string) (string, Data, error) {
if !q.Valid() {
- return "", fmt.Errorf("quadrant must be 1-4, got %d", q)
+ return "", Data{}, fmt.Errorf("quadrant must be 1-4, got %d", q)
}
label = strings.TrimSpace(label)
if err := task.ValidateLabel(label); err != nil {
- return "", err
+ return "", Data{}, err
}
var result string
- _, err := s.Mutate(func(d *Data) error {
+ d, err := s.Mutate(func(d *Data) error {
was := d.Labels.Of(q)
if label == was {
result = was
@@ -185,7 +192,7 @@ func (s *Store) SetQuadrantLabel(q task.Quadrant, label string) (string, error)
result = d.Labels.Of(q)
return nil
})
- return result, err
+ return result, d, err
}
// QuadrantLabels returns the display names of all four quadrants, custom where
@@ -195,11 +202,18 @@ func (s *Store) QuadrantLabels() (Labels, error) {
if err != nil {
return nil, err
}
+ return d.QuadrantLabels(), nil
+}
+
+// QuadrantLabels returns the display names of all four quadrants, custom where
+// set and default otherwise. It is the pure form of Store.QuadrantLabels, for
+// callers that already hold the data — every mutation hands theirs back.
+func (d Data) QuadrantLabels() Labels {
out := make(Labels, 4)
for q := task.Do; q <= task.Eliminate; q++ {
out[q] = d.Labels.Of(q)
}
- return out, nil
+ return out
}
// SetMCPEnabled turns agent access to this matrix on or off, and reports
@@ -207,6 +221,9 @@ func (s *Store) QuadrantLabels() (Labels, error) {
//
// This is a permission, not an edit: it is deliberately kept off the undo
// stack, so no sequence of undo or redo can re-open access the owner closed.
+// It also does not return Data the way the task operations do — nothing
+// renders a result from it, and handing an MCP-gated caller a full copy of the
+// matrix from the call that flips the gate would be a poor shape.
func (s *Store) SetMCPEnabled(on bool) (changed bool, err error) {
_, err = s.Mutate(func(d *Data) error {
changed = d.MCPEnabled != on
@@ -226,10 +243,10 @@ func (s *Store) MCPEnabled() (bool, error) {
}
// Rename changes a task's title.
-func (s *Store) Rename(id int, title string) (task.Task, error) {
+func (s *Store) Rename(id int, title string) (task.Task, Data, error) {
title = strings.TrimSpace(title)
var renamed task.Task
- _, err := s.Mutate(func(d *Data) error {
+ d, err := s.Mutate(func(d *Data) error {
i, err := findTask(d, id)
if err != nil {
return err
@@ -242,14 +259,14 @@ func (s *Store) Rename(id int, title string) (task.Task, error) {
renamed = d.Tasks[i]
return nil
})
- return renamed, err
+ return renamed, d, err
}
// Delete removes an active task permanently (it does not go to the archive).
// It is still undoable until it falls off the undo stack.
-func (s *Store) Delete(id int) (task.Task, error) {
+func (s *Store) Delete(id int) (task.Task, Data, error) {
var deleted task.Task
- _, err := s.Mutate(func(d *Data) error {
+ d, err := s.Mutate(func(d *Data) error {
i, err := findTask(d, id)
if err != nil {
return err
@@ -259,16 +276,16 @@ func (s *Store) Delete(id int) (task.Task, error) {
d.Tasks = append(d.Tasks[:i], d.Tasks[i+1:]...)
return nil
})
- return deleted, err
+ return deleted, d, err
}
// Undo reverts the most recent recorded mutation and returns its label. It
// restores both task lists but deliberately leaves next_id alone: IDs stay
// monotonic and are never reused, so undoing an add does not free its ID.
// The undone state moves to the redo stack, so Redo puts it back.
-func (s *Store) Undo() (string, error) {
+func (s *Store) Undo() (string, Data, error) {
var label string
- _, err := s.Mutate(func(d *Data) error {
+ d, err := s.Mutate(func(d *Data) error {
if len(d.Undo) == 0 {
return ErrNothingToUndo
}
@@ -280,15 +297,15 @@ func (s *Store) Undo() (string, error) {
label = snap.Label
return nil
})
- return label, err
+ return label, d, err
}
// Redo re-applies the most recently undone change and returns its label. It
// is available only until the next real mutation, which discards the redo
// stack. A redo is itself undoable.
-func (s *Store) Redo() (string, error) {
+func (s *Store) Redo() (string, Data, error) {
var label string
- _, err := s.Mutate(func(d *Data) error {
+ d, err := s.Mutate(func(d *Data) error {
if len(d.Redo) == 0 {
return ErrNothingToRedo
}
@@ -301,7 +318,7 @@ func (s *Store) Redo() (string, error) {
label = snap.Label
return nil
})
- return label, err
+ return label, d, err
}
// UndoLabel reports what the next Undo would revert, or "" if the stack is
@@ -411,6 +428,13 @@ func (s *Store) List(q task.Quadrant) ([]task.Task, error) {
if err != nil {
return nil, err
}
+ return d.List(q), nil
+}
+
+// List returns d's active tasks, optionally filtered to one quadrant (q == 0
+// means all), in display order. It is the single definition of that list, used
+// by Store.List and rendered directly by the TUI from the data it already has.
+func (d Data) List(q task.Quadrant) []task.Task {
tasks := make([]task.Task, 0, len(d.Tasks))
for _, t := range d.Tasks {
if q == 0 || t.Quadrant == q {
@@ -418,7 +442,7 @@ func (s *Store) List(q task.Quadrant) ([]task.Task, error) {
}
}
task.SortOrder(tasks)
- return tasks, nil
+ return tasks
}
// ListArchive returns archived tasks, newest completion first.
@@ -427,6 +451,17 @@ func (s *Store) ListArchive() ([]task.Task, error) {
if err != nil {
return nil, err
}
+ return d.ListArchive(), nil
+}
+
+// ListArchive returns d's archived tasks, newest completion first. It is the
+// single definition of archive order: `ike archive` and the TUI's archive view
+// both render this, so they cannot drift apart. Tasks with no completion stamp
+// — reachable from a hand-edited or pre-archive data file — sort by ID, which
+// is why this is not just a reversal of the stored slice.
+func (d Data) ListArchive() []task.Task {
+ // Not slices.Clone: it preserves nil, and `ike archive --json` must emit []
+ // rather than null for an empty archive.
arch := make([]task.Task, len(d.Archive))
copy(arch, d.Archive)
sort.SliceStable(arch, func(i, j int) bool {
@@ -436,7 +471,7 @@ func (s *Store) ListArchive() ([]task.Task, error) {
}
return arch[i].ID > arch[j].ID
})
- return arch, nil
+ return arch
}
func findTask(d *Data, id int) (int, error) {
diff --git a/internal/store/ops_test.go b/internal/store/ops_test.go
index 42add80..e736a8c 100644
--- a/internal/store/ops_test.go
+++ b/internal/store/ops_test.go
@@ -2,29 +2,28 @@ package store
import (
"encoding/json"
- "errors"
"os"
"path/filepath"
- "strings"
+ "slices"
"testing"
+ "time"
"github.com/jonascript/ike/internal/task"
)
// titles returns the titles of q's tasks in display order.
-func titles(t *testing.T, s *Store, q task.Quadrant) []string {
- t.Helper()
- ts, err := s.List(q)
- if err != nil {
- t.Fatal(err)
- }
+
+func titlesOf(ts []task.Task) []string {
out := make([]string, len(ts))
- for i, tk := range ts {
- out[i] = tk.Title
+ for i, t := range ts {
+ out[i] = t.Title
}
return out
}
+// An empty archive must marshal as [] rather than null: `ike archive --json`
+// is a machine interface, and a nil slice would change its shape.
+
func equal(a, b []string) bool {
if len(a) != len(b) {
return false
@@ -37,17 +36,31 @@ func equal(a, b []string) bool {
return true
}
+// titles returns the titles of q's tasks in display order.
+func titles(t *testing.T, s *Store, q task.Quadrant) []string {
+ t.Helper()
+ ts, err := s.List(q)
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := make([]string, len(ts))
+ for i, tk := range ts {
+ out[i] = tk.Title
+ }
+ return out
+}
+
func TestRestoreUnarchives(t *testing.T) {
s := testStore(t)
- added, err := s.Add("write the thing", task.Delegate)
+ added, _, err := s.Add("write the thing", task.Delegate)
if err != nil {
t.Fatal(err)
}
- if _, err := s.Complete(added.ID); err != nil {
+ if _, _, err := s.Complete(added.ID); err != nil {
t.Fatal(err)
}
- restored, err := s.Restore(added.ID)
+ restored, _, err := s.Restore(added.ID)
if err != nil {
t.Fatal(err)
}
@@ -72,24 +85,24 @@ func TestRestoreUnarchives(t *testing.T) {
func TestRestoreUnknownID(t *testing.T) {
s := testStore(t)
- a, _ := s.Add("still active", task.Do)
- if _, err := s.Restore(a.ID); err == nil {
+ a, _, _ := s.Add("still active", task.Do)
+ if _, _, err := s.Restore(a.ID); err == nil {
t.Error("restoring an active (not archived) task should error")
}
- if _, err := s.Restore(999); err == nil {
+ if _, _, err := s.Restore(999); err == nil {
t.Error("restoring an unknown id should error")
}
}
func TestRestoreGoesToBottom(t *testing.T) {
s := testStore(t)
- a, _ := s.Add("first", task.Do)
+ a, _, _ := s.Add("first", task.Do)
s.Add("second", task.Do)
- if _, err := s.Complete(a.ID); err != nil {
+ if _, _, err := s.Complete(a.ID); err != nil {
t.Fatal(err)
}
s.Add("third", task.Do)
- if _, err := s.Restore(a.ID); err != nil {
+ if _, _, err := s.Restore(a.ID); err != nil {
t.Fatal(err)
}
got := titles(t, s, task.Do)
@@ -102,24 +115,24 @@ func TestRestoreGoesToBottom(t *testing.T) {
func TestReorderWithinQuadrant(t *testing.T) {
s := testStore(t)
s.Add("a", task.Schedule)
- b, _ := s.Add("b", task.Schedule)
- c, _ := s.Add("c", task.Schedule)
+ b, _, _ := s.Add("b", task.Schedule)
+ c, _, _ := s.Add("c", task.Schedule)
- if _, err := s.Reorder(c.ID, -1); err != nil {
+ if _, _, err := s.Reorder(c.ID, -1); err != nil {
t.Fatal(err)
}
if got, want := titles(t, s, task.Schedule), []string{"a", "c", "b"}; !equal(got, want) {
t.Fatalf("after c up: %v, want %v", got, want)
}
- if _, err := s.Reorder(b.ID, ToTop); err != nil {
+ if _, _, err := s.Reorder(b.ID, ToTop); err != nil {
t.Fatal(err)
}
if got, want := titles(t, s, task.Schedule), []string{"b", "a", "c"}; !equal(got, want) {
t.Fatalf("after b to top: %v, want %v", got, want)
}
- if _, err := s.Reorder(b.ID, ToBottom); err != nil {
+ if _, _, err := s.Reorder(b.ID, ToBottom); err != nil {
t.Fatal(err)
}
if got, want := titles(t, s, task.Schedule), []string{"a", "c", "b"}; !equal(got, want) {
@@ -129,11 +142,11 @@ func TestReorderWithinQuadrant(t *testing.T) {
func TestReorderClampsAtEnds(t *testing.T) {
s := testStore(t)
- a, _ := s.Add("a", task.Do)
+ a, _, _ := s.Add("a", task.Do)
s.Add("b", task.Do)
// Already at the top; moving up is a no-op, not an error.
- if _, err := s.Reorder(a.ID, -1); err != nil {
+ if _, _, err := s.Reorder(a.ID, -1); err != nil {
t.Fatal(err)
}
if got, want := titles(t, s, task.Do), []string{"a", "b"}; !equal(got, want) {
@@ -153,10 +166,10 @@ func TestReorderClampsAtEnds(t *testing.T) {
func TestReorderDoesNotLeakAcrossQuadrants(t *testing.T) {
s := testStore(t)
s.Add("do-1", task.Do)
- sched, _ := s.Add("sched-1", task.Schedule)
+ sched, _, _ := s.Add("sched-1", task.Schedule)
s.Add("sched-2", task.Schedule)
- if _, err := s.Reorder(sched.ID, ToBottom); err != nil {
+ if _, _, err := s.Reorder(sched.ID, ToBottom); err != nil {
t.Fatal(err)
}
if got, want := titles(t, s, task.Do), []string{"do-1"}; !equal(got, want) {
@@ -169,15 +182,15 @@ func TestReorderDoesNotLeakAcrossQuadrants(t *testing.T) {
func TestReorderSurvivesManyMoves(t *testing.T) {
s := testStore(t)
- a, _ := s.Add("a", task.Do)
+ a, _, _ := s.Add("a", task.Do)
s.Add("b", task.Do)
// Ranks are rewritten per quadrant, so swapping repeatedly must not drift.
for i := 0; i < 200; i++ {
- if _, err := s.Reorder(a.ID, 1); err != nil {
+ if _, _, err := s.Reorder(a.ID, 1); err != nil {
t.Fatal(err)
}
- if _, err := s.Reorder(a.ID, -1); err != nil {
+ if _, _, err := s.Reorder(a.ID, -1); err != nil {
t.Fatal(err)
}
}
@@ -192,574 +205,6 @@ func TestReorderSurvivesManyMoves(t *testing.T) {
}
}
-func TestQuadrantLabelDefaults(t *testing.T) {
- s := testStore(t)
- labels, err := s.QuadrantLabels()
- if err != nil {
- t.Fatal(err)
- }
- want := map[task.Quadrant]string{
- task.Do: "Do It First",
- task.Schedule: "Schedule It",
- task.Delegate: "Delegate It",
- task.Eliminate: "Consider Eliminating It",
- }
- for q, w := range want {
- if got := labels.Of(q); got != w {
- t.Errorf("quadrant %d label = %q, want %q", q, got, w)
- }
- if labels.IsCustom(q) {
- t.Errorf("quadrant %d reported as custom before any rename", q)
- }
- }
-}
-
-func TestSetQuadrantLabel(t *testing.T) {
- s := testStore(t)
- got, err := s.SetQuadrantLabel(task.Do, "Firefighting")
- if err != nil {
- t.Fatal(err)
- }
- if got != "Firefighting" {
- t.Errorf("SetQuadrantLabel returned %q", got)
- }
-
- labels, err := s.QuadrantLabels()
- if err != nil {
- t.Fatal(err)
- }
- if labels.Of(task.Do) != "Firefighting" {
- t.Errorf("label = %q, want Firefighting", labels.Of(task.Do))
- }
- if !labels.IsCustom(task.Do) {
- t.Error("renamed quadrant should report as custom")
- }
- // Renaming one quadrant must not disturb the others.
- if labels.Of(task.Schedule) != "Schedule It" {
- t.Errorf("Schedule label = %q, want the default", labels.Of(task.Schedule))
- }
-}
-
-func TestSetQuadrantLabelResetsOnBlank(t *testing.T) {
- s := testStore(t)
- if _, err := s.SetQuadrantLabel(task.Eliminate, "Junk"); err != nil {
- t.Fatal(err)
- }
- got, err := s.SetQuadrantLabel(task.Eliminate, " ")
- if err != nil {
- t.Fatal(err)
- }
- if got != "Consider Eliminating It" {
- t.Errorf("reset returned %q, want the default", got)
- }
- d, err := s.Load()
- if err != nil {
- t.Fatal(err)
- }
- // The override is removed, not stored as an empty string.
- if _, ok := d.Labels[task.Eliminate]; ok {
- t.Error("reset should delete the override, not blank it")
- }
-}
-
-func TestSetQuadrantLabelValidates(t *testing.T) {
- s := testStore(t)
- if _, err := s.SetQuadrantLabel(9, "Nope"); err == nil {
- t.Error("invalid quadrant should error")
- }
- long := strings.Repeat("x", task.MaxLabelLen+1)
- if _, err := s.SetQuadrantLabel(task.Do, long); err == nil {
- t.Error("over-long label should error")
- }
- labels, _ := s.QuadrantLabels()
- if labels.Of(task.Do) != "Do It First" {
- t.Errorf("failed rename changed the label to %q", labels.Of(task.Do))
- }
-}
-
-func TestQuadrantLabelIsUndoable(t *testing.T) {
- s := testStore(t)
- if _, err := s.SetQuadrantLabel(task.Delegate, "Hand Off"); err != nil {
- t.Fatal(err)
- }
- label, err := s.Undo()
- if err != nil {
- t.Fatal(err)
- }
- if !strings.Contains(label, "Hand Off") {
- t.Errorf("undo label = %q, want it to name the rename", label)
- }
- labels, _ := s.QuadrantLabels()
- if labels.Of(task.Delegate) != "Delegate It" {
- t.Errorf("after undo, label = %q, want the default back", labels.Of(task.Delegate))
- }
-
- if _, err := s.Redo(); err != nil {
- t.Fatal(err)
- }
- labels, _ = s.QuadrantLabels()
- if labels.Of(task.Delegate) != "Hand Off" {
- t.Errorf("after redo, label = %q, want Hand Off", labels.Of(task.Delegate))
- }
-}
-
-func TestUndoOfTaskChangeLeavesLabelsAlone(t *testing.T) {
- s := testStore(t)
- if _, err := s.SetQuadrantLabel(task.Do, "Firefighting"); err != nil {
- t.Fatal(err)
- }
- a, _ := s.Add("something", task.Do)
- if _, err := s.Delete(a.ID); err != nil {
- t.Fatal(err)
- }
- // Undoing the delete must not roll the rename back with it.
- if _, err := s.Undo(); err != nil {
- t.Fatal(err)
- }
- labels, _ := s.QuadrantLabels()
- if labels.Of(task.Do) != "Firefighting" {
- t.Errorf("label = %q, want the rename to survive an unrelated undo", labels.Of(task.Do))
- }
-}
-
-func TestSetSameLabelIsANoOp(t *testing.T) {
- s := testStore(t)
- s.Add("anchor", task.Do)
- if _, err := s.SetQuadrantLabel(task.Do, "Do It First"); err != nil {
- t.Fatal(err)
- }
- d, err := s.Load()
- if err != nil {
- t.Fatal(err)
- }
- if UndoLabel(d) != `add "anchor"` {
- t.Errorf("undo top = %q; setting the label it already has should not record", UndoLabel(d))
- }
-}
-
-func TestMCPDisabledByDefault(t *testing.T) {
- s := testStore(t)
- on, err := s.MCPEnabled()
- if err != nil {
- t.Fatal(err)
- }
- if on {
- t.Error("a fresh matrix should have MCP access off")
- }
- // Adding tasks must not switch it on by side effect.
- s.Add("a task", task.Do)
- if on, _ := s.MCPEnabled(); on {
- t.Error("MCP access turned on by an unrelated write")
- }
-}
-
-func TestMCPEnabledPersists(t *testing.T) {
- dir := t.TempDir()
- p := filepath.Join(dir, "tasks.json")
-
- changed, err := OpenAt(p).SetMCPEnabled(true)
- if err != nil {
- t.Fatal(err)
- }
- if !changed {
- t.Error("enabling from the default should report a change")
- }
- // A separate Store instance, as a later process would see it.
- if on, _ := OpenAt(p).MCPEnabled(); !on {
- t.Error("setting did not survive a reload")
- }
-
- changed, err = OpenAt(p).SetMCPEnabled(true)
- if err != nil {
- t.Fatal(err)
- }
- if changed {
- t.Error("enabling twice should report no change")
- }
-
- if _, err := OpenAt(p).SetMCPEnabled(false); err != nil {
- t.Fatal(err)
- }
- if on, _ := OpenAt(p).MCPEnabled(); on {
- t.Error("disable did not stick")
- }
-}
-
-func TestMCPSettingIsNotUndoable(t *testing.T) {
- s := testStore(t)
- s.Add("a task", task.Do)
- if _, err := s.SetMCPEnabled(true); err != nil {
- t.Fatal(err)
- }
-
- // Undo must reach past the permission change to the task change, and must
- // not restore the old permission on the way.
- label, err := s.Undo()
- if err != nil {
- t.Fatal(err)
- }
- if label != `add "a task"` {
- t.Errorf("undo label = %q; the MCP setting should not occupy an undo slot", label)
- }
- if on, _ := s.MCPEnabled(); !on {
- t.Error("undo switched MCP access back off")
- }
-}
-
-func TestUndoCannotReopenRevokedAccess(t *testing.T) {
- s := testStore(t)
- if _, err := s.SetMCPEnabled(true); err != nil {
- t.Fatal(err)
- }
- s.Add("a task", task.Do)
- if _, err := s.SetMCPEnabled(false); err != nil {
- t.Fatal(err)
- }
-
- // No amount of undo or redo may hand access back.
- for i := 0; i < 5; i++ {
- if _, err := s.Undo(); err != nil {
- break
- }
- if on, _ := s.MCPEnabled(); on {
- t.Fatalf("undo %d re-enabled revoked MCP access", i)
- }
- }
- for i := 0; i < 5; i++ {
- if _, err := s.Redo(); err != nil {
- break
- }
- if on, _ := s.MCPEnabled(); on {
- t.Fatalf("redo %d re-enabled revoked MCP access", i)
- }
- }
-}
-
-func TestUndoRestoresPreviousState(t *testing.T) {
- s := testStore(t)
- a, _ := s.Add("keep me", task.Do)
-
- if _, err := s.Complete(a.ID); err != nil {
- t.Fatal(err)
- }
- label, err := s.Undo()
- if err != nil {
- t.Fatal(err)
- }
- if label != `complete "keep me"` {
- t.Errorf("label = %q, want the complete label", label)
- }
- d, _ := s.Load()
- if len(d.Tasks) != 1 || len(d.Archive) != 0 {
- t.Fatalf("after undo: %d active, %d archived; want 1 and 0", len(d.Tasks), len(d.Archive))
- }
-
- // Undo the add itself.
- if _, err := s.Undo(); err != nil {
- t.Fatal(err)
- }
- d, _ = s.Load()
- if len(d.Tasks) != 0 {
- t.Errorf("after second undo: %d active, want 0", len(d.Tasks))
- }
-}
-
-func TestUndoOfDeleteBringsTaskBack(t *testing.T) {
- s := testStore(t)
- a, _ := s.Add("oops", task.Do)
- if _, err := s.Delete(a.ID); err != nil {
- t.Fatal(err)
- }
- if _, err := s.Undo(); err != nil {
- t.Fatal(err)
- }
- got := titles(t, s, task.Do)
- if !equal(got, []string{"oops"}) {
- t.Errorf("after undoing delete: %v, want [oops]", got)
- }
-}
-
-func TestUndoDoesNotReuseIDs(t *testing.T) {
- s := testStore(t)
- a, _ := s.Add("first", task.Do)
- if _, err := s.Undo(); err != nil { // undo the add
- t.Fatal(err)
- }
- b, err := s.Add("second", task.Do)
- if err != nil {
- t.Fatal(err)
- }
- if b.ID == a.ID {
- t.Errorf("ID %d was reused after undo; IDs must stay monotonic", b.ID)
- }
-}
-
-func TestUndoEmptyStack(t *testing.T) {
- s := testStore(t)
- if _, err := s.Undo(); err == nil {
- t.Error("undo with nothing to undo should error")
- }
-}
-
-func TestRepeatedUndoWalksBack(t *testing.T) {
- s := testStore(t)
- s.Add("a", task.Do)
- s.Add("b", task.Do)
- if _, err := s.Undo(); err != nil { // undoes add "b"
- t.Fatal(err)
- }
- label, err := s.Undo() // must undo add "a", not re-apply add "b"
- if err != nil {
- t.Fatal(err)
- }
- if label != `add "a"` {
- t.Errorf("second undo label = %q, want `add \"a\"`", label)
- }
- if got := titles(t, s, task.Do); len(got) != 0 {
- t.Errorf("after two undos: %v, want nothing", got)
- }
-}
-
-func TestRedoReappliesUndoneChange(t *testing.T) {
- s := testStore(t)
- a, _ := s.Add("ship it", task.Do)
- if _, err := s.Complete(a.ID); err != nil {
- t.Fatal(err)
- }
- if _, err := s.Undo(); err != nil {
- t.Fatal(err)
- }
- if arch, _ := s.ListArchive(); len(arch) != 0 {
- t.Fatal("undo should have un-archived the task")
- }
-
- label, err := s.Redo()
- if err != nil {
- t.Fatal(err)
- }
- if label != `complete "ship it"` {
- t.Errorf("redo label = %q, want the complete label", label)
- }
- active, _ := s.List(0)
- arch, _ := s.ListArchive()
- if len(active) != 0 || len(arch) != 1 {
- t.Errorf("after redo: active=%d archive=%d, want 0/1", len(active), len(arch))
- }
-}
-
-func TestRedoRoundTripIsExact(t *testing.T) {
- s := testStore(t)
- s.Add("a", task.Do)
- b, _ := s.Add("b", task.Do)
- s.Add("c", task.Do)
- if _, err := s.Reorder(b.ID, ToTop); err != nil {
- t.Fatal(err)
- }
- want := titles(t, s, task.Do)
-
- if _, err := s.Undo(); err != nil {
- t.Fatal(err)
- }
- if got := titles(t, s, task.Do); equal(got, want) {
- t.Fatal("undo did not change the order")
- }
- if _, err := s.Redo(); err != nil {
- t.Fatal(err)
- }
- if got := titles(t, s, task.Do); !equal(got, want) {
- t.Errorf("after undo+redo: %v, want %v (ordering must survive the round trip)", got, want)
- }
-}
-
-func TestNewChangeDiscardsRedo(t *testing.T) {
- s := testStore(t)
- a, _ := s.Add("first", task.Do)
- if _, err := s.Complete(a.ID); err != nil {
- t.Fatal(err)
- }
- if _, err := s.Undo(); err != nil {
- t.Fatal(err)
- }
-
- // Diverging from the undone branch must strand it: redoing the complete
- // here would clobber the task added below.
- if _, err := s.Add("second", task.Do); err != nil {
- t.Fatal(err)
- }
- d, err := s.Load()
- if err != nil {
- t.Fatal(err)
- }
- if len(d.Redo) != 0 {
- t.Errorf("redo stack = %d entries, want 0 after a new change", len(d.Redo))
- }
- if _, err := s.Redo(); err == nil {
- t.Error("redo after a diverging change should error")
- }
- if got, want := titles(t, s, task.Do), []string{"first", "second"}; !equal(got, want) {
- t.Errorf("tasks = %v, want %v", got, want)
- }
-}
-
-func TestRedoAcrossFrontendsIsDiscardedToo(t *testing.T) {
- dir := t.TempDir()
- p := filepath.Join(dir, "tasks.json")
-
- a, err := OpenAt(p).Add("mine", task.Do)
- if err != nil {
- t.Fatal(err)
- }
- if _, err := OpenAt(p).Delete(a.ID); err != nil {
- t.Fatal(err)
- }
- if _, err := OpenAt(p).Undo(); err != nil {
- t.Fatal(err)
- }
- // A different "process" (CLI or MCP agent) writes.
- if _, err := OpenAt(p).Add("theirs", task.Schedule); err != nil {
- t.Fatal(err)
- }
- if _, err := OpenAt(p).Redo(); err == nil {
- t.Error("a write from another frontend should invalidate redo")
- }
-}
-
-func TestRedoMultipleSteps(t *testing.T) {
- s := testStore(t)
- s.Add("a", task.Do)
- s.Add("b", task.Do)
- s.Add("c", task.Do)
-
- for i := 0; i < 3; i++ {
- if _, err := s.Undo(); err != nil {
- t.Fatalf("undo %d: %v", i, err)
- }
- }
- if got := titles(t, s, task.Do); len(got) != 0 {
- t.Fatalf("after three undos: %v, want nothing", got)
- }
-
- // Redo must walk forward the same distance. This is what breaks if Redo
- // clears the redo stack via pushUndo.
- for i := 0; i < 3; i++ {
- if _, err := s.Redo(); err != nil {
- t.Fatalf("redo %d: %v", i, err)
- }
- }
- if got, want := titles(t, s, task.Do), []string{"a", "b", "c"}; !equal(got, want) {
- t.Errorf("after three redos: %v, want %v", got, want)
- }
- if _, err := s.Redo(); err == nil {
- t.Error("a fourth redo should error")
- }
-}
-
-func TestRedoIsUndoable(t *testing.T) {
- s := testStore(t)
- a, _ := s.Add("wobble", task.Do)
- s.Delete(a.ID)
- s.Undo() // task is back
- if _, err := s.Redo(); err != nil {
- t.Fatal(err)
- }
- if got := titles(t, s, task.Do); len(got) != 0 {
- t.Fatalf("redo should have re-deleted: %v", got)
- }
- if _, err := s.Undo(); err != nil {
- t.Fatal(err)
- }
- if got, want := titles(t, s, task.Do), []string{"wobble"}; !equal(got, want) {
- t.Errorf("undo after redo = %v, want %v", got, want)
- }
-}
-
-func TestRedoEmptyStack(t *testing.T) {
- s := testStore(t)
- s.Add("a", task.Do)
- if _, err := s.Redo(); err == nil {
- t.Error("redo with nothing undone should error")
- }
-}
-
-func TestRedoStackIsCapped(t *testing.T) {
- s := testStore(t)
- for i := 0; i < undoDepth+5; i++ {
- if _, err := s.Add("t", task.Do); err != nil {
- t.Fatal(err)
- }
- }
- for i := 0; i < undoDepth; i++ {
- if _, err := s.Undo(); err != nil {
- t.Fatalf("undo %d: %v", i, err)
- }
- }
- d, err := s.Load()
- if err != nil {
- t.Fatal(err)
- }
- if len(d.Redo) != undoDepth {
- t.Errorf("redo stack depth = %d, want %d", len(d.Redo), undoDepth)
- }
-}
-
-func TestUndoStackIsCapped(t *testing.T) {
- s := testStore(t)
- for i := 0; i < undoDepth+15; i++ {
- if _, err := s.Add("t", task.Do); err != nil {
- t.Fatal(err)
- }
- }
- d, err := s.Load()
- if err != nil {
- t.Fatal(err)
- }
- if len(d.Undo) != undoDepth {
- t.Errorf("undo stack depth = %d, want %d", len(d.Undo), undoDepth)
- }
-}
-
-func TestUndoSurvivesReload(t *testing.T) {
- dir := t.TempDir()
- p := filepath.Join(dir, "tasks.json")
-
- // One "process" makes a change...
- a, err := OpenAt(p).Add("cross-process", task.Do)
- if err != nil {
- t.Fatal(err)
- }
- if _, err := OpenAt(p).Complete(a.ID); err != nil {
- t.Fatal(err)
- }
- // ...and another undoes it.
- label, err := OpenAt(p).Undo()
- if err != nil {
- t.Fatal(err)
- }
- if label != `complete "cross-process"` {
- t.Errorf("label = %q", label)
- }
- d, _ := OpenAt(p).Load()
- if len(d.Tasks) != 1 {
- t.Errorf("undo across processes left %d active tasks, want 1", len(d.Tasks))
- }
-}
-
-func TestFailedMutationDoesNotRecordUndo(t *testing.T) {
- s := testStore(t)
- a, _ := s.Add("valid", task.Do)
- if _, err := s.Rename(a.ID, " "); err == nil {
- t.Fatal("rename to blank should fail")
- }
- d, err := s.Load()
- if err != nil {
- t.Fatal(err)
- }
- if len(d.Undo) != 1 || UndoLabel(d) != `add "valid"` {
- t.Errorf("undo stack = %d entries, top %q; a failed rename should not record",
- len(d.Undo), UndoLabel(d))
- }
-}
-
func TestUpgradesVersionOneFile(t *testing.T) {
p := filepath.Join(t.TempDir(), "tasks.json")
// A version-1 file: no ranks, no undo stack.
@@ -784,7 +229,7 @@ func TestUpgradesVersionOneFile(t *testing.T) {
}
// Reordering works immediately, and the write persists version 2 + ranks.
- if _, err := s.Reorder(3, ToTop); err != nil {
+ if _, _, err := s.Reorder(3, ToTop); err != nil {
t.Fatal(err)
}
if got, want := titles(t, s, task.Do), []string{"third", "first", "second"}; !equal(got, want) {
@@ -808,126 +253,71 @@ func TestUpgradesVersionOneFile(t *testing.T) {
// through, so it sanitizes. SetQuadrantLabel rejects control characters on the
// way in; this covers a label that reached the file some other way — an older
// build, a hand edit, or a synced copy.
-func TestLabelsOfSanitizesUntrustedFile(t *testing.T) {
- l := Labels{task.Do: "red\x1b[31m", task.Schedule: "two\nlines"}
- got := l.Of(task.Do)
- if strings.ContainsRune(got, 0x1b) {
- t.Errorf("Of(Do) = %q, still contains an escape", got)
- }
- if !strings.Contains(got, "red") {
- t.Errorf("Of(Do) = %q, dropped visible text", got)
- }
- if got := l.Of(task.Schedule); strings.ContainsRune(got, '\n') {
- t.Errorf("Of(Schedule) = %q, still contains a newline", got)
- }
- // An unrenamed quadrant still falls back to its default.
- if got, want := l.Of(task.Delegate), task.Delegate.Label(); got != want {
- t.Errorf("Of(Delegate) = %q, want the default %q", got, want)
+// Archive order is defined once, in Data.ListArchive, and both `ike archive`
+// and the TUI's archive view render it. The TUI used to reverse the stored
+// slice instead, which agrees only while every archived task carries a
+// completion stamp — a file written by an older build, or hand-edited, need
+// not. This pins the definition that both now share.
+func TestListArchiveOrdersUnstampedTasksByID(t *testing.T) {
+ done := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
+ d := Data{Archive: []task.Task{
+ {ID: 1, Title: "no stamp, low id"},
+ {ID: 3, Title: "stamped", DoneAt: &done},
+ {ID: 2, Title: "no stamp, high id"},
+ }}
+
+ var got []int
+ for _, t := range d.ListArchive() {
+ got = append(got, t.ID)
}
- // The stored label itself is untouched; only the rendered form changes.
- if l[task.Do] != "red\x1b[31m" {
- t.Error("Of must not rewrite the stored label")
+ // Descending by ID wherever a completion time is missing, newest first
+ // where it is present — never the raw slice order.
+ want := []int{3, 2, 1}
+ if !slices.Equal(got, want) {
+ t.Errorf("ListArchive order = %v, want %v", got, want)
}
}
-// The gate used to be checked once, before serving. A client that stayed
-// connected therefore kept full access after `ike mcp disable`, while
-// `ike mcp status` reported "off". These pin the data-layer check that closed
-// that window.
-func TestMCPGateRevokesLiveSession(t *testing.T) {
- s := testStore(t)
- if _, err := s.SetMCPEnabled(true); err != nil {
- t.Fatal(err)
- }
+// The store's own listing and the pure form over the same data must agree,
+// since the frontends split between them.
- // The session a connected client holds.
- live := s.ForMCP()
- if _, err := live.Add("while enabled", task.Do); err != nil {
- t.Fatalf("Add with access on: %v", err)
- }
- if _, err := live.Load(); err != nil {
- t.Fatalf("Load with access on: %v", err)
+// The store's own listing and the pure form over the same data must agree,
+// since the frontends split between them.
+func TestStoreListMatchesDataList(t *testing.T) {
+ s := testStore(t)
+ for _, title := range []string{"a", "b", "c"} {
+ if _, _, err := s.Add(title, task.Schedule); err != nil {
+ t.Fatal(err)
+ }
}
-
- // Revoked from another process, on the same file, mid-session.
- if _, err := s.SetMCPEnabled(false); err != nil {
+ if _, _, err := s.Add("urgent", task.Do); err != nil {
t.Fatal(err)
}
- if _, err := live.Add("after revoke", task.Do); !errors.Is(err, ErrMCPDisabled) {
- t.Errorf("Add after revoke: err = %v, want ErrMCPDisabled", err)
- }
- if _, err := live.Load(); !errors.Is(err, ErrMCPDisabled) {
- t.Errorf("Load after revoke: err = %v, want ErrMCPDisabled", err)
- }
- if _, err := live.Complete(1); !errors.Is(err, ErrMCPDisabled) {
- t.Errorf("Complete after revoke: err = %v, want ErrMCPDisabled", err)
- }
- if _, err := live.Delete(1); !errors.Is(err, ErrMCPDisabled) {
- t.Errorf("Delete after revoke: err = %v, want ErrMCPDisabled", err)
- }
- if _, err := live.Undo(); !errors.Is(err, ErrMCPDisabled) {
- t.Errorf("Undo after revoke: err = %v, want ErrMCPDisabled", err)
- }
-
- // The revoked mutations must not have landed, and the owner's own access is
- // unaffected — that is what `ike mcp status` and the TUI keep using.
d, err := s.Load()
if err != nil {
t.Fatal(err)
}
- if len(d.Tasks) != 1 || d.Tasks[0].Title != "while enabled" {
- t.Errorf("tasks = %+v, want only the pre-revoke task", d.Tasks)
- }
-
- // Re-enabling restores the same session, without reconnecting.
- if _, err := s.SetMCPEnabled(true); err != nil {
- t.Fatal(err)
- }
- if _, err := live.Load(); err != nil {
- t.Errorf("Load after re-enable: %v", err)
- }
-}
-
-// A store that was never marked for MCP use is unaffected by the setting, so
-// the TUI and CLI keep working while agent access is off.
-func TestGateDoesNotAffectOwnerAccess(t *testing.T) {
- s := testStore(t)
- if enabled, err := s.MCPEnabled(); err != nil || enabled {
- t.Fatalf("MCPEnabled() = %v, %v; want false, nil", enabled, err)
- }
- if _, err := s.Add("owner task", task.Do); err != nil {
- t.Errorf("owner Add with MCP off: %v", err)
- }
- if _, err := s.Load(); err != nil {
- t.Errorf("owner Load with MCP off: %v", err)
+ for _, q := range []task.Quadrant{0, task.Do, task.Schedule} {
+ viaStore, err := s.List(q)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(titlesOf(viaStore), titlesOf(d.List(q))) {
+ t.Errorf("quadrant %d: Store.List = %v, Data.List = %v",
+ q, titlesOf(viaStore), titlesOf(d.List(q)))
+ }
}
}
-func TestMCPErrorsOmitDataFilePath(t *testing.T) {
- dir := t.TempDir()
- path := filepath.Join(dir, "tasks.json")
- if err := os.WriteFile(path, []byte("{ not json"), 0o600); err != nil {
- t.Fatal(err)
+// An empty archive must marshal as [] rather than null: `ike archive --json`
+// is a machine interface, and a nil slice would change its shape.
+func TestListArchiveIsNeverNil(t *testing.T) {
+ if got := (Data{}).ListArchive(); got == nil {
+ t.Error("ListArchive() on an empty archive returned nil, want an empty slice")
}
- gated := OpenAt(path).ForMCP()
-
- _, err := gated.Load()
- if err == nil {
- t.Fatal("expected a parse error")
- }
- if strings.Contains(err.Error(), dir) {
- t.Errorf("error discloses the data file's directory to the agent: %v", err)
- }
- // The file name still appears, so the message stays actionable.
- if !strings.Contains(err.Error(), "tasks.json") {
- t.Errorf("error should still name the file: %v", err)
- }
-
- // The owner's view keeps the full path, which is what makes a CLI error
- // useful.
- if _, err := OpenAt(path).Load(); err == nil || !strings.Contains(err.Error(), dir) {
- t.Errorf("ungated error should keep the full path: %v", err)
+ if got := (Data{}).List(task.Do); got == nil {
+ t.Error("List() with no tasks returned nil, want an empty slice")
}
}
diff --git a/internal/store/store_test.go b/internal/store/store_test.go
index d7360ae..3f50272 100644
--- a/internal/store/store_test.go
+++ b/internal/store/store_test.go
@@ -18,14 +18,14 @@ func testStore(t *testing.T) *Store {
func TestAddListRoundTrip(t *testing.T) {
s := testStore(t)
- a, err := s.Add("fix prod bug", task.Do)
+ a, _, err := s.Add("fix prod bug", task.Do)
if err != nil {
t.Fatal(err)
}
if a.ID != 1 {
t.Errorf("first ID = %d, want 1", a.ID)
}
- b, err := s.Add("plan roadmap", task.Schedule)
+ b, _, err := s.Add("plan roadmap", task.Schedule)
if err != nil {
t.Fatal(err)
}
@@ -51,20 +51,20 @@ func TestAddListRoundTrip(t *testing.T) {
func TestAddValidates(t *testing.T) {
s := testStore(t)
- if _, err := s.Add(" ", task.Do); err == nil {
+ if _, _, err := s.Add(" ", task.Do); err == nil {
t.Error("Add with blank title should fail")
}
- if _, err := s.Add("x", 9); err == nil {
+ if _, _, err := s.Add("x", 9); err == nil {
t.Error("Add with bad quadrant should fail")
}
}
func TestCompleteMovesToArchiveAndKeepsID(t *testing.T) {
s := testStore(t)
- a, _ := s.Add("one", task.Do)
+ a, _, _ := s.Add("one", task.Do)
s.Add("two", task.Do)
- done, err := s.Complete(a.ID)
+ done, _, err := s.Complete(a.ID)
if err != nil {
t.Fatal(err)
}
@@ -82,37 +82,37 @@ func TestCompleteMovesToArchiveAndKeepsID(t *testing.T) {
}
// IDs are never reused, even after completion.
- c, _ := s.Add("three", task.Do)
+ c, _, _ := s.Add("three", task.Do)
if c.ID != 3 {
t.Errorf("ID after completion = %d, want 3", c.ID)
}
- if _, err := s.Complete(a.ID); err == nil {
+ if _, _, err := s.Complete(a.ID); err == nil {
t.Error("completing an archived task should fail")
}
}
func TestMoveRenameDelete(t *testing.T) {
s := testStore(t)
- a, _ := s.Add("one", task.Do)
+ a, _, _ := s.Add("one", task.Do)
- m, err := s.Move(a.ID, task.Eliminate)
+ m, _, err := s.Move(a.ID, task.Eliminate)
if err != nil || m.Quadrant != task.Eliminate {
t.Errorf("Move = %+v, %v", m, err)
}
- if _, err := s.Move(a.ID, 7); err == nil {
+ if _, _, err := s.Move(a.ID, 7); err == nil {
t.Error("Move to invalid quadrant should fail")
}
- r, err := s.Rename(a.ID, "renamed")
+ r, _, err := s.Rename(a.ID, "renamed")
if err != nil || r.Title != "renamed" {
t.Errorf("Rename = %+v, %v", r, err)
}
- if _, err := s.Rename(a.ID, ""); err == nil {
+ if _, _, err := s.Rename(a.ID, ""); err == nil {
t.Error("Rename to empty should fail")
}
- if _, err := s.Delete(a.ID); err != nil {
+ if _, _, err := s.Delete(a.ID); err != nil {
t.Fatal(err)
}
active, _ := s.List(0)
@@ -120,7 +120,7 @@ func TestMoveRenameDelete(t *testing.T) {
if len(active) != 0 || len(arch) != 0 {
t.Error("Delete should remove permanently, not archive")
}
- if _, err := s.Delete(a.ID); err == nil {
+ if _, _, err := s.Delete(a.ID); err == nil {
t.Error("deleting a missing task should fail")
}
}
@@ -152,7 +152,7 @@ func TestCorruptAndWrongVersion(t *testing.T) {
// A mutation must not clobber a corrupt file either.
os.WriteFile(p, []byte("{not json"), 0o644)
- if _, err := OpenAt(p).Add("x", task.Do); err == nil {
+ if _, _, err := OpenAt(p).Add("x", task.Do); err == nil {
t.Error("Add over corrupt file should error")
}
}
@@ -171,7 +171,7 @@ func TestConcurrentWriters(t *testing.T) {
defer wg.Done()
s := OpenAt(p) // separate Store instances, like separate processes
for i := 0; i < perWriter; i++ {
- if _, err := s.Add("t", task.Do); err != nil {
+ if _, _, err := s.Add("t", task.Do); err != nil {
t.Error(err)
return
}
diff --git a/internal/task/task.go b/internal/task/task.go
index 03ad77e..0e0de61 100644
--- a/internal/task/task.go
+++ b/internal/task/task.go
@@ -118,6 +118,22 @@ type Task struct {
// encoding/json escapes control characters itself.
func (t Task) DisplayTitle() string { return SanitizeDisplay(t.Title) }
+// ArchiveDate is the local completion date, or "" for a task carrying no
+// completion stamp — reachable from a hand-edited or pre-archive data file.
+func (t Task) ArchiveDate() string {
+ if t.DoneAt == nil {
+ return ""
+ }
+ return t.DoneAt.Local().Format(time.DateOnly)
+}
+
+// ArchiveRow formats one line of an archive listing. `ike archive` and the
+// TUI's archive view both render through it, so the two cannot drift apart;
+// title is passed in because only the TUI truncates it to the pane width.
+func (t Task) ArchiveRow(title string) string {
+ return fmt.Sprintf(" %3d %s %s", t.ID, t.ArchiveDate(), title)
+}
+
// Less reports whether a sorts before b in display order: by quadrant, then
// by rank within the quadrant, then by ID. Rank is assigned by the store; a
// zero rank means "not ranked yet" and falls back to ID order.
diff --git a/internal/task/task_test.go b/internal/task/task_test.go
index 909fdeb..8389e50 100644
--- a/internal/task/task_test.go
+++ b/internal/task/task_test.go
@@ -3,6 +3,7 @@ package task
import (
"strings"
"testing"
+ "time"
)
func TestQuadrantValid(t *testing.T) {
@@ -157,3 +158,59 @@ func TestDisplayTitleNeutralizesUntrustedFile(t *testing.T) {
t.Errorf("DisplayTitle() = %q, dropped visible text", got)
}
}
+
+func TestArchiveDate(t *testing.T) {
+ when := time.Date(2026, 3, 4, 12, 0, 0, 0, time.UTC)
+ got := Task{ID: 1, DoneAt: &when}.ArchiveDate()
+ if want := when.Local().Format("2006-01-02"); got != want {
+ t.Errorf("ArchiveDate() = %q, want %q", got, want)
+ }
+ // A task with no completion stamp — reachable from a hand-edited or
+ // pre-archive file — renders a blank date rather than a zero-time one.
+ if got := (Task{ID: 1}).ArchiveDate(); got != "" {
+ t.Errorf("ArchiveDate() with no stamp = %q, want empty", got)
+ }
+}
+
+// ArchiveRow is the single definition of an archive line, rendered by both
+// `ike archive` and the TUI's archive view.
+func TestArchiveRow(t *testing.T) {
+ when := time.Date(2026, 3, 4, 12, 0, 0, 0, time.UTC)
+ tk := Task{ID: 7, Title: "ship it", DoneAt: &when}
+
+ got := tk.ArchiveRow(tk.DisplayTitle())
+ want := " 7 " + tk.ArchiveDate() + " ship it"
+ if got != want {
+ t.Errorf("ArchiveRow() = %q, want %q", got, want)
+ }
+ // The title is supplied, so the TUI can pass a width-truncated one.
+ if got := tk.ArchiveRow("ship…"); !strings.HasSuffix(got, "ship…") {
+ t.Errorf("ArchiveRow() should render the title it is given: %q", got)
+ }
+}
+
+func TestLessAndSortOrder(t *testing.T) {
+ ts := []Task{
+ {ID: 4, Quadrant: Schedule, Rank: 1024},
+ {ID: 1, Quadrant: Do, Rank: 2048},
+ {ID: 2, Quadrant: Do, Rank: 1024},
+ {ID: 3, Quadrant: Do}, // unranked: sorts by ID, after ranked peers
+ }
+ SortOrder(ts)
+
+ var got []int
+ for _, t := range ts {
+ got = append(got, t.ID)
+ }
+ // Quadrant first, then rank, then ID. Rank 0 sorts ahead of any real rank,
+ // which is why normalizeRanks backfills it on every read.
+ want := []int{3, 2, 1, 4}
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("SortOrder = %v, want %v", got, want)
+ }
+ }
+ if Less(ts[0], ts[0]) {
+ t.Error("Less must be irreflexive")
+ }
+}
diff --git a/internal/tui/model.go b/internal/tui/model.go
index aeb5c1a..8e2fbe2 100644
--- a/internal/tui/model.go
+++ b/internal/tui/model.go
@@ -3,7 +3,6 @@ package tui
import (
"fmt"
- "slices"
"time"
"charm.land/bubbles/v2/key"
@@ -95,29 +94,9 @@ func tick() tea.Cmd {
return tea.Tick(refreshInterval, func(t time.Time) tea.Msg { return tickMsg(t) })
}
-// tasksIn returns the active tasks of quadrant q in display order.
-func (m Model) tasksIn(q task.Quadrant) []task.Task {
- var out []task.Task
- for _, t := range m.data.Tasks {
- if t.Quadrant == q {
- out = append(out, t)
- }
- }
- task.SortOrder(out)
- return out
-}
-
-// archiveList returns the archive newest-completion-first — the order the
-// archive view renders and archCursor indexes into.
-func (m Model) archiveList() []task.Task {
- arch := slices.Clone(m.data.Archive)
- slices.Reverse(arch)
- return arch
-}
-
// selected returns the task under the cursor, if any.
func (m Model) selected() (task.Task, bool) {
- tasks := m.tasksIn(m.focus)
+ tasks := m.data.List(m.focus)
i := m.cursor[m.focus]
if i < 0 || i >= len(tasks) {
return task.Task{}, false
@@ -127,7 +106,7 @@ func (m Model) selected() (task.Task, bool) {
func (m *Model) clampCursors() {
for q := task.Do; q <= task.Eliminate; q++ {
- n := len(m.tasksIn(q))
+ n := len(m.data.List(q))
if m.cursor[q] >= n {
m.cursor[q] = n - 1
}
@@ -135,6 +114,8 @@ func (m *Model) clampCursors() {
m.cursor[q] = 0
}
}
+ // A count, not an index: ListArchive is a permutation of Archive, so the
+ // lengths agree. Anything that *indexes* must go through ListArchive.
if n := len(m.data.Archive); m.archCursor >= n {
m.archCursor = max(n-1, 0)
}
@@ -149,21 +130,27 @@ func (m *Model) refresh(d store.Data) {
m.clampCursors()
}
-// mutate runs fn against the store and refreshes, surfacing errors in status.
-func (m *Model) mutate(fn func() (store.Data, error)) {
- d, err := fn()
+// apply takes the two results of a store mutation and re-renders from them,
+// reporting whether it succeeded.
+//
+// Callers use the bool to decide whether to set a success message. Signaling
+// failure through m.status instead was the reason a failed complete, delete, or
+// move used to overwrite its own error with "done: …" and leave the row on
+// screen: there was nothing to check but the status text itself.
+func (m *Model) apply(d store.Data, err error) bool {
if err != nil {
m.status = err.Error()
- return
+ return false
}
m.refresh(d)
+ return true
}
// cursorTo puts the cursor on the task with the given ID, so the selection
// follows a task that moved.
func (m *Model) cursorTo(id int) {
for q := task.Do; q <= task.Eliminate; q++ {
- for i, t := range m.tasksIn(q) {
+ for i, t := range m.data.List(q) {
if t.ID == id {
m.cursor[q] = i
return
@@ -173,19 +160,10 @@ func (m *Model) cursorTo(id int) {
}
// history runs an undo or redo step, reporting what moved in the status line.
-// Either stack being empty surfaces as an ordinary status message via mutate.
-func (m *Model) history(verb string, step func() (string, error)) {
- var label string
- m.status = ""
- m.mutate(func() (store.Data, error) {
- l, err := step()
- if err != nil {
- return store.Data{}, err
- }
- label = l
- return m.store.Load()
- })
- if label != "" {
+// Either stack being empty arrives as an ordinary error and shows as one.
+func (m *Model) history(verb string, step func() (string, store.Data, error)) {
+ label, d, err := step()
+ if m.apply(d, err) {
m.status = fmt.Sprintf("%s %s", verb, label)
}
}
@@ -196,14 +174,10 @@ func (m *Model) reorder(delta int) {
if !ok {
return
}
- m.status = ""
- m.mutate(func() (store.Data, error) {
- if _, err := m.store.Reorder(t.ID, delta); err != nil {
- return store.Data{}, err
- }
- return m.store.Load()
- })
- m.cursorTo(t.ID)
+ if _, d, err := m.store.Reorder(t.ID, delta); m.apply(d, err) {
+ m.status = ""
+ m.cursorTo(t.ID)
+ }
}
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
@@ -251,6 +225,29 @@ func (m Model) handleKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
return m.handleNormalKey(msg)
}
+// enterInput switches to input mode with all four pieces of input state set
+// together. Setting them one at a time across the call sites left the previous
+// session's placeholder visible in the next one.
+func (m *Model) enterInput(editingID int, labelTarget task.Quadrant, value, placeholder string) tea.Cmd {
+ m.mode = modeInput
+ m.editingID = editingID
+ m.labelTarget = labelTarget
+ m.input.SetValue(value)
+ m.input.Placeholder = placeholder
+ m.input.CursorEnd()
+ m.status = ""
+ return m.input.Focus()
+}
+
+// exitInput returns to normal mode and clears the input state, so nothing from
+// this session can leak into the next one.
+func (m *Model) exitInput() {
+ m.mode = modeNormal
+ m.editingID = 0
+ m.labelTarget = 0
+ m.input.Blur()
+}
+
func (m Model) handleNormalKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
// Any key other than a second `d` clears a pending delete.
pending := m.pendingDelete
@@ -273,7 +270,7 @@ func (m Model) handleNormalKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
m.focus = (m.focus+2)%4 + 1
case key.Matches(msg, keys.Down):
- if m.cursor[m.focus] < len(m.tasksIn(m.focus))-1 {
+ if m.cursor[m.focus] < len(m.data.List(m.focus))-1 {
m.cursor[m.focus]++
}
@@ -289,45 +286,22 @@ func (m Model) handleNormalKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
m.reorder(1)
case key.Matches(msg, keys.Add):
- m.mode = modeInput
- m.editingID = 0
- m.labelTarget = 0
- m.input.SetValue("")
- m.input.Placeholder = "task title"
- m.status = ""
- return m, m.input.Focus()
+ return m, m.enterInput(0, 0, "", "task title")
case key.Matches(msg, keys.Edit):
if t, ok := m.selected(); ok {
- m.mode = modeInput
- m.editingID = t.ID
- m.labelTarget = 0
- m.input.SetValue(t.Title)
- m.input.CursorEnd()
- m.status = ""
- return m, m.input.Focus()
+ return m, m.enterInput(t.ID, 0, t.Title, "task title")
}
case key.Matches(msg, keys.Title):
- m.mode = modeInput
- m.editingID = 0
- m.labelTarget = m.focus
- m.input.SetValue(m.data.Labels.Of(m.focus))
- m.input.CursorEnd()
- m.input.Placeholder = "quadrant name (empty resets to the default)"
- m.status = ""
- return m, m.input.Focus()
+ return m, m.enterInput(0, m.focus, m.data.Labels.Of(m.focus),
+ "quadrant name (empty resets to the default)")
case key.Matches(msg, keys.Done):
if t, ok := m.selected(); ok {
- m.mutate(func() (store.Data, error) {
- _, err := m.store.Complete(t.ID)
- if err != nil {
- return store.Data{}, err
- }
- return m.store.Load()
- })
- m.status = fmt.Sprintf("done: %s", t.DisplayTitle())
+ if _, d, err := m.store.Complete(t.ID); m.apply(d, err) {
+ m.status = fmt.Sprintf("done: %s", t.DisplayTitle())
+ }
}
case key.Matches(msg, keys.Move):
@@ -338,18 +312,11 @@ func (m Model) handleNormalKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
case key.Matches(msg, keys.Delete):
if t, ok := m.selected(); ok {
- if pending == t.ID {
- m.mutate(func() (store.Data, error) {
- _, err := m.store.Delete(t.ID)
- if err != nil {
- return store.Data{}, err
- }
- return m.store.Load()
- })
- m.status = fmt.Sprintf("deleted: %s", t.DisplayTitle())
- } else {
+ if pending != t.ID {
m.pendingDelete = t.ID
m.status = fmt.Sprintf("press d again to delete %q", t.DisplayTitle())
+ } else if _, d, err := m.store.Delete(t.ID); m.apply(d, err) {
+ m.status = fmt.Sprintf("deleted: %s", t.DisplayTitle())
}
}
@@ -372,43 +339,35 @@ func (m Model) handleNormalKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
func (m Model) handleInputKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
switch {
case key.Matches(msg, keys.Cancel):
- m.mode = modeNormal
- m.labelTarget = 0
- m.input.Blur()
+ m.exitInput()
return m, nil
case key.Matches(msg, keys.Confirm):
- title := m.input.Value()
- editing := m.editingID
- target := m.labelTarget
- m.status = ""
- m.mutate(func() (store.Data, error) {
- var err error
- switch {
- case target != 0:
- _, err = m.store.SetQuadrantLabel(target, title)
- case editing == 0:
- _, err = m.store.Add(title, m.focus)
- default:
- _, err = m.store.Rename(editing, title)
- }
- if err != nil {
- return store.Data{}, err
- }
- return m.store.Load()
- })
- if m.status == "" {
+ value := m.input.Value()
+ editing, target := m.editingID, m.labelTarget
+
+ var d store.Data
+ var err error
+ switch {
+ case target != 0:
+ _, d, err = m.store.SetQuadrantLabel(target, value)
+ case editing == 0:
+ _, d, err = m.store.Add(value, m.focus)
+ default:
+ _, d, err = m.store.Rename(editing, value)
+ }
+
+ if m.apply(d, err) {
+ m.status = ""
switch {
case target != 0:
m.status = fmt.Sprintf("quadrant %d is now %q", target, m.data.Labels.Of(target))
case editing == 0:
// Move the cursor to the task just added (last in its quadrant).
- m.cursor[m.focus] = max(len(m.tasksIn(m.focus))-1, 0)
+ m.cursor[m.focus] = max(len(m.data.List(m.focus))-1, 0)
}
}
- m.mode = modeNormal
- m.labelTarget = 0
- m.input.Blur()
+ m.exitInput()
return m, nil
}
@@ -423,14 +382,9 @@ func (m Model) handleMoveKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
if key.Matches(msg, keys.Quadrant) {
dest := task.Quadrant(msg.Key().Code - '0')
if t, ok := m.selected(); ok && dest != t.Quadrant {
- m.mutate(func() (store.Data, error) {
- _, err := m.store.Move(t.ID, dest)
- if err != nil {
- return store.Data{}, err
- }
- return m.store.Load()
- })
- m.status = fmt.Sprintf("moved to %d · %s", dest, m.data.Labels.Of(dest))
+ if _, d, err := m.store.Move(t.ID, dest); m.apply(d, err) {
+ m.status = fmt.Sprintf("moved to %d · %s", dest, m.data.Labels.Of(dest))
+ }
}
}
return m, nil
@@ -443,18 +397,12 @@ func (m Model) handleArchiveKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
m.status = ""
case key.Matches(msg, keys.Restore):
- arch := m.archiveList()
+ arch := m.data.ListArchive()
if m.archCursor < len(arch) {
t := arch[m.archCursor]
- m.status = ""
- m.mutate(func() (store.Data, error) {
- if _, err := m.store.Restore(t.ID); err != nil {
- return store.Data{}, err
- }
- return m.store.Load()
- })
- if m.status == "" {
- m.status = fmt.Sprintf("restored %q to %d · %s", t.DisplayTitle(), t.Quadrant, m.data.Labels.Of(t.Quadrant))
+ if _, d, err := m.store.Restore(t.ID); m.apply(d, err) {
+ m.status = fmt.Sprintf("restored %q to %d · %s",
+ t.DisplayTitle(), t.Quadrant, m.data.Labels.Of(t.Quadrant))
}
}
diff --git a/internal/tui/model_test.go b/internal/tui/model_test.go
index 72d7910..1cbcde5 100644
--- a/internal/tui/model_test.go
+++ b/internal/tui/model_test.go
@@ -93,7 +93,7 @@ func TestAddTaskFlow(t *testing.T) {
if len(tasks) != 1 || tasks[0].Title != "plan roadmap" {
t.Errorf("store tasks = %+v, want the added task in Schedule", tasks)
}
- if got := m.tasksIn(task.Schedule); len(got) != 1 {
+ if got := m.data.List(task.Schedule); len(got) != 1 {
t.Errorf("model shows %d tasks in Schedule, want 1", len(got))
}
}
@@ -162,7 +162,7 @@ func TestRenameQuadrant(t *testing.T) {
func TestRenameQuadrantToBlankRestoresDefault(t *testing.T) {
m, s := testModel(t)
- if _, err := s.SetQuadrantLabel(task.Do, "Firefighting"); err != nil {
+ if _, _, err := s.SetQuadrantLabel(task.Do, "Firefighting"); err != nil {
t.Fatal(err)
}
m.refreshFromStore(t)
@@ -226,7 +226,7 @@ func TestAddStillWorksAfterRenaming(t *testing.T) {
func TestQuadrantHeadersAreJustNames(t *testing.T) {
m, s := testModel(t)
- if _, err := s.SetQuadrantLabel(task.Do, "Firefighting"); err != nil {
+ if _, _, err := s.SetQuadrantLabel(task.Do, "Firefighting"); err != nil {
t.Fatal(err)
}
m.refreshFromStore(t)
@@ -374,7 +374,7 @@ func TestUndoKey(t *testing.T) {
if !strings.Contains(m.status, "undid") {
t.Errorf("status = %q, want it to mention the undo", m.status)
}
- if len(m.tasksIn(task.Do)) != 1 {
+ if len(m.data.List(task.Do)) != 1 {
t.Error("model did not re-render the restored task")
}
}
@@ -542,7 +542,7 @@ func TestRefreshPicksUpExternalChanges(t *testing.T) {
s.Add("from elsewhere", task.Do)
next, _ := m.Update(tickMsg{})
m = next.(Model)
- if len(m.tasksIn(task.Do)) != 1 {
+ if len(m.data.List(task.Do)) != 1 {
t.Error("tick did not reload externally-added task")
}
}
@@ -591,7 +591,7 @@ func (m *Model) refreshFromStore(t *testing.T) {
// the screen quietly disagreed with the file.
func TestRefreshTickSurfacesAReadError(t *testing.T) {
m, s := testModel(t)
- if _, err := s.Add("real task", task.Do); err != nil {
+ if _, _, err := s.Add("real task", task.Do); err != nil {
t.Fatal(err)
}
m.refreshFromStore(t)
@@ -632,3 +632,89 @@ func TestRefreshTickSurfacesAReadError(t *testing.T) {
t.Errorf("stale error still shown after recovery:\n%s", got)
}
}
+
+// corrupt makes the next store operation fail, so the tests below can check
+// what the TUI does with a mutation that did not happen.
+func corrupt(t *testing.T, s *store.Store) {
+ t.Helper()
+ if err := os.WriteFile(s.Path(), []byte("{ not json"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// A mutation that fails must not report success. These three used to set their
+// status message unconditionally, overwriting the error that mutate had just
+// written into it — so a failed complete said "done: …" while the task stayed
+// on screen. apply's bool return is what makes the success message conditional.
+func TestFailedMutationsDoNotReportSuccess(t *testing.T) {
+ cases := []struct {
+ name string
+ keys []string
+ wrongly string
+ }{
+ {"complete", []string{"x"}, "done:"},
+ {"delete", []string{"d", "d"}, "deleted:"},
+ {"move", []string{"m", "2"}, "moved to"},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ m, s := testModel(t)
+ if _, _, err := s.Add("ship v2", task.Do); err != nil {
+ t.Fatal(err)
+ }
+ m.refreshFromStore(t)
+ corrupt(t, s)
+
+ m = press(t, m, c.keys...)
+
+ if strings.Contains(m.status, c.wrongly) {
+ t.Errorf("failed %s reported success: %q", c.name, m.status)
+ }
+ if m.status == "" {
+ t.Errorf("failed %s left no error in the status line", c.name)
+ }
+ // The matrix on screen still shows the task, because nothing changed.
+ if got := len(m.data.List(task.Do)); got != 1 {
+ t.Errorf("task count = %d, want 1 — a failed mutation must not alter the view", got)
+ }
+ })
+ }
+}
+
+// Entering input mode sets every piece of input state together. Setting them
+// one field at a time let the quadrant-rename placeholder survive into the next
+// task edit, where it read "quadrant name (empty resets to the default)".
+func TestInputPlaceholderDoesNotLeakBetweenModes(t *testing.T) {
+ m, s := testModel(t)
+ if _, _, err := s.Add("ship v2", task.Do); err != nil {
+ t.Fatal(err)
+ }
+ m.refreshFromStore(t)
+
+ m = press(t, m, "t") // rename the quadrant
+ m = press(t, m, "esc") // cancel
+ m = press(t, m, "e") // now edit a task title
+
+ if strings.Contains(m.input.Placeholder, "quadrant") {
+ t.Errorf("quadrant placeholder leaked into the task edit: %q", m.input.Placeholder)
+ }
+ if m.labelTarget != 0 {
+ t.Errorf("labelTarget = %d, want 0 while editing a task", m.labelTarget)
+ }
+}
+
+// Canceling an edit clears the task being edited, so the next add cannot be
+// mistaken for a rename of it.
+func TestCancelClearsEditingID(t *testing.T) {
+ m, s := testModel(t)
+ if _, _, err := s.Add("ship v2", task.Do); err != nil {
+ t.Fatal(err)
+ }
+ m.refreshFromStore(t)
+
+ m = press(t, m, "e")
+ m = press(t, m, "esc")
+ if m.editingID != 0 {
+ t.Errorf("editingID = %d, want 0 after canceling", m.editingID)
+ }
+}
diff --git a/internal/tui/view.go b/internal/tui/view.go
index 1c84bd9..22de9df 100644
--- a/internal/tui/view.go
+++ b/internal/tui/view.go
@@ -140,7 +140,7 @@ func (m Model) renderQuadrant(q task.Quadrant, w, h int) string {
}
func (m Model) renderTaskLines(q task.Quadrant, w, visible int, focused bool) []string {
- tasks := m.tasksIn(q)
+ tasks := m.data.List(q)
if len(tasks) == 0 {
return []string{lipgloss.NewStyle().Foreground(m.dimColor()).Italic(true).Render("empty")}
}
@@ -259,7 +259,7 @@ func (m Model) renderArchive() string {
title := lipgloss.NewStyle().Bold(true).Render(fmt.Sprintf("Archive — %d completed", len(m.data.Archive)))
// Newest completion first, matching `ike archive`.
- arch := m.archiveList()
+ arch := m.data.ListArchive()
visible := m.height - 4 // title + blank + status + footer
offset := 0
@@ -273,11 +273,7 @@ func (m Model) renderArchive() string {
}
for i := offset; i < len(arch) && i-offset < visible; i++ {
t := arch[i]
- when := ""
- if t.DoneAt != nil {
- when = t.DoneAt.Local().Format("2006-01-02")
- }
- line := fmt.Sprintf(" %3d %s %s", t.ID, when, ansi.Truncate(t.DisplayTitle(), max(m.width-20, 4), "…"))
+ line := t.ArchiveRow(ansi.Truncate(t.DisplayTitle(), max(m.width-20, 4), "…"))
if i == m.archCursor {
line = lipgloss.NewStyle().Bold(true).Render("▸" + line[1:])
}