bosshogg 2026.5.3

BossHogg — the agent-first PostHog CLI. Feature flags, HogQL queries, insights, dashboards, cohorts, persons, events, experiments, and more — from the terminal or from a Claude Code / Cursor / other coding-agent loop. Ships with a Claude Code skill (~200 idle tokens) that teaches models how to use it.
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
// src/commands/dashboard.rs
use clap::{Args, Subcommand};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::path::PathBuf;

use crate::commands::context::CommandContext;
use crate::commands::util::{env_id_required, read_json_file, read_text_file};
use crate::error::{BosshoggError, Result};
use crate::output;

// ── Typed struct ────────────────────────────────────────────────────────────

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Dashboard {
    pub id: i64,
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub pinned: Option<bool>,
    #[serde(default)]
    pub created_at: Option<String>,
    #[serde(default)]
    pub created_by: Option<Value>,
    #[serde(default)]
    pub is_shared: Option<bool>,
    #[serde(default)]
    pub deleted: bool,
    #[serde(default)]
    pub creation_mode: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub tiles: Option<Value>,
    #[serde(default)]
    pub filters: Value,
    #[serde(default)]
    pub variables: Option<Value>,
    #[serde(default)]
    pub restriction_level: Option<i32>,
    #[serde(default)]
    pub effective_privilege_level: Option<i32>,
}

// ── Clap tree ────────────────────────────────────────────────────────────────

#[derive(Args, Debug)]
pub struct DashboardArgs {
    #[command(subcommand)]
    pub command: DashboardCommand,
}

#[derive(Subcommand, Debug)]
pub enum DashboardCommand {
    /// List dashboards with optional filters.
    List {
        #[arg(long)]
        tag: Option<String>,
        #[arg(long)]
        search: Option<String>,
        /// Cap results at N rows (default: fetch all pages).
        #[arg(long)]
        limit: Option<usize>,
    },
    /// Get a single dashboard by numeric id.
    Get { id: i64 },
    /// Trigger insight refresh for all tiles on a dashboard.
    Refresh { id: i64 },
    /// Create a new dashboard.
    Create {
        #[arg(long)]
        name: String,
        /// Path to a text file containing the description.
        #[arg(long)]
        description_file: Option<PathBuf>,
        /// Path to a JSON file containing the filters object.
        #[arg(long)]
        filters_file: Option<PathBuf>,
    },
    /// Update dashboard fields (name, description, tags, etc.).
    Update {
        id: i64,
        #[arg(long)]
        name: Option<String>,
        /// Path to a text file containing the new description.
        #[arg(long)]
        description_file: Option<PathBuf>,
        /// Add a tag (can be repeated).
        #[arg(long)]
        tag: Vec<String>,
    },
    /// Soft-delete a dashboard (PATCH deleted=true).
    Delete { id: i64 },
    /// Manage tiles on a dashboard.
    #[command(subcommand)]
    Tiles(TilesCommand),
    /// View sharing settings for a dashboard (read-only in M3).
    Share { id: i64 },
}

#[derive(Subcommand, Debug)]
pub enum TilesCommand {
    /// Add an insight as a tile to a dashboard.
    Add {
        dashboard_id: i64,
        /// Insight id to add as a tile.
        #[arg(long)]
        insight: i64,
    },
    /// Remove a tile from a dashboard.
    Remove {
        dashboard_id: i64,
        /// Tile id to remove.
        #[arg(long)]
        tile: i64,
    },
}

// ── Dispatch ─────────────────────────────────────────────────────────────────

pub async fn execute(args: DashboardArgs, cx: &CommandContext) -> Result<()> {
    match args.command {
        DashboardCommand::List { tag, search, limit } => {
            list_dashboards(cx, tag, search, limit).await
        }
        DashboardCommand::Get { id } => get_dashboard(cx, id).await,
        DashboardCommand::Refresh { id } => refresh_dashboard(cx, id).await,
        DashboardCommand::Create {
            name,
            description_file,
            filters_file,
        } => create_dashboard(cx, name, description_file, filters_file).await,
        DashboardCommand::Update {
            id,
            name,
            description_file,
            tag,
        } => update_dashboard(cx, id, name, description_file, tag).await,
        DashboardCommand::Delete { id } => delete_dashboard(cx, id).await,
        DashboardCommand::Tiles(tiles_cmd) => dispatch_tiles(cx, tiles_cmd).await,
        DashboardCommand::Share { id } => share_dashboard(cx, id).await,
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

// ── list ──────────────────────────────────────────────────────────────────────

#[derive(Serialize)]
struct ListOutput {
    count: usize,
    results: Vec<Dashboard>,
}

async fn list_dashboards(
    cx: &CommandContext,
    tag: Option<String>,
    search: Option<String>,
    limit: Option<usize>,
) -> Result<()> {
    let client = &cx.client;
    let env_id = env_id_required(client)?;

    let mut qs: Vec<(String, String)> = Vec::new();
    if let Some(t) = tag {
        qs.push(("tags".into(), t));
    }
    if let Some(s) = search {
        qs.push(("search".into(), s));
    }

    let query = if qs.is_empty() {
        String::new()
    } else {
        let joined = qs
            .iter()
            .map(|(k, v)| format!("{}={}", k, urlencoding::encode(v)))
            .collect::<Vec<_>>()
            .join("&");
        format!("?{joined}")
    };

    let path = format!("/api/environments/{env_id}/dashboards/{query}");
    let results: Vec<Dashboard> = client.get_paginated(&path, limit).await?;

    if cx.json_mode {
        output::print_json(&ListOutput {
            count: results.len(),
            results,
        });
    } else {
        let headers = &["ID", "NAME", "PINNED", "TAGS", "CREATED_AT"];
        let rows: Vec<Vec<String>> = results
            .iter()
            .map(|d| {
                vec![
                    d.id.to_string(),
                    d.name.clone(),
                    d.pinned
                        .map(|p| p.to_string())
                        .unwrap_or_else(|| "-".into()),
                    d.tags.join(","),
                    d.created_at.clone().unwrap_or_default(),
                ]
            })
            .collect();
        output::table::print(headers, &rows);
    }
    Ok(())
}

// ── get ───────────────────────────────────────────────────────────────────────

async fn get_dashboard(cx: &CommandContext, id: i64) -> Result<()> {
    let client = &cx.client;
    let env_id = env_id_required(client)?;
    let dashboard: Dashboard = client
        .get(&format!("/api/environments/{env_id}/dashboards/{id}/"))
        .await?;
    print_dashboard(&dashboard, cx.json_mode);
    Ok(())
}

// ── refresh ───────────────────────────────────────────────────────────────────

async fn refresh_dashboard(cx: &CommandContext, id: i64) -> Result<()> {
    let client = &cx.client;
    let env_id = env_id_required(client)?;
    let v: Value = client
        .get(&format!(
            "/api/environments/{env_id}/dashboards/{id}/run_insights/"
        ))
        .await?;
    if cx.json_mode {
        output::print_json(&v);
    } else {
        println!("Triggered insight refresh for dashboard {id}");
    }
    Ok(())
}

// ── create ────────────────────────────────────────────────────────────────────

async fn create_dashboard(
    cx: &CommandContext,
    name: String,
    description_file: Option<PathBuf>,
    filters_file: Option<PathBuf>,
) -> Result<()> {
    let client = &cx.client;
    let env_id = env_id_required(client)?;

    let mut body = json!({ "name": name });

    if let Some(p) = description_file.as_deref() {
        let desc = read_text_file(p).await?;
        body["description"] = Value::String(desc.trim().to_string());
    }
    if let Some(p) = filters_file.as_deref() {
        body["filters"] = read_json_file(p).await?;
    }

    let created: Dashboard = client
        .post(&format!("/api/environments/{env_id}/dashboards/"), &body)
        .await?;

    if cx.json_mode {
        #[derive(Serialize)]
        struct Out {
            ok: bool,
            action: &'static str,
            id: i64,
            name: String,
        }
        output::print_json(&Out {
            ok: true,
            action: "create",
            id: created.id,
            name: created.name,
        });
    } else {
        println!("Created dashboard '{}' (id {})", created.name, created.id);
    }
    Ok(())
}

// ── update ────────────────────────────────────────────────────────────────────

async fn update_dashboard(
    cx: &CommandContext,
    id: i64,
    name: Option<String>,
    description_file: Option<PathBuf>,
    tag: Vec<String>,
) -> Result<()> {
    let client = &cx.client;
    let env_id = env_id_required(client)?;

    let mut body = serde_json::Map::new();
    if let Some(n) = name {
        body.insert("name".into(), Value::String(n));
    }
    if let Some(p) = description_file.as_deref() {
        let desc = read_text_file(p).await?;
        body.insert("description".into(), Value::String(desc.trim().to_string()));
    }
    if !tag.is_empty() {
        let tag_vals: Vec<Value> = tag.iter().map(|t| Value::String(t.clone())).collect();
        body.insert("tags".into(), Value::Array(tag_vals));
    }

    if body.is_empty() {
        return Err(BosshoggError::BadRequest(
            "no update flags provided (try --name, --description-file, --tag)".into(),
        ));
    }

    cx.confirm(&format!("update dashboard `{id}`; continue?"))?;

    let updated: Dashboard = client
        .patch(
            &format!("/api/environments/{env_id}/dashboards/{id}/"),
            &Value::Object(body),
        )
        .await?;

    if cx.json_mode {
        output::print_json(&updated);
    } else {
        println!("Updated dashboard '{}' (id {})", updated.name, updated.id);
    }
    Ok(())
}

// ── delete ────────────────────────────────────────────────────────────────────

async fn delete_dashboard(cx: &CommandContext, id: i64) -> Result<()> {
    let client = &cx.client;
    let env_id = env_id_required(client)?;

    cx.confirm(&format!("soft-delete dashboard `{id}`; continue?"))?;

    client
        .delete(&format!("/api/environments/{env_id}/dashboards/{id}/"))
        .await?;

    if cx.json_mode {
        #[derive(Serialize)]
        struct Out {
            ok: bool,
            action: &'static str,
            id: i64,
        }
        output::print_json(&Out {
            ok: true,
            action: "delete",
            id,
        });
    } else {
        println!("Deleted dashboard {id}");
    }
    Ok(())
}

// ── tiles dispatch ────────────────────────────────────────────────────────────

async fn dispatch_tiles(cx: &CommandContext, cmd: TilesCommand) -> Result<()> {
    match cmd {
        TilesCommand::Add {
            dashboard_id,
            insight,
        } => {
            cx.confirm(&format!(
                "add insight {insight} to dashboard {dashboard_id}; continue?"
            ))?;
            tiles_add(cx, dashboard_id, insight).await
        }
        TilesCommand::Remove { dashboard_id, tile } => {
            cx.confirm(&format!(
                "remove tile {tile} from dashboard {dashboard_id}; continue?"
            ))?;
            tiles_remove(cx, dashboard_id, tile).await
        }
    }
}

// ── tiles add ─────────────────────────────────────────────────────────────────

async fn tiles_add(cx: &CommandContext, dashboard_id: i64, insight: i64) -> Result<()> {
    let client = &cx.client;
    let env_id = env_id_required(client)?;
    // Modern PostHog attaches insights to dashboards by PATCHing the
    // INSIGHT with an updated `dashboards` array. The legacy
    // `PATCH /dashboards/{id}/ {"tiles": [...]}` path is silently dropped
    // on current accounts — the response returns 200 but `tiles` stays empty.
    let insight_path = format!("/api/environments/{env_id}/insights/{insight}/");

    let current: Value = client.get(&insight_path).await?;
    let mut dashboards: Vec<i64> = current
        .get("dashboards")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(|v| v.as_i64()).collect())
        .unwrap_or_default();

    if !dashboards.contains(&dashboard_id) {
        dashboards.push(dashboard_id);
    }

    let v: Value = client
        .patch(&insight_path, &json!({ "dashboards": dashboards }))
        .await?;

    if cx.json_mode {
        output::print_json(&v);
    } else {
        println!("Added insight {insight} to dashboard {dashboard_id}");
    }
    Ok(())
}

// ── tiles remove ──────────────────────────────────────────────────────────────

async fn tiles_remove(cx: &CommandContext, dashboard_id: i64, tile: i64) -> Result<()> {
    let client = &cx.client;
    let env_id = env_id_required(client)?;

    // Symmetric with tiles_add: modern PostHog detaches an insight from a
    // dashboard by PATCHing the INSIGHT with `dashboards` minus this
    // dashboard_id. The legacy `PATCH /dashboards/{id}/ {"tiles": [...]}`
    // path is silently dropped on current accounts.
    //
    // Since the input is a tile_id (not insight_id), we first GET the
    // dashboard to find the tile's insight.
    let dash_path = format!("/api/environments/{env_id}/dashboards/{dashboard_id}/");
    let dashboard: Dashboard = client.get(&dash_path).await?;
    let insight_id = dashboard
        .tiles
        .as_ref()
        .and_then(|t| t.as_array())
        .and_then(|arr| {
            arr.iter()
                .find(|t| t.get("id").and_then(Value::as_i64) == Some(tile))
                .and_then(|t| t.get("insight"))
                .and_then(|i| i.get("id"))
                .and_then(Value::as_i64)
        })
        .ok_or_else(|| {
            BosshoggError::NotFound(format!("tile {tile} on dashboard {dashboard_id}"))
        })?;

    let insight_path = format!("/api/environments/{env_id}/insights/{insight_id}/");
    let current: Value = client.get(&insight_path).await?;
    let dashboards: Vec<i64> = current
        .get("dashboards")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_i64())
                .filter(|id| *id != dashboard_id)
                .collect()
        })
        .unwrap_or_default();

    let v: Value = client
        .patch(&insight_path, &json!({ "dashboards": dashboards }))
        .await?;

    if cx.json_mode {
        output::print_json(&v);
    } else {
        println!("Removed tile {tile} from dashboard {dashboard_id}");
    }
    Ok(())
}

// ── share ─────────────────────────────────────────────────────────────────────

async fn share_dashboard(cx: &CommandContext, id: i64) -> Result<()> {
    let client = &cx.client;
    let env_id = env_id_required(client)?;
    let v: Value = client
        .get(&format!(
            "/api/environments/{env_id}/dashboards/{id}/sharing/"
        ))
        .await?;
    if cx.json_mode {
        output::print_json(&v);
    } else {
        let enabled = v.get("enabled").and_then(Value::as_bool).unwrap_or(false);
        let token = v
            .get("access_token")
            .and_then(Value::as_str)
            .unwrap_or("<none>");
        println!("Sharing enabled: {enabled}");
        println!("Access token:    {token}");
    }
    Ok(())
}

// ── print helper ──────────────────────────────────────────────────────────────

fn print_dashboard(dashboard: &Dashboard, json_mode: bool) {
    if json_mode {
        output::print_json(dashboard);
    } else {
        println!("ID:           {}", dashboard.id);
        println!("Name:         {}", dashboard.name);
        if let Some(d) = dashboard.description.as_deref() {
            println!("Description:  {d}");
        }
        println!("Pinned:       {}", dashboard.pinned.unwrap_or(false));
        if !dashboard.tags.is_empty() {
            println!("Tags:         {}", dashboard.tags.join(", "));
        }
        if let Some(ca) = dashboard.created_at.as_deref() {
            println!("Created:      {ca}");
        }
        println!("Deleted:      {}", dashboard.deleted);
    }
}

// ── unit tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dashboard_roundtrip_minimal() {
        let raw = r#"{
            "id": 1,
            "name": "My Dashboard",
            "deleted": false,
            "tags": [],
            "filters": {}
        }"#;
        let d: Dashboard = serde_json::from_str(raw).unwrap();
        assert_eq!(d.id, 1);
        assert_eq!(d.name, "My Dashboard");
        assert!(!d.deleted);
        assert!(d.tags.is_empty());
    }

    #[test]
    fn dashboard_roundtrip_full() {
        let raw = r#"{
            "id": 42,
            "name": "Analytics",
            "description": "Main analytics dashboard",
            "pinned": true,
            "created_at": "2026-01-01T00:00:00Z",
            "created_by": {"id": 1, "email": "test@example.com"},
            "is_shared": false,
            "deleted": false,
            "creation_mode": "default",
            "tags": ["prod", "analytics"],
            "tiles": [{"id": 1}],
            "filters": {"date_from": "-7d"},
            "variables": null,
            "restriction_level": 21,
            "effective_privilege_level": 21
        }"#;
        let d: Dashboard = serde_json::from_str(raw).unwrap();
        assert_eq!(d.id, 42);
        assert_eq!(d.name, "Analytics");
        assert_eq!(d.tags, vec!["prod", "analytics"]);
        assert_eq!(d.restriction_level, Some(21));
        assert!(d.pinned.unwrap_or(false));
    }
}