Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6253: add `multica issue timeline` CLI command (#7285)

Bohan Jianga107570e3bfc
diff --git a/server/cmd/multica/cmd_issue_timeline.go b/server/cmd/multica/cmd_issue_timeline.go
new file mode 100644
index 0000000000..6aba2f016e
--- /dev/null
+++ b/server/cmd/multica/cmd_issue_timeline.go
@@ -0,0 +1,337 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/url"
+ "os"
+ "sort"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/spf13/cobra"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+)
+
+// noneMarker stands in for a missing side of a transition — an issue that had
+// no assignee before, or was unassigned after.
+const noneMarker = "(none)"
+
+// headerTimelineTruncated mirrors handler.HeaderTimelineTruncated. Declared as
+// a literal rather than imported because the CLI does not depend on the
+// handler package (same convention as the X-Multica-Next-Before cursors in
+// `issue comment list`). Value is a comma-separated kind list: "activity",
+// "comment", or "activity,comment".
+const headerTimelineTruncated = "X-Timeline-Truncated"
+
+var issueTimelineCmd = &cobra.Command{
+ Use: "timeline <id>",
+ Aliases: []string{"history"},
+ Short: "Chronological issue history — when status/assignee changed, how long it has been stuck",
+ Long: `Chronological history of an issue: the activity log — status / priority /
+assignee / title / date changes, plus whatever task_completed / task_failed
+records the server already writes — merged with comments, oldest first.
+
+Use it for the questions the current issue fields cannot answer:
+
+ - When did this issue move to in_review?
+ - How long has it been sitting in its current status?
+ - What changed on this issue since yesterday?
+
+For "what is the state RIGHT NOW", prefer ` + "`issue get`" + ` — that is the authoritative
+current snapshot. This command explains how it got there, which comments alone
+cannot: a status change writes an activity record, never a comment, so a merge
+that flipped the issue to done leaves no trace in the comment stream.
+
+Comments are included by default. --activity-only drops comment bodies and
+keeps every activity record; to isolate the state transitions behind "how long
+has this been stuck", filter by action instead.
+
+The server caps how far back it will read. When it reports that the response
+was truncated, a warning naming the affected kinds is printed to stderr —
+durations and "first entered <status>" cannot be concluded from a truncated
+read, because the transition you are looking for may be the one that fell off.
+
+Examples:
+ # How long has MUL-123 been in its current status?
+ multica issue timeline MUL-123 --action status_changed
+
+ # Every state change, no comment bodies
+ multica issue timeline MUL-123 --activity-only --output json
+
+ # What changed since yesterday?
+ multica issue timeline MUL-123 --since 2026-08-19T00:00:00Z`,
+ Args: exactArgs(1),
+ RunE: runIssueTimeline,
+}
+
+func init() {
+ issueTimelineCmd.Flags().String("output", "table", "Output format: table or json")
+ issueTimelineCmd.Flags().Bool("activity-only", false, "Drop comments and return every activity record — including the task_completed / task_failed entries the server already writes, not just field changes. Much cheaper to read than the full timeline; use --action when you want only state transitions.")
+ issueTimelineCmd.Flags().StringSlice("action", nil, "Only return activities with these actions (repeatable or comma-separated). Implies --activity-only, since comments carry no action. Known actions: created, status_changed, priority_changed, assignee_changed, title_changed, description_updated, start_date_changed, due_date_changed, task_completed, task_failed, squad_leader_evaluated.")
+ issueTimelineCmd.Flags().String("since", "", "Only return entries created after this timestamp (RFC3339)")
+ issueTimelineCmd.Flags().Int("tail", 0, "Only return the N most recent entries (applied after every other filter)")
+ issueTimelineCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")
+
+ issueCmd.AddCommand(issueTimelineCmd)
+}
+
+func runIssueTimeline(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+
+ filter, err := timelineFilterFromFlags(cmd)
+ if err != nil {
+ return err
+ }
+
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ issueRef, err := resolveIssueRef(ctx, client, args[0])
+ if err != nil {
+ return fmt.Errorf("resolve issue: %w", err)
+ }
+
+ // Deliberately sent without limit/before/after/around: the endpoint only
+ // returns the flat oldest-first array when no pagination param is present.
+ var entries []map[string]any
+ respHeaders, err := client.GetJSONWithHeaders(ctx, "/api/issues/"+url.PathEscape(issueRef.ID)+"/timeline", &entries)
+ if err != nil {
+ return fmt.Errorf("list issue timeline: %w", err)
+ }
+ warnTimelineTruncated(os.Stderr, respHeaders.Get(headerTimelineTruncated))
+
+ entries = filter.apply(entries)
+
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, entries)
+ }
+
+ fullID, _ := cmd.Flags().GetBool("full-id")
+ printIssueTimelineTable(entries, loadActorDisplayLookup(ctx, client), fullID)
+ return nil
+}
+
+// warnTimelineTruncated surfaces the server's truncation signal on stderr, so
+// it never contaminates a piped --output json read.
+//
+// The endpoint caps each kind independently and reports which ones lost rows.
+// Swallowing that makes a partial read look complete, which is precisely wrong
+// for this command's headline question: if the transition that set the current
+// status fell off the back of the window, --action status_changed returns a
+// plausible, shorter, wrong answer to "how long has this been stuck".
+func warnTimelineTruncated(w io.Writer, kinds string) {
+ if kinds == "" {
+ return
+ }
+ fmt.Fprintf(w, "warning: timeline truncated by the server cap (%s): older entries are missing. "+
+ "Durations and \"first entered <status>\" cannot be concluded from this read.\n", kinds)
+}
+
+// timelineFilter narrows a timeline response client-side. The endpoint takes no
+// filter parameters and returns the whole timeline in one shot, so every flag
+// here is applied after the fetch: it bounds what the caller has to read, not
+// what the server has to do.
+type timelineFilter struct {
+ activityOnly bool
+ actions map[string]bool
+ since time.Time
+ tail int
+}
+
+func timelineFilterFromFlags(cmd *cobra.Command) (timelineFilter, error) {
+ var f timelineFilter
+
+ f.activityOnly, _ = cmd.Flags().GetBool("activity-only")
+
+ f.tail, _ = cmd.Flags().GetInt("tail")
+ if f.tail < 0 {
+ return f, fmt.Errorf("--tail must be >= 0")
+ }
+
+ actions, _ := cmd.Flags().GetStringSlice("action")
+ for _, a := range actions {
+ if a = strings.TrimSpace(a); a == "" {
+ continue
+ }
+ if f.actions == nil {
+ f.actions = map[string]bool{}
+ }
+ f.actions[a] = true
+ }
+ if len(f.actions) > 0 {
+ // Comments carry no action, so filtering by action can only ever mean
+ // activities.
+ f.activityOnly = true
+ }
+
+ if raw, _ := cmd.Flags().GetString("since"); raw != "" {
+ ts, err := time.Parse(time.RFC3339, raw)
+ if err != nil {
+ return f, fmt.Errorf("invalid --since %q: expected RFC3339, e.g. 2026-08-19T00:00:00Z", raw)
+ }
+ f.since = ts
+ }
+
+ return f, nil
+}
+
+func (f timelineFilter) apply(entries []map[string]any) []map[string]any {
+ out := make([]map[string]any, 0, len(entries))
+ for _, e := range entries {
+ if f.activityOnly && strVal(e, "type") != "activity" {
+ continue
+ }
+ if len(f.actions) > 0 && !f.actions[strVal(e, "action")] {
+ continue
+ }
+ if !f.since.IsZero() {
+ // An entry whose timestamp will not parse cannot be shown to fall
+ // inside the window, so a time-bounded read drops it.
+ ts, err := time.Parse(time.RFC3339, strVal(e, "created_at"))
+ if err != nil || !ts.After(f.since) {
+ continue
+ }
+ }
+ out = append(out, e)
+ }
+
+ // Entries arrive oldest-first, so the most recent N is the trailing slice.
+ if f.tail > 0 && len(out) > f.tail {
+ out = out[len(out)-f.tail:]
+ }
+ return out
+}
+
+func printIssueTimelineTable(entries []map[string]any, actors actorDisplayLookup, fullID bool) {
+ headers := []string{"TIME", "TYPE", "ACTOR", "DETAIL"}
+ rows := make([][]string, 0, len(entries))
+ for _, e := range entries {
+ when := strVal(e, "created_at")
+ if len(when) >= 16 {
+ when = when[:16]
+ }
+ // An activity is far more legible labelled by its action than by the
+ // literal "activity".
+ kind := strVal(e, "type")
+ if action := strVal(e, "action"); action != "" {
+ kind = action
+ }
+ rows = append(rows, []string{
+ when,
+ kind,
+ timelineActor(strVal(e, "actor_type"), strVal(e, "actor_id"), actors, fullID),
+ timelineDetail(e, actors, fullID),
+ })
+ }
+ cli.PrintTable(os.Stdout, headers, rows)
+}
+
+// timelineActor renders an actor as "member:Alice", falling back to a shortened
+// id when the workspace lookup cannot name it (deleted member, foreign id).
+func timelineActor(actorType, actorID string, actors actorDisplayLookup, fullID bool) string {
+ switch {
+ case actorType == "" && actorID == "":
+ return ""
+ case actorID == "":
+ // System-authored activities carry a type with no id, and the lookup
+ // returns nothing for those. A GitHub PR merge flipping the issue to
+ // done is exactly this shape, so leaving the column blank would erase
+ // the actor on the transition this command exists to explain.
+ return actorType
+ case actorType == "":
+ if fullID {
+ return actorID
+ }
+ return truncateID(actorID)
+ }
+ display := actors.actor(actorType, actorID)
+ if !fullID && strings.HasSuffix(display, ":"+actorID) {
+ return actorType + ":" + truncateID(actorID)
+ }
+ return display
+}
+
+// timelineDetail renders one entry's payload for table output: a comment's
+// clipped body, or an activity's transition. Activity details are free-form
+// JSON keyed per action, so unrecognised shapes fall back to sorted key=value
+// rather than being dropped.
+func timelineDetail(entry map[string]any, actors actorDisplayLookup, fullID bool) string {
+ if strVal(entry, "type") == "comment" {
+ return clipTimelineText(singleLineText(strVal(entry, "content")), 60)
+ }
+
+ details, _ := entry["details"].(map[string]any)
+ if len(details) == 0 {
+ return ""
+ }
+
+ // status / priority / title / date changes: {"from": ..., "to": ...}
+ if _, ok := details["from"]; ok {
+ return transitionText(strVal(details, "from"), strVal(details, "to"))
+ }
+ if _, ok := details["to"]; ok {
+ return transitionText("", strVal(details, "to"))
+ }
+
+ // assignee_changed: {"from_type","from_id","to_type","to_id"}, any of which
+ // is absent when that side was unassigned.
+ if hasAnyKey(details, "from_type", "from_id", "to_type", "to_id") {
+ return transitionText(
+ timelineActor(strVal(details, "from_type"), strVal(details, "from_id"), actors, fullID),
+ timelineActor(strVal(details, "to_type"), strVal(details, "to_id"), actors, fullID),
+ )
+ }
+
+ keys := make([]string, 0, len(details))
+ for k := range details {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ parts := make([]string, 0, len(keys))
+ for _, k := range keys {
+ parts = append(parts, k+"="+strVal(details, k))
+ }
+ return clipTimelineText(strings.Join(parts, " "), 60)
+}
+
+func transitionText(from, to string) string {
+ if from == "" {
+ from = noneMarker
+ }
+ if to == "" {
+ to = noneMarker
+ }
+ return from + " → " + to
+}
+
+func hasAnyKey(m map[string]any, keys ...string) bool {
+ for _, k := range keys {
+ if _, ok := m[k]; ok {
+ return true
+ }
+ }
+ return false
+}
+
+func singleLineText(s string) string {
+ return strings.Join(strings.Fields(s), " ")
+}
+
+func clipTimelineText(s string, max int) string {
+ if max <= 0 || utf8.RuneCountInString(s) <= max {
+ return s
+ }
+ runes := []rune(s)
+ if max <= 3 {
+ return string(runes[:max])
+ }
+ return string(runes[:max-3]) + "..."
+}
diff --git a/server/cmd/multica/cmd_issue_timeline_test.go b/server/cmd/multica/cmd_issue_timeline_test.go
new file mode 100644
index 0000000000..faadc23973
--- /dev/null
+++ b/server/cmd/multica/cmd_issue_timeline_test.go
@@ -0,0 +1,507 @@
+package main
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/spf13/cobra"
+)
+
+func newIssueTimelineTestCmd() *cobra.Command {
+ cmd := &cobra.Command{Use: "timeline"}
+ cmd.Flags().String("output", "table", "")
+ cmd.Flags().Bool("activity-only", false, "")
+ cmd.Flags().StringSlice("action", nil, "")
+ cmd.Flags().String("since", "", "")
+ cmd.Flags().Int("tail", 0, "")
+ cmd.Flags().Bool("full-id", false, "")
+ return cmd
+}
+
+// timelineFixture mirrors the #7040 scenario: an agent comment that says the PR
+// is still waiting for review, followed by the status transitions that made it
+// stale.
+func timelineFixture() []map[string]any {
+ return []map[string]any{
+ {
+ "type": "activity", "id": "a1", "actor_type": "member", "actor_id": "m1",
+ "created_at": "2026-08-18T10:00:00Z", "action": "created",
+ "details": map[string]any{},
+ },
+ {
+ "type": "comment", "id": "c1", "actor_type": "agent", "actor_id": "g1",
+ "created_at": "2026-08-18T11:00:00Z",
+ "content": "PR open, waiting for human review/merge.",
+ },
+ {
+ "type": "activity", "id": "a2", "actor_type": "member", "actor_id": "m1",
+ "created_at": "2026-08-19T09:00:00Z", "action": "status_changed",
+ "details": map[string]any{"from": "in_progress", "to": "in_review"},
+ },
+ {
+ "type": "activity", "id": "a3", "actor_type": "system", "actor_id": "",
+ "created_at": "2026-08-20T08:00:00Z", "action": "status_changed",
+ "details": map[string]any{"from": "in_review", "to": "done"},
+ },
+ }
+}
+
+func mustTime(t *testing.T, s string) time.Time {
+ t.Helper()
+ ts, err := time.Parse(time.RFC3339, s)
+ if err != nil {
+ t.Fatalf("parse %q: %v", s, err)
+ }
+ return ts
+}
+
+func entryIDs(entries []map[string]any) []string {
+ ids := make([]string, 0, len(entries))
+ for _, e := range entries {
+ ids = append(ids, strVal(e, "id"))
+ }
+ return ids
+}
+
+func TestTimelineFilterApply(t *testing.T) {
+ tests := []struct {
+ name string
+ filter timelineFilter
+ want []string
+ }{
+ {
+ name: "no filter keeps everything",
+ filter: timelineFilter{},
+ want: []string{"a1", "c1", "a2", "a3"},
+ },
+ {
+ name: "activity-only drops comments",
+ filter: timelineFilter{activityOnly: true},
+ want: []string{"a1", "a2", "a3"},
+ },
+ {
+ name: "action filter narrows to matching activities",
+ filter: timelineFilter{activityOnly: true, actions: map[string]bool{"status_changed": true}},
+ want: []string{"a2", "a3"},
+ },
+ {
+ name: "since keeps only strictly later entries",
+ filter: timelineFilter{since: mustTime(t, "2026-08-18T11:00:00Z")},
+ want: []string{"a2", "a3"},
+ },
+ {
+ name: "tail keeps the most recent entries",
+ filter: timelineFilter{tail: 2},
+ want: []string{"a2", "a3"},
+ },
+ {
+ name: "tail larger than the result is a no-op",
+ filter: timelineFilter{tail: 99},
+ want: []string{"a1", "c1", "a2", "a3"},
+ },
+ {
+ name: "tail applies after the other filters",
+ filter: timelineFilter{activityOnly: true, tail: 1},
+ want: []string{"a3"},
+ },
+ {
+ name: "unknown action matches nothing",
+ filter: timelineFilter{activityOnly: true, actions: map[string]bool{"nope": true}},
+ want: []string{},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := entryIDs(tt.filter.apply(timelineFixture()))
+ if len(got) != len(tt.want) {
+ t.Fatalf("ids = %v, want %v", got, tt.want)
+ }
+ for i := range got {
+ if got[i] != tt.want[i] {
+ t.Fatalf("ids = %v, want %v", got, tt.want)
+ }
+ }
+ })
+ }
+}
+
+func TestTimelineFilterApplyDropsUnparsableTimestampsWhenSinceSet(t *testing.T) {
+ entries := []map[string]any{
+ {"type": "activity", "id": "bad", "created_at": "not-a-timestamp"},
+ {"type": "activity", "id": "good", "created_at": "2026-08-20T08:00:00Z"},
+ }
+ f := timelineFilter{since: mustTime(t, "2026-08-01T00:00:00Z")}
+ if got := entryIDs(f.apply(entries)); len(got) != 1 || got[0] != "good" {
+ t.Fatalf("ids = %v, want [good]", got)
+ }
+}
+
+func TestTimelineFilterFromFlagsActionImpliesActivityOnly(t *testing.T) {
+ cmd := newIssueTimelineTestCmd()
+ _ = cmd.Flags().Set("action", "status_changed")
+
+ f, err := timelineFilterFromFlags(cmd)
+ if err != nil {
+ t.Fatalf("timelineFilterFromFlags: %v", err)
+ }
+ if !f.activityOnly {
+ t.Fatal("activityOnly = false, want true when --action is set")
+ }
+ if !f.actions["status_changed"] {
+ t.Fatalf("actions = %v, want status_changed", f.actions)
+ }
+}
+
+func TestTimelineFilterFromFlagsRejectsBadInput(t *testing.T) {
+ t.Run("since", func(t *testing.T) {
+ cmd := newIssueTimelineTestCmd()
+ _ = cmd.Flags().Set("since", "yesterday")
+ if _, err := timelineFilterFromFlags(cmd); err == nil {
+ t.Fatal("expected an error for a non-RFC3339 --since")
+ }
+ })
+ t.Run("tail", func(t *testing.T) {
+ cmd := newIssueTimelineTestCmd()
+ _ = cmd.Flags().Set("tail", "-1")
+ if _, err := timelineFilterFromFlags(cmd); err == nil {
+ t.Fatal("expected an error for a negative --tail")
+ }
+ })
+}
+
+func TestTimelineDetail(t *testing.T) {
+ var actors actorDisplayLookup // zero value: no workspace lookup, id fallback
+
+ tests := []struct {
+ name string
+ entry map[string]any
+ want string
+ }{
+ {
+ name: "status transition",
+ entry: map[string]any{"type": "activity", "details": map[string]any{"from": "in_review", "to": "done"}},
+ want: "in_review → done",
+ },
+ {
+ name: "assignee set from nobody",
+ entry: map[string]any{"type": "activity", "details": map[string]any{"to_type": "agent", "to_id": "abcdefgh1234"}},
+ want: "(none) → agent:abcdefgh",
+ },
+ {
+ name: "unassigned",
+ entry: map[string]any{"type": "activity", "details": map[string]any{"from_type": "member", "from_id": "abcdefgh1234"}},
+ want: "member:abcdefgh → (none)",
+ },
+ {
+ name: "task_completed carries no from/to and falls back",
+ entry: map[string]any{"type": "activity", "details": map[string]any{"task_id": "t1"}},
+ want: "task_id=t1",
+ },
+ {
+ name: "empty details render as blank",
+ entry: map[string]any{"type": "activity", "details": map[string]any{}},
+ want: "",
+ },
+ {
+ name: "unknown detail shape falls back to sorted key=value",
+ entry: map[string]any{"type": "activity", "details": map[string]any{"outcome": "no_action", "task_id": "t1"}},
+ want: "outcome=no_action task_id=t1",
+ },
+ {
+ name: "comment body is flattened to one line",
+ entry: map[string]any{"type": "comment", "content": "PR open,\n\nwaiting for review."},
+ want: "PR open, waiting for review.",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := timelineDetail(tt.entry, actors, false); got != tt.want {
+ t.Fatalf("timelineDetail = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+// A GitHub PR merge flipping the issue to done publishes with actor type
+// "system" and no actor id (server/internal/handler/github.go). That is the
+// transition this command exists to explain, so the actor must not render
+// blank.
+func TestTimelineActorSystemWithoutIDRendersType(t *testing.T) {
+ var actors actorDisplayLookup
+
+ if got := timelineActor("system", "", actors, false); got != "system" {
+ t.Fatalf("system actor = %q, want %q", got, "system")
+ }
+ if got := timelineActor("", "", actors, false); got != "" {
+ t.Fatalf("empty actor = %q, want empty", got)
+ }
+ if got := timelineActor("member", "abcdefgh1234", actors, false); got != "member:abcdefgh" {
+ t.Fatalf("member actor = %q, want member:abcdefgh", got)
+ }
+ if got := timelineActor("member", "abcdefgh1234", actors, true); got != "member:abcdefgh1234" {
+ t.Fatalf("member actor with --full-id = %q, want the full id", got)
+ }
+}
+
+func TestWarnTimelineTruncated(t *testing.T) {
+ t.Run("silent when the header is absent", func(t *testing.T) {
+ var buf strings.Builder
+ warnTimelineTruncated(&buf, "")
+ if buf.String() != "" {
+ t.Fatalf("warning = %q, want none", buf.String())
+ }
+ })
+
+ t.Run("names the truncated kinds and voids duration claims", func(t *testing.T) {
+ var buf strings.Builder
+ warnTimelineTruncated(&buf, "activity,comment")
+ got := buf.String()
+ for _, want := range []string{"truncated", "activity,comment", "Durations"} {
+ if !strings.Contains(got, want) {
+ t.Fatalf("warning %q missing %q", got, want)
+ }
+ }
+ })
+}
+
+// The truncation signal is the difference between "this is the whole history"
+// and "the transition you need may have fallen off the back", so it must
+// survive the round trip — and land on stderr, where it cannot corrupt a piped
+// --output json read.
+func TestRunIssueTimelineReportsTruncationOnStderr(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/issues/MUL-6253":
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "issue-uuid", "identifier": "MUL-6253"})
+ case "/api/issues/issue-uuid/timeline":
+ w.Header().Set("X-Timeline-Truncated", "activity")
+ _ = json.NewEncoder(w).Encode(timelineFixture())
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueTimelineTestCmd()
+ _ = cmd.Flags().Set("output", "json")
+
+ outR, outW, _ := os.Pipe()
+ errR, errW, _ := os.Pipe()
+ oldOut, oldErr := os.Stdout, os.Stderr
+ os.Stdout, os.Stderr = outW, errW
+ err := runIssueTimeline(cmd, []string{"MUL-6253"})
+ _ = outW.Close()
+ _ = errW.Close()
+ os.Stdout, os.Stderr = oldOut, oldErr
+ stdout, _ := io.ReadAll(outR)
+ stderr, _ := io.ReadAll(errR)
+ if err != nil {
+ t.Fatalf("runIssueTimeline: %v", err)
+ }
+
+ if !strings.Contains(string(stderr), "truncated") || !strings.Contains(string(stderr), "activity") {
+ t.Fatalf("stderr = %q, want a truncation warning naming the kind", string(stderr))
+ }
+ // stdout must stay valid JSON: the warning belongs on stderr only.
+ var entries []map[string]any
+ if err := json.Unmarshal(stdout, &entries); err != nil {
+ t.Fatalf("stdout is not clean JSON: %v\n%s", err, string(stdout))
+ }
+ if len(entries) != len(timelineFixture()) {
+ t.Fatalf("entries = %d, want %d", len(entries), len(timelineFixture()))
+ }
+}
+
+func TestRunIssueTimelineSilentWhenNotTruncated(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/issues/MUL-6253":
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "issue-uuid", "identifier": "MUL-6253"})
+ case "/api/issues/issue-uuid/timeline":
+ _ = json.NewEncoder(w).Encode(timelineFixture())
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueTimelineTestCmd()
+ _ = cmd.Flags().Set("output", "json")
+
+ outR, outW, _ := os.Pipe()
+ errR, errW, _ := os.Pipe()
+ oldOut, oldErr := os.Stdout, os.Stderr
+ os.Stdout, os.Stderr = outW, errW
+ err := runIssueTimeline(cmd, []string{"MUL-6253"})
+ _ = outW.Close()
+ _ = errW.Close()
+ os.Stdout, os.Stderr = oldOut, oldErr
+ _, _ = io.ReadAll(outR)
+ stderr, _ := io.ReadAll(errR)
+ if err != nil {
+ t.Fatalf("runIssueTimeline: %v", err)
+ }
+ if len(stderr) != 0 {
+ t.Fatalf("stderr = %q, want nothing when the response is complete", string(stderr))
+ }
+}
+
+// The help text is the discovery surface: this command is deliberately absent
+// from the runtime brief, so an agent only finds it by scanning `issue --help`
+// for the question it is trying to answer. These anchors are the contract.
+func TestIssueTimelineHelpCarriesDiscoveryContract(t *testing.T) {
+ if want := "how long it has been stuck"; !strings.Contains(issueTimelineCmd.Short, want) {
+ t.Errorf("timeline Short missing %q, got: %s", want, issueTimelineCmd.Short)
+ }
+
+ for _, want := range []string{
+ // Points back at the authoritative current state, so nobody
+ // reconstructs "now" from history.
+ "issue get",
+ "authoritative",
+ // Why comments alone cannot answer this.
+ "never a comment",
+ // The truncation caveat must be discoverable, not just printed.
+ "truncated",
+ } {
+ if !strings.Contains(issueTimelineCmd.Long, want) {
+ t.Errorf("timeline Long missing %q, got:\n%s", want, issueTimelineCmd.Long)
+ }
+ }
+
+ // The action list must stay honest about what the server actually writes;
+ // omitting the task events is what made the first cut of this command
+ // misdescribe --activity-only.
+ help := issueTimelineCmd.Flags().FlagUsages()
+ for _, want := range []string{"task_completed", "task_failed", "status_changed", "Implies --activity-only"} {
+ if !strings.Contains(help, want) {
+ t.Errorf("timeline rendered flag help missing %q, got:\n%s", want, help)
+ }
+ }
+}
+
+func TestClipTimelineText(t *testing.T) {
+ if got := clipTimelineText("短", 10); got != "短" {
+ t.Fatalf("clip short = %q", got)
+ }
+ // Clipping counts runes, not bytes, so multi-byte text is not cut mid-character.
+ if got := clipTimelineText("一二三四五六七八九十", 5); got != "一二..." {
+ t.Fatalf("clip multibyte = %q, want 一二...", got)
+ }
+}
+
+// The endpoint only returns the flat oldest-first array when NO pagination
+// parameter is present; sending limit= flips it to a wrapped object and the
+// decode into []map[string]any would silently yield nothing.
+func TestRunIssueTimelineRequestsFlatShapeAndFilters(t *testing.T) {
+ var gotPaths []string
+ var gotRawQuery string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotPaths = append(gotPaths, r.URL.Path)
+ switch r.URL.Path {
+ case "/api/issues/MUL-6253":
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "id": "issue-uuid",
+ "identifier": "MUL-6253",
+ "title": "timeline CLI",
+ })
+ case "/api/issues/issue-uuid/timeline":
+ gotRawQuery = r.URL.RawQuery
+ _ = json.NewEncoder(w).Encode(timelineFixture())
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueTimelineTestCmd()
+ _ = cmd.Flags().Set("output", "json")
+ _ = cmd.Flags().Set("action", "status_changed")
+
+ old := os.Stdout
+ r, w, _ := os.Pipe()
+ os.Stdout = w
+ err := runIssueTimeline(cmd, []string{"MUL-6253"})
+ _ = w.Close()
+ os.Stdout = old
+ out, _ := io.ReadAll(r)
+ if err != nil {
+ t.Fatalf("runIssueTimeline: %v", err)
+ }
+
+ if gotRawQuery != "" {
+ t.Fatalf("timeline query = %q, want empty (any pagination param changes the response shape)", gotRawQuery)
+ }
+ want := []string{"/api/issues/MUL-6253", "/api/issues/issue-uuid/timeline"}
+ if len(gotPaths) != len(want) || gotPaths[0] != want[0] || gotPaths[1] != want[1] {
+ t.Fatalf("paths = %v, want %v", gotPaths, want)
+ }
+
+ var entries []map[string]any
+ if err := json.Unmarshal(out, &entries); err != nil {
+ t.Fatalf("decode JSON output: %v\n%s", err, string(out))
+ }
+ if got := entryIDs(entries); len(got) != 2 || got[0] != "a2" || got[1] != "a3" {
+ t.Fatalf("ids = %v, want [a2 a3]", got)
+ }
+}
+
+func TestRunIssueTimelineEmptyResultPrintsEmptyJSONArray(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/issues/MUL-6253":
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "issue-uuid", "identifier": "MUL-6253"})
+ case "/api/issues/issue-uuid/timeline":
+ _ = json.NewEncoder(w).Encode([]map[string]any{})
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueTimelineTestCmd()
+ _ = cmd.Flags().Set("output", "json")
+
+ old := os.Stdout
+ r, w, _ := os.Pipe()
+ os.Stdout = w
+ err := runIssueTimeline(cmd, []string{"MUL-6253"})
+ _ = w.Close()
+ os.Stdout = old
+ out, _ := io.ReadAll(r)
+ if err != nil {
+ t.Fatalf("runIssueTimeline: %v", err)
+ }
+
+ var entries []map[string]any
+ if err := json.Unmarshal(out, &entries); err != nil {
+ t.Fatalf("decode JSON output: %v\n%s", err, string(out))
+ }
+ if len(entries) != 0 {
+ t.Fatalf("entries = %v, want empty", entries)
+ }
+}