Skip to content

Discord Commands

Discord slash command definitions and handlers.

Discord slash commands for AgentQueue.

All commands delegate their business logic to the shared CommandHandler, ensuring feature parity with the chat agent LLM tools. This file is intentionally a thin formatting layer: each slash command calls handler.execute(name, args) and only handles Discord-specific presentation (ephemeral replies, embeds, file attachments, autocomplete). No business logic lives here -- see src/command_handler.py for that.

Classes

NoteContentView

NoteContentView(project_id: str, note_slug: str, handler=None, bot=None)

Bases: View

View attached to a note content message with Dismiss, Delete, and Plan buttons.

Source code in src/discord/commands.py
def __init__(self, project_id: str, note_slug: str, handler=None, bot=None) -> None:
    super().__init__(timeout=None)
    self.add_item(_NotePlanButton(project_id, note_slug, handler, bot))
    self.add_item(_NoteDismissButton(project_id, note_slug, bot))
    self.add_item(_NoteDeleteButton(project_id, note_slug, handler, bot))

NotesView

NotesView(project_id: str, notes: list[dict], page: int = 0, handler=None, bot=None)

Bases: View

Interactive table-of-contents for project notes with per-note buttons.

Source code in src/discord/commands.py
def __init__(
    self,
    project_id: str,
    notes: list[dict],
    page: int = 0,
    handler=None,
    bot=None,
) -> None:
    super().__init__(timeout=None)
    self.project_id = project_id
    self.notes = notes
    self.page = page
    self._handler = handler
    self._bot = bot
    self.total_pages = max(1, (len(notes) + _NOTES_PER_PAGE - 1) // _NOTES_PER_PAGE)
    self._rebuild_components()

MenuView

MenuView(handler, bot)

Bases: View

Persistent interactive control panel for agent-queue.

Provides clickable buttons for common actions — useful for mobile usage and remote control without typing slash commands. The view never times out so the message stays interactive as long as the bot is running.

Source code in src/discord/commands.py
def __init__(self, handler, bot) -> None:
    super().__init__(timeout=None)
    self._handler = handler
    self._bot = bot

Functions

all_tasks_button async
all_tasks_button(interaction: Interaction, button: Button) -> None

Show all tasks across all projects in tree view format.

Source code in src/discord/commands.py
@discord.ui.button(
    label="All Tasks",
    style=discord.ButtonStyle.primary,
    emoji="🌳",
    row=0,
)
async def all_tasks_button(
    self, interaction: discord.Interaction, button: discord.ui.Button
) -> None:
    """Show all tasks across all projects in tree view format."""
    await interaction.response.defer(ephemeral=True)

    # Get all projects so we can fetch tree views per project.
    proj_result = await self._handler.execute("list_projects", {})
    projects = proj_result.get("projects", [])
    if not projects:
        await interaction.followup.send(
            "No projects configured.", ephemeral=True
        )
        return

    lines: list[str] = []
    grand_total = 0

    for proj in projects:
        pid = proj["id"]
        result = await self._handler.execute(
            "list_tasks",
            {
                "project_id": pid,
                "display_mode": "tree",
                "include_completed": False,
            },
        )

        trees = result.get("trees", [])
        total_tasks = result.get("total_tasks", 0)
        if not trees:
            continue

        grand_total += total_tasks
        lines.append(f"\n**📁 {proj.get('name', pid)}** (`{pid}`) — {total_tasks} tasks")

        for tree in trees:
            formatted = tree.get("formatted", "")
            if formatted:
                lines.append(formatted)

    if not lines:
        await interaction.followup.send(
            "No active tasks across any project.", ephemeral=True
        )
        return

    header = f"## 🌳 All Tasks — Tree View ({grand_total} total)"
    msg = header + "\n" + "\n".join(lines)
    if len(msg) > 2000:
        msg = msg[:1997] + "…"
    await interaction.followup.send(msg, ephemeral=True)
restart_task_button async
restart_task_button(interaction: Interaction, button: Button) -> None

Show failed/blocked tasks and let user pick one to restart.

Source code in src/discord/commands.py
@discord.ui.button(
    label="Restart Task",
    style=discord.ButtonStyle.secondary,
    emoji="🔄",
    row=1,
)
async def restart_task_button(
    self, interaction: discord.Interaction, button: discord.ui.Button
) -> None:
    """Show failed/blocked tasks and let user pick one to restart."""
    await interaction.response.defer(ephemeral=True)
    result = await self._handler.execute(
        "list_active_tasks_all_projects",
        {"include_completed": False},
    )
    by_project = result.get("by_project", {})
    restartable = []
    for tasks in by_project.values():
        for t in tasks:
            if t["status"] in ("FAILED", "BLOCKED", "PAUSED"):
                restartable.append(t)

    if not restartable:
        await interaction.followup.send(
            "No failed/blocked/paused tasks to restart.", ephemeral=True
        )
        return

    lines = ["**Restartable tasks** (use `/restart-task <id>`):"]
    for t in restartable[:15]:
        emoji = STATUS_EMOJIS.get(t["status"], "⚪")
        lines.append(f"{emoji} `{t['id']}` — {t['title'][:60]}")
    if len(restartable) > 15:
        lines.append(f"_...and {len(restartable) - 15} more_")
    await interaction.followup.send("\n".join(lines), ephemeral=True)
hooks_button async
hooks_button(interaction: Interaction, button: Button) -> None

Show all configured hooks across all projects with inline edit buttons.

Source code in src/discord/commands.py
@discord.ui.button(
    label="Hooks",
    style=discord.ButtonStyle.secondary,
    emoji="🪝",
    row=1,
)
async def hooks_button(
    self, interaction: discord.Interaction, button: discord.ui.Button
) -> None:
    """Show all configured hooks across all projects with inline edit buttons."""
    await interaction.response.defer(ephemeral=True)
    result = await self._handler.execute("list_hooks", {})
    hooks = result.get("hooks", [])
    if not hooks:
        await interaction.followup.send("No hooks configured.", ephemeral=True)
        return

    view = HooksListView(hooks, self._handler)
    msg = view.build_content()
    if len(msg) > 2000:
        msg = msg[:1997] + "…"
    await interaction.followup.send(msg, view=view, ephemeral=True)

HooksListView

HooksListView(hooks: list[dict], handler, *, page: int = 0)

Bases: View

Interactive hooks list with per-hook Edit buttons.

Source code in src/discord/commands.py
def __init__(self, hooks: list[dict], handler, *, page: int = 0) -> None:
    super().__init__(timeout=300)
    self._hooks = hooks
    self._handler = handler
    self.page = page
    self.total_pages = max(1, (len(hooks) + _HOOKS_PER_PAGE - 1) // _HOOKS_PER_PAGE)
    self._rebuild_components()

Functions

build_content
build_content() -> str

Build the text content for the hooks list message.

Source code in src/discord/commands.py
def build_content(self) -> str:
    """Build the text content for the hooks list message."""
    if not self._hooks:
        return "**No hooks configured.**"
    lines = [f"**🪝 Hooks ({len(self._hooks)}):**"]
    start = self.page * _HOOKS_PER_PAGE
    page_hooks = self._hooks[start : start + _HOOKS_PER_PAGE]
    for h in page_hooks:
        status = "✅" if h.get("enabled") else "❌"
        trigger = h.get("trigger", {})
        trigger_type = trigger.get("type", "?") if isinstance(trigger, dict) else "?"
        if trigger_type == "periodic":
            interval = trigger.get("interval_seconds", "?") if isinstance(trigger, dict) else "?"
            trigger_desc = f"every {interval}s"
        elif trigger_type == "event":
            event = (
                trigger.get("event_type") or trigger.get("event", "?")
            ) if isinstance(trigger, dict) else "?"
            trigger_desc = f"on `{event}`"
        else:
            trigger_desc = trigger_type
        lines.append(
            f"{status} **{h['name']}** (`{h['id']}`) — {trigger_desc} "
            f"• project: `{h.get('project_id', '?')}`"
        )
    if self.total_pages > 1:
        lines.append(f"\n_Page {self.page + 1}/{self.total_pages}_")
    return "\n".join(lines)

Functions

setup_commands

setup_commands(bot: Bot) -> None

Register all slash commands on the bot.

Source code in src/discord/commands.py
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
def setup_commands(bot: commands.Bot) -> None:
    """Register all slash commands on the bot."""

    # Shortcut — the shared command handler is owned by the ChatAgent.
    # Every slash command calls `handler.execute(name, args)` for its
    # business logic and only handles Discord-specific formatting here.
    handler = bot.agent.handler

    # ---------------------------------------------------------------------------
    # Channel→project resolution helper
    # ---------------------------------------------------------------------------

    async def _resolve_project_from_context(
        interaction: discord.Interaction,
        project_id: str | None,
    ) -> str | None:
        """Resolve *project_id*, falling back to the channel→project mapping.

        If *project_id* was explicitly supplied by the user it is returned
        unchanged.  Otherwise the interaction's channel is checked against
        the bot's reverse channel-to-project lookup so that commands run
        inside a project-specific channel automatically inherit that project.

        For threads inside a project channel, the parent channel is also
        checked so that slash commands invoked from threads still resolve
        to the correct project.
        """
        if project_id is not None:
            return project_id
        # Direct channel lookup
        result = bot.get_project_for_channel(interaction.channel_id)
        if result:
            return result
        # If the interaction is in a thread, check the parent channel
        channel = interaction.channel
        parent_id = getattr(channel, "parent_id", None)
        if parent_id:
            return bot.get_project_for_channel(parent_id)
        return None

    _NO_PROJECT_MSG = (
        "Could not determine project — please provide `project_id` "
        "or run this command from a project channel."
    )

    # ---------------------------------------------------------------------------
    # Shared task-detail helper
    # ---------------------------------------------------------------------------

    async def _format_task_detail(task_id: str) -> str | None:
        """Fetch and format full task details. Returns None if task not found."""
        result = await handler.execute("get_task", {"task_id": task_id})
        if "error" in result:
            return None

        # Build type tag prefix
        tags = []
        if result.get("is_plan_subtask"):
            tags.append(TYPE_TAGS["plan_subtask"])
        if result.get("subtasks"):
            tags.append(TYPE_TAGS["has_subtasks"])
        if result.get("pr_url"):
            tags.append(TYPE_TAGS["has_pr"])
        if result.get("requires_approval"):
            tags.append(TYPE_TAGS["approval_required"])
        tag_str = " ".join(tags) + " " if tags else ""

        status = result['status']
        emoji = STATUS_EMOJIS.get(status, "⚪")

        lines = [
            f"## {tag_str}Task `{result['id']}`",
            f"**Title:** {result['title']}",
            f"**Status:** {emoji} {status}",
            f"**Project:** `{result['project_id']}`",
            f"**Priority:** {result['priority']}",
        ]
        if result.get("assigned_agent"):
            lines.append(f"**Agent:** {result['assigned_agent']}")
        if result.get("retry_count"):
            lines.append(f"**Retries:** {result['retry_count']} / {result['max_retries']}")
        if result.get("parent_task_id"):
            lines.append(f"**Parent Task:** `{result['parent_task_id']}`")
        if result.get("pr_url"):
            lines.append(f"**PR:** {result['pr_url']}")

        # Dependency visualization
        depends_on = result.get("depends_on", [])
        if depends_on:
            lines.append("\n**Depends On:**")
            for dep in depends_on:
                dep_emoji = STATUS_EMOJIS.get(dep["status"], "⚪")
                lines.append(f"  {dep_emoji} `{dep['id']}` — {dep['title']} ({dep['status']})")

        blocks = result.get("blocks", [])
        if blocks:
            lines.append("\n**Blocks:**")
            for blk in blocks:
                blk_emoji = STATUS_EMOJIS.get(blk["status"], "⚪")
                lines.append(f"  {blk_emoji} `{blk['id']}` — {blk['title']} ({blk['status']})")

        # Subtask tree view
        subtasks = result.get("subtasks", [])
        if subtasks:
            completed = sum(1 for st in subtasks if st["status"] == "COMPLETED")
            bar = progress_bar(completed, len(subtasks), width=8)
            lines.append(f"\n**Subtasks:** {bar}")
            for i, st in enumerate(subtasks):
                is_last = (i == len(subtasks) - 1)
                st_emoji = STATUS_EMOJIS.get(st["status"], "⚪")
                connector = "└── " if is_last else "├── "
                lines.append(f"  {connector}{st_emoji} `{st['id']}` — {st['title']}")

        desc = result.get("description", "")
        if desc:
            desc = desc if len(desc) <= 800 else desc[:800] + "..."
            lines.append(f"\n**Description:**\n{desc}")
        return "\n".join(lines)

    # ---------------------------------------------------------------------------
    # Interactive UI components for task lists
    # ---------------------------------------------------------------------------

    _STATUS_ORDER = [
        "IN_PROGRESS", "ASSIGNED", "READY", "DEFINED",
        "PAUSED", "WAITING_INPUT", "AWAITING_APPROVAL", "VERIFYING",
        "FAILED", "BLOCKED", "COMPLETED",
    ]
    _STATUS_DISPLAY: dict[str, str] = {
        "DEFINED": "Defined", "READY": "Ready", "ASSIGNED": "Assigned",
        "IN_PROGRESS": "In Progress", "VERIFYING": "Verifying",
        "COMPLETED": "Completed", "PAUSED": "Paused",
        "WAITING_INPUT": "Waiting Input", "FAILED": "Failed",
        "BLOCKED": "Blocked", "AWAITING_APPROVAL": "Awaiting Approval",
    }
    # Sections expanded by default (active/actionable states)
    _DEFAULT_EXPANDED = {
        "IN_PROGRESS", "ASSIGNED", "READY",
        "FAILED", "BLOCKED", "PAUSED", "WAITING_INPUT", "AWAITING_APPROVAL",
    }
    _MAX_TASKS_PER_SECTION = 15

    class StatusToggleButton(discord.ui.Button):
        """Toggles a status section between expanded and collapsed."""

        def __init__(self, status: str, count: int, is_expanded: bool) -> None:
            emoji = _STATUS_EMOJIS.get(status, "⚪")
            display = _STATUS_DISPLAY.get(status, status)
            label = f"{display} ({count})"
            style = (
                discord.ButtonStyle.primary if is_expanded
                else discord.ButtonStyle.secondary
            )
            super().__init__(style=style, label=label, emoji=emoji)
            self.status = status

        async def callback(self, interaction: discord.Interaction) -> None:
            view: TaskReportView = self.view
            if self.status in view.expanded:
                view.expanded.discard(self.status)
            else:
                view.expanded.add(self.status)
            view._rebuild_components()
            content = view.build_content()
            await interaction.response.edit_message(content=content, view=view)

    class TaskDetailSelect(discord.ui.Select):
        """Dropdown to pick a task and view its full details."""

        def __init__(self, options: list[discord.SelectOption]) -> None:
            super().__init__(
                placeholder="Select a task for details...",
                options=options,
            )

        async def callback(self, interaction: discord.Interaction) -> None:
            task_id = self.values[0]
            await interaction.response.defer(ephemeral=True)
            detail = await _format_task_detail(task_id)
            if detail is None:
                await interaction.followup.send(
                    f"Task `{task_id}` not found.", ephemeral=True
                )
            else:
                await interaction.followup.send(detail, ephemeral=True)

    class TaskReportView(discord.ui.View):
        """Grouped task report with collapsible status sections and detail select.

        Displays tasks grouped by status with tree-view for parent/subtask
        relationships and type tags for quick identification.
        """

        def __init__(
            self,
            tasks_by_status: dict[str, list],
            total: int,
            *,
            all_tasks: list | None = None,
        ) -> None:
            super().__init__(timeout=600)
            self.tasks_by_status = tasks_by_status
            self.total = total
            # Build parent→subtask lookup for tree view
            self._all_tasks = all_tasks or []
            self._subtask_ids: set[str] = set()
            self._subtask_map: dict[str, list] = {}  # parent_id → [child tasks]
            for t in self._all_tasks:
                pid = t.get("parent_task_id")
                if pid:
                    self._subtask_ids.add(t["id"])
                    self._subtask_map.setdefault(pid, []).append(t)
            self.expanded: set[str] = set()
            for status in _DEFAULT_EXPANDED:
                if status in tasks_by_status:
                    self.expanded.add(status)
            # If nothing expanded, expand the first non-empty section
            if not self.expanded:
                for status in _STATUS_ORDER:
                    if status in tasks_by_status:
                        self.expanded.add(status)
                        break
            self._rebuild_components()

        def _get_type_tag(self, task: dict) -> str:
            """Return a type tag emoji based on task properties."""
            tags = []
            if task.get("is_plan_subtask"):
                tags.append(TYPE_TAGS["plan_subtask"])
            if task["id"] in self._subtask_map:
                tags.append(TYPE_TAGS["has_subtasks"])
            if task.get("pr_url"):
                tags.append(TYPE_TAGS["has_pr"])
            return "".join(tags)

        def _rebuild_components(self) -> None:
            self.clear_items()
            # Toggle buttons for each status that has tasks
            for status in _STATUS_ORDER:
                if status not in self.tasks_by_status:
                    continue
                count = len(self.tasks_by_status[status])
                is_expanded = status in self.expanded
                self.add_item(StatusToggleButton(status, count, is_expanded))
            # Select dropdown with tasks from expanded sections
            options: list[discord.SelectOption] = []
            for status in _STATUS_ORDER:
                if status not in self.expanded:
                    continue
                for t in self.tasks_by_status.get(status, []):
                    if len(options) >= 25:
                        break
                    title = t["title"]
                    tag = self._get_type_tag(t)
                    if tag:
                        title = f"{tag} {title}"
                    if len(title) > 95:
                        title = title[:92] + "..."
                    options.append(discord.SelectOption(
                        label=title,
                        value=t["id"],
                        description=t["id"],
                    ))
                if len(options) >= 25:
                    break
            if options:
                self.add_item(TaskDetailSelect(options))

        def _format_task_line(self, t: dict, *, show_children: bool = True) -> list[str]:
            """Format a task with optional tree-view subtasks."""
            tag = self._get_type_tag(t)
            tag_str = f"{tag} " if tag else ""
            lines = [f"{tag_str}**{t['title']}** `{t['id']}`"]

            # Show inline subtask count if parent has children
            children = self._subtask_map.get(t["id"], [])
            if children and show_children:
                completed = sum(
                    1 for c in children if c.get("status") == "COMPLETED"
                )
                total = len(children)
                if total <= 4:
                    # Show individual subtasks in tree view
                    for i, child in enumerate(children):
                        is_last = (i == total - 1)
                        child_emoji = _STATUS_EMOJIS.get(child.get("status", ""), "⚪")
                        connector = "└── " if is_last else "├── "
                        child_tag = TYPE_TAGS["plan_subtask"] + " " if child.get("is_plan_subtask") else ""
                        lines.append(
                            f"  {connector}{child_emoji} {child_tag}{child['title']} `{child['id']}`"
                        )
                else:
                    # Compact subtask summary
                    bar = progress_bar(completed, total, width=6)
                    lines.append(f"  └── {total} subtasks: {bar}")
            return lines

        def build_content(self) -> str:
            lines: list[str] = []
            # Add progress summary at top — use _all_tasks for accurate totals
            # since tasks_by_status may be filtered (e.g. completed hidden).
            if self._all_tasks:
                all_count = len(self._all_tasks)
                completed_count = sum(
                    1 for t in self._all_tasks if t.get("status") == "COMPLETED"
                )
            else:
                all_count = sum(len(v) for v in self.tasks_by_status.values())
                completed_count = len(self.tasks_by_status.get("COMPLETED", []))
            if all_count > 0:
                bar = progress_bar(completed_count, all_count, width=10)
                lines.append(f"**Progress:** {bar}")
                # Show counts for all non-completed statuses that have tasks.
                # Ordered by visual priority: active work → needs attention → queued.
                _STAT_LABELS: list[tuple[str, str]] = [
                    ("IN_PROGRESS", "In Progress"),
                    ("VERIFYING", "Verifying"),
                    ("ASSIGNED", "Assigned"),
                    ("AWAITING_APPROVAL", "Awaiting Approval"),
                    ("WAITING_INPUT", "Waiting Input"),
                    ("PAUSED", "Paused"),
                    ("FAILED", "Failed"),
                    ("BLOCKED", "Blocked"),
                    ("READY", "Ready"),
                    ("DEFINED", "Defined"),
                ]
                stat_parts: list[str] = []
                for status_val, label in _STAT_LABELS:
                    cnt = len(self.tasks_by_status.get(status_val, []))
                    if cnt > 0:
                        emoji = _STATUS_EMOJIS.get(status_val, "⚪")
                        stat_parts.append(f"{emoji} {cnt} {label}")
                if stat_parts:
                    lines.append(" · ".join(stat_parts))
                lines.append("")

            for status in _STATUS_ORDER:
                if status not in self.tasks_by_status:
                    continue
                tasks = self.tasks_by_status[status]
                emoji = _STATUS_EMOJIS.get(status, "⚪")
                display = _STATUS_DISPLAY.get(status, status)
                count = len(tasks)
                if status in self.expanded:
                    lines.append(f"### {emoji} {display} ({count})")
                    shown = tasks[:_MAX_TASKS_PER_SECTION]
                    for t in shown:
                        # Skip subtasks that are shown under their parent
                        if t["id"] in self._subtask_ids:
                            # Only skip if parent is in the same expanded section
                            parent_id = t.get("parent_task_id")
                            parent_in_section = any(
                                pt["id"] == parent_id
                                for pt in self.tasks_by_status.get(status, [])
                            )
                            if parent_in_section:
                                continue
                        task_lines = self._format_task_line(t)
                        lines.extend(task_lines)
                    if count > _MAX_TASKS_PER_SECTION:
                        lines.append(
                            f"_...and {count - _MAX_TASKS_PER_SECTION} more_"
                        )
                    lines.append("")
                else:
                    lines.append(f"{emoji} **{display}** ({count})")
            content = "\n".join(lines)
            # Trim if over Discord's 2000-char message limit.
            # Progressively reduce the per-section cap until content fits.
            if len(content) > 1950:
                for cap in (8, 4, 2):
                    lines = []
                    for status in _STATUS_ORDER:
                        if status not in self.tasks_by_status:
                            continue
                        tasks = self.tasks_by_status[status]
                        emoji = _STATUS_EMOJIS.get(status, "⚪")
                        display = _STATUS_DISPLAY.get(status, status)
                        count = len(tasks)
                        if status in self.expanded:
                            lines.append(f"### {emoji} {display} ({count})")
                            for t in tasks[:cap]:
                                tag = self._get_type_tag(t)
                                tag_str = f"{tag} " if tag else ""
                                lines.append(f"{tag_str}**{t['title']}** `{t['id']}`")
                            if count > cap:
                                lines.append(f"_...and {count - cap} more_")
                            lines.append("")
                        else:
                            lines.append(f"{emoji} **{display}** ({count})")
                    content = "\n".join(lines)
                    if len(content) <= 1950:
                        break
                # Final safety net: hard-truncate if still over limit
                if len(content) > 1950:
                    content = content[:1947] + "..."
            return content

    # ---------------------------------------------------------------------------
    # Shared formatting helpers
    # ---------------------------------------------------------------------------

    # Status visual mappings -- canonical definitions live in
    # src/discord/embeds.py; local aliases for backward compatibility
    # with the many references inside this function's nested closures.
    _STATUS_COLORS = STATUS_COLORS
    _STATUS_EMOJIS = STATUS_EMOJIS

    async def _send_long(interaction, text: str, *, followup: bool = False):
        """Send a potentially long response, splitting or attaching as file."""
        send = interaction.followup.send if followup else interaction.response.send_message
        if len(text) <= 2000:
            await send(text)
        elif len(text) <= 6000:
            chunks, current = [], ""
            for line in text.split("\n"):
                candidate = current + ("\n" if current else "") + line
                if len(candidate) > 2000:
                    if current:
                        chunks.append(current)
                    current = line
                else:
                    current = candidate
            if current:
                chunks.append(current)
            for chunk in chunks:
                await interaction.followup.send(chunk)
        else:
            file = discord.File(
                fp=io.BytesIO(text.encode("utf-8")),
                filename="response.md",
            )
            preview = text[:300].rstrip() + "\n\n*Full output attached.*"
            await send(preview, file=file)

    async def _send_error(
        interaction,
        message: str,
        *,
        followup: bool = False,
        ephemeral: bool = True,
    ):
        """Send an error response as a rich embed.

        Replaces the plain-text ``f"Error: {msg}"`` pattern with a consistent
        red embed, improving visual clarity in the Discord channel.
        """
        embed = error_embed("Error", description=message)
        if followup:
            await interaction.followup.send(embed=embed, ephemeral=ephemeral)
        else:
            await interaction.response.send_message(embed=embed, ephemeral=ephemeral)

    async def _send_success(
        interaction,
        title: str,
        *,
        description: str | None = None,
        fields: list[tuple[str, str, bool]] | None = None,
        followup: bool = False,
        ephemeral: bool = False,
        result: dict | None = None,
    ):
        """Send a success response as a rich green embed.

        If *result* contains a ``"warning"`` key the warning text is appended
        to the embed *description* so it remains visible.
        """
        if result and result.get("warning"):
            warning_text = f"⚠️ {result['warning']}"
            description = f"{description}\n\n{warning_text}" if description else warning_text
        embed = success_embed(title, description=description, fields=fields)
        if followup:
            await interaction.followup.send(embed=embed, ephemeral=ephemeral)
        else:
            await interaction.response.send_message(embed=embed, ephemeral=ephemeral)

    async def _send_info(
        interaction,
        title: str,
        *,
        description: str | None = None,
        fields: list[tuple[str, str, bool]] | None = None,
        followup: bool = False,
        ephemeral: bool = False,
    ):
        """Send an informational response as a rich blue embed."""
        embed = info_embed(title, description=description, fields=fields)
        if followup:
            await interaction.followup.send(embed=embed, ephemeral=ephemeral)
        else:
            await interaction.response.send_message(embed=embed, ephemeral=ephemeral)

    async def _send_warning(
        interaction,
        title: str,
        *,
        description: str | None = None,
        fields: list[tuple[str, str, bool]] | None = None,
        followup: bool = False,
        ephemeral: bool = False,
    ):
        """Send a warning response as a rich amber embed."""
        embed = warning_embed(title, description=description, fields=fields)
        if followup:
            await interaction.followup.send(embed=embed, ephemeral=ephemeral)
        else:
            await interaction.response.send_message(embed=embed, ephemeral=ephemeral)

    def _with_warning(msg: str, result: dict) -> str:
        """Append an in-progress task warning to *msg* if present in *result*.

        .. deprecated::
            Prefer passing ``result=result`` to ``_send_success()`` instead.
        """
        warning = result.get("warning")
        if warning:
            return f"{msg}\n\n⚠️ {warning}"
        return msg

    # ===================================================================
    # SYSTEM / STATUS COMMANDS
    # ===================================================================

    @bot.tree.command(name="status", description="Show system status overview")
    async def status_command(interaction: discord.Interaction):
        result = await handler.execute("get_status", {})

        tasks = result["tasks"]
        by_status = tasks.get("by_status", {})
        total = tasks.get("total", 0)
        completed = by_status.get("COMPLETED", 0)
        in_progress = by_status.get("IN_PROGRESS", 0)
        failed = by_status.get("FAILED", 0)

        lines = []
        if result.get("orchestrator_paused"):
            lines.append("⏸ **Orchestrator is PAUSED** — scheduling suspended")
            lines.append("")
        lines.append("## System Status")

        # Progress bar for overall completion
        if total > 0:
            bar = progress_bar(completed, total, width=12)
            lines.append(f"**Progress:** {bar}")
        # Build task breakdown — include all statuses that have nonzero counts
        # so the numbers always add up to the total.
        pending = by_status.get('DEFINED', 0)
        ready = by_status.get('READY', 0)
        assigned = by_status.get('ASSIGNED', 0)
        active = in_progress + assigned
        waiting = by_status.get('WAITING_INPUT', 0)
        paused = by_status.get('PAUSED', 0)
        verifying = by_status.get('VERIFYING', 0)
        awaiting = by_status.get('AWAITING_APPROVAL', 0)
        blocked = by_status.get('BLOCKED', 0)

        parts = []
        if pending:
            parts.append(f"{pending} pending")
        if active:
            parts.append(f"{active} active")
        if ready:
            parts.append(f"{ready} ready")
        if waiting:
            parts.append(f"{waiting} waiting input")
        if paused:
            parts.append(f"{paused} paused")
        if verifying:
            parts.append(f"{verifying} verifying")
        if awaiting:
            parts.append(f"{awaiting} awaiting approval")
        if completed:
            parts.append(f"{completed} completed")
        if failed:
            parts.append(f"{failed} failed")
        if blocked:
            parts.append(f"{blocked} blocked")

        lines.append(f"**Tasks:** {total} total — " + ", ".join(parts))
        lines.append("")

        # Agent details
        agents = result.get("agents", [])
        if agents:
            lines.append("**Agents:**")
            for a in agents:
                working_on = a.get("working_on")
                if working_on:
                    lines.append(
                        f"• **{a['name']}** ({a['state']}) → "
                        f"working on `{working_on['task_id']}` — {working_on['title']}"
                    )
                else:
                    lines.append(f"• **{a['name']}** ({a['state']})")
        else:
            lines.append("**Agents:** none registered")

        # Ready tasks
        ready = tasks.get("ready_to_work", [])
        if ready:
            lines.append("")
            lines.append(f"**Queued ({len(ready)}):**")
            for t in ready[:5]:
                lines.append(f"• `{t['id']}` {t['title']}")
            if len(ready) > 5:
                lines.append(f"_...and {len(ready) - 5} more_")

        await interaction.response.send_message("\n".join(lines))

    @bot.tree.command(name="projects", description="List all projects")
    async def projects_command(interaction: discord.Interaction):
        result = await handler.execute("list_projects", {})
        projects = result.get("projects", [])
        if not projects:
            await _send_info(interaction, "No Projects", description="No projects configured.")
            return
        lines = []
        for p in projects:
            line = f"• **{p['name']}** (`{p['id']}`) — {p['status']}, weight={p['credit_weight']}"
            if p.get("discord_channel_id"):
                line += f" | <#{p['discord_channel_id']}>"
            lines.append(line)
        await interaction.response.send_message("\n".join(lines))

    @bot.tree.command(name="agents", description="List all agents")
    async def agents_command(interaction: discord.Interaction):
        result = await handler.execute("list_agents", {})
        agents = result.get("agents", [])
        if not agents:
            await _send_info(interaction, "No Agents", description="No agents configured.")
            return
        lines = []
        for a in agents:
            task_info = f" → `{a['current_task']}`" if a.get("current_task") else ""
            lines.append(f"• **{a['name']}** (`{a['id']}`) — {a['state']}{task_info}")
        await interaction.response.send_message("\n".join(lines))

    @bot.tree.command(
        name="usage",
        description="Show Claude Code usage — active sessions, tokens, rate limits",
    )
    async def usage_command(interaction: discord.Interaction):
        await interaction.response.defer()
        result = await handler.execute("claude_usage", {})
        if "error" in result:
            await _send_error(interaction, result["error"], followup=True)
            return

        lines = ["## 📊 Claude Code Usage"]

        # Subscription info
        sub = result.get("subscription", "unknown")
        tier = result.get("rate_limit_tier", "unknown")
        lines.append(f"**Plan:** {sub} — **Tier:** `{tier}`")

        # Rate-limit status (from API probe)
        rl = result.get("rate_limit", {})
        if rl and "error" not in rl:
            status = rl.get("status", "unknown")
            status_emoji = {"allowed": "🟢", "allowed_warning": "🟡", "rejected": "🔴"}.get(
                status, "⚪"
            )
            lines.append(f"\n### Rate Limit: {status_emoji} {status}")

            for k, v in sorted(rl.items()):
                if k.endswith("_pct"):
                    claim = k.replace("_pct", "").replace("-", " ").title()
                    try:
                        pct_val = float(v.rstrip("%"))
                        bar = progress_bar(int(pct_val), 100, width=12)
                        lines.append(f"{bar} **{v}** — {claim}")
                    except ValueError:
                        lines.append(f"• **{claim}:** {v}")

            reset_human = rl.get("reset_human")
            resets_in = rl.get("resets_in")
            if reset_human:
                reset_line = f"⏰ **Resets:** {reset_human}"
                if resets_in:
                    reset_line += f" (in {resets_in})"
                lines.append(reset_line)
        elif rl_err := result.get("rate_limit_error"):
            lines.append(f"\n⚠️ Rate limit probe failed: {rl_err}")

        # Active sessions with live token counts
        sessions = result.get("active_sessions", [])
        if sessions:
            total_active = result.get("active_total_tokens", 0)
            lines.append(f"\n### Active Sessions ({len(sessions)})"
                         f" — {total_active:,} tokens total")
            for s in sorted(sessions, key=lambda x: -x["total_tokens"]):
                u = s["usage"]
                lines.append(
                    f"• **{s['project']}** (since {s['started']}) — "
                    f"{s['total_tokens']:,} tokens "
                    f"({u['input']:,} in · {u['output']:,} out · "
                    f"{u['cache_read']:,} cache · {u['cache_create']:,} create)"
                )

        # Cumulative model usage from stats-cache
        mu = result.get("model_usage", {})
        if mu:
            stats_date = result.get("stats_date", "?")
            lines.append(f"\n### All-Time Token Usage (as of {stats_date})")
            for model, data in sorted(mu.items(), key=lambda x: -x[1]["total"]):
                total = data["total"]
                lines.append(
                    f"• **{model}:** {total:,} total "
                    f"({data['input']:,} in · {data['output']:,} out · "
                    f"{data['cache_read']:,} cache-read)"
                )

        if stats_err := result.get("stats_error"):
            lines.append(f"\n⚠️ Stats: {stats_err}")

        msg = "\n".join(lines)
        if len(msg) > 2000:
            msg = msg[:1997] + "..."
        await interaction.followup.send(msg)

    @bot.tree.command(name="events", description="Show recent system events")
    @app_commands.describe(limit="Number of events to show (default 10)")
    async def events_command(interaction: discord.Interaction, limit: int = 10):
        result = await handler.execute("get_recent_events", {"limit": limit})
        events = result.get("events", [])
        if not events:
            await _send_info(interaction, "No Events", description="No recent events.")
            return
        lines = ["## Recent Events"]
        for evt in events:
            ts = evt.get("timestamp", "")
            etype = evt.get("event_type", "unknown")
            project = evt.get("project_id", "")
            task = evt.get("task_id", "")
            parts = [f"**{etype}**"]
            if project:
                parts.append(f"project=`{project}`")
            if task:
                parts.append(f"task=`{task}`")
            if ts:
                parts.append(f"at {ts}")
            lines.append(f"• {' — '.join(parts)}")
        msg = "\n".join(lines)
        if len(msg) > 2000:
            msg = msg[:1997] + "..."
        await interaction.response.send_message(msg)

    # ===================================================================
    # PROJECT COMMANDS
    # ===================================================================

    @bot.tree.command(
        name="new-project",
        description="Create a new project with an interactive wizard",
    )
    async def new_project_command(interaction: discord.Interaction):
        """Launch the interactive project-creation wizard.

        Opens a modal to collect project name, description, tech stack,
        and branch, then guides the user through repo setup and workspace
        selection before creating everything automatically.
        """
        modal = ProjectInfoModal(handler, bot)
        await interaction.response.send_modal(modal)

    @bot.tree.command(name="edit-project", description="Edit a project's settings")
    @app_commands.describe(
        project_id="Project ID",
        name="New name (optional)",
        credit_weight="New scheduling weight (optional)",
        max_concurrent_agents="New max agents (optional)",
        budget_limit="Token budget limit (optional, 0 to clear)",
        channel="Discord channel to link to this project (optional)",
    )
    async def edit_project_command(
        interaction: discord.Interaction,
        project_id: str,
        name: str | None = None,
        credit_weight: float | None = None,
        max_concurrent_agents: int | None = None,
        budget_limit: int | None = None,
        channel: discord.TextChannel | None = None,
    ):
        args: dict = {"project_id": project_id}
        if name is not None:
            args["name"] = name
        if credit_weight is not None:
            args["credit_weight"] = credit_weight
        if max_concurrent_agents is not None:
            args["max_concurrent_agents"] = max_concurrent_agents
        if budget_limit is not None:
            args["budget_limit"] = budget_limit if budget_limit > 0 else None
        if channel is not None:
            args["discord_channel_id"] = str(channel.id)
        result = await handler.execute("edit_project", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        fields = ", ".join(result.get("fields", []))
        desc = f"Project `{project_id}` updated: {fields}"
        if channel is not None:
            desc += f"\nChannel: {channel.mention}"
            bot.update_project_channel(project_id, channel)
        await _send_success(
            interaction, "Project Updated",
            description=desc,
        )

    @bot.tree.command(
        name="set-default-branch",
        description="Set the default branch for a project (creates it if needed)",
    )
    @app_commands.describe(
        project_id="Project ID",
        branch="Branch name to use as default (e.g. dev, main, master)",
    )
    async def set_default_branch_command(
        interaction: discord.Interaction,
        project_id: str,
        branch: str,
    ):
        await interaction.response.defer()
        result = await handler.execute(
            "set_default_branch",
            {"project_id": project_id, "branch": branch},
        )
        if "error" in result:
            await _send_error(interaction, result["error"], followup=True)
            return
        desc = (
            f"Project `{project_id}` default branch set to `{result['default_branch']}`"
            f"\n(was `{result['previous_branch']}`)"
        )
        if result.get("branch_created"):
            desc += f"\n\n🌿 Branch `{branch}` was created on the remote."
        await _send_success(
            interaction,
            "Default Branch Updated",
            description=desc,
            followup=True,
        )

    @bot.tree.command(name="delete-project", description="Delete a project and all its data")
    @app_commands.describe(
        project_id="Project ID to delete",
        archive_channels="Archive the project's Discord channels instead of leaving them (default: False)",
    )
    @app_commands.choices(archive_channels=[
        app_commands.Choice(name="Yes – archive channels", value=1),
        app_commands.Choice(name="No – leave channels as-is", value=0),
    ])
    async def delete_project_command(
        interaction: discord.Interaction,
        project_id: str,
        archive_channels: app_commands.Choice[int] | None = None,
    ):
        do_archive = archive_channels is not None and archive_channels.value == 1
        result = await handler.execute(
            "delete_project",
            {"project_id": project_id, "archive_channels": do_archive},
        )
        if "error" in result:
            await _send_error(interaction, result['error'])
            return

        # The command handler's _on_project_deleted callback already cleared
        # the bot's in-memory caches.  Now handle optional channel archival.
        archived: list[str] = []
        if do_archive and result.get("channel_ids"):
            guild = interaction.guild
            if guild:
                for ch_type, ch_id in result["channel_ids"].items():
                    channel = guild.get_channel(int(ch_id))
                    if channel and isinstance(channel, discord.TextChannel):
                        try:
                            # Archive by moving to read-only: deny Send Messages
                            # for @everyone while preserving history.
                            overwrite = channel.overwrites_for(guild.default_role)
                            overwrite.send_messages = False
                            await channel.set_permissions(
                                guild.default_role, overwrite=overwrite,
                                reason=f"Archived: project {project_id} deleted",
                            )
                            await channel.edit(
                                name=f"archived-{channel.name}",
                                reason=f"Archived: project {project_id} deleted",
                            )
                            archived.append(f"#{channel.name} ({ch_type})")
                        except discord.Forbidden:
                            archived.append(f"#{channel.name} ({ch_type}) — no permission to archive")

        desc = f"Project **{result.get('name', project_id)}** (`{project_id}`) deleted."
        if archived:
            desc += "\n📦 Archived channels: " + ", ".join(archived)
        elif do_archive:
            desc += "\n*(No linked channels to archive.)*"
        await _send_success(interaction, "Project Deleted", description=desc)

    # -------------------------------------------------------------------
    # CHANNEL MANAGEMENT COMMANDS
    # -------------------------------------------------------------------
    # Note: /set-channel and /set-control-interface have been removed.
    # Use /edit-project with the channel parameter instead.

    @bot.tree.command(
        name="create-channel",
        description="Create a new Discord channel for a project",
    )
    @app_commands.describe(
        project_id="Project ID",
        channel_name="Name for the new channel (defaults to project ID)",
        category="Category to create the channel in (optional)",
    )
    async def create_channel_command(
        interaction: discord.Interaction,
        project_id: str,
        channel_name: str | None = None,
        category: discord.CategoryChannel | None = None,
    ):
        await interaction.response.defer()

        # Validate project exists (direct lookup)
        project_check = await handler.execute("get_project_channels", {"project_id": project_id})
        if "error" in project_check:
            await _send_error(interaction, f"Project `{project_id}` not found.", followup=True)
            return

        name = channel_name or project_id
        # Create the Discord channel
        guild = interaction.guild
        if not guild:
            await _send_error(interaction, "Not in a guild.", followup=True)
            return

        topic = f"Agent Queue channel for project: {project_id}"

        # Make the channel private: deny @everyone, allow the bot
        overwrites = {
            guild.default_role: discord.PermissionOverwrite(read_messages=False),
            guild.me: discord.PermissionOverwrite(
                read_messages=True,
                send_messages=True,
                manage_channels=True,
                manage_messages=True,
            ),
        }

        try:
            new_channel = await guild.create_text_channel(
                name=name,
                category=category,
                topic=topic,
                overwrites=overwrites,
                reason=f"AgentQueue: channel for project {project_id}",
            )
        except discord.Forbidden:
            await _send_error(interaction, "Bot lacks permission to create channels.", followup=True)
            return
        except discord.HTTPException as e:
            await _send_error(interaction, f"Error creating channel: {e}", followup=True)
            return

        # Link it to the project in the database
        result = await handler.execute("set_project_channel", {
            "project_id": project_id,
            "channel_id": str(new_channel.id),
        })
        if "error" in result:
            await _send_error(interaction, f"Channel created but linking failed: {result['error']}", followup=True)
            return

        # Update the bot's channel cache immediately
        bot.update_project_channel(project_id, new_channel)
        await _send_success(
            interaction, "Channel Created",
            description=f"Created {new_channel.mention} as channel for project `{project_id}`",
            followup=True,
        )

    @bot.tree.command(
        name="channel-map",
        description="Show all project-to-channel mappings",
    )
    async def channel_map_command(interaction: discord.Interaction):
        result = await handler.execute("list_projects", {})
        projects = result.get("projects", [])
        if not projects:
            await _send_info(interaction, "No Projects", description="No projects configured.")
            return

        # Build a channel-centric view: collect all channel assignments
        lines = ["**Channel Map**\n"]
        assigned = []
        unassigned = []

        for p in projects:
            channel_id = p.get("discord_channel_id")
            if channel_id:
                assigned.append(
                    f"**{p['name']}** (`{p['id']}`) → <#{channel_id}>"
                )
            else:
                unassigned.append(f"`{p['id']}`")

        if assigned:
            lines.append("**Projects with dedicated channels:**")
            for entry in assigned:
                lines.append(f"• {entry}")
        else:
            lines.append("_No projects have dedicated channels yet._")

        if unassigned:
            lines.append(f"\n**Using global channels:** {', '.join(unassigned)}")

        lines.append(
            f"\n_Use `/set-channel` or `/create-channel` to assign project channels._"
        )
        await interaction.response.send_message("\n".join(lines))

    @bot.tree.command(name="pause", description="Pause a project")
    async def pause_command(interaction: discord.Interaction):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        result = await handler.execute("pause_project", {"project_id": project_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_info(
            interaction, "Project Paused",
            description=f"Project **{result.get('name', project_id)}** is now paused.",
        )

    @bot.tree.command(name="resume", description="Resume a paused project")
    async def resume_command(interaction: discord.Interaction):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        result = await handler.execute("resume_project", {"project_id": project_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_success(
            interaction, "Project Resumed",
            description=f"Project **{result.get('name', project_id)}** is now active.",
        )

    @bot.tree.command(name="set-project", description="Set or clear the active project for the chat agent")
    @app_commands.describe(project_id="Project ID to set as active (leave empty to clear)")
    async def set_project_command(interaction: discord.Interaction, project_id: str | None = None):
        args = {"project_id": project_id} if project_id else {}
        result = await handler.execute("set_active_project", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        if result.get("active_project"):
            await _send_success(
                interaction, "Active Project Set",
                description=f"Active project set to **{result.get('name', '')}** (`{result['active_project']}`)",
            )
        else:
            await _send_info(
                interaction, "Active Project Cleared",
                description="No active project is set for the chat agent.",
            )

    # ===================================================================
    # TASK COMMANDS
    # ===================================================================

    @bot.tree.command(name="tasks", description="List tasks for a project")
    async def tasks_command(
        interaction: discord.Interaction,
    ):
        await interaction.response.defer()
        try:
            project_id = await _resolve_project_from_context(interaction, None)

            args: dict = {
                "include_completed": True,
                "display_mode": "flat",
            }
            if project_id:
                args["project_id"] = project_id

            result = await handler.execute("list_tasks", args)

            if "error" in result:
                await interaction.followup.send(
                    embed=error_embed("Error", description=result["error"]),
                )
                return

            tasks = result.get("tasks", [])
            if not tasks:
                desc = "No tasks found"
                if project_id:
                    desc += f" for project `{project_id}`"
                    desc += ". Check `/status` for a cross-project overview."
                else:
                    desc += "."
                await interaction.followup.send(
                    embed=info_embed("No Tasks", description=desc),
                )
                return

            # Group tasks by status for the interactive report view
            tasks_by_status: dict[str, list] = {}
            for t in tasks:
                tasks_by_status.setdefault(t["status"], []).append(t)
            total = result.get("total", len(tasks))
            view_widget = TaskReportView(tasks_by_status, total, all_tasks=tasks)
            content = view_widget.build_content()
            await interaction.followup.send(content, view=view_widget)
        except Exception as e:
            print(f"ERROR in /tasks: {e!r}\n{traceback.format_exc()}")
            try:
                await interaction.followup.send(
                    embed=error_embed("Error", description=f"Failed to list tasks: {e}"),
                )
            except Exception:
                pass  # interaction may have expired

    @bot.tree.command(
        name="active-tasks",
        description="List active tasks across ALL projects",
    )
    @app_commands.describe(
        show_completed="Include completed/failed/blocked tasks (default: hide)",
    )
    async def active_tasks_command(
        interaction: discord.Interaction,
        show_completed: bool = False,
    ):
        await interaction.response.defer()
        result = await handler.execute(
            "list_active_tasks_all_projects",
            {"include_completed": show_completed},
        )

        by_project: dict[str, list] = result.get("by_project", {})
        total = result.get("total", 0)
        hidden = result.get("hidden_completed", 0)

        if total == 0:
            desc = (
                "No active tasks across any project."
                if not show_completed
                else "No tasks found across any project."
            )
            if hidden > 0:
                desc += (
                    f"\n\n_{hidden} completed/failed task(s) hidden — "
                    f"use `/active-tasks show_completed:True` to view._"
                )
            await interaction.followup.send(
                embed=info_embed("No Tasks", description=desc),
            )
            return

        # Build embed with one field per project (up to 25 field limit).
        label = "tasks" if show_completed else "active tasks"
        description = f"**{total} {label}** across **{len(by_project)} project(s)**"
        if hidden > 0:
            description += f"\n_{hidden} completed/failed task(s) hidden_"

        # Build per-project fields. Each project gets one embed field.
        # Cap tasks per project to fit within 1024-char field value limit.
        fields: list[tuple[str, str, bool]] = []
        max_tasks_per_field = 12  # keep field values well under 1024 chars
        for project_id in sorted(by_project.keys()):
            project_tasks = by_project[project_id]
            task_lines: list[str] = []
            for t in project_tasks[:max_tasks_per_field]:
                emoji = STATUS_EMOJIS.get(t["status"], "\u26AA")
                title = t["title"]
                if len(title) > 60:
                    title = title[:57] + "..."
                agent_info = ""
                if t.get("assigned_agent"):
                    agent_info = f" \u2190 `{t['assigned_agent']}`"
                task_lines.append(f"{emoji} **{title}** `{t['id']}`{agent_info}")
            if len(project_tasks) > max_tasks_per_field:
                task_lines.append(
                    f"_...and {len(project_tasks) - max_tasks_per_field} more_"
                )
            field_value = "\n".join(task_lines)
            # Truncate field value to Discord's limit as a safety net
            field_value = truncate(field_value, LIMIT_FIELD_VALUE)
            fields.append((
                f"`{project_id}` ({len(project_tasks)})",
                field_value,
                False,  # not inline — each project gets a full-width field
            ))

        embed = info_embed(
            "Active Tasks — All Projects",
            description=description,
            fields=fields,
        )
        await interaction.followup.send(embed=embed)

    @bot.tree.command(name="task", description="Show full details of a task")
    @app_commands.describe(task_id="Task ID")
    async def task_command(interaction: discord.Interaction, task_id: str):
        detail = await _format_task_detail(task_id)
        if detail is None:
            await interaction.response.send_message(
                embed=error_embed("Task Not Found", description=f"Task `{task_id}` was not found."),
                ephemeral=True,
            )
            return
        await interaction.response.send_message(detail)

    @bot.tree.command(name="add-task", description="Add a task manually to the active project")
    @app_commands.describe(description="What the task should do")
    async def add_task_command(interaction: discord.Interaction, description: str):
        project_id = (
            bot.get_project_for_channel(interaction.channel_id)
            or handler._active_project_id
        )
        if not project_id:
            await interaction.response.send_message(
                "No project context — use this in a project channel or set an active project.",
                ephemeral=True,
            )
            return
        title = description[:100] if len(description) > 100 else description
        result = await handler.execute("create_task", {
            "project_id": project_id,
            "title": title,
            "description": description,
        })
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        desc_preview = truncate(description, LIMIT_FIELD_VALUE)
        embed = success_embed(
            "Task Added",
            fields=[
                ("ID", f"`{result['created']}`", True),
                ("Project", f"`{result['project_id']}`", True),
                ("Status", "🔵 READY", True),
                ("Description", desc_preview, False),
            ],
        )
        await interaction.response.send_message(embed=embed)

    @bot.tree.command(name="edit-task", description="Edit a task's properties")
    @app_commands.describe(
        task_id="Task ID",
        title="New title (optional)",
        description="New description (optional)",
        priority="New priority (optional)",
        task_type="New task type (optional)",
        status="New status — admin override (optional)",
        max_retries="Max retry attempts (optional)",
        verification_type="How to verify task output (optional)",
    )
    @app_commands.choices(
        task_type=[
            app_commands.Choice(name="feature",  value="feature"),
            app_commands.Choice(name="bugfix",   value="bugfix"),
            app_commands.Choice(name="refactor", value="refactor"),
            app_commands.Choice(name="test",     value="test"),
            app_commands.Choice(name="docs",     value="docs"),
            app_commands.Choice(name="chore",    value="chore"),
            app_commands.Choice(name="research", value="research"),
            app_commands.Choice(name="plan",     value="plan"),
        ],
        status=[
            app_commands.Choice(name="DEFINED",     value="DEFINED"),
            app_commands.Choice(name="READY",       value="READY"),
            app_commands.Choice(name="IN_PROGRESS", value="IN_PROGRESS"),
            app_commands.Choice(name="COMPLETED",   value="COMPLETED"),
            app_commands.Choice(name="FAILED",      value="FAILED"),
            app_commands.Choice(name="BLOCKED",     value="BLOCKED"),
        ],
        verification_type=[
            app_commands.Choice(name="auto_test", value="auto_test"),
            app_commands.Choice(name="qa_agent",  value="qa_agent"),
            app_commands.Choice(name="human",     value="human"),
        ],
    )
    async def edit_task_command(
        interaction: discord.Interaction,
        task_id: str,
        title: str | None = None,
        description: str | None = None,
        priority: int | None = None,
        task_type: app_commands.Choice[str] | None = None,
        status: app_commands.Choice[str] | None = None,
        max_retries: int | None = None,
        verification_type: app_commands.Choice[str] | None = None,
    ):
        args: dict = {"task_id": task_id}
        if title is not None:
            args["title"] = title
        if description is not None:
            args["description"] = description
        if priority is not None:
            args["priority"] = priority
        if task_type is not None:
            args["task_type"] = task_type.value
        if status is not None:
            args["status"] = status.value
        if max_retries is not None:
            args["max_retries"] = max_retries
        if verification_type is not None:
            args["verification_type"] = verification_type.value
        result = await handler.execute("edit_task", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        fields = ", ".join(result.get("fields", []))
        desc = f"Task `{task_id}` updated: {fields}"
        if result.get("old_status"):
            from src.discord.embeds import STATUS_EMOJIS
            old_emoji = STATUS_EMOJIS.get(result["old_status"], "")
            new_emoji = STATUS_EMOJIS.get(result["new_status"], "")
            desc += f"\n{old_emoji} **{result['old_status']}** → {new_emoji} **{result['new_status']}**"
        await _send_success(
            interaction, "Task Updated",
            description=desc,
        )

    @bot.tree.command(name="stop-task", description="Stop a task that is currently in progress")
    @app_commands.describe(task_id="Task ID to stop")
    async def stop_task_command(interaction: discord.Interaction, task_id: str):
        result = await handler.execute("stop_task", {"task_id": task_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_success(interaction, "Task Stopped", description=f"Task `{task_id}` has been stopped.")

    @bot.tree.command(name="restart-task", description="Reset a task back to READY for re-execution")
    @app_commands.describe(task_id="Task ID to restart")
    async def restart_task_command(interaction: discord.Interaction, task_id: str):
        result = await handler.execute("restart_task", {"task_id": task_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_success(
            interaction, "Task Restarted",
            description=f"Task `{task_id}` restarted ({result.get('previous_status', '?')} → READY)",
        )

    @bot.tree.command(
        name="reopen-with-feedback",
        description="Reopen a completed/failed task with feedback for rework",
    )
    @app_commands.describe(
        task_id="Task ID to reopen",
        feedback="QA feedback explaining what went wrong or needs fixing",
    )
    async def reopen_with_feedback_command(
        interaction: discord.Interaction, task_id: str, feedback: str,
    ):
        result = await handler.execute(
            "reopen_with_feedback", {"task_id": task_id, "feedback": feedback},
        )
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        prev = result.get('previous_status', '?')
        title = result.get('title', '')
        await _send_success(
            interaction, "Task Reopened with Feedback",
            description=(
                f"Task `{task_id}` ({title}) reopened ({prev} → READY).\n\n"
                f"**Feedback added:**\n{feedback[:500]}"
            ),
        )

    @bot.tree.command(name="delete-task", description="Delete a task")
    @app_commands.describe(task_id="Task ID to delete")
    async def delete_task_command(interaction: discord.Interaction, task_id: str):
        result = await handler.execute("delete_task", {"task_id": task_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_success(
            interaction, "Task Deleted",
            description=f"Task `{task_id}` ({result.get('title', '')}) deleted.",
        )

    @bot.tree.command(
        name="archive-tasks",
        description="Archive completed tasks (DB + markdown notes in workspace)",
    )
    @app_commands.describe(
        project_id="Project to archive completed tasks from (optional — omit for all projects)",
        include_failed="Also archive FAILED and BLOCKED tasks (default: false)",
    )
    async def archive_tasks_command(
        interaction: discord.Interaction,
        project_id: str | None = None,
        include_failed: bool = False,
    ):
        args: dict = {"include_failed": include_failed}
        if project_id:
            args["project_id"] = project_id
        await interaction.response.defer()
        result = await handler.execute("archive_tasks", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        if "message" in result:
            await _send_info(
                interaction, "Nothing to Archive",
                description=result["message"], followup=True,
            )
            return
        count = result.get("archived_count", 0)
        scope = f" from `{project_id}`" if project_id else ""
        archive_dir = result.get("archive_dir")
        desc = f"Archived **{count}** task{'s' if count != 1 else ''}{scope}."
        if archive_dir:
            desc += f"\nNotes written to `{archive_dir}`"
        await _send_success(
            interaction, "Tasks Archived", description=desc, followup=True,
        )

    @bot.tree.command(
        name="archive-task",
        description="Archive a single completed/failed/blocked task",
    )
    @app_commands.describe(task_id="Task ID to archive")
    async def archive_task_command(interaction: discord.Interaction, task_id: str):
        result = await handler.execute("archive_task", {"task_id": task_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_success(
            interaction, "Task Archived",
            description=(
                f"Task `{task_id}` ({result.get('title', '')}) archived "
                f"(was {result.get('status', '?')})."
            ),
        )

    @bot.tree.command(
        name="list-archived",
        description="View archived tasks",
    )
    @app_commands.describe(
        project_id="Filter by project (optional)",
        limit="Max tasks to show (default 25)",
    )
    async def list_archived_command(
        interaction: discord.Interaction,
        project_id: str | None = None,
        limit: int = 25,
    ):
        args: dict = {"limit": limit}
        if project_id:
            args["project_id"] = project_id
        result = await handler.execute("list_archived", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        tasks = result.get("tasks", [])
        total = result.get("total", 0)
        if not tasks:
            scope = f" in project `{project_id}`" if project_id else ""
            await _send_info(
                interaction, "No Archived Tasks",
                description=f"No archived tasks found{scope}.",
            )
            return
        lines = []
        for t in tasks:
            status = t.get("status", "?")
            title = t.get("title", "")
            tid = t.get("id", "?")
            lines.append(f"• `{tid}` — {title} ({status})")
        body = "\n".join(lines)
        showing = f"Showing {len(tasks)} of {total}" if total > len(tasks) else f"{len(tasks)} task{'s' if len(tasks) != 1 else ''}"
        scope = f" in `{project_id}`" if project_id else ""
        await _send_info(
            interaction, f"Archived Tasks{scope}",
            description=f"{showing}\n\n{body}",
        )

    @bot.tree.command(
        name="restore-task",
        description="Restore an archived task back to active status",
    )
    @app_commands.describe(task_id="Archived task ID to restore")
    async def restore_task_command(interaction: discord.Interaction, task_id: str):
        result = await handler.execute("restore_task", {"task_id": task_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_success(
            interaction, "Task Restored",
            description=(
                f"Task `{task_id}` ({result.get('title', '')}) restored "
                f"with status DEFINED."
            ),
        )

    @bot.tree.command(
        name="archive-settings",
        description="View auto-archive configuration and status",
    )
    async def archive_settings_command(interaction: discord.Interaction):
        result = await handler.execute("archive_settings", {})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        enabled = "✅ Enabled" if result["enabled"] else "❌ Disabled"
        hours = result["after_hours"]
        statuses = ", ".join(result["statuses"]) if result["statuses"] else "None"
        archived = result["archived_count"]
        eligible = result["eligible_count"]
        desc = (
            f"**Auto-Archive:** {enabled}\n"
            f"**Archive After:** {hours} hours\n"
            f"**Eligible Statuses:** {statuses}\n\n"
            f"**Currently Archived:** {archived} task{'s' if archived != 1 else ''}\n"
            f"**Eligible Now:** {eligible} task{'s' if eligible != 1 else ''} "
            f"ready to be auto-archived"
        )
        await _send_info(interaction, "Archive Settings", description=desc)

    @bot.tree.command(name="approve-task", description="Approve a task that is awaiting approval")
    @app_commands.describe(task_id="Task ID to approve")
    async def approve_task_command(interaction: discord.Interaction, task_id: str):
        result = await handler.execute("approve_task", {"task_id": task_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_success(
            interaction, "Task Approved",
            description=f"Task `{task_id}` ({result.get('title', '')}) approved and completed.",
        )

    @bot.tree.command(
        name="skip-task",
        description="Skip a blocked/failed task to unblock its dependency chain",
    )
    @app_commands.describe(task_id="Task ID to skip")
    async def skip_task_command(interaction: discord.Interaction, task_id: str):
        result = await handler.execute("skip_task", {"task_id": task_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        unblocked_count = result.get("unblocked_count", 0)
        desc = f"Task `{task_id}` skipped (marked COMPLETED)."
        if unblocked_count:
            unblocked_list = ", ".join(
                f"`{t['id']}`" for t in result.get("unblocked", [])
            )
            desc += f"\n{unblocked_count} task(s) unblocked: {unblocked_list}"
        await _send_success(interaction, "Task Skipped", description=desc)

    @bot.tree.command(
        name="chain-health",
        description="Check dependency chain health for stuck tasks",
    )
    @app_commands.describe(
        task_id="(Optional) Check a specific blocked task",
    )
    async def chain_health_command(
        interaction: discord.Interaction,
        task_id: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        args = {}
        if task_id:
            args["task_id"] = task_id
        if project_id:
            args["project_id"] = project_id
        result = await handler.execute("get_chain_health", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return

        if "task_id" in result:
            stuck = result.get("stuck_downstream", [])
            if not stuck:
                await _send_success(
                    interaction, "Chain Healthy",
                    description=f"No stuck downstream tasks for `{result['task_id']}`.",
                )
            else:
                lines = [
                    f"**Stuck Chain:** `{result['task_id']}` — {result.get('title', '')}",
                    f"{len(stuck)} downstream task(s) stuck:",
                ]
                for t in stuck[:15]:
                    lines.append(f"  • `{t['id']}` — {t['title']} ({t['status']})")
                if len(stuck) > 15:
                    lines.append(f"  … and {len(stuck) - 15} more")
                await _send_warning(
                    interaction, "Stuck Chain Detected",
                    description="\n".join(lines),
                )
        else:
            chains = result.get("stuck_chains", [])
            if not chains:
                scope = f" in project `{result.get('project_id')}`" if result.get("project_id") else ""
                await _send_success(
                    interaction, "Chains Healthy",
                    description=f"No stuck dependency chains{scope}.",
                )
            else:
                lines = [f"**{len(chains)} stuck chain(s):**"]
                for chain in chains[:10]:
                    bt = chain["blocked_task"]
                    lines.append(
                        f"  • `{bt['id']}` — {bt['title']} "
                        f"→ {chain['stuck_count']} stuck task(s)"
                    )
                if len(chains) > 10:
                    lines.append(f"  … and {len(chains) - 10} more chains")
                await _send_warning(
                    interaction, "Stuck Chains Found",
                    description="\n".join(lines),
                )

    # Note: /set-status has been removed. Use /edit-task with the status
    # parameter instead.

    @bot.tree.command(name="task-result", description="Show the results/output of a completed task")
    @app_commands.describe(task_id="Task ID to inspect")
    async def task_result_command(interaction: discord.Interaction, task_id: str):
        await interaction.response.defer(ephemeral=True)
        result = await handler.execute("get_task_result", {"task_id": task_id})
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        fields: list[tuple[str, str, bool]] = [
            ("Result", result.get("result", "unknown"), True),
        ]
        summary = result.get("summary") or ""
        if summary:
            fields.append(("Summary", truncate(summary, LIMIT_FIELD_VALUE), False))
        files = result.get("files_changed") or []
        if files:
            file_list = "\n".join(f"• `{f}`" for f in files[:20])
            if len(files) > 20:
                file_list += f"\n_...and {len(files) - 20} more_"
            fields.append(("Files Changed", truncate(file_list, LIMIT_FIELD_VALUE), False))
        tokens = result.get("tokens_used", 0)
        if tokens:
            fields.append(("Tokens Used", f"{tokens:,}", True))
        error_msg = result.get("error_message") or ""
        if error_msg:
            snippet = truncate(error_msg, 500)
            fields.append(("Error", f"```\n{snippet}\n```", False))
        if result.get("result") == "completed":
            embed = success_embed(f"Task Result: {task_id}", fields=fields)
        else:
            embed = error_embed(f"Task Result: {task_id}", fields=fields)
        await interaction.followup.send(embed=embed, ephemeral=True)

    @bot.tree.command(name="task-diff", description="Show the git diff for a task's branch")
    @app_commands.describe(task_id="Task ID")
    async def task_diff_command(interaction: discord.Interaction, task_id: str):
        await interaction.response.defer(ephemeral=True)
        result = await handler.execute("get_task_diff", {"task_id": task_id})
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        diff = result.get("diff", "(no changes)")
        branch = result.get("branch", "?")
        header = f"**Branch:** `{branch}`\n"
        if len(diff) > 1800:
            file = discord.File(
                fp=io.BytesIO(diff.encode("utf-8")),
                filename=f"diff-{task_id}.patch",
            )
            await interaction.followup.send(
                f"{header}*Diff attached ({len(diff):,} chars)*",
                file=file, ephemeral=True,
            )
        else:
            await interaction.followup.send(
                f"{header}```diff\n{diff}\n```", ephemeral=True,
            )

    @bot.tree.command(
        name="task-deps",
        description="Show dependency graph for a task (what it needs and blocks)",
    )
    @app_commands.describe(task_id="Task ID to inspect")
    async def task_deps_command(interaction: discord.Interaction, task_id: str):
        result = await handler.execute("task_deps", {"task_id": task_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return

        status = result["status"]
        title = result["title"]
        task_emoji = STATUS_EMOJIS.get(status, "⚪")

        depends_on: list[dict] = result.get("depends_on", [])
        blocks: list[dict] = result.get("blocks", [])

        # Build embed fields
        fields: list[tuple[str, str, bool]] = [
            ("Task", f"{task_emoji} `{task_id}` — {title}", False),
            ("Status", f"{task_emoji} {status}", True),
        ]

        # Upstream: what this task needs
        if depends_on:
            dep_lines = []
            for dep in depends_on:
                emoji = STATUS_EMOJIS.get(dep["status"], "⚪")
                dep_lines.append(f"{emoji} `{dep['id']}` — {dep['title']} ({dep['status']})")
            fields.append(("Depends On", truncate("\n".join(dep_lines), LIMIT_FIELD_VALUE), False))
        else:
            fields.append(("Depends On", "_No upstream dependencies_", False))

        # Downstream: what this task blocks
        if blocks:
            blk_lines = []
            for blk in blocks:
                emoji = STATUS_EMOJIS.get(blk["status"], "⚪")
                blk_lines.append(f"{emoji} `{blk['id']}` — {blk['title']} ({blk['status']})")
            fields.append(("Blocks", truncate("\n".join(blk_lines), LIMIT_FIELD_VALUE), False))
        else:
            fields.append(("Blocks", "_No downstream dependents_", False))

        embed = status_embed(
            status,
            f"Dependencies: {task_id}",
            fields=fields,
        )
        await interaction.response.send_message(embed=embed)

    @bot.tree.command(
        name="agent-error",
        description="Show the last error recorded for a task",
    )
    @app_commands.describe(task_id="Task ID to inspect")
    async def agent_error_command(interaction: discord.Interaction, task_id: str):
        await interaction.response.defer(ephemeral=True)
        result = await handler.execute("get_agent_error", {"task_id": task_id})
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        fields: list[tuple[str, str, bool]] = [
            ("Task", result.get("title", ""), False),
            ("Status", result.get("status", ""), True),
            ("Retries", result.get("retries", ""), True),
        ]

        if result.get("message"):
            embed = error_embed(
                f"Agent Error Report: {task_id}",
                description=f"_{result['message']}_",
                fields=fields,
            )
            await interaction.followup.send(embed=embed, ephemeral=True)
            return

        fields.append(("Result", result.get("result", "unknown"), True))
        fields.append(("Error Type", f"**{result.get('error_type', 'unknown')}**", False))
        error_msg = result.get("error_message") or ""
        if error_msg:
            snippet = truncate(error_msg, 990)
            fields.append(("Error Detail", f"```\n{snippet}\n```", False))
        else:
            fields.append(("Error Detail", "_No error message recorded._", False))
        fields.append(("Suggested Fix", result.get("suggested_fix", "Review the logs"), False))
        summary = result.get("agent_summary") or ""
        if summary:
            fields.append(("Agent Summary", truncate(summary, 500), False))
        embed = error_embed(f"Agent Error Report: {task_id}", fields=fields)
        await interaction.followup.send(embed=embed, ephemeral=True)

    # ===================================================================
    # AGENT COMMANDS
    # ===================================================================

    @bot.tree.command(name="create-agent", description="Register a new agent")
    @app_commands.describe(
        name="Agent display name (leave empty for auto-generated creative name)",
        agent_type="Agent type (claude, codex, cursor, aider)",
    )
    @app_commands.choices(agent_type=[
        app_commands.Choice(name="claude", value="claude"),
        app_commands.Choice(name="codex",  value="codex"),
        app_commands.Choice(name="cursor", value="cursor"),
        app_commands.Choice(name="aider",  value="aider"),
    ])
    async def create_agent_command(
        interaction: discord.Interaction,
        name: str | None = None,
        agent_type: app_commands.Choice[str] | None = None,
    ):
        args: dict = {}
        if name:
            args["name"] = name
        if agent_type:
            args["agent_type"] = agent_type.value
        result = await handler.execute("create_agent", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        agent_fields: list[tuple[str, str, bool]] = [
            ("Name", result.get("name", name), True),
            ("ID", f"`{result['created']}`", True),
            ("Type", args.get("agent_type", "claude"), True),
            ("State", result.get("state", "IDLE"), True),
        ]
        embed = success_embed("Agent Registered", fields=agent_fields)
        await interaction.response.send_message(embed=embed)

    @bot.tree.command(
        name="pause-agent",
        description="Pause an agent so it stops receiving new tasks",
    )
    @app_commands.describe(agent_id="Agent ID to pause")
    async def pause_agent_command(
        interaction: discord.Interaction,
        agent_id: str,
    ):
        result = await handler.execute("pause_agent", {"agent_id": agent_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        desc = f"Agent `{agent_id}` is now paused."
        if result.get("note"):
            desc += f"\n{result['note']}"
        embed = success_embed("Agent Paused", description=desc)
        await interaction.response.send_message(embed=embed)

    @bot.tree.command(
        name="resume-agent",
        description="Resume a paused agent so it can receive tasks again",
    )
    @app_commands.describe(agent_id="Agent ID to resume")
    async def resume_agent_command(
        interaction: discord.Interaction,
        agent_id: str,
    ):
        result = await handler.execute("resume_agent", {"agent_id": agent_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        embed = success_embed(
            "Agent Resumed",
            description=f"Agent `{agent_id}` is now IDLE and ready to receive tasks.",
        )
        await interaction.response.send_message(embed=embed)

    @bot.tree.command(name="edit-agent", description="Edit an agent's properties")
    @app_commands.describe(
        agent_id="Agent ID",
        name="New display name (optional)",
        agent_type="New agent type (optional)",
    )
    @app_commands.choices(agent_type=[
        app_commands.Choice(name="claude", value="claude"),
        app_commands.Choice(name="codex",  value="codex"),
        app_commands.Choice(name="cursor", value="cursor"),
        app_commands.Choice(name="aider",  value="aider"),
    ])
    async def edit_agent_command(
        interaction: discord.Interaction,
        agent_id: str,
        name: str | None = None,
        agent_type: app_commands.Choice[str] | None = None,
    ):
        args: dict = {"agent_id": agent_id}
        if name is not None:
            args["name"] = name
        if agent_type is not None:
            args["agent_type"] = agent_type.value
        result = await handler.execute("edit_agent", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        fields = ", ".join(result.get("fields", []))
        await _send_success(
            interaction, "Agent Updated",
            description=f"Agent `{agent_id}` updated: {fields}",
        )

    @bot.tree.command(
        name="delete-agent",
        description="Delete an agent and its workspace mappings",
    )
    @app_commands.describe(agent_id="Agent ID to delete")
    async def delete_agent_command(
        interaction: discord.Interaction,
        agent_id: str,
    ):
        result = await handler.execute("delete_agent", {"agent_id": agent_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        embed = success_embed(
            "Agent Deleted",
            description=f"Agent `{result['name']}` (`{agent_id}`) has been removed.",
        )
        await interaction.response.send_message(embed=embed)

    # ===================================================================
    # WORKSPACE COMMANDS
    # ===================================================================

    @bot.tree.command(name="workspaces", description="List project workspaces")
    async def workspaces_command(interaction: discord.Interaction):
        project_id = await _resolve_project_from_context(interaction, None)
        args = {}
        if project_id:
            args["project_id"] = project_id
        result = await handler.execute("list_workspaces", args)
        workspaces = result.get("workspaces", [])
        if not workspaces:
            await _send_info(
                interaction, "No Workspaces",
                description="No workspaces registered. Use `/add-workspace` to add one.",
            )
            return
        lines = ["## Workspaces"]
        for ws in workspaces:
            lock_info = ""
            if ws.get("locked_by_agent_id"):
                lock_info = f" 🔒 agent=`{ws['locked_by_agent_id']}`"
                if ws.get("locked_by_task_id"):
                    lock_info += f" task=`{ws['locked_by_task_id']}`"
            name_str = f" **{ws['name']}**" if ws.get("name") else ""
            lines.append(
                f"• `{ws['id']}`{name_str} ({ws['source_type']}) — "
                f"`{ws['workspace_path']}` project=`{ws['project_id']}`{lock_info}"
            )
        msg = "\n".join(lines)
        if len(msg) > 2000:
            msg = msg[:1997] + "..."
        await interaction.response.send_message(msg)

    @bot.tree.command(name="add-workspace", description="Add a workspace directory for a project")
    @app_commands.describe(
        source="How to set up the workspace",
        path="Directory path (required for link, auto-generated for clone)",
        name="Workspace name (optional)",
    )
    @app_commands.choices(source=[
        app_commands.Choice(name="clone", value="clone"),
        app_commands.Choice(name="link",  value="link"),
    ])
    async def add_workspace_command(
        interaction: discord.Interaction,
        source: app_commands.Choice[str],
        path: str | None = None,
        name: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        args: dict = {
            "project_id": project_id,
            "source": source.value,
        }
        if path:
            args["path"] = path
        if name:
            args["name"] = name
        result = await handler.execute("add_workspace", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        embed = success_embed(
            "Workspace Added",
            fields=[
                ("ID", f"`{result['created']}`", True),
                ("Source", source.value, True),
                ("Project", f"`{project_id}`", True),
                ("Path", f"`{result.get('workspace_path', '')}`", False),
            ],
        )
        await interaction.response.send_message(embed=embed)

    @bot.tree.command(
        name="release-workspace",
        description="Force-release a stuck workspace lock",
    )
    @app_commands.describe(workspace_id="Workspace ID to release")
    async def release_workspace_command(
        interaction: discord.Interaction,
        workspace_id: str,
    ):
        result = await handler.execute("release_workspace", {"workspace_id": workspace_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_success(
            interaction, "Workspace Released",
            description=f"Workspace `{workspace_id}` lock has been released.",
        )

    @bot.tree.command(
        name="remove-workspace",
        description="Delete a workspace from a project (must not be locked)",
    )
    @app_commands.describe(workspace_id="Workspace ID or name to delete")
    async def remove_workspace_command(
        interaction: discord.Interaction,
        workspace_id: str,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        args: dict = {"workspace_id": workspace_id}
        if project_id:
            args["project_id"] = project_id
        result = await handler.execute("remove_workspace", args)
        if "error" in result:
            await _send_error(interaction, result["error"])
            return
        embed = success_embed(
            "Workspace Deleted",
            fields=[
                ("ID", f"`{result['deleted']}`", True),
                ("Name", result.get("name") or "—", True),
                ("Project", f"`{result.get('project_id', '')}`", True),
                ("Path", f"`{result.get('workspace_path', '')}`", False),
            ],
        )
        await interaction.response.send_message(embed=embed)

    @bot.tree.command(
        name="sync-workspaces",
        description="Sync all project workspaces to the latest main branch",
    )
    async def sync_workspaces_command(interaction: discord.Interaction):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        await interaction.response.defer()
        result = await handler.execute("sync_workspaces", {"project_id": project_id})
        if "error" in result:
            await _send_error(interaction, result["error"], followup=True)
            return

        total = result.get("total_workspaces", 0)
        synced = result.get("synced", 0)
        skipped = result.get("skipped", 0)
        errors = result.get("errors", 0)

        lines = [
            f"## Workspace Sync — `{project_id}`",
            f"**{synced}** synced · **{skipped}** skipped · **{errors}** errors "
            f"(of {total} total)",
            "",
        ]
        for ws in result.get("workspaces", []):
            status = ws.get("status", "unknown")
            name = ws.get("workspace_name") or ws.get("workspace_id", "?")
            if status == "synced":
                emoji = "✅"
            elif status == "skipped":
                emoji = "⏭️"
            elif status == "conflict":
                emoji = "⚠️"
            else:
                emoji = "❌"

            detail = ws.get("action") or ws.get("reason") or ""
            branch = ws.get("current_branch", "")
            branch_str = f" (`{branch}`)" if branch else ""
            lines.append(f"{emoji} **{name}**{branch_str}: {detail}")

        msg = "\n".join(lines)
        if len(msg) > 2000:
            msg = msg[:1997] + "..."
        await interaction.followup.send(msg)

    # ===================================================================
    # GIT COMMANDS
    # ===================================================================

    @bot.tree.command(
        name="git-status",
        description="Show the git status of a project's repository",
    )
    async def git_status_command(interaction: discord.Interaction):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        await interaction.response.defer()
        result = await handler.execute("get_git_status", {"project_id": project_id})
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return

        project_name = result.get("project_name", project_id)
        repo_statuses = result.get("repos", [])
        sections: list[str] = []

        for rs in repo_statuses:
            if "error" in rs:
                ws_label = rs.get("workspace_name") or rs.get("workspace_id") or "?"
                sections.append(
                    f"### Workspace: `{ws_label}`\n⚠️ {rs['error']}"
                )
                continue
            ws_name = rs.get("workspace_name")
            ws_id = rs.get("workspace_id") or "?"
            header = f"### Workspace: `{ws_name}`" if ws_name else f"### Workspace: `{ws_id}`"
            if ws_name:
                header += f" (`{ws_id}`)"
            lines = [header]
            if rs.get("path"):
                lines.append(f"**Path:** `{rs['path']}`")
            if rs.get("branch"):
                lines.append(f"**Branch:** `{rs['branch']}`")
            status_output = rs.get("status", "(clean)")
            lines.append(f"\n**Status:**\n```\n{status_output}\n```")
            if rs.get("recent_commits"):
                lines.append(f"**Recent commits:**\n```\n{rs['recent_commits']}\n```")
            sections.append("\n".join(lines))

        header = f"## Git Status: {project_name} (`{project_id}`)\n"
        full_message = header + "\n\n".join(sections)
        await _send_long(interaction, full_message, followup=True)

    # -------------------------------------------------------------------
    # GIT MANAGEMENT COMMANDS
    # -------------------------------------------------------------------
    # Project-based git commands that auto-detect the project from the
    # Discord channel.  These call the newer project-oriented handlers
    # (create_branch, checkout_branch, commit_changes, push_branch,
    # merge_branch, git_branch) which resolve repos via project_id.

    @bot.tree.command(
        name="git-branches",
        description="List branches or create a new branch in a project's repository",
    )
    @app_commands.describe(
        name="New branch name to create (omit to list branches)",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def git_branches_command(
        interaction: discord.Interaction,
        name: str | None = None,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        await interaction.response.defer()
        args: dict = {"project_id": project_id}
        if name:
            args["name"] = name
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("git_branch", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return

        if "created" in result:
            await _send_success(
                interaction, "Branch Created",
                description=f"Created and switched to branch `{result['created']}` on `{project_id}`",
                followup=True,
            )
        else:
            current = result.get("current_branch", "?")
            branches = result.get("branches", [])
            branch_list = "\n".join(branches) if branches else "(no branches)"
            text = (
                f"## Branches: `{project_id}`\n"
                f"**Current:** `{current}`\n```\n{branch_list}\n```"
            )
            await _send_long(interaction, text, followup=True)

    @bot.tree.command(
        name="git-checkout",
        description="Switch to an existing branch in a project's repository",
    )
    @app_commands.describe(
        branch_name="Branch name to switch to",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def git_checkout_command(
        interaction: discord.Interaction,
        branch_name: str,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        await interaction.response.defer()
        args: dict = {"project_id": project_id, "branch_name": branch_name}
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("checkout_branch", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        await _send_success(
            interaction, "Branch Switched",
            description=f"Switched to branch `{result['branch']}` on `{project_id}`",
            followup=True,
            result=result,
        )

    @bot.tree.command(
        name="project-commit",
        description="Stage all changes and commit in a project's repository",
    )
    @app_commands.describe(
        message="Commit message",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def project_commit_command(
        interaction: discord.Interaction,
        message: str,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        await interaction.response.defer()
        args: dict = {"project_id": project_id, "message": message}
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("commit_changes", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        if result.get("status") == "committed":
            repo_label = project_id
            await _send_success(
                interaction, "Changes Committed",
                description=f"Committed in `{repo_label}` on `{project_id}`: {message}",
                followup=True,
                result=result,
            )
        else:
            await _send_info(
                interaction, "Nothing to Commit",
                description=f"Working tree clean on `{project_id}`.",
                followup=True,
            )

    @bot.tree.command(
        name="project-push",
        description="Push a branch to origin in a project's repository",
    )
    @app_commands.describe(
        branch_name="Branch to push (defaults to current branch)",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def project_push_command(
        interaction: discord.Interaction,
        branch_name: str | None = None,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        await interaction.response.defer()
        args: dict = {"project_id": project_id}
        if branch_name:
            args["branch_name"] = branch_name
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("push_branch", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        pushed_branch = result.get("branch", "?")
        await _send_success(
            interaction, "Branch Pushed",
            description=f"Pushed `{pushed_branch}` to origin on `{project_id}`",
            followup=True,
        )

    @bot.tree.command(
        name="project-merge",
        description="Merge a branch into the default branch in a project's repository",
    )
    @app_commands.describe(
        branch_name="Branch to merge",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def project_merge_command(
        interaction: discord.Interaction,
        branch_name: str,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        await interaction.response.defer()
        args: dict = {"project_id": project_id, "branch_name": branch_name}
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("merge_branch", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        target = result.get("target", "main")
        if result.get("status") == "conflict":
            await _send_warning(
                interaction, "Merge Conflict",
                description=(
                    f"`{branch_name}` could not be merged into `{target}` "
                    f"on `{project_id}`. Merge was aborted."
                ),
                followup=True,
            )
        else:
            await _send_success(
                interaction, "Branch Merged",
                description=f"Merged `{branch_name}` into `{target}` on `{project_id}`",
                followup=True,
                result=result,
            )

    @bot.tree.command(
        name="project-create-branch",
        description="Create and switch to a new branch in a project's repository",
    )
    @app_commands.describe(
        branch_name="Name for the new branch",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def project_create_branch_command(
        interaction: discord.Interaction,
        branch_name: str,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        await interaction.response.defer()
        args: dict = {"project_id": project_id, "branch_name": branch_name}
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("create_branch", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        await _send_success(
            interaction, "Branch Created",
            description=f"Created and switched to branch `{result['branch']}` on `{project_id}`",
            followup=True,
        )

    @bot.tree.command(
        name="create-branch",
        description="Create a new git branch in a project's repo",
    )
    @app_commands.describe(
        branch_name="Name for the new branch",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def create_branch_command(
        interaction: discord.Interaction,
        branch_name: str,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        args: dict = {"project_id": project_id, "branch_name": branch_name}
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("create_branch", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_success(
            interaction, "Branch Created",
            description=f"Branch `{branch_name}` created in `{project_id}`",
        )

    @bot.tree.command(
        name="checkout-branch",
        description="Switch to an existing git branch",
    )
    @app_commands.describe(
        branch_name="Branch name to check out",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def checkout_branch_command(
        interaction: discord.Interaction,
        branch_name: str,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        args: dict = {"project_id": project_id, "branch_name": branch_name}
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("checkout_branch", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_success(
            interaction, "Branch Switched",
            description=f"Switched to branch `{branch_name}` in `{project_id}`",
            result=result,
        )

    @bot.tree.command(
        name="commit",
        description="Stage all changes and commit",
    )
    @app_commands.describe(
        message="Commit message",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def commit_command(
        interaction: discord.Interaction,
        message: str,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        args: dict = {"project_id": project_id, "message": message}
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("commit_changes", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        if result.get("status") == "nothing_to_commit":
            await _send_info(
                interaction, "Nothing to Commit",
                description=f"Working tree clean in `{project_id}`.",
            )
            return
        await _send_success(
            interaction, "Changes Committed",
            description=f"Committed in `{project_id}`: {message}",
            result=result,
        )

    @bot.tree.command(
        name="push",
        description="Push a branch to the remote",
    )
    @app_commands.describe(
        branch_name="Branch to push (optional — pushes current branch)",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def push_command(
        interaction: discord.Interaction,
        branch_name: str | None = None,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        args: dict = {"project_id": project_id}
        if branch_name:
            args["branch_name"] = branch_name
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("push_branch", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        pushed_branch = result.get("branch", branch_name or "current")
        await _send_success(
            interaction, "Branch Pushed",
            description=f"Pushed `{pushed_branch}` in `{project_id}`",
        )

    @bot.tree.command(
        name="merge",
        description="Merge a branch into the default branch",
    )
    @app_commands.describe(
        branch_name="Branch to merge",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def merge_command(
        interaction: discord.Interaction,
        branch_name: str,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        args: dict = {"project_id": project_id, "branch_name": branch_name}
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("merge_branch", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        if result.get("status") == "conflict":
            await _send_warning(
                interaction, "Merge Conflict",
                description=(
                    f"Merge conflict: `{branch_name}` → `{result.get('target', 'main')}` "
                    f"in `{project_id}`. Merge was aborted."
                ),
            )
            return
        await _send_success(
            interaction, "Branch Merged",
            description=f"Merged `{branch_name}` → `{result.get('target', 'main')}` in `{project_id}`",
            result=result,
        )

    @bot.tree.command(
        name="git-commit",
        description="Stage all changes and commit in a repository",
    )
    @app_commands.describe(
        message="Commit message",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def git_commit_command(
        interaction: discord.Interaction,
        message: str,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        # Set active project from channel context so _resolve_repo_path can
        # infer the repository even when project_id is not in the args dict.
        if project_id:
            handler.set_active_project(project_id)
        await interaction.response.defer()
        args: dict = {"message": message}
        if project_id:
            args["project_id"] = project_id
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("git_commit", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        label = project_id or "repo"
        if result.get("committed"):
            await _send_success(
                interaction, "Changes Committed",
                description=f"Committed in `{label}`: {message}",
                followup=True,
            )
        else:
            await _send_info(
                interaction, "Nothing to Commit",
                description=f"Working tree clean in `{label}`.",
                followup=True,
            )

    @bot.tree.command(
        name="git-pull",
        description="Pull (fetch + merge) a branch from remote origin",
    )
    @app_commands.describe(
        branch="Branch name to pull (defaults to current branch)",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def git_pull_command(
        interaction: discord.Interaction,
        branch: str | None = None,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if project_id:
            handler.set_active_project(project_id)
        await interaction.response.defer()
        args: dict = {}
        if project_id:
            args["project_id"] = project_id
        if branch:
            args["branch"] = branch
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("git_pull", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        label = project_id or "repo"
        await _send_success(
            interaction, "Branch Pulled",
            description=f"Pulled `{result['pulled']}` in `{label}`",
            followup=True,
        )

    @bot.tree.command(
        name="git-push",
        description="Push a branch to remote origin",
    )
    @app_commands.describe(
        branch="Branch name to push (defaults to current branch)",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def git_push_command(
        interaction: discord.Interaction,
        branch: str | None = None,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if project_id:
            handler.set_active_project(project_id)
        await interaction.response.defer()
        args: dict = {}
        if project_id:
            args["project_id"] = project_id
        if branch:
            args["branch"] = branch
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("git_push", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        label = project_id or "repo"
        await _send_success(
            interaction, "Branch Pushed",
            description=f"Pushed `{result['pushed']}` in `{label}`",
            followup=True,
        )

    @bot.tree.command(
        name="git-branch",
        description="Create and switch to a new git branch",
    )
    @app_commands.describe(
        branch_name="Name for the new branch",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def git_branch_command(
        interaction: discord.Interaction,
        branch_name: str,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if project_id:
            handler.set_active_project(project_id)
        await interaction.response.defer()
        args: dict = {"branch_name": branch_name}
        if project_id:
            args["project_id"] = project_id
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("git_create_branch", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        label = project_id or "repo"
        await _send_success(
            interaction, "Branch Created",
            description=f"Created and switched to branch `{branch_name}` in `{label}`",
            followup=True,
        )

    @bot.tree.command(
        name="git-merge",
        description="Merge a branch into the default branch",
    )
    @app_commands.describe(
        branch_name="Branch to merge",
        default_branch="Target branch (defaults to repo's default branch)",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def git_merge_command(
        interaction: discord.Interaction,
        branch_name: str,
        default_branch: str | None = None,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if project_id:
            handler.set_active_project(project_id)
        await interaction.response.defer()
        args: dict = {"branch_name": branch_name}
        if project_id:
            args["project_id"] = project_id
        if default_branch:
            args["default_branch"] = default_branch
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("git_merge", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        label = project_id or "repo"
        if result.get("merged"):
            await _send_success(
                interaction, "Branch Merged",
                description=f"Merged `{branch_name}` into `{result['into']}` in `{label}`",
                followup=True,
            )
        else:
            await _send_warning(
                interaction, "Merge Conflict",
                description=(
                    f"`{branch_name}` could not be merged into "
                    f"`{result.get('into', 'default')}` in `{label}`. Merge was aborted."
                ),
                followup=True,
            )

    @bot.tree.command(
        name="git-pr",
        description="Create a GitHub pull request",
    )
    @app_commands.describe(
        title="PR title",
        body="PR description (optional)",
        branch="Head branch (defaults to current)",
        base="Base branch (defaults to repo default)",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def git_pr_command(
        interaction: discord.Interaction,
        title: str,
        body: str = "",
        branch: str | None = None,
        base: str | None = None,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if project_id:
            handler.set_active_project(project_id)
        await interaction.response.defer()
        args: dict = {"title": title, "body": body}
        if project_id:
            args["project_id"] = project_id
        if workspace:
            args["workspace"] = workspace
        if branch:
            args["branch"] = branch
        if base:
            args["base"] = base
        result = await handler.execute("git_create_pr", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        pr_url = result.get("pr_url", "")
        await _send_success(
            interaction, "Pull Request Created",
            description=(
                f"[View PR]({pr_url})\n"
                f"**Branch:** `{result.get('branch', '?')}` → `{result.get('base', '?')}`"
            ),
            followup=True,
        )

    @bot.tree.command(
        name="git-files",
        description="List files changed compared to a base branch",
    )
    @app_commands.describe(
        base_branch="Branch to compare against (defaults to repo default)",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def git_files_command(
        interaction: discord.Interaction,
        base_branch: str | None = None,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if project_id:
            handler.set_active_project(project_id)
        await interaction.response.defer()
        args: dict = {}
        if project_id:
            args["project_id"] = project_id
        if base_branch:
            args["base_branch"] = base_branch
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("git_changed_files", args)
        if "error" in result:
            await _send_error(interaction, result['error'], followup=True)
            return
        label = project_id or "repo"
        files = result.get("files", [])
        count = result.get("count", 0)
        base = result.get("base_branch", "main")
        if not files:
            await _send_info(
                interaction, "No Changes",
                description=f"No files changed in `{label}` vs `{base}`",
                followup=True,
            )
            return
        file_list = "\n".join(f"• `{f}`" for f in files[:50])
        if count > 50:
            file_list += f"\n_...and {count - 50} more_"
        msg = (
            f"## Changed Files: `{label}` vs `{base}`\n"
            f"**{count} file(s) changed:**\n{file_list}"
        )
        await _send_long(interaction, msg, followup=True)

    @bot.tree.command(
        name="git-log",
        description="Show recent git commits",
    )
    @app_commands.describe(
        count="Number of commits to show (default 10)",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def git_log_command(
        interaction: discord.Interaction,
        count: int = 10,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        args: dict = {"project_id": project_id, "count": count}
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("git_log", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        branch = result.get("branch", "?")
        log = result.get("log", "(no commits)")
        repo_label = project_id
        msg = f"## Git Log: `{repo_label}` (branch: `{branch}`)\n```\n{log}\n```"
        await _send_long(interaction, msg, followup=False)

    @bot.tree.command(
        name="git-diff",
        description="Show git diff for a project's repo",
    )
    @app_commands.describe(
        base_branch="Base branch to diff against (optional — shows working tree diff)",
        workspace="Workspace ID or name (optional — defaults to first workspace)",
    )
    async def git_diff_command(
        interaction: discord.Interaction,
        base_branch: str | None = None,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        args: dict = {"project_id": project_id}
        if base_branch:
            args["base_branch"] = base_branch
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("git_diff", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return

        diff = result.get("diff", "(no changes)")
        base_label = result.get("base_branch", "working tree")
        repo_label = project_id
        header = f"**Repo:** `{repo_label}` | **Diff against:** `{base_label}`\n"

        if len(diff) > 1800:
            await interaction.response.defer()
            await interaction.followup.send(
                content=f"{header}*Diff attached ({len(diff):,} chars)*",
                file=discord.File(
                    fp=io.BytesIO(diff.encode("utf-8")),
                    filename=f"diff-{project_id}.patch",
                ),
            )
        else:
            await interaction.response.send_message(
                f"{header}```diff\n{diff}\n```"
            )

    # ===================================================================
    # HOOK COMMANDS
    # ===================================================================

    @bot.tree.command(name="hooks", description="List automation hooks")
    async def hooks_command(interaction: discord.Interaction):
        project_id = await _resolve_project_from_context(interaction, None)
        args = {}
        if project_id:
            args["project_id"] = project_id
        result = await handler.execute("list_hooks", args)
        hooks = result.get("hooks", [])
        if not hooks:
            await _send_info(interaction, "No Hooks", description="No hooks configured.")
            return
        view = HooksListView(hooks, handler)
        msg = view.build_content()
        if len(msg) > 2000:
            msg = msg[:1997] + "..."
        await interaction.response.send_message(msg, view=view)

    # --- Hook wizard state management ---
    # In-memory store keyed by Discord user ID.
    _hook_wizard_states: dict[int, dict] = {}


    # Context step types available in the wizard.
    _HOOK_STEP_TYPES: list[tuple[str, str]] = [
        ("shell", "Run a shell command"),
        ("read_file", "Read a file"),
        ("http", "HTTP request"),
        ("db_query", "Database query"),
        ("git_diff", "Git diff"),
        ("memory_search", "Search memory"),
        ("create_task", "Create a new task"),
        ("run_tests", "Run test suite"),
        ("list_files", "List files in directory"),
        ("file_diff", "Diff a specific file"),
    ]

    def _wizard_state(user_id: int) -> dict:
        """Get or create wizard state for a user."""
        if user_id not in _hook_wizard_states:
            _hook_wizard_states[user_id] = {
                "name": None,
                "project_id": None,
                "trigger": None,
                "context_steps": [],
                "prompt_template": None,
                "cooldown_seconds": 3600,
                "llm_config": None,
            }
        return _hook_wizard_states[user_id]

    def _wizard_summary(state: dict) -> str:
        """Build a summary string for the current wizard state."""
        lines = ["## 🪝 Hook Wizard"]
        if state.get("name"):
            lines.append(f"**Name:** {state['name']}")
        if state.get("project_id"):
            lines.append(f"**Project:** `{state['project_id']}`")
        if state.get("trigger"):
            t = state["trigger"]
            if t["type"] == "periodic":
                secs = t["interval_seconds"]
                if secs >= 86400:
                    lines.append(f"**Trigger:** every {secs // 86400}d")
                elif secs >= 3600:
                    lines.append(f"**Trigger:** every {secs // 3600}h")
                elif secs >= 60:
                    lines.append(f"**Trigger:** every {secs // 60}m")
                else:
                    lines.append(f"**Trigger:** every {secs}s")
            else:
                lines.append(f"**Trigger:** event `{t.get('event_type', '?')}`")
        if state.get("context_steps"):
            step_list = ", ".join(
                s.get("type", "?") for s in state["context_steps"]
            )
            lines.append(f"**Context steps:** {step_list}")
        if state.get("prompt_template"):
            tmpl = state["prompt_template"]
            preview = tmpl[:80] + ("…" if len(tmpl) > 80 else "")
            lines.append(f"**Prompt:** {preview}")
        lines.append(f"**Cooldown:** {state.get('cooldown_seconds', 3600)}s")
        if state.get("llm_config"):
            lines.append(f"**LLM config:** custom override set")
        return "\n".join(lines)

    # ---- Wizard views & components ----

    class _HookWizardStartView(discord.ui.View):
        """Step 1: Choose hook type (periodic vs event)."""

        def __init__(self) -> None:
            super().__init__(timeout=300)

        def build_content(self, state: dict) -> str:
            return _wizard_summary(state) + "\n\n**Choose the hook type:**"

        @discord.ui.button(label="⏱️ Periodic", style=discord.ButtonStyle.primary, row=0)
        async def periodic_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            state = _wizard_state(interaction.user.id)
            view = _HookPeriodicUnitView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

        @discord.ui.button(label="📡 Event", style=discord.ButtonStyle.primary, row=0)
        async def event_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            state = _wizard_state(interaction.user.id)
            view = _HookEventCategoryView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

        @discord.ui.button(label="Cancel", style=discord.ButtonStyle.danger, row=1)
        async def cancel_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            _hook_wizard_states.pop(interaction.user.id, None)
            await interaction.response.edit_message(
                content="🪝 Hook wizard cancelled.", view=None,
            )

    class _HookPeriodicUnitView(discord.ui.View):
        """Step 2a: Choose interval unit for periodic hooks."""

        def __init__(self) -> None:
            super().__init__(timeout=300)

        def build_content(self, state: dict) -> str:
            return _wizard_summary(state) + "\n\n**Choose interval unit:**"

        @discord.ui.button(label="Minutes", style=discord.ButtonStyle.secondary, row=0)
        async def minutes_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            state = _wizard_state(interaction.user.id)
            state["_interval_unit"] = "minutes"
            view = _HookPeriodicValueView("minutes")
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

        @discord.ui.button(label="Hours", style=discord.ButtonStyle.secondary, row=0)
        async def hours_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            state = _wizard_state(interaction.user.id)
            state["_interval_unit"] = "hours"
            view = _HookPeriodicValueView("hours")
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

        @discord.ui.button(label="Days", style=discord.ButtonStyle.secondary, row=0)
        async def days_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            state = _wizard_state(interaction.user.id)
            state["_interval_unit"] = "days"
            view = _HookPeriodicValueView("days")
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

        @discord.ui.button(label="◀ Back", style=discord.ButtonStyle.secondary, row=1)
        async def back_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            state = _wizard_state(interaction.user.id)
            view = _HookWizardStartView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

        @discord.ui.button(label="Cancel", style=discord.ButtonStyle.danger, row=1)
        async def cancel_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            _hook_wizard_states.pop(interaction.user.id, None)
            await interaction.response.edit_message(
                content="🪝 Hook wizard cancelled.", view=None,
            )

    class _HookPeriodicValueView(discord.ui.View):
        """Step 2b: Choose interval value with preset buttons + custom."""

        def __init__(self, unit: str) -> None:
            super().__init__(timeout=300)
            self._unit = unit
            multiplier = {"minutes": 60, "hours": 3600, "days": 86400}[unit]
            presets = {"minutes": [5, 10, 15, 30], "hours": [1, 2, 4, 12], "days": [1, 2, 7]}[unit]
            for val in presets:
                btn = discord.ui.Button(
                    label=f"{val} {unit}",
                    style=discord.ButtonStyle.primary,
                    row=0,
                )
                secs = val * multiplier
                btn.callback = self._make_preset_callback(secs)
                self.add_item(btn)
            # Custom button
            custom_btn = discord.ui.Button(
                label="Custom…",
                style=discord.ButtonStyle.secondary,
                row=0,
            )
            custom_btn.callback = self._custom_callback
            self.add_item(custom_btn)

        def build_content(self, state: dict) -> str:
            return _wizard_summary(state) + f"\n\n**Choose interval ({self._unit}):**"

        def _make_preset_callback(self, seconds: int):
            async def callback(interaction: discord.Interaction) -> None:
                state = _wizard_state(interaction.user.id)
                state["trigger"] = {"type": "periodic", "interval_seconds": seconds}
                view = _HookConfigView()
                await interaction.response.edit_message(
                    content=view.build_content(state), view=view,
                )
            return callback

        async def _custom_callback(self, interaction: discord.Interaction) -> None:
            await interaction.response.send_modal(_HookCustomIntervalModal(self._unit))

    class _HookCustomIntervalModal(discord.ui.Modal, title="Custom Interval"):
        """Modal for entering a custom periodic interval value."""

        interval_value = discord.ui.TextInput(
            label="Interval value (number)",
            placeholder="e.g. 45",
            required=True,
            max_length=10,
        )

        def __init__(self, unit: str) -> None:
            super().__init__()
            self._unit = unit

        async def on_submit(self, interaction: discord.Interaction) -> None:
            try:
                val = int(self.interval_value.value)
                if val <= 0:
                    raise ValueError
            except ValueError:
                await interaction.response.send_message(
                    "Please enter a positive integer.", ephemeral=True,
                )
                return
            multiplier = {"minutes": 60, "hours": 3600, "days": 86400}[self._unit]
            state = _wizard_state(interaction.user.id)
            state["trigger"] = {"type": "periodic", "interval_seconds": val * multiplier}
            view = _HookConfigView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

    class _HookEventCategoryView(discord.ui.View):
        """Step 2c: Choose event category, then event type."""

        def __init__(self, page: int = 0) -> None:
            super().__init__(timeout=300)
            self.page = page
            self._rebuild()

        def _rebuild(self) -> None:
            self.clear_items()
            # Build a flat list of all events grouped for select menu
            options = []
            for cat, events in _HOOK_EVENT_CATEGORIES:
                for evt in events:
                    label = evt
                    desc = f"{cat} event"
                    options.append(discord.SelectOption(label=label, value=evt, description=desc))
            # Discord select menus support up to 25 options — we're well under.
            select = discord.ui.Select(
                placeholder="Select an event type…",
                options=options,
                row=0,
            )
            select.callback = self._select_callback
            self.add_item(select)
            # Custom event type
            custom_btn = discord.ui.Button(
                label="Custom event type…",
                style=discord.ButtonStyle.secondary,
                row=1,
            )
            custom_btn.callback = self._custom_callback
            self.add_item(custom_btn)
            # Back
            back_btn = discord.ui.Button(
                label="◀ Back",
                style=discord.ButtonStyle.secondary,
                row=2,
            )
            back_btn.callback = self._back_callback
            self.add_item(back_btn)
            # Cancel
            cancel_btn = discord.ui.Button(
                label="Cancel",
                style=discord.ButtonStyle.danger,
                row=2,
            )
            cancel_btn.callback = self._cancel_callback
            self.add_item(cancel_btn)

        def build_content(self, state: dict) -> str:
            return _wizard_summary(state) + "\n\n**Select the event type to trigger on:**"

        async def _select_callback(self, interaction: discord.Interaction) -> None:
            event_type = interaction.data.get("values", [None])[0]
            if not event_type:
                return
            state = _wizard_state(interaction.user.id)
            state["trigger"] = {"type": "event", "event_type": event_type}
            view = _HookConfigView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

        async def _custom_callback(self, interaction: discord.Interaction) -> None:
            await interaction.response.send_modal(_HookCustomEventModal())

        async def _back_callback(self, interaction: discord.Interaction) -> None:
            state = _wizard_state(interaction.user.id)
            view = _HookWizardStartView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

        async def _cancel_callback(self, interaction: discord.Interaction) -> None:
            _hook_wizard_states.pop(interaction.user.id, None)
            await interaction.response.edit_message(
                content="🪝 Hook wizard cancelled.", view=None,
            )

    class _HookCustomEventModal(discord.ui.Modal, title="Custom Event Type"):
        """Modal for entering a custom event type string."""

        event_type = discord.ui.TextInput(
            label="Event type",
            placeholder="e.g. task.completed or custom.my_event",
            required=True,
            max_length=100,
        )

        async def on_submit(self, interaction: discord.Interaction) -> None:
            state = _wizard_state(interaction.user.id)
            state["trigger"] = {"type": "event", "event_type": self.event_type.value.strip()}
            view = _HookConfigView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

    class _HookConfigView(discord.ui.View):
        """Step 3: Main configuration hub — add steps, set prompt, options."""

        def __init__(self) -> None:
            super().__init__(timeout=300)

        def build_content(self, state: dict) -> str:
            return _wizard_summary(state) + "\n\n**Configure your hook:**"

        @discord.ui.button(label="📝 Set Prompt", style=discord.ButtonStyle.primary, row=0)
        async def prompt_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            await interaction.response.send_modal(_HookPromptModal())

        @discord.ui.button(label="➕ Add Context Step", style=discord.ButtonStyle.secondary, row=0)
        async def add_step_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            state = _wizard_state(interaction.user.id)
            view = _HookStepTypeView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

        @discord.ui.button(label="⏱️ Set Cooldown", style=discord.ButtonStyle.secondary, row=1)
        async def cooldown_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            await interaction.response.send_modal(_HookCooldownModal())

        @discord.ui.button(label="🤖 LLM Config", style=discord.ButtonStyle.secondary, row=1)
        async def llm_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            await interaction.response.send_modal(_HookLLMConfigModal())

        @discord.ui.button(label="✅ Create Hook", style=discord.ButtonStyle.success, row=2)
        async def create_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            state = _wizard_state(interaction.user.id)
            # Validate required fields
            missing = []
            if not state.get("name"):
                missing.append("name")
            if not state.get("trigger"):
                missing.append("trigger")
            if not state.get("prompt_template"):
                missing.append("prompt template")
            if missing:
                await interaction.response.send_message(
                    f"Missing required fields: {', '.join(missing)}. "
                    "Please complete them before creating.",
                    ephemeral=True,
                )
                return
            # Build the hook
            import json as _json
            args = {
                "project_id": state["project_id"],
                "name": state["name"],
                "trigger": state["trigger"],
                "prompt_template": state["prompt_template"],
                "cooldown_seconds": state.get("cooldown_seconds", 3600),
            }
            if state.get("context_steps"):
                args["context_steps"] = state["context_steps"]
            if state.get("llm_config"):
                args["llm_config"] = state["llm_config"]
            result = await handler.execute("create_hook", args)
            _hook_wizard_states.pop(interaction.user.id, None)
            if "error" in result:
                await interaction.response.edit_message(
                    content=f"❌ Error creating hook: {result['error']}", view=None,
                )
                return
            await interaction.response.edit_message(
                content=(
                    f"✅ Hook **{state['name']}** (`{result['created']}`) "
                    f"created in `{state['project_id']}`!"
                ),
                view=None,
            )

        @discord.ui.button(label="◀ Back", style=discord.ButtonStyle.secondary, row=2)
        async def back_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            state = _wizard_state(interaction.user.id)
            view = _HookWizardStartView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

        @discord.ui.button(label="Cancel", style=discord.ButtonStyle.danger, row=2)
        async def cancel_btn(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
            _hook_wizard_states.pop(interaction.user.id, None)
            await interaction.response.edit_message(
                content="🪝 Hook wizard cancelled.", view=None,
            )

    class _HookPromptModal(discord.ui.Modal, title="Hook Prompt Template"):
        """Modal for setting the prompt template."""

        prompt = discord.ui.TextInput(
            label="Prompt template",
            style=discord.TextStyle.long,
            placeholder="Use {{step_0}}, {{event}}, {{event.field}} placeholders…",
            required=True,
            max_length=2000,
        )

        async def on_submit(self, interaction: discord.Interaction) -> None:
            state = _wizard_state(interaction.user.id)
            state["prompt_template"] = self.prompt.value
            view = _HookConfigView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

    class _HookCooldownModal(discord.ui.Modal, title="Set Cooldown"):
        """Modal for setting cooldown seconds."""

        cooldown = discord.ui.TextInput(
            label="Cooldown (seconds)",
            placeholder="3600",
            required=True,
            max_length=10,
            default="3600",
        )

        async def on_submit(self, interaction: discord.Interaction) -> None:
            try:
                val = int(self.cooldown.value)
                if val < 0:
                    raise ValueError
            except ValueError:
                await interaction.response.send_message(
                    "Cooldown must be a non-negative integer.", ephemeral=True,
                )
                return
            state = _wizard_state(interaction.user.id)
            state["cooldown_seconds"] = val
            view = _HookConfigView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

    class _HookLLMConfigModal(discord.ui.Modal, title="LLM Config Override"):
        """Modal for optional LLM config override."""

        provider = discord.ui.TextInput(
            label="Provider",
            placeholder="anthropic",
            required=False,
            max_length=50,
        )
        model = discord.ui.TextInput(
            label="Model",
            placeholder="claude-sonnet-4-20250514",
            required=False,
            max_length=100,
        )

        async def on_submit(self, interaction: discord.Interaction) -> None:
            state = _wizard_state(interaction.user.id)
            prov = self.provider.value.strip()
            mdl = self.model.value.strip()
            if prov or mdl:
                config = {}
                if prov:
                    config["provider"] = prov
                if mdl:
                    config["model"] = mdl
                state["llm_config"] = config
            else:
                state["llm_config"] = None
            view = _HookConfigView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

    class _HookStepTypeView(discord.ui.View):
        """Choose context step type to add."""

        def __init__(self) -> None:
            super().__init__(timeout=300)
            options = [
                discord.SelectOption(label=stype, value=stype, description=desc)
                for stype, desc in _HOOK_STEP_TYPES
            ]
            select = discord.ui.Select(
                placeholder="Choose step type…",
                options=options,
                row=0,
            )
            select.callback = self._select_callback
            self.add_item(select)
            back_btn = discord.ui.Button(
                label="◀ Back",
                style=discord.ButtonStyle.secondary,
                row=1,
            )
            back_btn.callback = self._back_callback
            self.add_item(back_btn)

        def build_content(self, state: dict) -> str:
            return _wizard_summary(state) + "\n\n**Choose context step type to add:**"

        async def _select_callback(self, interaction: discord.Interaction) -> None:
            step_type = interaction.data.get("values", [None])[0]
            if not step_type:
                return
            await interaction.response.send_modal(_HookStepConfigModal(step_type))

        async def _back_callback(self, interaction: discord.Interaction) -> None:
            state = _wizard_state(interaction.user.id)
            view = _HookConfigView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

    class _HookStepConfigModal(discord.ui.Modal, title="Configure Context Step"):
        """Modal to configure a context step based on its type."""

        param1 = discord.ui.TextInput(
            label="Primary parameter",
            style=discord.TextStyle.short,
            required=True,
            max_length=500,
        )
        param2 = discord.ui.TextInput(
            label="Secondary parameter (optional)",
            style=discord.TextStyle.short,
            required=False,
            max_length=500,
        )
        skip_condition = discord.ui.TextInput(
            label="Short-circuit condition (optional)",
            placeholder="skip_llm_if_exit_zero / skip_llm_if_empty / skip_llm_if_status_ok",
            required=False,
            max_length=100,
        )

        _PARAM_LABELS = {
            "shell": ("Command (e.g. npm test)", "Timeout seconds (default 60)"),
            "read_file": ("File path", "Max lines (default 500)"),
            "http": ("URL", "Timeout seconds (default 30)"),
            "db_query": ("Query name (recent_task_results / task_detail / ...)", "Params JSON (optional)"),
            "git_diff": ("Workspace path (default .)", "Base branch (default main)"),
            "memory_search": ("Search query", "Top K results (default 3)"),
        }

        def __init__(self, step_type: str) -> None:
            super().__init__()
            self._step_type = step_type
            labels = self._PARAM_LABELS.get(step_type, ("Value", "Extra (optional)"))
            self.param1.label = labels[0]
            self.param2.label = labels[1]
            # Set useful placeholders per type
            placeholders = {
                "shell": ("npm test", "60"),
                "read_file": ("./README.md", "500"),
                "http": ("https://api.example.com/status", "30"),
                "db_query": ("recent_task_results", '{"task_id": "{{event.task_id}}"}'),
                "git_diff": (".", "main"),
                "memory_search": ("API endpoints", "3"),
            }
            ph = placeholders.get(step_type, ("", ""))
            self.param1.placeholder = ph[0]
            self.param2.placeholder = ph[1]

        async def on_submit(self, interaction: discord.Interaction) -> None:
            import json as _json
            step: dict = {"type": self._step_type}
            p1 = self.param1.value.strip()
            p2 = self.param2.value.strip()
            skip = self.skip_condition.value.strip()

            if self._step_type == "shell":
                step["command"] = p1
                if p2:
                    try:
                        step["timeout"] = int(p2)
                    except ValueError:
                        pass
            elif self._step_type == "read_file":
                step["path"] = p1
                if p2:
                    try:
                        step["max_lines"] = int(p2)
                    except ValueError:
                        pass
            elif self._step_type == "http":
                step["url"] = p1
                if p2:
                    try:
                        step["timeout"] = int(p2)
                    except ValueError:
                        pass
            elif self._step_type == "db_query":
                step["query"] = p1
                if p2:
                    try:
                        step["params"] = _json.loads(p2)
                    except _json.JSONDecodeError:
                        pass
            elif self._step_type == "git_diff":
                step["workspace"] = p1 or "."
                step["base_branch"] = p2 or "main"
            elif self._step_type == "memory_search":
                step["query"] = p1
                if p2:
                    try:
                        step["top_k"] = int(p2)
                    except ValueError:
                        pass

            if skip:
                step[skip] = True

            state = _wizard_state(interaction.user.id)
            state["context_steps"].append(step)
            view = _HookConfigView()
            await interaction.response.edit_message(
                content=view.build_content(state), view=view,
            )

    # ---- Wizard entry point (slash command) ----

    @bot.tree.command(name="create-hook", description="Create an automation hook")
    async def create_hook_command(interaction: discord.Interaction):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        # Initialize wizard state
        state = _wizard_state(interaction.user.id)
        state["project_id"] = project_id
        state["name"] = None
        state["trigger"] = None
        state["context_steps"] = []
        state["prompt_template"] = None
        state["cooldown_seconds"] = 3600
        state["llm_config"] = None
        # Show name modal first
        await interaction.response.send_modal(_HookNameModal())

    @bot.tree.command(name="add-hook", description="Create an automation hook (interactive wizard)")
    async def add_hook_command(interaction: discord.Interaction):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        # Initialize wizard state
        state = _wizard_state(interaction.user.id)
        state["project_id"] = project_id
        state["name"] = None
        state["trigger"] = None
        state["context_steps"] = []
        state["prompt_template"] = None
        state["cooldown_seconds"] = 3600
        state["llm_config"] = None
        # Show name modal first
        await interaction.response.send_modal(_HookNameModal())

    class _HookNameModal(discord.ui.Modal, title="Name Your Hook"):
        """First modal: enter the hook name."""

        hook_name = discord.ui.TextInput(
            label="Hook name",
            placeholder="e.g. post-failure-analysis",
            required=True,
            max_length=100,
        )

        async def on_submit(self, interaction: discord.Interaction) -> None:
            state = _wizard_state(interaction.user.id)
            state["name"] = self.hook_name.value.strip()
            view = _HookWizardStartView()
            await interaction.response.send_message(
                content=view.build_content(state), view=view,
                ephemeral=True,
            )

    @bot.tree.command(name="edit-hook", description="Edit an automation hook")
    @app_commands.describe(
        hook_id="Hook ID",
        name="New hook name (optional)",
        enabled="Enable or disable the hook",
        prompt_template="New prompt template (optional)",
        cooldown_seconds="New cooldown in seconds (optional)",
        max_tokens_per_run="Max tokens per run (optional, 0 to clear)",
    )
    async def edit_hook_command(
        interaction: discord.Interaction,
        hook_id: str,
        name: str | None = None,
        enabled: bool | None = None,
        prompt_template: str | None = None,
        cooldown_seconds: int | None = None,
        max_tokens_per_run: int | None = None,
    ):
        args: dict = {"hook_id": hook_id}
        if name is not None:
            args["name"] = name
        if enabled is not None:
            args["enabled"] = enabled
        if prompt_template is not None:
            args["prompt_template"] = prompt_template
        if cooldown_seconds is not None:
            args["cooldown_seconds"] = cooldown_seconds
        if max_tokens_per_run is not None:
            args["max_tokens_per_run"] = max_tokens_per_run if max_tokens_per_run > 0 else None
        result = await handler.execute("edit_hook", args)
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        fields = ", ".join(result.get("fields", []))
        await _send_success(
            interaction, "Hook Updated",
            description=f"Hook `{hook_id}` updated: {fields}",
        )

    @bot.tree.command(name="delete-hook", description="Delete an automation hook")
    @app_commands.describe(hook_id="Hook ID to delete")
    async def delete_hook_command(interaction: discord.Interaction, hook_id: str):
        result = await handler.execute("delete_hook", {"hook_id": hook_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_success(
            interaction, "Hook Deleted",
            description=f"Hook **{result.get('name', hook_id)}** (`{hook_id}`) deleted.",
        )

    @bot.tree.command(name="hook-runs", description="Show recent execution history for a hook")
    @app_commands.describe(
        hook_id="Hook ID",
        limit="Number of runs to show (default 10)",
    )
    async def hook_runs_command(
        interaction: discord.Interaction, hook_id: str, limit: int = 10
    ):
        result = await handler.execute("list_hook_runs", {"hook_id": hook_id, "limit": limit})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        runs = result.get("runs", [])
        hook_name = result.get("hook_name", hook_id)
        if not runs:
            await _send_info(
                interaction, "No Hook Runs",
                description=f"No runs found for hook **{hook_name}**.",
            )
            return
        lines = [f"## Hook Runs: {hook_name}"]
        for r in runs:
            status_emoji = {"completed": "✅", "failed": "❌", "skipped": "⏭️"}.get(
                r.get("status", ""), "🔄"
            )
            line = f"• {status_emoji} {r.get('trigger_reason', '?')} — tokens: {r.get('tokens_used', 0):,}"
            if r.get("skipped_reason"):
                line += f" (skipped: {r['skipped_reason'][:50]})"
            lines.append(line)
        msg = "\n".join(lines)
        if len(msg) > 2000:
            msg = msg[:1997] + "..."
        await interaction.response.send_message(msg)

    @bot.tree.command(name="fire-hook", description="Manually trigger a hook immediately")
    @app_commands.describe(hook_id="Hook ID to fire")
    async def fire_hook_command(interaction: discord.Interaction, hook_id: str):
        result = await handler.execute("fire_hook", {"hook_id": hook_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_success(
            interaction, "Hook Fired",
            description=f"Hook `{hook_id}` fired — status: {result.get('status', 'running')}",
        )

    # ===================================================================
    # NOTES COMMANDS
    # ===================================================================

    @bot.tree.command(name="notes", description="View and manage notes for a project")
    async def notes_command(interaction: discord.Interaction):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        result = await handler.execute("list_notes", {"project_id": project_id})
        if "error" in result:
            await _send_error(interaction, result['error'])
            return

        # Look up project name for the header
        projects_result = await handler.execute("list_projects", {})
        project_name = project_id
        for p in projects_result.get("projects", []):
            if p["id"] == project_id:
                project_name = p["name"]
                break

        notes = result.get("notes", [])
        view = NotesView(project_id, notes, handler=handler, bot=bot)
        await interaction.response.send_message(
            view.build_content(), view=view,
        )

        # Create a thread for interactive note management
        msg = await interaction.original_response()
        thread = await msg.create_thread(
            name=f"Notes: {project_name}"[:100],
            auto_archive_duration=1440,
        )
        await thread.send(
            f"💬 Type ideas and I'll organize them into notes for **{project_name}**.\n"
            f"Click a note button above to view its content."
        )
        await bot.register_notes_thread(thread.id, project_id)

        # Track TOC message for view persistence
        toc_messages = getattr(bot, "_notes_toc_messages", {})
        toc_messages[thread.id] = msg.id
        bot._notes_toc_messages = toc_messages
        await bot._save_notes_threads()

    @bot.tree.command(name="write-note", description="Create or update a project note")
    @app_commands.describe(
        title="Note title",
        content="Note content (markdown)",
    )
    async def write_note_command(
        interaction: discord.Interaction,
        title: str,
        content: str,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        result = await handler.execute("write_note", {
            "project_id": project_id,
            "title": title,
            "content": content,
        })
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        status = result.get("status", "created")
        await _send_success(
            interaction, f"Note {status.title()}",
            description=f"Note **{title}** {status} in `{project_id}`",
        )

    @bot.tree.command(name="delete-note", description="Delete a project note")
    @app_commands.describe(
        title="Note title",
    )
    async def delete_note_command(
        interaction: discord.Interaction,
        title: str,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        result = await handler.execute("delete_note", {
            "project_id": project_id,
            "title": title,
        })
        if "error" in result:
            await _send_error(interaction, result['error'])
            return
        await _send_success(
            interaction, "Note Deleted",
            description=f"Note **{title}** deleted from `{project_id}`",
        )

    # ===================================================================
    # MEMORY COMMANDS
    # ===================================================================

    @bot.tree.command(name="memory-stats", description="Show memory index statistics for a project")
    @app_commands.describe(
        project="Project ID (defaults to the project linked to this channel)",
    )
    async def memory_stats_command(
        interaction: discord.Interaction,
        project: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, project)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return

        result = await handler.execute("memory_stats", {"project_id": project_id})
        if "error" in result:
            await _send_error(interaction, result["error"])
            return

        enabled = result.get("enabled", False)
        available = result.get("available", False)

        if not enabled:
            await _send_info(
                interaction, "Memory Disabled",
                description=(
                    f"Memory is **not enabled** for `{project_id}`.\n"
                    f"memsearch installed: {'Yes' if available else 'No'}\n\n"
                    "Set `memory.enabled = true` in your config to enable."
                ),
            )
            return

        if not available:
            await _send_warning(
                interaction, "Memory Unavailable",
                description=(
                    f"Memory is enabled for `{project_id}` but the "
                    "`memsearch` package is not installed."
                ),
            )
            return

        fields = [
            ("Collection", f"`{result.get('collection', 'N/A')}`", True),
            ("Embedding Provider", f"`{result.get('embedding_provider', 'N/A')}`", True),
            ("Milvus URI", f"`{result.get('milvus_uri', 'N/A')}`", False),
            ("Auto Recall", "Enabled" if result.get("auto_recall") else "Disabled", True),
            ("Auto Remember", "Enabled" if result.get("auto_remember") else "Disabled", True),
            ("Recall Top-K", str(result.get("recall_top_k", "N/A")), True),
        ]

        await _send_success(
            interaction, f"Memory Stats — {project_id}",
            description="Memory subsystem is **active** and operational.",
            fields=fields,
        )

    @bot.tree.command(name="memory-search", description="Semantic search across project memory")
    @app_commands.describe(
        query="Semantic search query",
        project="Project ID (defaults to the project linked to this channel)",
        top_k="Number of results to return (default: 5)",
    )
    async def memory_search_command(
        interaction: discord.Interaction,
        query: str,
        project: str | None = None,
        top_k: int = 5,
    ):
        project_id = await _resolve_project_from_context(interaction, project)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return

        await interaction.response.defer()

        result = await handler.execute("memory_search", {
            "project_id": project_id,
            "query": query,
            "top_k": top_k,
        })
        if "error" in result:
            await _send_error(interaction, result["error"], followup=True)
            return

        results = result.get("results", [])
        count = result.get("count", 0)

        if count == 0:
            await _send_info(
                interaction, "No Results",
                description=f"No memories matched your query in `{project_id}`.\n\n**Query:** {query}",
                followup=True,
            )
            return

        # Build result entries for the embed description
        desc_parts = [f"**Query:** {query}", f"**Project:** `{project_id}`", ""]
        for r in results:
            score = r.get("score", 0)
            source = r.get("source", "unknown")
            heading = r.get("heading", "")
            content = r.get("content", "")

            # Truncate content preview
            preview = content.replace("\n", " ").strip()
            if len(preview) > 200:
                preview = preview[:197] + "..."

            # Format source — show just the filename
            source_short = source.rsplit("/", 1)[-1] if "/" in source else source

            rank = r.get("rank", "?")
            score_pct = f"{score * 100:.1f}%" if isinstance(score, (int, float)) else "N/A"
            entry = (
                f"**{rank}.** `{source_short}` — {score_pct}\n"
            )
            if heading:
                entry += f"> **{heading}**\n"
            entry += f"> {preview}"
            desc_parts.append(entry)

        description = "\n\n".join(desc_parts)
        # Truncate to Discord limit if needed
        if len(description) > 4000:
            description = description[:3997] + "..."

        embed = info_embed(
            f"Memory Search — {count} result{'s' if count != 1 else ''}",
            description=description,
        )
        await interaction.followup.send(embed=embed)

    # ===================================================================
    # SYSTEM CONTROL COMMANDS
    # ===================================================================

    @bot.tree.command(name="orchestrator", description="Pause or resume task scheduling")
    @app_commands.describe(action="pause | resume | status")
    @app_commands.choices(action=[
        app_commands.Choice(name="pause",  value="pause"),
        app_commands.Choice(name="resume", value="resume"),
        app_commands.Choice(name="status", value="status"),
    ])
    async def orchestrator_command(
        interaction: discord.Interaction, action: app_commands.Choice[str]
    ):
        result = await handler.execute("orchestrator_control", {"action": action.value})
        if action.value == "pause":
            await _send_info(
                interaction, "Orchestrator Paused",
                description="No new tasks will be scheduled.",
            )
        elif action.value == "resume":
            await _send_success(
                interaction, "Orchestrator Resumed",
                description="Task scheduling is now active.",
            )
        else:
            running = result.get("running_tasks", 0)
            is_paused = result.get("status") == "paused"
            state = "⏸ PAUSED" if is_paused else "▶ RUNNING"
            embed_fn = _send_info if is_paused else _send_success
            await embed_fn(
                interaction, f"Orchestrator {state}",
                description=f"**Running tasks:** {running}",
            )

    @bot.tree.command(name="restart", description="Restart the agent-queue daemon")
    @app_commands.describe(reason="Why are you restarting? (required)")
    async def restart_command(interaction: discord.Interaction, reason: str):
        user_name = interaction.user.display_name
        full_reason = f"User {user_name} requested a restart: {reason}"

        # Gather git info for the restart message
        git_info_parts: list[str] = []
        try:
            short_hash = await _async_git_output(["rev-parse", "--short", "HEAD"], timeout=5)
            if short_hash:
                git_info_parts.append(f"commit `{short_hash}`")
        except Exception:
            pass
        try:
            await _async_git_output(["fetch", "--quiet"], timeout=15)
            behind = await _async_git_output(["rev-list", "--count", "HEAD..@{u}"], timeout=5)
            if behind and int(behind) > 0:
                git_info_parts.append(f"**{behind}** commit{'s' if int(behind) != 1 else ''} behind origin")
        except Exception:
            pass

        desc = f"Agent-queue daemon is restarting…\n**Reason:** {full_reason}"
        if git_info_parts:
            desc += "\n" + " · ".join(git_info_parts)

        await _send_warning(interaction, "Restarting", description=desc)
        await handler.execute("restart_daemon", {"reason": full_reason})

    @bot.tree.command(
        name="shutdown",
        description="Shut down the bot and all running agents",
    )
    @app_commands.describe(
        reason="Why are you shutting down? (required)",
        force="Force-stop all running agents immediately (default: graceful)",
    )
    async def shutdown_command(
        interaction: discord.Interaction,
        reason: str,
        force: bool = False,
    ):
        user_name = interaction.user.display_name
        full_reason = f"User {user_name} requested shutdown: {reason}"
        mode = "force" if force else "graceful"

        # Count running tasks for the confirmation message
        running_count = len(handler.orchestrator._running_tasks)

        # Build description
        desc_parts = [
            f"Agent-queue daemon is shutting down ({mode})…",
            f"**Reason:** {full_reason}",
        ]
        if running_count > 0:
            if force:
                desc_parts.append(
                    f"⚠️ **{running_count}** running task(s) will be force-stopped."
                )
            else:
                desc_parts.append(
                    f"⏳ Waiting for **{running_count}** running task(s) to complete…"
                )
        else:
            desc_parts.append("No tasks currently running.")

        await _send_warning(
            interaction, "Shutting Down", description="\n".join(desc_parts)
        )

        # Set bot status to invisible/offline before shutting down
        try:
            await bot.change_presence(status=discord.Status.invisible)
        except Exception:
            pass

        await handler.execute("shutdown", {"reason": full_reason, "force": force})

    @bot.tree.command(
        name="update",
        description="Pull latest source, install deps, and restart the daemon",
    )
    @app_commands.describe(reason="Why are you updating? (optional, auto-filled if omitted)")
    async def update_command(interaction: discord.Interaction, reason: str | None = None):
        user_name = interaction.user.display_name
        full_reason = f"User {user_name} requested an update" + (f": {reason}" if reason else "")

        await interaction.response.defer(ephemeral=False)

        # Show current commit before pulling
        repo_dir = str(Path(__file__).resolve().parent.parent.parent)
        before_hash = ""
        try:
            before_hash = await _async_git_output(
                ["rev-parse", "--short", "HEAD"], cwd=repo_dir, timeout=5,
            )
        except Exception:
            pass

        result = await handler.execute("update_and_restart", {"reason": full_reason})

        if "error" in result:
            await _send_error(interaction, result["error"], followup=True)
            return

        pull_output = result.get("pull_output", "")
        after_hash = ""
        try:
            after_hash = await _async_git_output(
                ["rev-parse", "--short", "HEAD"], cwd=repo_dir, timeout=5,
            )
        except Exception:
            pass

        desc_parts = ["Pulled latest changes and restarting…"]
        if before_hash and after_hash and before_hash != after_hash:
            desc_parts.append(f"`{before_hash}` → `{after_hash}`")
        elif before_hash and after_hash:
            desc_parts.append(f"Already up to date at `{after_hash}`")
        if pull_output and "Already up to date" not in pull_output:
            # Show abbreviated pull output
            lines = pull_output.splitlines()
            if len(lines) > 6:
                lines = lines[:6] + [f"… and {len(lines) - 6} more lines"]
            desc_parts.append("```\n" + "\n".join(lines) + "\n```")

        await _send_warning(
            interaction, "Updating & Restarting",
            description="\n".join(desc_parts),
            followup=True,
        )

    # ===================================================================
    # CHANNEL MANAGEMENT
    # ===================================================================

    @bot.tree.command(
        name="clear",
        description="Clear messages from the current channel",
    )
    @app_commands.describe(
        count="Number of messages to delete (default: all, max: 1000)",
    )
    async def clear_command(
        interaction: discord.Interaction,
        count: int | None = None,
    ):
        channel = interaction.channel

        # Validate the channel supports bulk deletion
        if not hasattr(channel, "purge"):
            await _send_error(
                interaction,
                "This command can only be used in text channels.",
            )
            return

        # Check bot permissions
        bot_member = interaction.guild.me if interaction.guild else None
        if bot_member:
            perms = channel.permissions_for(bot_member)
            if not perms.manage_messages:
                await _send_error(
                    interaction,
                    "I need the **Manage Messages** permission to clear messages.",
                )
                return

        limit = min(count, 1000) if count is not None else 1000

        await interaction.response.defer(ephemeral=True)

        try:
            deleted = await channel.purge(limit=limit)
            await _send_success(
                interaction,
                "Channel Cleared",
                description=f"Deleted **{len(deleted)}** message{'s' if len(deleted) != 1 else ''}.",
                followup=True,
                ephemeral=True,
            )
        except discord.Forbidden:
            await _send_error(
                interaction,
                "Missing permissions to delete messages in this channel.",
                followup=True,
            )
        except discord.HTTPException as exc:
            await _send_error(
                interaction,
                f"Failed to clear messages: {exc}",
                followup=True,
            )

    # ===================================================================
    # FILE BROWSER & EDITOR
    # ===================================================================

    def _format_file_size(size: int) -> str:
        """Format bytes into a human-readable string."""
        if size < 1024:
            return f"{size} B"
        elif size < 1024 * 1024:
            return f"{size / 1024:.1f} KB"
        else:
            return f"{size / (1024 * 1024):.1f} MB"

    class _FileBrowserView(discord.ui.View):
        """Interactive view for browsing repository files and directories."""

        def __init__(
            self,
            handler,
            project_id: str,
            current_path: str,
            directories: list[str],
            files: list[dict],
            workspace_path: str,
            workspace_name: str = "",
        ):
            super().__init__(timeout=300)
            self._handler = handler
            self._project_id = project_id
            self._current_path = current_path
            # Always resolve to absolute path to prevent CWD-relative issues
            self._workspace_path = os.path.realpath(workspace_path) if workspace_path else workspace_path
            self._workspace_name = workspace_name
            self._directories = directories
            self._files = files
            self._dir_page = 0
            self._file_page = 0
            self._items_per_page = 20
            self._build_buttons()

        def _build_buttons(self):
            self.clear_items()

            # Parent directory button (row 0)
            if self._current_path and self._current_path != "/":
                parent = discord.ui.Button(
                    label="⬆ Parent Directory",
                    style=discord.ButtonStyle.secondary,
                    row=0,
                )
                parent.callback = self._go_parent
                self.add_item(parent)

            # Directory select menu (row 1) — show up to 25 dirs per page
            dir_start = self._dir_page * self._items_per_page
            dir_end = dir_start + self._items_per_page
            page_dirs = self._directories[dir_start:dir_end]
            if page_dirs:
                dir_select = discord.ui.Select(
                    placeholder=f"📁 Navigate to directory... (page {self._dir_page + 1})",
                    options=[
                        discord.SelectOption(label=d[:100], value=d[:100], emoji="📁")
                        for d in page_dirs
                    ],
                    row=1,
                )
                dir_select.callback = self._navigate_dir
                self.add_item(dir_select)

            # File select menu (row 2) — show up to 25 files per page
            file_start = self._file_page * self._items_per_page
            file_end = file_start + self._items_per_page
            page_files = self._files[file_start:file_end]
            if page_files:
                file_select = discord.ui.Select(
                    placeholder=f"📄 View/edit file... (page {self._file_page + 1})",
                    options=[
                        discord.SelectOption(
                            label=f["name"][:100],
                            value=f["name"][:100],
                            description=_format_file_size(f.get("size", 0)),
                            emoji="📄",
                        )
                        for f in page_files
                    ],
                    row=2,
                )
                file_select.callback = self._view_file
                self.add_item(file_select)

            # Pagination buttons (row 3)
            total_dir_pages = max(1, -(-len(self._directories) // self._items_per_page))
            total_file_pages = max(1, -(-len(self._files) // self._items_per_page))

            if total_dir_pages > 1:
                if self._dir_page > 0:
                    prev_dir = discord.ui.Button(
                        label="◀ Prev Dirs", style=discord.ButtonStyle.secondary, row=3,
                    )
                    prev_dir.callback = self._prev_dir_page
                    self.add_item(prev_dir)
                if self._dir_page < total_dir_pages - 1:
                    next_dir = discord.ui.Button(
                        label="Next Dirs ▶", style=discord.ButtonStyle.secondary, row=3,
                    )
                    next_dir.callback = self._next_dir_page
                    self.add_item(next_dir)

            if total_file_pages > 1:
                if self._file_page > 0:
                    prev_file = discord.ui.Button(
                        label="◀ Prev Files", style=discord.ButtonStyle.secondary, row=3,
                    )
                    prev_file.callback = self._prev_file_page
                    self.add_item(prev_file)
                if self._file_page < total_file_pages - 1:
                    next_file = discord.ui.Button(
                        label="Next Files ▶", style=discord.ButtonStyle.secondary, row=3,
                    )
                    next_file.callback = self._next_file_page
                    self.add_item(next_file)

        def _build_embed(self) -> discord.Embed:
            path_display = self._current_path or "/"
            ws_label = f"\n**Workspace:** `{self._workspace_name}`" if self._workspace_name else ""
            embed = discord.Embed(
                title=f"📂 {path_display}",
                description=f"**Project:** `{self._project_id}`{ws_label}",
                color=0x3498DB,
            )
            dir_count = len(self._directories)
            file_count = len(self._files)
            embed.add_field(
                name="Contents",
                value=f"📁 {dir_count} director{'y' if dir_count == 1 else 'ies'}, "
                      f"📄 {file_count} file{'s' if file_count != 1 else ''}",
                inline=False,
            )
            # Show the resolved workspace path for transparency
            if self._workspace_path:
                embed.set_footer(text=self._workspace_path)
            return embed

        async def _refresh(self, interaction: discord.Interaction):
            await interaction.response.defer()

            # Use the command handler for consistent workspace resolution.
            args: dict = {
                "project_id": self._project_id,
                "path": self._current_path or "",
            }
            if self._workspace_name:
                args["workspace"] = self._workspace_name

            result = await self._handler.execute("list_directory", args)

            if "error" in result:
                await interaction.edit_original_response(
                    content=f"❌ {result['error']}", embed=None, view=None,
                )
                return
            # Update workspace path from the resolved result to stay in sync
            if result.get("workspace_path"):
                self._workspace_path = result["workspace_path"]
            self._directories = result["directories"]
            self._files = result["files"]
            self._dir_page = 0
            self._file_page = 0
            self._build_buttons()
            await interaction.edit_original_response(
                content=None, embed=self._build_embed(), view=self,
            )

        async def _go_parent(self, interaction: discord.Interaction):
            if self._current_path and self._current_path != "/":
                parts = self._current_path.rstrip("/").rsplit("/", 1)
                self._current_path = parts[0] if len(parts) > 1 else ""
            else:
                self._current_path = ""
            await self._refresh(interaction)

        async def _navigate_dir(self, interaction: discord.Interaction):
            selected = interaction.data["values"][0]
            if self._current_path and self._current_path != "/":
                self._current_path = f"{self._current_path}/{selected}"
            else:
                self._current_path = selected
            await self._refresh(interaction)

        async def _view_file(self, interaction: discord.Interaction):
            selected = interaction.data["values"][0]
            if self._current_path and self._current_path != "/":
                file_rel = f"{self._current_path}/{selected}"
            else:
                file_rel = selected
            file_full = f"{self._workspace_path}/{file_rel}"

            # Get file size synchronously — fast stat call, no need for thread.
            try:
                file_size = os.path.getsize(os.path.realpath(file_full))
            except OSError:
                file_size = 0

            # Respond immediately with file info and action buttons.
            # No file I/O happens here — just metadata we already have.
            embed = discord.Embed(
                title=f"📄 {selected}",
                color=0x3498DB,
            )
            embed.add_field(name="Path", value=f"`{file_rel}`", inline=False)
            embed.add_field(name="Size", value=_format_file_size(file_size), inline=True)

            view = _FileInfoView(
                handler=self._handler,
                file_path=file_full,
                file_rel=file_rel,
                project_id=self._project_id,
            )
            await interaction.response.send_message(
                embed=embed, view=view, ephemeral=True,
            )

        async def _prev_dir_page(self, interaction: discord.Interaction):
            self._dir_page = max(0, self._dir_page - 1)
            self._build_buttons()
            await interaction.response.defer()
            await interaction.edit_original_response(embed=self._build_embed(), view=self)

        async def _next_dir_page(self, interaction: discord.Interaction):
            self._dir_page += 1
            self._build_buttons()
            await interaction.response.defer()
            await interaction.edit_original_response(embed=self._build_embed(), view=self)

        async def _prev_file_page(self, interaction: discord.Interaction):
            self._file_page = max(0, self._file_page - 1)
            self._build_buttons()
            await interaction.response.defer()
            await interaction.edit_original_response(embed=self._build_embed(), view=self)

        async def _next_file_page(self, interaction: discord.Interaction):
            self._file_page += 1
            self._build_buttons()
            await interaction.response.defer()
            await interaction.edit_original_response(embed=self._build_embed(), view=self)

    class _FileInfoView(discord.ui.View):
        """View shown when a file is selected — offers View Content and Edit buttons."""

        def __init__(self, handler, file_path: str, file_rel: str, project_id: str):
            super().__init__(timeout=300)
            self._handler = handler
            self._file_path = file_path
            self._file_rel = file_rel
            self._project_id = project_id

        @discord.ui.button(label="👁️ View Content", style=discord.ButtonStyle.secondary)
        async def view_button(self, interaction: discord.Interaction, button: discord.ui.Button):
            await interaction.response.defer(ephemeral=True)

            def _read_file_sync():
                real = os.path.realpath(self._file_path)
                if not os.path.isfile(real):
                    return {"error": f"File not found: {self._file_rel}"}
                try:
                    with open(real, "r") as f:
                        content = f.read(64_000)  # ~64 KB max
                    return {"content": content}
                except UnicodeDecodeError:
                    return {"error": "Binary file — cannot display contents"}
                except OSError as exc:
                    return {"error": str(exc)}

            result = await asyncio.to_thread(_read_file_sync)

            if "error" in result:
                await interaction.followup.send(
                    embed=error_embed("Error", description=result["error"]),
                    ephemeral=True,
                )
                return

            content = result["content"]
            # Determine file extension for syntax highlighting
            ext = os.path.splitext(self._file_rel)[1].lstrip(".")

            # Send as a file attachment — works for any size, no truncation issues
            buf = io.BytesIO(content.encode("utf-8"))
            filename = os.path.basename(self._file_rel)
            file = discord.File(buf, filename=filename)

            # Also include a short inline preview
            preview = content[:1800]
            if len(content) > 1800:
                preview += "\n… (full content attached above)"
            lang = ext if ext else ""
            await interaction.followup.send(
                f"### 📄 `{self._file_rel}`\n```{lang}\n{preview}\n```",
                file=file,
                ephemeral=True,
            )

        @discord.ui.button(label="✏️ Edit File", style=discord.ButtonStyle.primary)
        async def edit_button(self, interaction: discord.Interaction, button: discord.ui.Button):
            # Read the current content for the modal directly — skip handler overhead
            def _read_for_edit():
                real = os.path.realpath(self._file_path)
                if not os.path.isfile(real):
                    return {"error": f"File not found: {self._file_rel}"}
                try:
                    with open(real, "r") as f:
                        content = f.read(4000)  # Modal limit is 4000 chars
                    return {"content": content}
                except UnicodeDecodeError:
                    return {"error": "Binary file — cannot edit"}
                except OSError as exc:
                    return {"error": str(exc)}

            result = await asyncio.to_thread(_read_for_edit)

            if "error" in result:
                await interaction.response.send_message(
                    embed=error_embed("Error", description=result["error"]),
                    ephemeral=True,
                )
                return
            content = result.get("content", "")
            modal = _FileEditModal(
                handler=self._handler,
                file_path=self._file_path,
                file_rel=self._file_rel,
                current_content=content,
            )
            await interaction.response.send_modal(modal)

    class _FileEditModal(discord.ui.Modal, title="Edit File"):
        """Modal dialog for editing a text file's contents."""

        content_input = discord.ui.TextInput(
            label="File Content",
            style=discord.TextStyle.long,
            required=True,
            max_length=4000,
        )

        def __init__(self, handler, file_path: str, file_rel: str, current_content: str):
            super().__init__()
            self._handler = handler
            self._file_path = file_path
            self._file_rel = file_rel
            self.content_input.default = current_content
            self.title = f"Edit: {file_rel[-40:]}" if len(file_rel) > 45 else f"Edit: {file_rel}"

        async def on_submit(self, interaction: discord.Interaction) -> None:
            await interaction.response.defer(ephemeral=True)
            new_content = self.content_input.value
            result = await self._handler.execute(
                "write_file",
                {"path": self._file_path, "content": new_content},
            )
            if "error" in result:
                await interaction.followup.send(
                    embed=error_embed("Save Failed", description=result["error"]),
                    ephemeral=True,
                )
                return
            written = result.get("written", 0)
            await interaction.followup.send(
                embed=success_embed(
                    "File Saved ✅",
                    description=f"**`{self._file_rel}`** saved successfully.\n"
                                f"Wrote {written:,} characters.",
                ),
                ephemeral=True,
            )

    @bot.tree.command(
        name="browse",
        description="Browse project repository files and directories",
    )
    @app_commands.describe(
        path="Subdirectory to start browsing from (default: root)",
        workspace="Workspace name or ID to browse (default: first workspace)",
    )
    async def browse_command(
        interaction: discord.Interaction,
        path: str | None = None,
        workspace: str | None = None,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)
        await interaction.response.defer()

        args: dict = {"project_id": project_id}
        if path:
            args["path"] = path
        if workspace:
            args["workspace"] = workspace
        result = await handler.execute("list_directory", args)
        if "error" in result:
            await _send_error(interaction, result["error"], followup=True)
            return

        view = _FileBrowserView(
            handler=handler,
            project_id=project_id,
            current_path=result["path"] if result["path"] != "/" else "",
            directories=result["directories"],
            files=result["files"],
            workspace_path=result["workspace_path"],
            workspace_name=result.get("workspace_name", ""),
        )
        await interaction.followup.send(embed=view._build_embed(), view=view)

    @browse_command.autocomplete("workspace")
    async def _browse_workspace_autocomplete(
        interaction: discord.Interaction,
        current: str,
    ) -> list[app_commands.Choice[str]]:
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            return []
        workspaces = await handler.db.list_workspaces(project_id)
        choices = []
        for ws in workspaces:
            label = ws.name or ws.id
            if current and current.lower() not in label.lower():
                continue
            locked = " 🔒" if ws.locked_by_agent_id else ""
            choices.append(
                app_commands.Choice(name=f"{label}{locked}", value=ws.name or ws.id)
            )
            if len(choices) >= 25:
                break
        return choices

    @bot.tree.command(
        name="edit-file",
        description="Open a text editor dialog for any file in the project",
    )
    @app_commands.describe(
        path="Relative file path within the project workspace (e.g. src/main.py)",
    )
    async def edit_file_command(
        interaction: discord.Interaction,
        path: str,
    ):
        project_id = await _resolve_project_from_context(interaction, None)
        if not project_id:
            await _send_error(interaction, _NO_PROJECT_MSG)
            return
        handler.set_active_project(project_id)

        ws_path = await handler.db.get_project_workspace_path(project_id)
        if not ws_path:
            await _send_error(interaction, f"Project '{project_id}' has no workspaces.")
            return

        file_full = f"{ws_path}/{path}"
        result = await handler.execute(
            "read_file", {"path": file_full, "max_lines": 4000},
        )
        if "error" in result:
            await _send_error(interaction, result["error"])
            return

        content = result.get("content", "")
        if len(content) > 4000:
            content = content[:4000]

        modal = _FileEditModal(
            handler=handler,
            file_path=file_full,
            file_rel=path,
            current_content=content,
        )
        await interaction.response.send_modal(modal)

    # ===================================================================
    # INTERACTIVE MENU
    # ===================================================================

    @bot.tree.command(
        name="menu",
        description="Show an interactive control panel with clickable buttons",
    )
    async def menu_command(interaction: discord.Interaction):
        # Build a quick status summary for the menu message
        result = await handler.execute("get_status", {})
        tasks = result.get("tasks", {})
        by_status = tasks.get("by_status", {})
        total = tasks.get("total", 0)
        completed = by_status.get("COMPLETED", 0)
        in_progress = (
            by_status.get("IN_PROGRESS", 0) + by_status.get("ASSIGNED", 0)
        )
        failed = by_status.get("FAILED", 0)
        blocked = by_status.get("BLOCKED", 0)
        ready = by_status.get("READY", 0)

        agents = result.get("agents", [])
        busy_count = sum(1 for a in agents if a.get("state") == "BUSY")

        lines = ["## 🎛️ Agent Queue — Control Panel"]
        if result.get("orchestrator_paused"):
            lines.append("⏸ **Orchestrator is PAUSED**")
        else:
            lines.append("▶ Orchestrator running")

        bar = progress_bar(completed, total, width=12) if total > 0 else "—"
        lines.append(f"**Progress:** {bar}")
        lines.append(
            f"📊 {total} tasks — {in_progress} active, {ready} ready, "
            f"{failed} failed, {blocked} blocked"
        )
        lines.append(
            f"🤖 {len(agents)} agents — {busy_count} busy"
        )
        lines.append(
            "\n_Use the buttons below to view details and take actions._"
        )

        view = MenuView(handler=handler, bot=bot)
        await interaction.response.send_message(
            "\n".join(lines), view=view
        )