summaryrefslogtreecommitdiff
path: root/Omni/Task/Core.hs
blob: 54ed04d995c31bdbb1a0c085353f95ba37fb62c8 (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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}

module Omni.Task.Core where

import Alpha
import Data.Aeson (FromJSON, ToJSON, decode, encode)
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.KeyMap as KM
import Data.Aeson.Types (parseMaybe)
import qualified Data.ByteString.Lazy.Char8 as BLC
import qualified Data.List as List
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Data.Time (UTCTime, diffTimeToPicoseconds, getCurrentTime, utctDayTime)
import GHC.Generics ()
import System.Directory (createDirectoryIfMissing, doesFileExist)
import System.Environment (lookupEnv)

-- Core data types
data Task = Task
  { taskId :: Text,
    taskTitle :: Text,
    taskType :: TaskType,
    taskParent :: Maybe Text, -- Parent epic ID
    taskNamespace :: Maybe Text, -- Optional namespace (e.g., "Omni/Task", "Biz/Cloud")
    taskStatus :: Status,
    taskPriority :: Priority, -- Priority level (0-4)
    taskDependencies :: [Dependency], -- List of dependencies with types
    taskCreatedAt :: UTCTime,
    taskUpdatedAt :: UTCTime
  }
  deriving (Show, Eq, Generic)

data TaskType = Epic | WorkTask
  deriving (Show, Eq, Generic)

data Status = Open | InProgress | Review | Done
  deriving (Show, Eq, Generic)

-- Priority levels (matching beads convention)
data Priority = P0 | P1 | P2 | P3 | P4
  deriving (Show, Eq, Ord, Generic)

data Dependency = Dependency
  { depId :: Text, -- ID of the task this depends on
    depType :: DependencyType -- Type of dependency relationship
  }
  deriving (Show, Eq, Generic)

data DependencyType
  = Blocks -- Hard dependency, blocks ready work queue
  | DiscoveredFrom -- Work discovered during other work
  | ParentChild -- Epic/subtask relationship
  | Related -- Soft relationship, doesn't block
  deriving (Show, Eq, Generic)

instance ToJSON TaskType

instance FromJSON TaskType

instance ToJSON Status

instance FromJSON Status

instance ToJSON Priority

instance FromJSON Priority

instance ToJSON DependencyType

instance FromJSON DependencyType

instance ToJSON Dependency

instance FromJSON Dependency

instance ToJSON Task

instance FromJSON Task

-- Get the tasks database file path (use test file if TASK_TEST_MODE is set)
getTasksFilePath :: IO FilePath
getTasksFilePath = do
  customPath <- lookupEnv "TASK_DB_PATH"
  testMode <- lookupEnv "TASK_TEST_MODE"
  pure <| case (customPath, testMode) of
    (Just path, _) -> path
    (_, Just "1") -> ".tasks/tasks-test.jsonl"
    _ -> ".tasks/tasks.jsonl"

-- Initialize the task database
initTaskDb :: IO ()
initTaskDb = do
  createDirectoryIfMissing True ".tasks"
  tasksFile <- getTasksFilePath
  exists <- doesFileExist tasksFile
  unless exists <| do
    TIO.writeFile tasksFile ""
    putText <| "Initialized task database at " <> T.pack tasksFile

-- Generate a short ID using base62 encoding of timestamp
generateId :: IO Text
generateId = do
  now <- getCurrentTime
  -- Convert current time to microseconds since midnight
  let dayTime = utctDayTime now
      microseconds = diffTimeToPicoseconds dayTime `div` 1000000
      -- Convert to base62 for shorter IDs
      encoded = toBase62 (fromIntegral microseconds)
  pure <| "t-" <> T.pack encoded

-- Generate a child ID based on parent ID (e.g. "t-abc.1", "t-abc.1.2")
-- Finds the next available sequential suffix among existing children.
generateChildId :: Text -> IO Text
generateChildId parentId = do
  tasks <- loadTasks
  let children = filter (\t -> taskParent t == Just parentId) tasks
      -- Find the max suffix
      suffixes = mapMaybe (getSuffix parentId <. taskId) children
      nextSuffix = case suffixes of
        [] -> 1
        s -> maximum s + 1
  pure <| parentId <> "." <> T.pack (show nextSuffix)

getSuffix :: Text -> Text -> Maybe Int
getSuffix parent childId =
  if parent `T.isPrefixOf` childId && T.length childId > T.length parent
    then
      let rest = T.drop (T.length parent) childId
       in if T.head rest == '.'
            then readMaybe (T.unpack (T.tail rest))
            else Nothing
    else Nothing

-- Convert number to base62 (0-9, a-z, A-Z)
toBase62 :: Integer -> String
toBase62 0 = "0"
toBase62 n = reverse <| go n
  where
    alphabet = ['0' .. '9'] ++ ['a' .. 'z'] ++ ['A' .. 'Z']
    go 0 = []
    go x =
      let (q, r) = x `divMod` 62
          idx = fromIntegral r
          char = case drop idx alphabet of
            (c : _) -> c
            [] -> '0' -- Fallback (should never happen)
       in char : go q

-- Load all tasks from JSONL file (with migration support)
loadTasks :: IO [Task]
loadTasks = do
  tasksFile <- getTasksFilePath
  exists <- doesFileExist tasksFile
  if exists
    then do
      content <- TIO.readFile tasksFile
      let taskLines = T.lines content
      pure <| mapMaybe decodeTask taskLines
    else pure []
  where
    decodeTask :: Text -> Maybe Task
    decodeTask line =
      if T.null line
        then Nothing
        else case decode (BLC.pack <| T.unpack line) of
          Just task -> Just task
          Nothing -> migrateOldTask line

    -- Migrate old task format (with taskProject field or missing priority) to new format
    migrateOldTask :: Text -> Maybe Task
    migrateOldTask line = case Aeson.decode (BLC.pack <| T.unpack line) :: Maybe Aeson.Object of
      Nothing -> Nothing
      Just obj ->
        let taskId' = KM.lookup "taskId" obj +> parseMaybe Aeson.parseJSON
            taskTitle' = KM.lookup "taskTitle" obj +> parseMaybe Aeson.parseJSON
            taskStatus' = KM.lookup "taskStatus" obj +> parseMaybe Aeson.parseJSON
            taskCreatedAt' = KM.lookup "taskCreatedAt" obj +> parseMaybe Aeson.parseJSON
            taskUpdatedAt' = KM.lookup "taskUpdatedAt" obj +> parseMaybe Aeson.parseJSON
            -- Extract old taskDependencies (could be [Text] or [Dependency])
            oldDeps = KM.lookup "taskDependencies" obj +> parseMaybe Aeson.parseJSON :: Maybe [Text]
            newDeps = maybe [] (map (\tid -> Dependency {depId = tid, depType = Blocks})) oldDeps
            -- taskProject is ignored in new format (use epics instead)
            taskType' = WorkTask -- Old tasks become WorkTask by default
            taskParent' = Nothing
            taskNamespace' = KM.lookup "taskNamespace" obj +> parseMaybe Aeson.parseJSON
            -- Default priority to P2 (medium) for old tasks
            taskPriority' = fromMaybe P2 (KM.lookup "taskPriority" obj +> parseMaybe Aeson.parseJSON)
         in case (taskId', taskTitle', taskStatus', taskCreatedAt', taskUpdatedAt') of
              (Just tid, Just title, Just status, Just created, Just updated) ->
                Just
                  Task
                    { taskId = tid,
                      taskTitle = title,
                      taskType = taskType',
                      taskParent = taskParent',
                      taskNamespace = taskNamespace',
                      taskStatus = status,
                      taskPriority = taskPriority',
                      taskDependencies = newDeps,
                      taskCreatedAt = created,
                      taskUpdatedAt = updated
                    }
              _ -> Nothing

-- Save a single task (append to JSONL)
saveTask :: Task -> IO ()
saveTask task = do
  tasksFile <- getTasksFilePath
  let json = encode task
  BLC.appendFile tasksFile (json <> "\n")

-- Create a new task
createTask :: Text -> TaskType -> Maybe Text -> Maybe Text -> Priority -> [Dependency] -> IO Task
createTask title taskType parent namespace priority deps = do
  tid <- maybe generateId generateChildId parent
  now <- getCurrentTime
  let task =
        Task
          { taskId = tid,
            taskTitle = title,
            taskType = taskType,
            taskParent = parent,
            taskNamespace = namespace,
            taskStatus = Open,
            taskPriority = priority,
            taskDependencies = deps,
            taskCreatedAt = now,
            taskUpdatedAt = now
          }
  saveTask task
  pure task

-- Update task status
updateTaskStatus :: Text -> Status -> IO ()
updateTaskStatus tid newStatus = do
  tasks <- loadTasks
  now <- getCurrentTime
  let updatedTasks = map updateIfMatch tasks
      updateIfMatch t =
        if taskId t == tid
          then t {taskStatus = newStatus, taskUpdatedAt = now}
          else t
  -- Rewrite the entire file (simple approach for MVP)
  tasksFile <- getTasksFilePath
  TIO.writeFile tasksFile ""
  traverse_ saveTask updatedTasks

-- List tasks, optionally filtered by type, parent, status, or namespace
listTasks :: Maybe TaskType -> Maybe Text -> Maybe Status -> Maybe Text -> IO [Task]
listTasks maybeType maybeParent maybeStatus maybeNamespace = do
  tasks <- loadTasks
  let filtered =
        tasks
          |> filterByType maybeType
          |> filterByParent maybeParent
          |> filterByStatus maybeStatus
          |> filterByNamespace maybeNamespace
  pure filtered
  where
    filterByType Nothing ts = ts
    filterByType (Just typ) ts = filter (\t -> taskType t == typ) ts
    filterByParent Nothing ts = ts
    filterByParent (Just pid) ts = filter (\t -> taskParent t == Just pid) ts
    filterByStatus Nothing ts = ts
    filterByStatus (Just status) ts = filter (\t -> taskStatus t == status) ts
    filterByNamespace Nothing ts = ts
    filterByNamespace (Just ns) ts = filter (\t -> taskNamespace t == Just ns) ts

-- Get ready tasks (not blocked by dependencies and not a parent)
getReadyTasks :: IO [Task]
getReadyTasks = do
  allTasks <- loadTasks
  let openTasks = filter (\t -> taskStatus t /= Done) allTasks
      doneIds = map taskId <| filter (\t -> taskStatus t == Done) allTasks

      -- Find all tasks that act as parents
      parentIds = mapMaybe taskParent allTasks
      isParent tid = tid `elem` parentIds

      -- Only Blocks and ParentChild dependencies block ready work
      blockingDepIds task = [depId dep | dep <- taskDependencies task, depType dep `elem` [Blocks, ParentChild]]
      isReady task =
        not (isParent (taskId task))
          && all (`elem` doneIds) (blockingDepIds task)
  pure <| filter isReady openTasks

-- Get dependency tree for a task (returns tasks)
getDependencyTree :: Text -> IO [Task]
getDependencyTree tid = do
  tasks <- loadTasks
  case filter (\t -> taskId t == tid) tasks of
    [] -> pure []
    (task : _) -> pure <| collectDeps tasks task
  where
    collectDeps :: [Task] -> Task -> [Task]
    collectDeps allTasks task =
      let depIds = map depId (taskDependencies task)
          deps = filter (\t -> taskId t `elem` depIds) allTasks
       in task : concatMap (collectDeps allTasks) deps

-- Show dependency tree for a task
showDependencyTree :: Text -> IO ()
showDependencyTree tid = do
  tasks <- loadTasks
  case filter (\t -> taskId t == tid) tasks of
    [] -> putText "Task not found"
    (task : _) -> printTree tasks task 0
  where
    printTree :: [Task] -> Task -> Int -> IO ()
    printTree allTasks task indent = do
      putText <| T.pack (replicate (indent * 2) ' ') <> taskId task <> ": " <> taskTitle task
      let depIds = map depId (taskDependencies task)
          deps = filter (\t -> taskId t `elem` depIds) allTasks
      traverse_ (\dep -> printTree allTasks dep (indent + 1)) deps

-- Get task tree (returns tasks hierarchically)
getTaskTree :: Maybe Text -> IO [Task]
getTaskTree maybeId = do
  tasks <- loadTasks
  case maybeId of
    Nothing -> do
      -- Return all epics with their children
      let epics = filter (\t -> taskType t == Epic) tasks
       in pure <| concatMap (collectChildren tasks) epics
    Just tid -> do
      -- Return specific task/epic with its children
      case filter (\t -> taskId t == tid) tasks of
        [] -> pure []
        (task : _) -> pure <| collectChildren tasks task
  where
    collectChildren :: [Task] -> Task -> [Task]
    collectChildren allTasks task =
      let children = filter (\t -> taskParent t == Just (taskId task)) allTasks
       in task : concatMap (collectChildren allTasks) children

-- Show task tree (epic with children, or all epics if no ID given)
showTaskTree :: Maybe Text -> IO ()
showTaskTree maybeId = do
  tasks <- loadTasks
  case maybeId of
    Nothing -> do
      -- Show all epics with their children
      let epics = filter (\t -> taskType t == Epic) tasks
      if null epics
        then putText "No epics found"
        else traverse_ (printEpicTree tasks) epics
    Just tid -> do
      -- Show specific task/epic with its children
      case filter (\t -> taskId t == tid) tasks of
        [] -> putText "Task not found"
        (task : _) -> printEpicTree tasks task
  where
    printEpicTree :: [Task] -> Task -> IO ()
    printEpicTree allTasks task = printTreeNode allTasks task 0

    printTreeNode :: [Task] -> Task -> Int -> IO ()
    printTreeNode allTasks task indent = printTreeNode' allTasks task indent []

    printTreeNode' :: [Task] -> Task -> Int -> [Bool] -> IO ()
    printTreeNode' allTasks task indent ancestry = do
      let children = filter (\t -> taskParent t == Just (taskId task)) allTasks
          -- Build tree prefix using box-drawing characters
          prefix =
            if indent == 0
              then ""
              else
                let ancestorPrefixes = map (\hasMore -> if hasMore then "│   " else "    ") (List.init ancestry)
                    myPrefix = if List.last ancestry then "├── " else "└── "
                 in T.pack <| concat ancestorPrefixes ++ myPrefix
          -- For epics, show progress count [completed/total]; for tasks, show status checkbox
          statusStr = case taskType task of
            Epic ->
              let total = length children
                  completed = length <| filter (\t -> taskStatus t == Done) children
               in "[" <> T.pack (show completed) <> "/" <> T.pack (show total) <> "]"
            WorkTask -> case taskStatus task of
              Open -> "[ ]"
              InProgress -> "[~]"
              Review -> "[?]"
              Done -> "[✓]"
          nsStr = case taskNamespace task of
            Nothing -> ""
            Just ns -> "[" <> ns <> "] "
          -- Calculate available width for title (80 cols - prefix - id - labels)
          usedWidth = T.length prefix + T.length (taskId task) + T.length statusStr + T.length nsStr + 2
          availableWidth = max 20 (80 - usedWidth)
          truncatedTitle =
            if T.length (taskTitle task) > availableWidth
              then T.take (availableWidth - 3) (taskTitle task) <> "..."
              else taskTitle task
      putText <| prefix <> taskId task <> " " <> statusStr <> " " <> nsStr <> truncatedTitle

      -- Print children with updated ancestry
      let indexedChildren = zip [1 ..] children
          totalChildren = length children
      traverse_
        ( \(idx, child) ->
            let hasMoreSiblings = idx < totalChildren
             in printTreeNode' allTasks child (indent + 1) (ancestry ++ [hasMoreSiblings])
        )
        indexedChildren

-- Helper to print a task
printTask :: Task -> IO ()
printTask t = do
  tasks <- loadTasks
  let progressInfo =
        if taskType t == Epic
          then
            let children = filter (\child -> taskParent child == Just (taskId t)) tasks
                total = length children
                completed = length <| filter (\child -> taskStatus child == Done) children
             in " [" <> T.pack (show completed) <> "/" <> T.pack (show total) <> "]"
          else ""
      parentInfo = case taskParent t of
        Nothing -> ""
        Just p -> " (parent: " <> p <> ")"
      namespaceInfo = case taskNamespace t of
        Nothing -> ""
        Just ns -> " [" <> ns <> "]"
  putText
    <| taskId t
    <> " ["
    <> T.pack (show (taskType t))
    <> "] ["
    <> T.pack (show (taskStatus t))
    <> "]"
    <> progressInfo
    <> " "
    <> taskTitle t
    <> parentInfo
    <> namespaceInfo

-- Show detailed task information (human-readable)
showTaskDetailed :: Task -> IO ()
showTaskDetailed t = do
  tasks <- loadTasks
  putText "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  putText <| "Task: " <> taskId t
  putText "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  putText <| "Title:      " <> taskTitle t
  putText <| "Type:       " <> T.pack (show (taskType t))
  putText <| "Status:     " <> T.pack (show (taskStatus t))
  putText <| "Priority:   " <> T.pack (show (taskPriority t)) <> priorityDesc

  -- Show epic progress if this is an epic
  when (taskType t == Epic) <| do
    let children = filter (\child -> taskParent child == Just (taskId t)) tasks
        total = length children
        completed = length <| filter (\child -> taskStatus child == Done) children
        percentage = if total == 0 then 0 else (completed * 100) `div` total
    putText <| "Progress:   " <> T.pack (show completed) <> "/" <> T.pack (show total) <> " (" <> T.pack (show percentage) <> "%)"

  case taskParent t of
    Nothing -> pure ()
    Just p -> putText <| "Parent:     " <> p
  case taskNamespace t of
    Nothing -> pure ()
    Just ns -> putText <| "Namespace:  " <> ns
  putText <| "Created:    " <> T.pack (show (taskCreatedAt t))
  putText <| "Updated:    " <> T.pack (show (taskUpdatedAt t))

  -- Show dependencies
  unless (null (taskDependencies t)) <| do
    putText ""
    putText "Dependencies:"
    traverse_ printDependency (taskDependencies t)

  putText "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  where
    priorityDesc = case taskPriority t of
      P0 -> " (Critical)"
      P1 -> " (High)"
      P2 -> " (Medium)"
      P3 -> " (Low)"
      P4 -> " (Backlog)"

    printDependency dep =
      putText <| "  - " <> depId dep <> " [" <> T.pack (show (depType dep)) <> "]"

-- Export tasks: Consolidate JSONL file (remove duplicates, keep latest version)
exportTasks :: IO ()
exportTasks = do
  tasks <- loadTasks
  -- Rewrite the entire file with deduplicated tasks
  tasksFile <- getTasksFilePath
  TIO.writeFile tasksFile ""
  traverse_ saveTask tasks

-- Task statistics
data TaskStats = TaskStats
  { totalTasks :: Int,
    openTasks :: Int,
    inProgressTasks :: Int,
    reviewTasks :: Int,
    doneTasks :: Int,
    totalEpics :: Int,
    readyTasks :: Int,
    blockedTasks :: Int,
    tasksByPriority :: [(Priority, Int)],
    tasksByNamespace :: [(Text, Int)]
  }
  deriving (Show, Eq, Generic)

instance ToJSON TaskStats

instance FromJSON TaskStats

-- Get task statistics
getTaskStats :: IO TaskStats
getTaskStats = do
  tasks <- loadTasks
  ready <- getReadyTasks
  let total = length tasks
      open = length <| filter (\t -> taskStatus t == Open) tasks
      inProg = length <| filter (\t -> taskStatus t == InProgress) tasks
      review = length <| filter (\t -> taskStatus t == Review) tasks
      done = length <| filter (\t -> taskStatus t == Done) tasks
      epics = length <| filter (\t -> taskType t == Epic) tasks
      readyCount = length ready
      blockedCount = total - readyCount - done
      -- Count tasks by priority
      byPriority =
        [ (P0, length <| filter (\t -> taskPriority t == P0) tasks),
          (P1, length <| filter (\t -> taskPriority t == P1) tasks),
          (P2, length <| filter (\t -> taskPriority t == P2) tasks),
          (P3, length <| filter (\t -> taskPriority t == P3) tasks),
          (P4, length <| filter (\t -> taskPriority t == P4) tasks)
        ]
      -- Count tasks by namespace
      namespaces = mapMaybe taskNamespace tasks
      uniqueNs = List.nub namespaces
      byNamespace = map (\ns -> (ns, length <| filter (\t -> taskNamespace t == Just ns) tasks)) uniqueNs
  pure
    TaskStats
      { totalTasks = total,
        openTasks = open,
        inProgressTasks = inProg,
        reviewTasks = review,
        doneTasks = done,
        totalEpics = epics,
        readyTasks = readyCount,
        blockedTasks = blockedCount,
        tasksByPriority = byPriority,
        tasksByNamespace = byNamespace
      }

-- Show task statistics (human-readable)
showTaskStats :: IO ()
showTaskStats = do
  stats <- getTaskStats
  putText "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  putText "Task Statistics"
  putText "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  putText <| "Total tasks:       " <> T.pack (show (totalTasks stats))
  putText <| "  Open:            " <> T.pack (show (openTasks stats))
  putText <| "  In Progress:     " <> T.pack (show (inProgressTasks stats))
  putText <| "  Review:          " <> T.pack (show (reviewTasks stats))
  putText <| "  Done:            " <> T.pack (show (doneTasks stats))
  putText ""
  putText <| "Epics:             " <> T.pack (show (totalEpics stats))
  putText ""
  putText <| "Ready to work:     " <> T.pack (show (readyTasks stats))
  putText <| "Blocked:           " <> T.pack (show (blockedTasks stats))
  putText ""
  putText "By Priority:"
  traverse_ printPriority (tasksByPriority stats)
  unless (null (tasksByNamespace stats)) <| do
    putText ""
    putText "By Namespace:"
    traverse_ printNamespace (tasksByNamespace stats)
  putText "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  where
    printPriority (p, count) =
      let label = case p of
            P0 -> "P0 (Critical)"
            P1 -> "P1 (High)"
            P2 -> "P2 (Medium)"
            P3 -> "P3 (Low)"
            P4 -> "P4 (Backlog)"
       in putText <| "  " <> T.pack (show count) <> " " <> label
    printNamespace (ns, count) =
      putText <| "  " <> T.pack (show count) <> " " <> ns

-- Import tasks: Read from another JSONL file and merge with existing tasks
importTasks :: FilePath -> IO ()
importTasks filePath = do
  exists <- doesFileExist filePath
  unless exists <| panic (T.pack filePath <> " does not exist")

  -- Load tasks from import file
  content <- TIO.readFile filePath
  let importLines = T.lines content
      importedTasks = mapMaybe decodeTask importLines

  -- Load existing tasks
  existingTasks <- loadTasks

  -- Create a map of existing task IDs for quick lookup
  let existingIds = map taskId existingTasks
      -- Filter to only new tasks (not already in our database)
      newTasks = filter (\t -> taskId t `notElem` existingIds) importedTasks
      -- For tasks that exist, update them with imported data
      updatedTasks = map (updateWithImported importedTasks) existingTasks
      -- Combine: updated existing tasks + new tasks
      allTasks = updatedTasks ++ newTasks

  -- Rewrite tasks.jsonl with merged data
  tasksFile <- getTasksFilePath
  TIO.writeFile tasksFile ""
  traverse_ saveTask allTasks
  where
    decodeTask :: Text -> Maybe Task
    decodeTask line =
      if T.null line
        then Nothing
        else decode (BLC.pack <| T.unpack line)

    -- Update an existing task if there's a newer version in imported tasks
    updateWithImported :: [Task] -> Task -> Task
    updateWithImported imported existing =
      case filter (\t -> taskId t == taskId existing) imported of
        [] -> existing -- No imported version, keep existing
        (importedTask : _) ->
          -- Use imported version if it's newer (based on updatedAt)
          if taskUpdatedAt importedTask > taskUpdatedAt existing
            then importedTask
            else existing