summaryrefslogtreecommitdiff
path: root/internal/askcli/command_info_add_test.go
blob: 9261a73896f4f17af3922fa5dfa7461b3e8bd7e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package askcli

import (
	"bytes"
	"context"
	"io"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

func TestHandleInfo_Success(t *testing.T) {
	dir := t.TempDir()
	oldRoot := taskAliasCacheRoot
	oldNow := nowTaskAliasCache
	taskAliasCacheRoot = func() (string, error) { return filepath.Join(dir, "hexai"), nil }
	nowTaskAliasCache = func() time.Time { return time.Date(2026, 3, 26, 12, 0, 0, 0, time.UTC) }
	defer func() {
		taskAliasCacheRoot = oldRoot
		nowTaskAliasCache = oldNow
	}()

	writeTaskAliasCacheForTest(t, taskAliasCache{
		NextID: 2,
		Entries: []taskAliasCacheEntry{
			{UUID: "dep-1", Alias: "1", CreatedAt: nowTaskAliasCache()},
			{UUID: "test-uuid", Alias: "0", CreatedAt: nowTaskAliasCache()},
		},
	})

	jsonData := `[{"uuid":"test-uuid","description":"Test task","status":"pending","priority":"H","tags":["cli","agent"],"urgency":15.0,"depends":["dep-1"],"annotations":[{"description":"Note 1","entry":"2026-03-22T10:00:00Z"}]}]`
	d := NewDispatcher(&spyRunner{runFn: func(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {
		// args[0] is "uuid:<uuid>" (the filter); emit data for any export call
		if len(args) > 0 && strings.HasPrefix(args[0], "uuid:") {
			io.WriteString(stdout, jsonData)
		}
		return 0, nil
	}})
	var stdout, stderr bytes.Buffer
	code, _ := d.Dispatch(context.Background(), []string{"info", "test-uuid"}, nil, &stdout, &stderr)
	if code != 0 {
		t.Fatalf("info code = %d, want 0", code)
	}
	output := stdout.String()
	if !strings.Contains(output, "ID:          0") {
		t.Fatalf("output missing alias ID: %s", output)
	}
	if !strings.Contains(output, "test-uuid") {
		t.Fatalf("output missing UUID: %s", output)
	}
	if !strings.Contains(output, "H") {
		t.Fatalf("output missing priority: %s", output)
	}
	if !strings.Contains(output, "Started:     no") {
		t.Fatalf("output missing explicit started state: %s", output)
	}
	if !strings.Contains(output, "Depends:     1 (dep-1)") {
		t.Fatalf("output missing formatted dependency alias: %s", output)
	}
}

func TestHandleInfo_AssignsDependencyAliasesFromInfo(t *testing.T) {
	dir := t.TempDir()
	oldRoot := taskAliasCacheRoot
	oldNow := nowTaskAliasCache
	taskAliasCacheRoot = func() (string, error) { return filepath.Join(dir, "hexai"), nil }
	nowTaskAliasCache = func() time.Time { return time.Date(2026, 3, 26, 12, 0, 0, 0, time.UTC) }
	defer func() {
		taskAliasCacheRoot = oldRoot
		nowTaskAliasCache = oldNow
	}()

	writeTaskAliasCacheForTest(t, taskAliasCache{
		NextID: 1,
		Entries: []taskAliasCacheEntry{
			{UUID: "test-uuid", Alias: "0", CreatedAt: nowTaskAliasCache()},
		},
	})

	jsonData := `[{"uuid":"test-uuid","description":"Test task","status":"pending","priority":"H","tags":["cli"],"urgency":15.0,"depends":["dep-b","dep-a"]}]`
	d := NewDispatcher(&spyRunner{runFn: func(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {
		if len(args) > 0 && strings.HasPrefix(args[0], "uuid:") {
			io.WriteString(stdout, jsonData)
		}
		return 0, nil
	}})

	var stdout, stderr bytes.Buffer
	code, _ := d.Dispatch(context.Background(), []string{"info", "test-uuid"}, nil, &stdout, &stderr)
	if code != 0 {
		t.Fatalf("info code = %d, want 0", code)
	}

	output := stdout.String()
	if !strings.Contains(output, "Depends:") ||
		!strings.Contains(output, "(dep-a)") ||
		!strings.Contains(output, "(dep-b)") {
		t.Fatalf("output missing assigned dependency aliases: %s", output)
	}
}

func TestHandleInfo_AliasSelector(t *testing.T) {
	dir := t.TempDir()
	oldRoot := taskAliasCacheRoot
	oldNow := nowTaskAliasCache
	taskAliasCacheRoot = func() (string, error) { return filepath.Join(dir, "hexai"), nil }
	nowTaskAliasCache = func() time.Time { return time.Date(2026, 3, 26, 12, 0, 0, 0, time.UTC) }
	defer func() {
		taskAliasCacheRoot = oldRoot
		nowTaskAliasCache = oldNow
	}()

	writeTaskAliasCacheForTest(t, taskAliasCache{
		NextID: 1,
		Entries: []taskAliasCacheEntry{
			{UUID: "test-uuid", Alias: "0", CreatedAt: nowTaskAliasCache()},
		},
	})

	jsonData := `[{"uuid":"test-uuid","description":"Test task","status":"pending","priority":"H","tags":["cli"],"urgency":15.0,"depends":[]}]`
	d := NewDispatcher(&spyRunner{runFn: func(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {
		if len(args) > 0 && strings.HasPrefix(args[0], "uuid:test-uuid") {
			io.WriteString(stdout, jsonData)
		}
		return 0, nil
	}})

	var stdout, stderr bytes.Buffer
	code, _ := d.Dispatch(context.Background(), []string{"info", "0"}, nil, &stdout, &stderr)
	if code != 0 {
		t.Fatalf("info code = %d, want 0", code)
	}
	if !strings.Contains(stdout.String(), "ID:          0") || !strings.Contains(stdout.String(), "UUID:        test-uuid") {
		t.Fatalf("stdout = %q, want alias and UUID", stdout.String())
	}
}

func TestHandleInfo_NumericID(t *testing.T) {
	d := NewDispatcher(&spyRunner{runFn: func(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {
		return 0, nil
	}})
	var stdout, stderr bytes.Buffer
	code, _ := d.Dispatch(context.Background(), []string{"info", "123"}, nil, &stdout, &stderr)
	if code != 1 {
		t.Fatalf("info code = %d, want 1 for numeric ID", code)
	}
}

func TestHandleInfo_MissingUUID(t *testing.T) {
	dir := t.TempDir()
	oldRoot := taskAliasCacheRoot
	oldNow := nowTaskAliasCache
	taskAliasCacheRoot = func() (string, error) { return filepath.Join(dir, "hexai"), nil }
	nowTaskAliasCache = func() time.Time { return time.Date(2026, 3, 26, 12, 0, 0, 0, time.UTC) }
	defer func() {
		taskAliasCacheRoot = oldRoot
		nowTaskAliasCache = oldNow
	}()

	jsonData := `[{"uuid":"started-uuid","description":"Started task","status":"pending","priority":"M","start":"2026-03-26T10:00:00Z","urgency":5.0,"depends":[]}]`
	d := NewDispatcher(&spyRunner{runFn: func(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {
		if len(args) == 2 && args[0] == "started" && args[1] == "export" {
			io.WriteString(stdout, jsonData)
		}
		return 0, nil
	}})
	var stdout, stderr bytes.Buffer
	code, _ := d.Dispatch(context.Background(), []string{"info"}, nil, &stdout, &stderr)
	if code != 0 {
		t.Fatalf("info code = %d, want 0 for implicit started task", code)
	}
	if !strings.Contains(stdout.String(), "ID:          0") || !strings.Contains(stdout.String(), "UUID:        started-uuid") {
		t.Fatalf("output missing alias and started task UUID: %s", stdout.String())
	}
}

func TestHandleInfo_MissingUUID_NoStartedTask(t *testing.T) {
	d := NewDispatcher(&spyRunner{runFn: func(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {
		if len(args) == 2 && args[0] == "started" && args[1] == "export" {
			io.WriteString(stdout, "[]")
		}
		return 0, nil
	}})
	var stdout, stderr bytes.Buffer
	code, _ := d.Dispatch(context.Background(), []string{"info"}, nil, &stdout, &stderr)
	if code != 1 {
		t.Fatalf("info code = %d, want 1 when no started task exists", code)
	}
	if !strings.Contains(stderr.String(), "no started task found") {
		t.Fatalf("stderr = %q, want no-started-task error", stderr.String())
	}
}

func TestHandleInfo_MissingUUID_MultipleStartedTasks(t *testing.T) {
	jsonData := `[{"uuid":"started-1","description":"Started task 1","status":"pending","priority":"M","start":"2026-03-26T10:00:00Z","urgency":5.0,"depends":[]},{"uuid":"started-2","description":"Started task 2","status":"pending","priority":"H","start":"2026-03-26T11:00:00Z","urgency":8.0,"depends":[]}]`
	d := NewDispatcher(&spyRunner{runFn: func(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {
		if len(args) == 2 && args[0] == "started" && args[1] == "export" {
			io.WriteString(stdout, jsonData)
		}
		return 0, nil
	}})
	var stdout, stderr bytes.Buffer
	code, _ := d.Dispatch(context.Background(), []string{"info"}, nil, &stdout, &stderr)
	if code != 1 {
		t.Fatalf("info code = %d, want 1 when multiple started tasks exist", code)
	}
	if !strings.Contains(stderr.String(), "multiple started tasks found") {
		t.Fatalf("stderr = %q, want multiple-started-tasks error", stderr.String())
	}
	if !strings.Contains(stderr.String(), "ID or UUID explicitly") {
		t.Fatalf("stderr = %q, want ID-or-UUID guidance", stderr.String())
	}
}

func TestHandleAdd_Success(t *testing.T) {
	now := useIsolatedTaskAliasCache(t)
	writeTaskAliasCacheForTest(t, taskAliasCache{
		NextID: 1,
		Entries: []taskAliasCacheEntry{
			{UUID: "existing-uuid", Alias: "0", CreatedAt: now},
		},
	})

	d := NewDispatcher(&spyRunner{runFn: func(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {
		io.WriteString(stdout, "Created task abc-123-def.")
		return 0, nil
	}})
	var stdout, stderr bytes.Buffer
	code, _ := d.Dispatch(context.Background(), []string{"add", "New task description"}, nil, &stdout, &stderr)
	if code != 0 {
		t.Fatalf("add code = %d, want 0", code)
	}
	if got := strings.TrimSpace(stdout.String()); got != "1" {
		t.Fatalf("stdout = %q, want alias 1", stdout.String())
	}
	cache := readTaskAliasCacheSnapshot(t)
	entry := findTaskAliasEntry(t, cache, "abc-123-def")
	if entry.Alias != "1" {
		t.Fatalf("created task alias = %q, want 1", entry.Alias)
	}
}

func TestHandleAdd_AliasAssignmentFailure(t *testing.T) {
	oldRoot := taskAliasCacheRoot
	taskAliasCacheRoot = func() (string, error) { return "", io.ErrUnexpectedEOF }
	defer func() { taskAliasCacheRoot = oldRoot }()

	d := NewDispatcher(&spyRunner{runFn: func(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {
		io.WriteString(stdout, "Created task abc-123-def.")
		return 0, nil
	}})

	var stdout, stderr bytes.Buffer
	code, _ := d.Dispatch(context.Background(), []string{"add", "New task description"}, nil, &stdout, &stderr)
	if code != 1 {
		t.Fatalf("add code = %d, want 1", code)
	}
	if stdout.Len() != 0 {
		t.Fatalf("stdout = %q, want empty output on alias assignment failure", stdout.String())
	}
	if !strings.Contains(stderr.String(), "failed to assign task alias") {
		t.Fatalf("stderr = %q, want alias assignment failure", stderr.String())
	}
}

func TestHandleAdd_MissingDescription(t *testing.T) {
	d := NewDispatcher(&spyRunner{runFn: func(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {
		return 0, nil
	}})
	var stdout, stderr bytes.Buffer
	code, _ := d.Dispatch(context.Background(), []string{"add"}, nil, &stdout, &stderr)
	if code != 1 {
		t.Fatalf("add code = %d, want 1 for missing description", code)
	}
}

func makeAddRunner(onAdd func(args []string, stdout io.Writer)) *spyRunner {
	return &spyRunner{runFn: func(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {
		onAdd(args, stdout)
		return 0, nil
	}}
}

func TestHandleAdd_MultipleWords(t *testing.T) {
	var capturedArgs []string
	d := NewDispatcher(makeAddRunner(func(args []string, stdout io.Writer) {
		capturedArgs = args
		io.WriteString(stdout, "Created task test-uuid.")
	}))
	var stdout, stderr bytes.Buffer
	d.Dispatch(context.Background(), []string{"add", "Multi", "word", "description"}, nil, &stdout, &stderr)
	// args[0]="add", args[1]="rc.verbose=nothing", args[2]="rc.verbose=new-uuid"
	if len(capturedArgs) < 4 || capturedArgs[0] != "add" || capturedArgs[1] != "rc.verbose=nothing" || capturedArgs[2] != "rc.verbose=new-uuid" {
		t.Fatalf("capturedArgs = %v, want [add, rc.verbose=nothing, rc.verbose=new-uuid, ...]", capturedArgs)
	}
}

func TestHandleAdd_WithPriority(t *testing.T) {
	var capturedArgs []string
	d := NewDispatcher(makeAddRunner(func(args []string, stdout io.Writer) {
		capturedArgs = args
		io.WriteString(stdout, "Created task test-uuid.")
	}))
	var stdout, stderr bytes.Buffer
	code, _ := d.Dispatch(context.Background(), []string{"add", "priority:H", "Fix critical bug"}, nil, &stdout, &stderr)
	if code != 0 {
		t.Fatalf("add code = %d, want 0", code)
	}
	// args: [add, rc.verbose=nothing, rc.verbose=new-uuid, priority:H, Fix critical bug]
	if len(capturedArgs) < 5 {
		t.Fatalf("capturedArgs = %v, want at least 5 elements", capturedArgs)
	}
	if capturedArgs[3] != "priority:H" {
		t.Errorf("capturedArgs[3] = %s, want priority:H", capturedArgs[3])
	}
	if capturedArgs[len(capturedArgs)-1] != "Fix critical bug" {
		t.Errorf("last arg = %s, want 'Fix critical bug'", capturedArgs[len(capturedArgs)-1])
	}
}

func TestHandleAdd_WithTag(t *testing.T) {
	var capturedArgs []string
	d := NewDispatcher(makeAddRunner(func(args []string, stdout io.Writer) {
		capturedArgs = args
		io.WriteString(stdout, "Created task test-uuid.")
	}))
	var stdout, stderr bytes.Buffer
	code, _ := d.Dispatch(context.Background(), []string{"add", "+cli", "New feature"}, nil, &stdout, &stderr)
	if code != 0 {
		t.Fatalf("add code = %d, want 0", code)
	}
	// args: [add, rc.verbose=nothing, rc.verbose=new-uuid, +cli, New feature]
	if capturedArgs[3] != "+cli" {
		t.Errorf("capturedArgs[3] = %s, want +cli", capturedArgs[3])
	}
}

func TestHandleAdd_WithPriorityAndTag(t *testing.T) {
	var capturedArgs []string
	d := NewDispatcher(makeAddRunner(func(args []string, stdout io.Writer) {
		capturedArgs = args
		io.WriteString(stdout, "Created task test-uuid.")
	}))
	var stdout, stderr bytes.Buffer
	code, _ := d.Dispatch(context.Background(), []string{"add", "priority:H", "+cli", "Complex task"}, nil, &stdout, &stderr)
	if code != 0 {
		t.Fatalf("add code = %d, want 0", code)
	}
	// args: [add, rc.verbose=nothing, rc.verbose=new-uuid, priority:H, +cli, Complex task]
	if capturedArgs[3] != "priority:H" || capturedArgs[4] != "+cli" {
		t.Errorf("capturedArgs = %v, want [add, rc.verbose=nothing, rc.verbose=new-uuid, priority:H, +cli, Complex task]", capturedArgs)
	}
}

func TestExtractUUIDFromAddOutput(t *testing.T) {
	if uuid := extractUUIDFromAddOutput("Created task abc-123-def."); uuid != "abc-123-def" {
		t.Fatalf("got %q, want abc-123-def", uuid)
	}
	if uuid := extractUUIDFromAddOutput("Created task abc-123-def.\nsome other line"); uuid != "abc-123-def" {
		t.Fatalf("got %q, want abc-123-def", uuid)
	}
	if uuid := extractUUIDFromAddOutput("no match here"); uuid != "" {
		t.Fatalf("got %q, want empty", uuid)
	}
}

func TestParseAddArgs(t *testing.T) {
	mods, desc := parseAddArgs([]string{"priority:H", "+cli", "Fix bug"})
	if desc != "Fix bug" || len(mods) != 2 {
		t.Fatalf("parseAddArgs([\"priority:H\", \"+cli\", \"Fix bug\"]) = mods=%v, desc=%q, want mods=[priority:H, +cli], desc=\"Fix bug\"", mods, desc)
	}

	mods, desc = parseAddArgs([]string{"Multi", "word", "description"})
	if desc != "Multi word description" || len(mods) != 0 {
		t.Fatalf("parseAddArgs([\"Multi\", \"word\", \"description\"]) = mods=%v, desc=%q, want mods=[], desc=\"Multi word description\"", mods, desc)
	}

	mods, desc = parseAddArgs([]string{"-deprecated", "Old task"})
	if desc != "Old task" || len(mods) != 1 || mods[0] != "-deprecated" {
		t.Fatalf("parseAddArgs([\"-deprecated\", \"Old task\"]) = mods=%v, desc=%q", mods, desc)
	}

	// An arg starting with "+" but containing spaces is NOT a modifier — it is
	// the start of the description. This prevents agents from quoting tag+desc
	// together (e.g. "+code-quality Fix foo") and having them land in the wrong
	// place.
	mods, desc = parseAddArgs([]string{"+code-quality Fix foo bar"})
	if desc != "+code-quality Fix foo bar" || len(mods) != 0 {
		t.Fatalf("space-containing +arg should be description, got mods=%v, desc=%q", mods, desc)
	}

	// Same issue when mixed: a proper tag precedes a space-containing arg.
	mods, desc = parseAddArgs([]string{"+cli", "+code-quality Fix foo bar"})
	if desc != "+code-quality Fix foo bar" || len(mods) != 1 || mods[0] != "+cli" {
		t.Fatalf("mixed case: mods=%v, desc=%q", mods, desc)
	}

	// All-modifier args (no description) should return empty description, not a
	// duplicate of the modifiers.
	mods, desc = parseAddArgs([]string{"+cli", "+agent"})
	if desc != "" || len(mods) != 2 {
		t.Fatalf("all-modifier case: mods=%v, desc=%q, want empty desc", mods, desc)
	}
}