trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Socket transport and JSON projections for one daemon's health surface.
//!
//! Why: the background poller needs a small, testable transport that yields a
//! projected [`PanelData`] or a clean error string, plus the per-daemon list
//! endpoints that feed the collections pane. Keeping the projections pure lets
//! them be unit-tested without a live daemon.
//! What: the [`HealthClient`] impl (poll / fetch / count / list / stop methods),
//! the [`client_for`] constructor, and the `project_*` helpers that turn raw
//! JSON payloads into typed counts and [`CollectionRow`]s.
//! Both daemons are reached over their Unix sockets: memory since #6286,
//! search since #9214 (ADR-0032 retires its TCP listener).
//! Test: `health_client_stores_base_url`, `poll_unreachable_daemon_is_offline`,
//! `project_memory_counts_reads_status_fields`, `project_palace_rows_reads_palaces`,
//! `project_log_tail_reads_fields`, `project_edge_kinds_sorts_desc`.

use std::path::{Path, PathBuf};
use std::time::Duration;

use serde_json::{Value, json};

use crate::daemon::search_rpc::{
    METHOD_HEALTH, METHOD_INDEX_STATUS, METHOD_INDEXES_LIST, call_at, search_socket,
};

use crate::tui::health::format::format_relative_time;
use crate::tui::health::types::{
    CollectionRow, Daemon, HealthClient, HealthWire, PanelData, PanelState,
};

/// Per-request timeout for a daemon health probe.
///
/// Why: a hung daemon must not stall the poll task; a short timeout turns an
/// unresponsive daemon into a clean "offline" state on the next tick.
/// What: three seconds, comfortably above a healthy local round-trip.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(3);

// #9214: daemon methods trusty-common has no constant for. Local so this slice
// needs no trusty-common release; names match `trusty-search` `service::rpc`.
/// `search.graph.stats` — node/edge counts and the per-kind breakdown.
const METHOD_GRAPH_STATS: &str = "search.graph.stats";
/// `search.logs.tail` — the most recent N lines from the daemon's log ring.
const METHOD_LOGS_TAIL: &str = "search.logs.tail";
/// `search.admin.stop` — ask the daemon to shut down gracefully.
const METHOD_ADMIN_STOP: &str = "search.admin.stop";

/// The socket path handed out when the search socket cannot be resolved.
///
/// Why: a path nothing binds, so every call fails as "daemon unreachable" and
/// the panel renders Offline instead of the TUI aborting (#9214).
const UNREACHABLE_SEARCH_SOCKET: &str = "/nonexistent/trusty-search/trusty-search.sock";

/// Resolve the trusty-search socket for the health screen and banner (#9214).
///
/// Why: the TUI must reach search over its socket, at the path
/// `TRUSTY_SEARCH_SOCKET` or the daemon's data directory names, and a
/// resolution failure must not take the TUI down. This mirrors trusty-common's
/// `resolve_memory_socket_or_unreachable` for the memory panel.
/// What: [`search_socket`], falling back to a path nothing binds on `Err`.
/// Test: `search_poll_over_the_socket_is_online_with_index_counts`,
/// `an_unresolvable_search_socket_falls_back_to_a_dead_path`.
pub fn resolve_search_socket_or_unreachable() -> PathBuf {
    socket_or_unreachable(search_socket())
}

/// The fallback half of [`resolve_search_socket_or_unreachable`], separated so
/// the `Err` arm is testable without breaking the data directory.
///
/// What: `Ok` passes through; `Err` logs a warning and yields
/// [`UNREACHABLE_SEARCH_SOCKET`]. It warns through `tracing`, not stderr,
/// because stderr would draw over the TUI's alternate screen.
/// Test: `an_unresolvable_search_socket_falls_back_to_a_dead_path`.
pub(crate) fn socket_or_unreachable(resolved: anyhow::Result<PathBuf>) -> PathBuf {
    resolved.unwrap_or_else(|e| {
        tracing::warn!("trusty-search socket unresolved, panel will show offline: {e:#}");
        PathBuf::from(UNREACHABLE_SEARCH_SOCKET)
    })
}

/// The index ids in a `search.indexes.list` answer; a malformed answer is empty.
fn index_ids(list: &Value) -> Vec<String> {
    list.get("indexes")
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

impl HealthClient {
    /// Build a client targeting `base` for the given `daemon`.
    ///
    /// Why: the health screen is pointed at a daemon address from a CLI flag or
    /// the documented default.
    /// What: stores the daemon's socket path and its [`Daemon`] tag.
    /// Test: `health_client_stores_base_url`.
    pub fn new(base: impl Into<String>, daemon: Daemon) -> Self {
        Self {
            base: base.into(),
            daemon,
        }
    }

    /// The socket path this client targets (#6286 memory, #9214 search).
    ///
    /// Why: the offline panel renders the daemon address it failed to reach.
    /// Test: `health_client_stores_base_url`.
    pub fn base_url(&self) -> &str {
        &self.base
    }

    /// Poll the daemon and project the result into a [`PanelState`].
    ///
    /// Why: the background task wants one infallible call per tick that always
    /// yields a renderable state — `Online` on success, `Offline` on any
    /// transport or decode failure.
    /// What: GETs `/health`, then the daemon-specific list endpoints for the
    /// key counts, folding everything into [`PanelData`]. Any error along the
    /// way becomes `Offline` carrying the error string.
    /// Test: live behaviour is covered by the daemon suites; the offline path
    /// is exercised by `poll_unreachable_daemon_is_offline`.
    /// One RPC call on trusty-memory's socket (#6286).
    ///
    /// Why: this client's `base` is a socket path when `daemon` is
    /// `Daemon::Memory`, and every memory leg below goes through here.
    async fn memory_call(&self, method: &str, params: serde_json::Value) -> anyhow::Result<Value> {
        trusty_common::memory_rpc::call_memory_tool_at_with_timeout(
            std::path::Path::new(&self.base),
            method,
            params,
            REQUEST_TIMEOUT,
        )
        .await
    }

    /// One RPC call on trusty-search's socket (#9214).
    ///
    /// Why: ADR-0032 retires search's TCP listener; every search leg below
    /// goes through here, bounded by [`REQUEST_TIMEOUT`].
    async fn search_call(&self, method: &str, params: Value) -> anyhow::Result<Value> {
        call_at(Path::new(&self.base), method, params, REQUEST_TIMEOUT).await
    }

    pub async fn poll(&self) -> PanelState {
        match self.fetch().await {
            Ok(data) => PanelState::Online(data),
            Err(e) => PanelState::Offline {
                last_error: e.to_string(),
            },
        }
    }

    /// Fetch and project the panel payload, returning a `Result` for `?`.
    ///
    /// Why: keeps [`Self::poll`]'s error-to-`Offline` mapping in one place
    /// while the happy path stays terse with `?`.
    /// What: reads the daemon's health and its list surface; for search the
    /// counts are index count + summed chunk counts, for memory they come from
    /// `memory.status`. Both legs use the daemons' sockets (#6286, #9214).
    /// Test: covered indirectly by `poll`; the count projections are unit-tested
    /// via `project_search_counts` / `project_memory_counts`.
    async fn fetch(&self) -> anyhow::Result<PanelData> {
        let health: HealthWire = match self.daemon {
            Daemon::Search => {
                serde_json::from_value(self.search_call(METHOD_HEALTH, json!({})).await?)?
            }
            Daemon::Memory => {
                serde_json::from_value(self.memory_call("memory.health", json!({})).await?)?
            }
        };

        let (count_a, count_b, count_c, count_d) = match self.daemon {
            Daemon::Search => self.search_counts().await,
            Daemon::Memory => self.memory_counts().await,
        };

        Ok(PanelData {
            version: health.version,
            rss_mb: health.rss_mb,
            cpu_pct: health.cpu_pct,
            uptime_secs: health.uptime_secs,
            disk_bytes: health.disk_bytes,
            count_a,
            count_b,
            count_c,
            count_d,
        })
    }

    /// Resolve the search key counts: `(indexes, total_chunks, 0, 0)`.
    ///
    /// Why: the search panel shows index count and summed chunk count; a
    /// failure to enumerate indexes degrades to zeroes rather than failing the
    /// whole poll, since the resource block already rendered.
    /// What: calls `search.indexes.list`, then `search.index.status` per index,
    /// summing `chunk_count`. A refused list yields all zeroes; a refused
    /// status adds no chunks.
    /// Test: `search_poll_over_the_socket_is_online_with_index_counts`,
    /// `search_counts_degrade_to_zero_when_the_index_list_is_refused`.
    async fn search_counts(&self) -> (u64, u64, u64, u64) {
        // #9214: socket methods replace GET /indexes and /indexes/:id/status.
        let Ok(list) = self.search_call(METHOD_INDEXES_LIST, json!({})).await else {
            return (0, 0, 0, 0);
        };
        let ids = index_ids(&list);
        let mut total_chunks = 0u64;
        for id in &ids {
            if let Ok(status) = self.index_status(id).await {
                total_chunks = total_chunks.saturating_add(
                    status
                        .get("chunk_count")
                        .and_then(|v| v.as_u64())
                        .unwrap_or(0),
                );
            }
        }
        (ids.len() as u64, total_chunks, 0, 0)
    }

    /// Resolve the memory key counts from `memory.status`.
    ///
    /// Why: the memory panel shows palaces, vectors, drawers, and KG triples;
    /// one method returns all four.
    /// What: calls `memory.status` and projects `palace_count`,
    /// `total_vectors`, `total_drawers`, `total_kg_triples`. Any error yields
    /// all zeroes.
    /// Test: the JSON projection is unit-tested via `project_memory_counts`.
    async fn memory_counts(&self) -> (u64, u64, u64, u64) {
        match self.memory_call("memory.status", json!({})).await {
            Ok(status) => project_memory_counts(&status),
            Err(_) => (0, 0, 0, 0),
        }
    }

    /// `search.index.status` for one index.
    async fn index_status(&self, id: &str) -> anyhow::Result<Value> {
        self.search_call(METHOD_INDEX_STATUS, json!({ "index_id": id }))
            .await
    }

    /// Fetch the most recent `n` log lines from the daemon.
    ///
    /// Why: the Logs tab (`[2]`) tails the daemon's in-memory log ring via
    /// the daemon's in-memory log ring (issue #35). Search answers
    /// `search.logs.tail` (#9214), memory answers `memory.logs_tail` (#6286).
    /// What: reads the daemon's log page and projects `lines` + `total`. A
    /// daemon that cannot answer yields `Ok((vec![], 0))` rather than an error,
    /// so the tab degrades to a placeholder cleanly.
    /// Test: `search_logs_tail_over_the_socket_reads_the_page`,
    /// `search_logs_tail_refusal_degrades_to_an_empty_page`; the projection
    /// is unit-tested via `project_log_tail_reads_fields`.
    pub async fn logs_tail(&self, n: u32) -> anyhow::Result<(Vec<String>, u64)> {
        let raw = match self.daemon {
            Daemon::Memory => self
                .memory_call("memory.logs_tail", json!({ "n": n }))
                .await
                .unwrap_or(Value::Null),
            // #9214: a refusal still degrades to an empty page, as on HTTP.
            Daemon::Search => self
                .search_call(METHOD_LOGS_TAIL, json!({ "n": n }))
                .await
                .unwrap_or(Value::Null),
        };
        Ok(project_log_tail(&raw))
    }

    /// Fetch the search daemon's index list with chunk counts.
    ///
    /// Why: the Collections list (left panel for the search service) wants a
    /// per-index name + chunk count so the operator can see at a glance
    /// which corpora are loaded.
    /// What: calls `search.indexes.list`, then `search.index.status` and
    /// `search.graph.stats` per index, projecting each into a
    /// [`CollectionRow`]. A refused list yields an empty list; a refused
    /// per-index call leaves that row's fields at zero. The community fields
    /// stay at their defaults: `/communities` was never served and has no
    /// socket method (#9214).
    /// Test: `search_collections_over_the_socket_read_status_and_graph_stats`,
    /// `search_collections_are_empty_when_the_index_list_is_refused`.
    pub async fn search_collections(&self) -> Vec<CollectionRow> {
        let Ok(list) = self.search_call(METHOD_INDEXES_LIST, json!({})).await else {
            return Vec::new();
        };
        let ids = index_ids(&list);
        let mut rows = Vec::with_capacity(ids.len());
        for id in ids {
            // Status: chunk count + last_indexed + disk bytes + context embedding.
            let status = self.index_status(&id).await.ok();
            let count = status
                .as_ref()
                .and_then(|v| v.get("chunk_count").and_then(|c| c.as_u64()))
                .unwrap_or(0);
            let last_indexed = status
                .as_ref()
                .and_then(|v| v.get("last_indexed").and_then(|c| c.as_str()))
                .map(str::to_string);
            let disk_bytes = status
                .as_ref()
                .and_then(|v| v.get("disk_bytes").and_then(|c| c.as_u64()))
                .unwrap_or(0);
            let has_context_embedding = status
                .as_ref()
                .and_then(|v| v.get("has_context_embedding").and_then(|c| c.as_bool()))
                .unwrap_or(false);

            // Graph stats: nodes, edges, edge kind histogram. Errors → zeroes.
            let graph = self
                .search_call(METHOD_GRAPH_STATS, json!({ "index_id": id }))
                .await
                .ok();
            let node_count = graph
                .as_ref()
                .and_then(|v| v.get("node_count").and_then(|c| c.as_u64()))
                .unwrap_or(0);
            let edge_count = graph
                .as_ref()
                .and_then(|v| v.get("edge_count").and_then(|c| c.as_u64()))
                .unwrap_or(0);
            let edge_kinds = graph.as_ref().map(project_edge_kinds).unwrap_or_default();

            let note = format_relative_time(last_indexed.as_deref());
            rows.push(CollectionRow {
                id,
                count,
                note,
                ok: true,
                last_indexed,
                node_count,
                edge_count,
                edge_kinds,
                disk_bytes,
                has_context_embedding,
                ..Default::default()
            });
        }
        rows
    }

    /// Fetch the memory daemon's palace roster for the Collections panel.
    ///
    /// Why: the Collections list (left panel for the memory service) needs the
    /// per-palace name, vector count, and KG triple count so the operator can
    /// see at a glance which palaces hold the most memory and which carry a
    /// knowledge graph. `memory.status` only exposes aggregate totals.
    ///
    /// What (#6286): one `memory.palaces_list` call. This fanned out
    /// `memory.palace_get` per id, because nothing on the socket answered a
    /// roster WITH counts — `palace_list` answers bare ids and the retired
    /// `GET /api/v1/palaces` reported peek-based placeholder zeros for any
    /// unresident palace (#4682). The fan-out also dropped a palace whose call
    /// failed, silently; `memory.palaces_list` carries a per-palace error
    /// instead, and [`project_palace_roster`] renders it.
    ///
    /// Why `counts: false` (#7125): this is a health probe on a 5-second
    /// timer, and counting is what opens every palace on disk — ~94 cold opens
    /// per tick on the estate that prompted the issue, each one left in the
    /// daemon's 64-slot LRU. A palace the daemon already has open still reports
    /// its real counts; one it does not comes back flagged `cached: false`, and
    /// [`project_palace_rows`] renders that as unknown rather than as empty.
    ///
    /// A whole-call failure still yields an empty list — the panel's other
    /// rows are worth showing, and the daemon's own health line already says
    /// it is unreachable.
    /// Test: `memory_collections_asks_for_a_roster_without_counts`; the
    /// projection is unit-tested via `project_palace_roster`.
    pub async fn memory_collections(&self) -> Vec<CollectionRow> {
        // #7125: a health poll must not open every palace on disk to count it.
        let Ok(listed) = self
            .memory_call("memory.palaces_list", json!({ "counts": false }))
            .await
        else {
            return Vec::new();
        };
        project_palace_roster(&listed)
    }

    /// Request a graceful shutdown of the daemon via its `admin/stop` endpoint.
    ///
    /// Why: the `[X]` key stops the focused daemon without the operator
    /// resolving a PID; both daemons expose a stop method on their socket.
    /// What: `search.admin.stop` for search (#9214), `memory.admin_stop` for
    /// memory (#6286). A refusal on either is an error.
    /// Test: `search_stop_sends_the_stop_method`,
    /// `search_stop_surfaces_a_daemon_refusal_as_err`.
    pub async fn stop(&self) -> anyhow::Result<()> {
        match self.daemon {
            Daemon::Search => {
                self.search_call(METHOD_ADMIN_STOP, json!({})).await?;
            }
            Daemon::Memory => {
                self.memory_call("memory.admin_stop", json!({})).await?;
            }
        }
        Ok(())
    }
}

/// Build a [`HealthClient`] for the given daemon at the given socket path.
///
/// Why: the background poller and the `[S]`/`[X]` key handlers all need a
/// client; centralising construction keeps the daemon→client mapping in one
/// place.
/// What: returns a [`HealthClient`] tagged with `daemon`.
/// Test: covered by `health_client_stores_base_url`.
pub fn client_for(daemon: Daemon, base_url: &str) -> HealthClient {
    HealthClient::new(base_url, daemon)
}

/// Project a `/api/v1/status` payload into `(palaces, vectors, drawers, kg)`.
///
/// Why: centralising the projection keeps [`HealthClient::memory_counts`]
/// testable without a live daemon and resilient to absent optional fields.
/// What: reads `palace_count`, `total_vectors`, `total_drawers`, and
/// `total_kg_triples`, defaulting any absent field to zero.
/// Test: `project_memory_counts`.
pub(crate) fn project_memory_counts(status: &serde_json::Value) -> (u64, u64, u64, u64) {
    let u = |key: &str| status.get(key).and_then(|v| v.as_u64()).unwrap_or(0);
    (
        u("palace_count"),
        u("total_vectors"),
        u("total_drawers"),
        u("total_kg_triples"),
    )
}

/// Project a `/logs/tail` response into `(lines, total)`.
///
/// Why: keeps the wire-shape parsing in one testable function so the client
/// stays terse and an older daemon's quirky payload cannot crash the TUI.
/// What: reads `lines` (array of strings, defaulting to `[]`) and `total`
/// (u64, defaulting to `lines.len()`).
/// Test: `project_log_tail_reads_fields`.
pub(crate) fn project_log_tail(body: &serde_json::Value) -> (Vec<String>, u64) {
    let lines: Vec<String> = body
        .get("lines")
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default();
    let total = body
        .get("total")
        .and_then(|v| v.as_u64())
        .unwrap_or(lines.len() as u64);
    (lines, total)
}

/// Project a `memory.palaces_list` answer into left-panel rows (#6286).
///
/// Why: the roster's rows come in two shapes — a palace the daemon read, and a
/// palace it could not. The second must be RENDERED rather than skipped: the
/// fan-out this replaced dropped it at the call site, so the panel could list
/// fewer palaces than the daemon has with nothing saying which or why.
/// What: a readable row goes through [`project_palace_rows`], keeping its
/// empty-palace filter. A row carrying `error` becomes a row with `ok: false`
/// and the daemon's reason as its note, exempt from that filter — a palace
/// whose counts could not be read must not be mistaken for one holding
/// nothing.
/// Test: `project_palace_roster_reads_counts`,
/// `project_palace_roster_renders_a_failed_row`.
pub(crate) fn project_palace_roster(answer: &serde_json::Value) -> Vec<CollectionRow> {
    let Some(rows) = answer.get("palaces").and_then(|v| v.as_array()) else {
        return Vec::new();
    };
    let mut out = Vec::with_capacity(rows.len());
    for row in rows {
        if let Some(palace) = row.get("palace").filter(|v| v.is_object()) {
            out.extend(project_palace_rows(&serde_json::Value::Array(vec![
                palace.clone(),
            ])));
            continue;
        }
        let Some(error) = row.get("error").and_then(|v| v.as_str()) else {
            continue;
        };
        let id = row
            .get("id")
            .and_then(|v| v.as_str())
            .unwrap_or("?")
            .to_string();
        out.push(CollectionRow {
            id,
            note: format!("counts unavailable: {error}"),
            ok: false,
            // #7125: its zeros are unknown for the same reason an unopened
            // palace's are — render `?v`, not the `--v` that reads as empty.
            counts_unknown: true,
            ..Default::default()
        });
    }
    out
}
/// Project a memory daemon `/api/v1/palaces` payload into palace rows.
///
/// Why: centralising the projection keeps the renderer terse and lets a unit
/// test assert the shape without a live daemon. The wire format is a JSON
/// array of `PalaceInfo` objects with per-palace `vector_count`,
/// `drawer_count`, and `kg_triple_count`. `/api/v1/status` exposes only
/// aggregate totals, so this is the only source of per-palace counts. Empty
/// palaces (no vectors AND no KG triples) are filtered out so the left pane
/// only lists palaces that actually hold memory — an empty palace is
/// indistinguishable from a placeholder and just adds visual noise.
/// What: reads the top-level array, projecting each entry's `name` (falling
/// back to `id`), `vector_count`, and `kg_triple_count` (any absent field
/// defaults to zero). Rows where both counts are zero are dropped. A
/// non-array payload yields an empty list.
///
/// The empty-palace filter reads a ZERO, and a zero only means empty when the
/// daemon actually counted (#4637). Since #7125 the poller asks for
/// `counts: false`, so a palace the daemon has not opened answers `cached:
/// false` with placeholder zeros — that row is flagged
/// [`CollectionRow::counts_unknown`] and exempted from the filter, or the panel
/// would go blank on a cold daemon and call every palace empty.
/// Test: `project_palace_rows_reads_palaces`,
/// `project_palace_rows_filters_empty`,
/// `project_palace_rows_keep_uncached_rows_as_unknown`.
pub(crate) fn project_palace_rows(list: &serde_json::Value) -> Vec<CollectionRow> {
    let Some(arr) = list.as_array() else {
        return Vec::new();
    };
    arr.iter()
        .filter_map(|p| {
            let id = p
                .get("name")
                .or_else(|| p.get("id"))
                .and_then(|v| v.as_str())
                .unwrap_or("?")
                .to_string();
            let count = p.get("vector_count").and_then(|v| v.as_u64()).unwrap_or(0);
            let kg_count = p
                .get("kg_triple_count")
                .and_then(|v| v.as_u64())
                .unwrap_or(0);
            let drawer_count = p.get("drawer_count").and_then(|v| v.as_u64()).unwrap_or(0);
            // #4811: prefer the truthful `room_count` (ADR-0027 T8); an older
            // daemon only sends `wing_count`, which held this same number.
            let room_count = p
                .get("room_count")
                .or_else(|| p.get("wing_count"))
                .and_then(|v| v.as_u64())
                .unwrap_or(0);
            let last_write_at = p
                .get("last_write_at")
                .and_then(|v| v.as_str())
                .map(str::to_string);
            let node_count = p.get("node_count").and_then(|v| v.as_u64()).unwrap_or(0);
            let edge_count = p.get("edge_count").and_then(|v| v.as_u64()).unwrap_or(0);
            let community_count = p
                .get("community_count")
                .and_then(|v| v.as_u64())
                .unwrap_or(0);
            let is_compacting = p
                .get("is_compacting")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            // #7125: `cached: false` means the daemon peeked instead of
            // opening, so these zeros are UNKNOWN (#4637), never empty.
            let counts_unknown = p.get("cached").and_then(|v| v.as_bool()) == Some(false);
            // Skip palaces with no vectors and no graph triples: they hold
            // nothing the operator can act on and clutter the left pane.
            if !counts_unknown && count == 0 && kg_count == 0 {
                return None;
            }
            Some(CollectionRow {
                id,
                count,
                kg_count,
                drawer_count,
                room_count,
                last_write_at,
                node_count,
                edge_count,
                community_count,
                is_compacting,
                counts_unknown,
                // Note left empty: the row shows vector + graph counts inline
                // (e.g. `12v 34g`), so a trailing badge would be redundant.
                note: String::new(),
                ok: true,
                ..Default::default()
            })
        })
        .collect()
}

/// Project a `/indexes/:id/graph/stats` payload's `edge_kinds` map into a
/// vec sorted by count descending.
///
/// Why: the INDEX tab renders one row per edge kind, ordered so the heaviest
/// relationship appears at the top; keeping the projection pure makes it
/// testable without a live daemon.
/// What: reads the `edge_kinds` object from `stats`, collects `(name, count)`
/// pairs, and sorts by count descending (ties broken by name ascending).
/// A missing object yields an empty vec.
/// Test: `project_edge_kinds_sorts_desc`.
pub(crate) fn project_edge_kinds(stats: &serde_json::Value) -> Vec<(String, u64)> {
    let Some(map) = stats.get("edge_kinds").and_then(|v| v.as_object()) else {
        return Vec::new();
    };
    let mut pairs: Vec<(String, u64)> = map
        .iter()
        .map(|(k, v)| (k.clone(), v.as_u64().unwrap_or(0)))
        .collect();
    pairs.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    pairs
}