tinytown 0.10.0

A simple, fast multi-agent orchestration system using Redis for message passing
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
/*
 * Copyright (c) 2024-Present, Jeremy Plichta
 * Licensed under the MIT License
 */

//! Migration support for town isolation.
//!
//! This module handles migrating old Redis key formats (without town namespacing)
//! to the new format with town name prefixes for isolation.
//!
//! Old format: `tt:agent:<uuid>`, `tt:inbox:<uuid>`, `tt:task:<uuid>`
//! New format: `tt:<town_name>:agent:<uuid>`, `tt:<town_name>:inbox:<uuid>`, etc.

use redis::AsyncCommands;
use redis::aio::ConnectionManager;
use tracing::{debug, info, warn};

use crate::error::{Error, Result};

/// Statistics from a migration operation.
#[derive(Debug, Default, Clone)]
pub struct MigrationStats {
    /// Number of agent keys migrated
    pub agents_migrated: usize,
    /// Number of inbox keys migrated  
    pub inboxes_migrated: usize,
    /// Number of urgent inbox keys migrated
    pub urgent_migrated: usize,
    /// Number of task keys migrated
    pub tasks_migrated: usize,
    /// Number of activity keys migrated
    pub activity_migrated: usize,
    /// Number of stop keys migrated
    pub stop_migrated: usize,
    /// Number of backlog items migrated
    pub backlog_migrated: usize,
    /// Keys that failed to migrate
    pub errors: Vec<String>,
}

impl MigrationStats {
    /// Total number of keys migrated successfully.
    pub fn total_migrated(&self) -> usize {
        self.agents_migrated
            + self.inboxes_migrated
            + self.urgent_migrated
            + self.tasks_migrated
            + self.activity_migrated
            + self.stop_migrated
            + self.backlog_migrated
    }

    /// Check if any migration occurred.
    pub fn has_changes(&self) -> bool {
        self.total_migrated() > 0
    }
}

/// Check if there are old-format keys that need migration.
///
/// Old format keys match patterns like:
/// - `tt:agent:<uuid>` (not `tt:<town>:agent:<uuid>`)
/// - `tt:inbox:<uuid>` (not `tt:<town>:inbox:<uuid>`)
pub async fn needs_migration(conn: &mut ConnectionManager) -> Result<bool> {
    let old_patterns = [
        "tt:agent:*",
        "tt:inbox:*",
        "tt:urgent:*",
        "tt:task:*",
        "tt:activity:*",
        "tt:stop:*",
        "tt:backlog",
        "tt:broadcast",
    ];

    for pattern in old_patterns {
        let keys: Vec<String> = redis::cmd("KEYS").arg(pattern).query_async(conn).await?;

        // Filter out keys that are already namespaced (have 4 parts)
        for key in keys {
            let parts: Vec<&str> = key.split(':').collect();
            // Old format: tt:type:uuid (3 parts) or tt:type (2 parts like tt:backlog, tt:broadcast)
            // New format: tt:town:type:uuid (4 parts) or tt:town:type (3 parts)
            if parts[0] == "tt" && (parts.len() == 2 || parts.len() == 3) {
                debug!("Found old-format key: {}", key);
                return Ok(true);
            }
        }
    }

    Ok(false)
}

/// Scan for old-format keys matching a pattern.
///
/// Old format keys have 2 or 3 colon-separated segments:
/// - 2 parts: `tt:backlog`, `tt:broadcast`
/// - 3 parts: `tt:agent:<uuid>`, `tt:inbox:<uuid>`, etc.
///
/// New format keys have 3 or 4 segments (with town name):
/// - 3 parts: `tt:<town>:backlog`
/// - 4 parts: `tt:<town>:agent:<uuid>`
async fn scan_old_keys(conn: &mut ConnectionManager, pattern: &str) -> Result<Vec<String>> {
    let mut cursor: u64 = 0;
    let mut all_keys = Vec::new();

    loop {
        let (next_cursor, keys): (u64, Vec<String>) = redis::cmd("SCAN")
            .arg(cursor)
            .arg("MATCH")
            .arg(pattern)
            .arg("COUNT")
            .arg(100)
            .query_async(conn)
            .await?;

        // Filter to only old-format keys (2 or 3 parts)
        for key in keys {
            let parts: Vec<&str> = key.split(':').collect();
            // Old format: tt:type (2 parts) or tt:type:uuid (3 parts)
            // New format: tt:town:type (3 parts) or tt:town:type:uuid (4 parts)
            if parts[0] == "tt" && (parts.len() == 2 || parts.len() == 3) {
                all_keys.push(key);
            }
        }

        cursor = next_cursor;
        if cursor == 0 {
            break;
        }
    }

    Ok(all_keys)
}

/// Migrate a single key to the new format.
///
/// Handles both 2-part and 3-part old-format keys:
/// - 2 parts: `tt:backlog` -> `tt:<town>:backlog`
/// - 3 parts: `tt:agent:<uuid>` -> `tt:<town>:agent:<uuid>`
async fn migrate_key(
    conn: &mut ConnectionManager,
    old_key: &str,
    town_name: &str,
) -> Result<String> {
    let parts: Vec<&str> = old_key.split(':').collect();
    if parts[0] != "tt" || (parts.len() != 2 && parts.len() != 3) {
        return Err(Error::Migration(format!(
            "Invalid old-format key: {}",
            old_key
        )));
    }

    let new_key = if parts.len() == 2 {
        // 2-part key like tt:backlog -> tt:<town>:backlog
        let key_type = parts[1];
        format!("tt:{}:{}", town_name, key_type)
    } else {
        // 3-part key like tt:agent:<uuid> -> tt:<town>:agent:<uuid>
        let key_type = parts[1];
        let id = parts[2];
        format!("tt:{}:{}:{}", town_name, key_type, id)
    };

    // Rename the key atomically
    let _: () = conn.rename(old_key, &new_key).await?;
    debug!("Migrated {} -> {}", old_key, new_key);

    Ok(new_key)
}

/// Migrate all old-format keys to the new town-namespaced format.
///
/// This function:
/// 1. Scans for old-format keys (tt:type:uuid)
/// 2. Renames them to new format (tt:town:type:uuid)
/// 3. Returns statistics about the migration
///
/// This is idempotent - running it multiple times is safe.
pub async fn migrate_to_town_isolation(
    conn: &mut ConnectionManager,
    town_name: &str,
) -> Result<MigrationStats> {
    let mut stats = MigrationStats::default();

    info!("Starting migration to town isolation for '{}'", town_name);

    // Migrate agent keys
    let agent_keys = scan_old_keys(conn, "tt:agent:*").await?;
    for key in agent_keys {
        match migrate_key(conn, &key, town_name).await {
            Ok(_) => stats.agents_migrated += 1,
            Err(e) => {
                warn!("Failed to migrate {}: {}", key, e);
                stats.errors.push(key);
            }
        }
    }

    // Migrate inbox keys
    let inbox_keys = scan_old_keys(conn, "tt:inbox:*").await?;
    for key in inbox_keys {
        match migrate_key(conn, &key, town_name).await {
            Ok(_) => stats.inboxes_migrated += 1,
            Err(e) => {
                warn!("Failed to migrate {}: {}", key, e);
                stats.errors.push(key);
            }
        }
    }

    // Migrate urgent inbox keys
    let urgent_keys = scan_old_keys(conn, "tt:urgent:*").await?;
    for key in urgent_keys {
        match migrate_key(conn, &key, town_name).await {
            Ok(_) => stats.urgent_migrated += 1,
            Err(e) => {
                warn!("Failed to migrate {}: {}", key, e);
                stats.errors.push(key);
            }
        }
    }

    // Migrate task keys
    let task_keys = scan_old_keys(conn, "tt:task:*").await?;
    for key in task_keys {
        match migrate_key(conn, &key, town_name).await {
            Ok(_) => stats.tasks_migrated += 1,
            Err(e) => {
                warn!("Failed to migrate {}: {}", key, e);
                stats.errors.push(key);
            }
        }
    }

    // Migrate activity keys
    let activity_keys = scan_old_keys(conn, "tt:activity:*").await?;
    for key in activity_keys {
        match migrate_key(conn, &key, town_name).await {
            Ok(_) => stats.activity_migrated += 1,
            Err(e) => {
                warn!("Failed to migrate {}: {}", key, e);
                stats.errors.push(key);
            }
        }
    }

    // Migrate stop keys
    let stop_keys = scan_old_keys(conn, "tt:stop:*").await?;
    for key in stop_keys {
        match migrate_key(conn, &key, town_name).await {
            Ok(_) => stats.stop_migrated += 1,
            Err(e) => {
                warn!("Failed to migrate {}: {}", key, e);
                stats.errors.push(key);
            }
        }
    }

    // Migrate backlog (single key)
    let backlog_exists: bool = conn.exists("tt:backlog").await?;
    if backlog_exists {
        let new_key = format!("tt:{}:backlog", town_name);
        let result: redis::RedisResult<()> = conn.rename("tt:backlog", &new_key).await;
        match result {
            Ok(_) => {
                debug!("Migrated tt:backlog -> {}", new_key);
                stats.backlog_migrated = 1;
            }
            Err(e) => {
                warn!("Failed to migrate tt:backlog: {}", e);
                stats.errors.push("tt:backlog".to_string());
            }
        }
    }

    info!(
        "Migration complete: {} keys migrated, {} errors",
        stats.total_migrated(),
        stats.errors.len()
    );

    Ok(stats)
}

// =============================================================================
// JSON String to Redis Hash Migration
// =============================================================================

/// Statistics from a JSON-to-Hash migration operation.
#[derive(Debug, Default, Clone)]
pub struct HashMigrationStats {
    /// Number of agent keys migrated from JSON to Hash
    pub agents_migrated: usize,
    /// Number of task keys migrated from JSON to Hash
    pub tasks_migrated: usize,
    /// Keys that were already Hash type (skipped)
    pub already_hash: usize,
    /// Keys that failed to migrate
    pub errors: Vec<String>,
}

impl HashMigrationStats {
    /// Total number of keys migrated successfully.
    pub fn total_migrated(&self) -> usize {
        self.agents_migrated + self.tasks_migrated
    }

    /// Check if any migration occurred.
    pub fn has_changes(&self) -> bool {
        self.total_migrated() > 0
    }
}

/// Check if there are JSON string keys that need migration to Hash.
///
/// Scans for agent and task keys that are stored as strings instead of hashes.
pub async fn needs_hash_migration(conn: &mut ConnectionManager, town_name: &str) -> Result<bool> {
    // Check agent keys
    let agent_pattern = format!("tt:{}:agent:*", town_name);
    let agent_keys: Vec<String> = redis::cmd("KEYS")
        .arg(&agent_pattern)
        .query_async(conn)
        .await?;

    for key in agent_keys {
        let key_type: String = redis::cmd("TYPE").arg(&key).query_async(conn).await?;
        if key_type == "string" {
            debug!("Found JSON string agent key: {}", key);
            return Ok(true);
        }
    }

    // Check task keys
    let task_pattern = format!("tt:{}:task:*", town_name);
    let task_keys: Vec<String> = redis::cmd("KEYS")
        .arg(&task_pattern)
        .query_async(conn)
        .await?;

    for key in task_keys {
        let key_type: String = redis::cmd("TYPE").arg(&key).query_async(conn).await?;
        if key_type == "string" {
            debug!("Found JSON string task key: {}", key);
            return Ok(true);
        }
    }

    Ok(false)
}

/// Migrate a single agent key from JSON string to Hash.
async fn migrate_agent_to_hash(conn: &mut ConnectionManager, key: &str) -> Result<()> {
    // Get the JSON string
    let json_str: String = conn.get(key).await?;

    // Parse the JSON into agent fields
    let agent: serde_json::Value = serde_json::from_str(&json_str)
        .map_err(|e| Error::Migration(format!("Failed to parse agent JSON: {}", e)))?;

    // Build hash fields from JSON
    let mut fields: Vec<(String, String)> = Vec::new();

    if let Some(id) = agent.get("id").and_then(|v| v.as_str()) {
        fields.push(("id".to_string(), id.to_string()));
    }
    if let Some(name) = agent.get("name").and_then(|v| v.as_str()) {
        fields.push(("name".to_string(), name.to_string()));
    }
    if let Some(agent_type) = agent.get("agent_type").and_then(|v| v.as_str()) {
        fields.push(("agent_type".to_string(), agent_type.to_string()));
    }
    if let Some(state) = agent.get("state").and_then(|v| v.as_str()) {
        fields.push(("state".to_string(), state.to_string()));
    }
    if let Some(cli) = agent.get("cli").and_then(|v| v.as_str()) {
        fields.push(("cli".to_string(), cli.to_string()));
    }
    if let Some(current_task) = agent.get("current_task").and_then(|v| v.as_str()) {
        fields.push(("current_task".to_string(), current_task.to_string()));
    }
    if let Some(created_at) = agent.get("created_at").and_then(|v| v.as_str()) {
        fields.push(("created_at".to_string(), created_at.to_string()));
    }
    if let Some(last_heartbeat) = agent.get("last_heartbeat").and_then(|v| v.as_str()) {
        fields.push(("last_heartbeat".to_string(), last_heartbeat.to_string()));
    }
    if let Some(tasks_completed) = agent.get("tasks_completed") {
        let val = if tasks_completed.is_u64() {
            tasks_completed.as_u64().unwrap().to_string()
        } else {
            tasks_completed.to_string()
        };
        fields.push(("tasks_completed".to_string(), val));
    }
    if let Some(rounds_completed) = agent.get("rounds_completed") {
        let val = if rounds_completed.is_u64() {
            rounds_completed.as_u64().unwrap().to_string()
        } else {
            rounds_completed.to_string()
        };
        fields.push(("rounds_completed".to_string(), val));
    }

    if fields.is_empty() {
        return Err(Error::Migration(format!(
            "No valid fields found in agent JSON for key: {}",
            key
        )));
    }

    // Delete old string key and set hash atomically via pipeline
    let mut pipe = redis::pipe();
    pipe.del(key);
    pipe.hset_multiple(key, &fields);
    let _: () = pipe.query_async(conn).await?;

    debug!("Migrated agent {} from JSON to Hash", key);
    Ok(())
}

/// Migrate a single task key from JSON string to Hash.
async fn migrate_task_to_hash(conn: &mut ConnectionManager, key: &str) -> Result<()> {
    // Get the JSON string
    let json_str: String = conn.get(key).await?;

    // Parse the JSON into task fields
    let task: serde_json::Value = serde_json::from_str(&json_str)
        .map_err(|e| Error::Migration(format!("Failed to parse task JSON: {}", e)))?;

    // Build hash fields from JSON
    let mut fields: Vec<(String, String)> = Vec::new();

    if let Some(id) = task.get("id").and_then(|v| v.as_str()) {
        fields.push(("id".to_string(), id.to_string()));
    }
    if let Some(description) = task.get("description").and_then(|v| v.as_str()) {
        fields.push(("description".to_string(), description.to_string()));
    }
    if let Some(state) = task.get("state").and_then(|v| v.as_str()) {
        fields.push(("state".to_string(), state.to_string()));
    }
    if let Some(assigned_to) = task.get("assigned_to").and_then(|v| v.as_str()) {
        fields.push(("assigned_to".to_string(), assigned_to.to_string()));
    }
    if let Some(created_at) = task.get("created_at").and_then(|v| v.as_str()) {
        fields.push(("created_at".to_string(), created_at.to_string()));
    }
    if let Some(updated_at) = task.get("updated_at").and_then(|v| v.as_str()) {
        fields.push(("updated_at".to_string(), updated_at.to_string()));
    }
    if let Some(started_at) = task.get("started_at").and_then(|v| v.as_str()) {
        fields.push(("started_at".to_string(), started_at.to_string()));
    }
    if let Some(completed_at) = task.get("completed_at").and_then(|v| v.as_str()) {
        fields.push(("completed_at".to_string(), completed_at.to_string()));
    }
    if let Some(result) = task.get("result").and_then(|v| v.as_str()) {
        fields.push(("result".to_string(), result.to_string()));
    }
    if let Some(parent_id) = task.get("parent_id").and_then(|v| v.as_str()) {
        fields.push(("parent_id".to_string(), parent_id.to_string()));
    }
    // Tags remain as JSON array string
    if let Some(tags) = task.get("tags")
        && tags.is_array()
    {
        fields.push((
            "tags".to_string(),
            serde_json::to_string(tags).unwrap_or_else(|_| "[]".to_string()),
        ));
    }

    if fields.is_empty() {
        return Err(Error::Migration(format!(
            "No valid fields found in task JSON for key: {}",
            key
        )));
    }

    // Delete old string key and set hash atomically via pipeline
    let mut pipe = redis::pipe();
    pipe.del(key);
    pipe.hset_multiple(key, &fields);
    let _: () = pipe.query_async(conn).await?;

    debug!("Migrated task {} from JSON to Hash", key);
    Ok(())
}

/// Migrate all JSON string keys to Redis Hashes for a town.
///
/// This function:
/// 1. Scans for agent and task keys with string type
/// 2. Parses the JSON and converts to Hash fields
/// 3. Atomically replaces the string key with a hash key
///
/// This is idempotent - running it multiple times is safe (already-migrated keys are skipped).
pub async fn migrate_json_to_hash(
    conn: &mut ConnectionManager,
    town_name: &str,
) -> Result<HashMigrationStats> {
    let mut stats = HashMigrationStats::default();

    info!("Starting JSON-to-Hash migration for town '{}'", town_name);

    // Migrate agent keys
    let agent_pattern = format!("tt:{}:agent:*", town_name);
    let agent_keys: Vec<String> = redis::cmd("KEYS")
        .arg(&agent_pattern)
        .query_async(conn)
        .await?;

    for key in agent_keys {
        let key_type: String = redis::cmd("TYPE").arg(&key).query_async(conn).await?;
        if key_type == "hash" {
            stats.already_hash += 1;
            continue;
        }
        if key_type != "string" {
            warn!("Unexpected key type '{}' for {}, skipping", key_type, key);
            continue;
        }

        match migrate_agent_to_hash(conn, &key).await {
            Ok(_) => stats.agents_migrated += 1,
            Err(e) => {
                warn!("Failed to migrate agent {}: {}", key, e);
                stats.errors.push(key);
            }
        }
    }

    // Migrate task keys
    let task_pattern = format!("tt:{}:task:*", town_name);
    let task_keys: Vec<String> = redis::cmd("KEYS")
        .arg(&task_pattern)
        .query_async(conn)
        .await?;

    for key in task_keys {
        let key_type: String = redis::cmd("TYPE").arg(&key).query_async(conn).await?;
        if key_type == "hash" {
            stats.already_hash += 1;
            continue;
        }
        if key_type != "string" {
            warn!("Unexpected key type '{}' for {}, skipping", key_type, key);
            continue;
        }

        match migrate_task_to_hash(conn, &key).await {
            Ok(_) => stats.tasks_migrated += 1,
            Err(e) => {
                warn!("Failed to migrate task {}: {}", key, e);
                stats.errors.push(key);
            }
        }
    }

    info!(
        "JSON-to-Hash migration complete: {} agents, {} tasks migrated, {} already hash, {} errors",
        stats.agents_migrated,
        stats.tasks_migrated,
        stats.already_hash,
        stats.errors.len()
    );

    Ok(stats)
}

/// Preview JSON-to-Hash migration without making changes.
///
/// Returns the list of keys that would be migrated.
pub async fn preview_hash_migration(
    conn: &mut ConnectionManager,
    town_name: &str,
) -> Result<Vec<String>> {
    let mut preview = Vec::new();

    // Check agent keys
    let agent_pattern = format!("tt:{}:agent:*", town_name);
    let agent_keys: Vec<String> = redis::cmd("KEYS")
        .arg(&agent_pattern)
        .query_async(conn)
        .await?;

    for key in agent_keys {
        let key_type: String = redis::cmd("TYPE").arg(&key).query_async(conn).await?;
        if key_type == "string" {
            preview.push(key);
        }
    }

    // Check task keys
    let task_pattern = format!("tt:{}:task:*", town_name);
    let task_keys: Vec<String> = redis::cmd("KEYS")
        .arg(&task_pattern)
        .query_async(conn)
        .await?;

    for key in task_keys {
        let key_type: String = redis::cmd("TYPE").arg(&key).query_async(conn).await?;
        if key_type == "string" {
            preview.push(key);
        }
    }

    Ok(preview)
}

// =============================================================================
// Town Isolation Migration (existing code)
// =============================================================================

/// Preview migration without making changes.
///
/// Returns the list of keys that would be migrated.
pub async fn preview_migration(conn: &mut ConnectionManager) -> Result<Vec<(String, String)>> {
    let mut preview = Vec::new();

    // Check all key types
    let patterns = [
        "tt:agent:*",
        "tt:inbox:*",
        "tt:urgent:*",
        "tt:task:*",
        "tt:activity:*",
        "tt:stop:*",
    ];

    for pattern in patterns {
        let keys = scan_old_keys(conn, pattern).await?;
        for key in keys {
            let parts: Vec<&str> = key.split(':').collect();
            if parts.len() == 2 {
                // 2-part key like tt:backlog
                let key_type = parts[1];
                preview.push((key.clone(), format!("tt:<town>:{}", key_type)));
            } else if parts.len() == 3 {
                // 3-part key like tt:agent:<uuid>
                let key_type = parts[1];
                let id = parts[2];
                preview.push((key.clone(), format!("tt:<town>:{}:{}", key_type, id)));
            }
        }
    }

    // Check backlog (also check for tt:broadcast)
    let backlog_exists: bool = conn.exists("tt:backlog").await?;
    if backlog_exists {
        preview.push(("tt:backlog".to_string(), "tt:<town>:backlog".to_string()));
    }
    let broadcast_exists: bool = conn.exists("tt:broadcast").await?;
    if broadcast_exists {
        preview.push((
            "tt:broadcast".to_string(),
            "tt:<town>:broadcast".to_string(),
        ));
    }

    Ok(preview)
}