wipe-daemon 0.3.1

Local HTTP/WS daemon that serves the wipe board UI and API.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
//! HTTP + WebSocket API handlers over `wipe-core`.

use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::extract::{Multipart, Path, Query, State};
use axum::http::{header, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::Json;
use chrono::Utc;
use serde::Deserialize;
use serde_json::{json, Value};
use tokio::sync::broadcast;

use wipe_core::forum::{self, NewReply, NewThread, SearchQuery};
use wipe_core::model::{Board, IdentityKind, Ticket};
use wipe_core::ops::{self, NewTicket, TicketPatch};
use wipe_core::{git, Store};

/// Shared server state.
#[derive(Clone)]
pub struct AppState {
    /// The project the daemon was started in, if any. Used only as the default
    /// target when a request omits `?project=`; every UI request names its project
    /// explicitly, so this is just a convenience for CLI-less callers. `None` when
    /// `wipe serve` runs outside a board (a purely global viewer).
    pub current: Option<PathBuf>,
    /// Broadcast channel for live-update notifications.
    pub tx: broadcast::Sender<String>,
    /// Number of live UI WebSocket clients. Drives idle-shutdown: when this is 0
    /// for long enough, an auto-served daemon exits.
    pub clients: Arc<AtomicUsize>,
}

/// An error that renders as a JSON `{ok:false,error}` body.
pub struct ApiError(anyhow::Error);

impl<E: Into<anyhow::Error>> From<E> for ApiError {
    fn from(e: E) -> Self {
        ApiError(e.into())
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let body = Json(json!({ "ok": false, "error": self.0.to_string() }));
        (StatusCode::BAD_REQUEST, body).into_response()
    }
}

type ApiResult = Result<Json<Value>, ApiError>;

/// Query string carrying an optional project root.
#[derive(Debug, Deserialize)]
pub struct ProjectQuery {
    project: Option<String>,
}

/// Resolve which board a request targets. Prefer the explicit `project` (every UI
/// request sends one); fall back to the daemon's launch project. Erroring when
/// neither is available keeps a stray request from silently hitting the wrong board.
fn store_for(state: &AppState, project: Option<String>) -> Result<Store, ApiError> {
    let root = project
        .map(PathBuf::from)
        .or_else(|| state.current.clone())
        .ok_or_else(|| ApiError(anyhow::anyhow!("no project selected")))?;
    Ok(Store::open(root)?)
}

fn notify(state: &AppState) {
    let _ = state.tx.send("changed".to_string());
}

/// Who to attribute a UI-driven mutation to for the activity timeline: an explicit
/// `actor` from the request if given, else the repo's configured git identity, else
/// a generic fallback.
fn resolve_actor(store: &Store, provided: Option<String>) -> String {
    provided
        .filter(|s| !s.trim().is_empty())
        .or_else(|| git::config_identity(store.root()))
        .unwrap_or_else(|| "someone".to_string())
}

fn board_json(board: &Board, view: &[(String, Vec<Ticket>)]) -> Value {
    let lists: Vec<Value> = view
        .iter()
        .map(|(list_id, tickets)| {
            let name = board
                .list(list_id)
                .map(|l| l.name.clone())
                .unwrap_or_else(|| list_id.clone());
            json!({ "list": list_id, "name": name, "tickets": tickets })
        })
        .collect();
    json!({ "board": board.name, "lists": lists })
}

// --- read endpoints --------------------------------------------------------

/// `GET /api/health`
pub async fn health() -> Json<Value> {
    Json(json!({ "ok": true, "service": "wipe-daemon", "version": env!("CARGO_PKG_VERSION") }))
}

/// `GET /api/config` - user-global UI preferences (accent/theme) so the board can
/// honor the styling chosen via `wipe config --global`.
pub async fn app_config() -> Json<Value> {
    let g = wipe_core::GlobalConfig::load();
    Json(json!({ "accent": g.ui_accent, "theme": g.ui_theme }))
}

/// `GET /api/projects`
///
/// Reports every registered board plus `current` - the project the daemon was
/// launched in - so the UI can default-open that board rather than an arbitrary
/// one. `current` is null when `wipe serve` was started outside any board.
pub async fn projects(State(state): State<AppState>) -> ApiResult {
    let current = state
        .current
        .as_ref()
        .filter(|root| Store::open(root).is_ok())
        .map(|root| root.display().to_string());
    if let Some(root) = &state.current {
        crate::registry::register(root);
    }
    Ok(Json(
        json!({ "projects": crate::registry::list(), "current": current }),
    ))
}

/// `GET /api/board`
pub async fn board(State(state): State<AppState>, Query(q): Query<ProjectQuery>) -> ApiResult {
    let store = store_for(&state, q.project)?;
    let (board, view) = ops::board_view(&store)?;
    Ok(Json(board_json(&board, &view)))
}

/// `GET /api/history` - commits touching `.wipe/`, most recent first.
pub async fn history(State(state): State<AppState>, Query(q): Query<ProjectQuery>) -> ApiResult {
    let store = store_for(&state, q.project)?;
    let commits = git::log(store.root(), Some(".wipe"), Some(200))?;
    Ok(Json(json!({ "commits": commits })))
}

/// Query for a historical board snapshot.
#[derive(Debug, Deserialize)]
pub struct AtQuery {
    project: Option<String>,
    commit: String,
}

/// `GET /api/board/at` - reconstruct the board as of a commit (the rewind feature).
pub async fn board_at(State(state): State<AppState>, Query(q): Query<AtQuery>) -> ApiResult {
    let store = store_for(&state, q.project)?;
    let root = store.root();
    let board_src = git::file_at_commit(root, &q.commit, ".wipe/board.json")?
        .ok_or_else(|| ApiError(anyhow::anyhow!("no board at commit {}", q.commit)))?;
    let board: Board = serde_json::from_str(&board_src)?;

    let mut lists = Vec::with_capacity(board.lists.len());
    for list in &board.lists {
        let mut tickets = Vec::with_capacity(list.cards.len());
        for id in &list.cards {
            let rel = format!(".wipe/tickets/{id}.json");
            if let Some(src) = git::file_at_commit(root, &q.commit, &rel)? {
                if let Ok(t) = serde_json::from_str::<Ticket>(&src) {
                    tickets.push(t);
                }
            }
        }
        lists.push(json!({ "list": list.id, "name": list.name, "tickets": tickets }));
    }
    Ok(Json(
        json!({ "board": board.name, "commit": q.commit, "lists": lists }),
    ))
}

// --- write endpoints -------------------------------------------------------

/// Body for creating a ticket.
#[derive(Debug, Deserialize)]
pub struct CreateTicketBody {
    project: Option<String>,
    title: String,
    #[serde(default)]
    body: Option<String>,
    #[serde(default)]
    priority: Option<String>,
    #[serde(default)]
    list: Option<String>,
    #[serde(default)]
    labels: Vec<String>,
    #[serde(default)]
    assignees: Vec<String>,
    #[serde(default)]
    actor: Option<String>,
}

/// `POST /api/tickets`
pub async fn create_ticket(
    State(state): State<AppState>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<CreateTicketBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    let actor = resolve_actor(&store, b.actor);
    let spec = NewTicket {
        title: b.title,
        body: b.body,
        priority: b.priority,
        list: b.list,
        labels: b.labels,
        assignees: b.assignees,
    };
    let ticket = ops::create_ticket(&store, spec, &actor, Utc::now())?;
    notify(&state);
    Ok(Json(serde_json::to_value(ticket)?))
}

/// Body for moving a ticket.
#[derive(Debug, Deserialize)]
pub struct MoveBody {
    project: Option<String>,
    to: String,
    #[serde(default)]
    pos: Option<usize>,
    #[serde(default)]
    actor: Option<String>,
}

/// `POST /api/tickets/{id}/move`
pub async fn move_ticket(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<MoveBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    let actor = resolve_actor(&store, b.actor);
    ops::move_ticket(&store, &id, &b.to, b.pos, &actor, Utc::now())?;
    notify(&state);
    Ok(Json(json!({ "ok": true, "id": id, "list": b.to })))
}

/// Body for adding a comment.
#[derive(Debug, Deserialize)]
pub struct CommentBody {
    project: Option<String>,
    #[serde(default)]
    author: Option<String>,
    body: String,
}

/// `POST /api/tickets/{id}/comments`
pub async fn add_comment(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<CommentBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    let author = b.author.unwrap_or_else(|| "ui".to_string());
    let cid = ops::add_comment(&store, &id, &author, &b.body, Utc::now())?;
    notify(&state);
    Ok(Json(json!({ "ok": true, "ticket": id, "comment": cid })))
}

/// `GET /api/definitions` - labels + priorities.
pub async fn definitions(
    State(state): State<AppState>,
    Query(q): Query<ProjectQuery>,
) -> ApiResult {
    let store = store_for(&state, q.project)?;
    Ok(Json(serde_json::to_value(store.load_definitions()?)?))
}

/// Body for creating a label definition. `color` is optional (auto-assigned).
#[derive(Debug, Deserialize)]
pub struct LabelBody {
    project: Option<String>,
    name: String,
    #[serde(default)]
    color: Option<String>,
    #[serde(default)]
    description: Option<String>,
}

/// `POST /api/labels` - define a new label (auto-colored if no color given).
pub async fn create_label(
    State(state): State<AppState>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<LabelBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    let label = ops::create_label(&store, &b.name, b.color, b.description)?;
    notify(&state);
    Ok(Json(serde_json::to_value(label)?))
}

/// Body for updating a label's color.
#[derive(Debug, Deserialize)]
pub struct LabelColorBody {
    project: Option<String>,
    color: String,
}

/// `PATCH /api/labels/{name}` - change a label's color.
pub async fn recolor_label(
    State(state): State<AppState>,
    Path(name): Path<String>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<LabelColorBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    let label = ops::set_label_color(&store, &name, &b.color)?;
    notify(&state);
    Ok(Json(serde_json::to_value(label)?))
}

/// `DELETE /api/labels/{name}` - delete a label and strip it from all tickets.
pub async fn delete_label(
    State(state): State<AppState>,
    Path(name): Path<String>,
    Query(q): Query<ProjectQuery>,
) -> ApiResult {
    let store = store_for(&state, q.project)?;
    ops::delete_label(&store, &name, Utc::now())?;
    notify(&state);
    Ok(Json(json!({ "ok": true })))
}

/// Body for patching a ticket. Absent fields are left unchanged; an explicit
/// `null` for `priority` clears it.
#[derive(Debug, Deserialize)]
pub struct PatchBody {
    project: Option<String>,
    #[serde(default)]
    title: Option<String>,
    #[serde(default)]
    body: Option<String>,
    #[serde(default)]
    priority: Option<Option<String>>,
    #[serde(default)]
    labels: Option<Vec<String>>,
    #[serde(default)]
    assignees: Option<Vec<String>>,
    #[serde(default)]
    actor: Option<String>,
}

/// `PATCH /api/tickets/{id}` - update ticket fields.
pub async fn patch_ticket(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<PatchBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    let actor = resolve_actor(&store, b.actor);
    let patch = TicketPatch {
        title: b.title,
        body: b.body,
        priority: b.priority,
        labels: b.labels,
        assignees: b.assignees,
    };
    let ticket = ops::update_ticket(&store, &id, patch, &actor, Utc::now())?;
    notify(&state);
    Ok(Json(serde_json::to_value(ticket)?))
}

/// `GET /api/identities` - humans (from git) + agents (registry).
pub async fn identities(State(state): State<AppState>, Query(q): Query<ProjectQuery>) -> ApiResult {
    let store = store_for(&state, q.project)?;
    Ok(Json(json!({ "identities": ops::list_identities(&store)? })))
}

/// Body for creating/updating an identity.
#[derive(Debug, Deserialize)]
pub struct IdentityBody {
    project: Option<String>,
    display_name: String,
    #[serde(default)]
    kind: Option<String>,
}

/// `PUT /api/identities/{id}` - set an identity's display name / kind.
pub async fn put_identity(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<IdentityBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    let kind = match b.kind.as_deref() {
        Some("agent") => Some(IdentityKind::Agent),
        Some("human") => Some(IdentityKind::Human),
        _ => None,
    };
    let ident = ops::upsert_identity(&store, &id, &b.display_name, kind)?;
    notify(&state);
    Ok(Json(serde_json::to_value(ident)?))
}

/// `DELETE /api/identities/{id}` - remove an identity from the registry (agents /
/// manual overrides; git-discovered humans reappear from history).
pub async fn delete_identity(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(q): Query<ProjectQuery>,
) -> ApiResult {
    let store = store_for(&state, q.project)?;
    ops::delete_identity(&store, &id)?;
    notify(&state);
    Ok(Json(json!({ "ok": true, "id": id })))
}

/// `POST /api/tickets/{id}/attachments` - multipart file upload (field `file`).
pub async fn upload_attachment(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(q): Query<ProjectQuery>,
    mut multipart: Multipart,
) -> ApiResult {
    let store = store_for(&state, q.project)?;
    let actor = resolve_actor(&store, None);
    let max = store.load_settings()?.max_attachment_mb * 1024 * 1024;

    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(|e| ApiError(anyhow::anyhow!("bad upload: {e}")))?
    {
        if field.name() != Some("file") {
            continue;
        }
        let name = field.file_name().unwrap_or("file").to_string();
        let mime = field
            .content_type()
            .map(|s| s.to_string())
            .unwrap_or_else(|| "application/octet-stream".to_string());
        let bytes = field
            .bytes()
            .await
            .map_err(|e| ApiError(anyhow::anyhow!("read upload: {e}")))?;
        if bytes.len() as u64 > max {
            return Err(ApiError(anyhow::anyhow!(
                "attachment is {:.1} MB, over the {} MB limit",
                bytes.len() as f64 / 1_048_576.0,
                max / 1024 / 1024
            )));
        }
        let att = ops::add_attachment(&store, &id, &name, &bytes, &mime, &actor, Utc::now())?;
        notify(&state);
        return Ok(Json(serde_json::to_value(att)?));
    }
    Err(ApiError(anyhow::anyhow!("no `file` field in upload")))
}

/// Body for detaching an attachment.
#[derive(Debug, Deserialize)]
pub struct DetachBody {
    project: Option<String>,
    path: String,
    #[serde(default)]
    actor: Option<String>,
}

/// `DELETE /api/tickets/{id}/attachments` - detach by repo-relative path.
pub async fn delete_attachment(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<DetachBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    let actor = resolve_actor(&store, b.actor);
    ops::remove_attachment(&store, &id, &b.path, &actor, Utc::now())?;
    notify(&state);
    Ok(Json(json!({ "ok": true })))
}

/// `GET /api/media/{*path}` - serve an attachment for preview/download.
pub async fn serve_media(
    State(state): State<AppState>,
    Query(q): Query<ProjectQuery>,
    Path(path): Path<String>,
) -> Response {
    let store = match store_for(&state, q.project) {
        Ok(s) => s,
        Err(e) => return e.into_response(),
    };
    let rel = path.replace('\\', "/");
    if rel.contains("..") {
        return (StatusCode::BAD_REQUEST, "invalid path").into_response();
    }
    let full = store.root().join(&rel);
    // Confine reads to within the project root.
    let within = std::fs::canonicalize(store.root())
        .ok()
        .zip(std::fs::canonicalize(&full).ok())
        .map(|(root, target)| target.starts_with(root))
        .unwrap_or(false);
    if !within {
        return (StatusCode::NOT_FOUND, "not found").into_response();
    }
    match std::fs::read(&full) {
        Ok(bytes) => {
            let mime = mime_guess::from_path(&full).first_or_octet_stream();
            ([(header::CONTENT_TYPE, mime.as_ref())], bytes).into_response()
        }
        Err(_) => (StatusCode::NOT_FOUND, "not found").into_response(),
    }
}

/// `GET /api/graph` - the commit graph (all branches) with board checkpoints.
pub async fn graph(State(state): State<AppState>, Query(q): Query<ProjectQuery>) -> ApiResult {
    let store = store_for(&state, q.project)?;
    let commits = git::graph(store.root(), Some(300))?;
    Ok(Json(json!({ "commits": commits })))
}

/// Body for adding a list.
#[derive(Debug, Deserialize)]
pub struct AddListBody {
    project: Option<String>,
    name: String,
}

/// `POST /api/lists` - add a list to the board.
pub async fn add_list(
    State(state): State<AppState>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<AddListBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    let id = ops::add_list(&store, &b.name, Utc::now())?;
    notify(&state);
    Ok(Json(json!({ "ok": true, "id": id, "name": b.name })))
}

/// Body for renaming a list.
#[derive(Debug, Deserialize)]
pub struct RenameListBody {
    project: Option<String>,
    name: String,
}

/// `PATCH /api/lists/{id}` - rename a list.
pub async fn rename_list(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<RenameListBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    ops::rename_list(&store, &id, &b.name, Utc::now())?;
    notify(&state);
    Ok(Json(json!({ "ok": true, "id": id, "name": b.name })))
}

/// Body for reordering a list.
#[derive(Debug, Deserialize)]
pub struct MoveListBody {
    project: Option<String>,
    index: usize,
}

/// `POST /api/lists/{id}/move` - reorder a list to a new index.
pub async fn move_list(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<MoveListBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    ops::move_list(&store, &id, b.index, Utc::now())?;
    notify(&state);
    Ok(Json(json!({ "ok": true, "id": id, "index": b.index })))
}

/// Query for removing a list.
#[derive(Debug, Deserialize)]
pub struct RemoveListQuery {
    project: Option<String>,
    #[serde(default)]
    force: bool,
}

/// `DELETE /api/lists/{id}` - remove a list (use `?force=true` to delete its cards).
pub async fn remove_list(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(q): Query<RemoveListQuery>,
) -> ApiResult {
    let store = store_for(&state, q.project)?;
    ops::remove_list(&store, &id, q.force, Utc::now())?;
    notify(&state);
    Ok(Json(json!({ "ok": true, "id": id })))
}

// --- forum -----------------------------------------------------------------

/// `GET /api/forum` - thread summaries (root posts + total post counts), newest first.
pub async fn forum_list(State(state): State<AppState>, Query(q): Query<ProjectQuery>) -> ApiResult {
    let store = store_for(&state, q.project)?;
    let all = forum::index(&store)?;
    let threads: Vec<Value> = all
        .iter()
        .filter(|p| p.depth == 0)
        .map(|r| {
            let posts = all.iter().filter(|p| p.thread_id == r.thread_id).count();
            json!({
                "id": r.thread_id,
                "title": r.thread_title,
                "author": r.author,
                "labels": r.labels,
                "posts": posts,
                "created": r.created,
            })
        })
        .collect();
    Ok(Json(json!({ "threads": threads })))
}

/// `GET /api/forum/{id}` - a whole thread (root + nested reply tree).
pub async fn forum_thread(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(q): Query<ProjectQuery>,
) -> ApiResult {
    let store = store_for(&state, q.project)?;
    Ok(Json(serde_json::to_value(forum::get_thread(&store, &id)?)?))
}

/// Body for creating a thread.
#[derive(Debug, Deserialize)]
pub struct ForumPostBody {
    project: Option<String>,
    title: String,
    #[serde(default)]
    body: String,
    #[serde(default)]
    labels: Vec<String>,
    #[serde(default)]
    refs: Vec<String>,
    #[serde(default)]
    actor: Option<String>,
}

/// `POST /api/forum` - open a new thread.
pub async fn forum_create(
    State(state): State<AppState>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<ForumPostBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    let actor = resolve_actor(&store, b.actor);
    let t = forum::create_thread(
        &store,
        NewThread {
            title: b.title,
            body: b.body,
            labels: b.labels,
            refs: b.refs,
            attachments: Vec::new(),
        },
        &actor,
        Utc::now(),
    )?;
    notify(&state);
    Ok(Json(serde_json::to_value(t)?))
}

/// Body for replying to a post.
#[derive(Debug, Deserialize)]
pub struct ForumReplyBody {
    project: Option<String>,
    body: String,
    #[serde(default)]
    labels: Vec<String>,
    #[serde(default)]
    refs: Vec<String>,
    #[serde(default)]
    actor: Option<String>,
}

/// `POST /api/forum/{id}/reply` - reply to a post at any depth.
pub async fn forum_reply(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<ForumReplyBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    let actor = resolve_actor(&store, b.actor);
    let child = forum::reply(
        &store,
        &id,
        NewReply {
            body: b.body,
            labels: b.labels,
            refs: b.refs,
            attachments: Vec::new(),
        },
        &actor,
        Utc::now(),
    )?;
    notify(&state);
    Ok(Json(json!({ "ok": true, "id": child, "parent": id })))
}

/// Body for editing a post.
#[derive(Debug, Deserialize)]
pub struct ForumEditBody {
    project: Option<String>,
    body: String,
}

/// `PATCH /api/forum/{id}` - edit a post's body.
pub async fn forum_edit(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(pq): Query<ProjectQuery>,
    Json(b): Json<ForumEditBody>,
) -> ApiResult {
    let store = store_for(&state, pq.project.or(b.project))?;
    forum::edit_post(&store, &id, &b.body, Utc::now())?;
    notify(&state);
    Ok(Json(json!({ "ok": true, "id": id })))
}

/// `DELETE /api/forum/{id}` - delete a post and its subtree.
pub async fn forum_delete(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(q): Query<ProjectQuery>,
) -> ApiResult {
    let store = store_for(&state, q.project)?;
    forum::delete_post(&store, &id, Utc::now())?;
    notify(&state);
    Ok(Json(json!({ "ok": true, "id": id })))
}

/// Query for a forum search.
#[derive(Debug, Deserialize)]
pub struct ForumSearchParams {
    project: Option<String>,
    #[serde(default)]
    q: Option<String>,
    #[serde(default)]
    author: Option<String>,
    #[serde(default)]
    label: Option<String>,
    #[serde(default)]
    scope: Option<String>,
    #[serde(default)]
    titles: Option<bool>,
    #[serde(default)]
    depth: Option<usize>,
    #[serde(default)]
    limit: Option<usize>,
}

/// `GET /api/forum/search` - regex + filter search over posts.
pub async fn forum_search(
    State(state): State<AppState>,
    Query(p): Query<ForumSearchParams>,
) -> ApiResult {
    let store = store_for(&state, p.project)?;
    let pattern = match p.q.as_deref() {
        Some(s) if !s.trim().is_empty() => Some(forum::compile_pattern(s, true)?),
        _ => None,
    };
    let query = SearchQuery {
        pattern,
        author: p.author,
        labels: p.label.into_iter().collect(),
        scope: p.scope,
        max_depth: p.depth,
        titles_only: p.titles.unwrap_or(false),
        limit: p.limit,
    };
    Ok(Json(json!({ "posts": forum::search(&store, &query)? })))
}

// --- websocket -------------------------------------------------------------

/// `GET /ws` - upgrade to a WebSocket that streams change notifications.
pub async fn ws_handler(ws: WebSocketUpgrade, State(state): State<AppState>) -> Response {
    ws.on_upgrade(move |socket| ws_loop(socket, state))
}

/// Decrements the live-client counter when a WebSocket handler ends.
struct ClientGuard(Arc<AtomicUsize>);
impl Drop for ClientGuard {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::SeqCst);
    }
}

async fn ws_loop(mut socket: WebSocket, state: AppState) {
    let mut rx = state.tx.subscribe();
    // Count this client for the lifetime of the socket so idle-shutdown knows the
    // board is actively being viewed; `_guard` decrements on drop (any exit path).
    state.clients.fetch_add(1, Ordering::SeqCst);
    let _guard = ClientGuard(state.clients.clone());
    let _ = socket.send(Message::Text("connected".into())).await;
    loop {
        tokio::select! {
            msg = rx.recv() => match msg {
                Ok(m) => {
                    if socket.send(Message::Text(m.into())).await.is_err() {
                        break;
                    }
                }
                Err(broadcast::error::RecvError::Closed) => break,
                Err(broadcast::error::RecvError::Lagged(_)) => {}
            },
            incoming = socket.recv() => match incoming {
                Some(Ok(_)) => {}
                _ => break,
            },
        }
    }
}