agent-bridge 0.6.2

Local-first CLI to read, compare, and hand off context across Codex, Claude, Gemini, and Cursor sessions.
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
mod adapters;
mod agents;
mod context_pack;
mod report;
mod utils;

use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use serde_json::json;

#[derive(Parser)]
#[command(name = "bridge")]
#[command(about = "Agent Bridge CLI", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Read a session from an agent
    Read {
        /// Agent to read from
        #[arg(long, value_enum)]
        agent: AgentType,

        /// Session ID or UUID (substring match supported)
        #[arg(long)]
        id: Option<String>,

        /// Working directory to scope search (defaults to current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// Explicit path to chats directory (Gemini only)
        #[arg(long)]
        chats_dir: Option<String>,

        /// Number of last assistant messages to return
        #[arg(long, default_value = "1")]
        last: usize,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Compare sources and return an analyze-mode report
    Compare {
        /// Source spec: <agent> or <agent>:<session-substring>
        #[arg(long = "source", required = true)]
        sources: Vec<String>,

        /// Working directory to scope current-session lookups
        #[arg(long)]
        cwd: Option<String>,

        /// Apply whitespace normalization before comparing
        #[arg(long)]
        normalize: bool,

        /// Emit structured JSON instead of markdown
        #[arg(long)]
        json: bool,
    },

    /// Build a report from a handoff packet JSON file
    Report {
        /// Path to handoff JSON file
        #[arg(long)]
        handoff: String,

        /// Working directory fallback for source lookups
        #[arg(long)]
        cwd: Option<String>,

        /// Emit structured JSON instead of markdown
        #[arg(long)]
        json: bool,
    },

    /// List sessions for an agent
    List {
        /// Agent to list sessions for
        #[arg(long, value_enum)]
        agent: AgentType,

        /// Working directory to scope search
        #[arg(long)]
        cwd: Option<String>,

        /// Maximum number of sessions to return
        #[arg(long, default_value = "10")]
        limit: usize,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Search sessions for a keyword
    Search {
        /// Keyword to search for
        #[arg(index = 1)]
        query: String,

        /// Agent to search
        #[arg(long, value_enum)]
        agent: AgentType,

        /// Working directory to scope search
        #[arg(long)]
        cwd: Option<String>,

        /// Maximum number of sessions to return
        #[arg(long, default_value = "10")]
        limit: usize,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Roast agents based on their session content (easter egg)
    #[command(name = "trash-talk")]
    TrashTalk {
        /// Working directory to scope search
        #[arg(long)]
        cwd: Option<String>,
    },

    /// Build/sync/install context-pack automation
    #[command(name = "context-pack")]
    ContextPack {
        #[command(subcommand)]
        command: ContextPackCommand,
    },
}

#[derive(Subcommand)]
enum ContextPackCommand {
    /// Build or refresh context pack files
    Build {
        /// Build reason (metadata only)
        #[arg(long)]
        reason: Option<String>,

        /// Base SHA for changed-file computation
        #[arg(long)]
        base: Option<String>,

        /// Head SHA for changed-file computation
        #[arg(long)]
        head: Option<String>,

        /// Override pack directory (default: .agent-context or BRIDGE_CONTEXT_PACK_DIR)
        #[arg(long)]
        pack_dir: Option<String>,

        /// Explicit changed file (repeatable)
        #[arg(long = "changed-file")]
        changed_files: Vec<String>,

        /// Force creating a new snapshot even when unchanged
        #[arg(long)]
        force_snapshot: bool,
    },

    /// Sync context pack during a main-branch push event
    #[command(name = "sync-main")]
    SyncMain {
        #[arg(long)]
        local_ref: String,

        #[arg(long)]
        local_sha: String,

        #[arg(long)]
        remote_ref: String,

        #[arg(long)]
        remote_sha: String,
    },

    /// Install/refresh pre-push hook wiring
    #[command(name = "install-hooks")]
    InstallHooks {
        /// Target directory inside repo (default: current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// Preview changes without writing
        #[arg(long)]
        dry_run: bool,
    },

    /// Restore context pack from snapshot
    Rollback {
        /// Snapshot ID (default: latest)
        #[arg(long)]
        snapshot: Option<String>,

        /// Override pack directory (default: .agent-context or BRIDGE_CONTEXT_PACK_DIR)
        #[arg(long)]
        pack_dir: Option<String>,
    },

    /// Warn when context-relevant files changed without pack update
    #[command(name = "check-freshness")]
    CheckFreshness {
        /// Base ref for diff (default: origin/main)
        #[arg(long)]
        base: Option<String>,

        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,
    },
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Debug)]
enum AgentType {
    Codex,
    Gemini,
    Claude,
    Cursor,
}

impl AgentType {
    fn as_str(&self) -> &'static str {
        match self {
            AgentType::Codex => "codex",
            AgentType::Gemini => "gemini",
            AgentType::Claude => "claude",
            AgentType::Cursor => "cursor",
        }
    }
}

fn main() {
    let cli = match Cli::try_parse() {
        Ok(c) => c,
        Err(e) => {
            // If --json was passed on the command line, emit structured error
            let raw_args: Vec<String> = std::env::args().collect();
            let has_json = raw_args.iter().any(|a| a == "--json");
            if has_json {
                let msg = e.to_string();
                // Detect unsupported agent from clap's error message
                let code = if msg.contains("invalid value") && msg.contains("--agent") {
                    agents::BridgeErrorCode::UnsupportedAgent
                } else {
                    agents::classify_error(&msg)
                };
                let error_json = serde_json::json!({
                    "error_code": code.as_str(),
                    "message": msg.to_string().lines().next().unwrap_or(""),
                });
                println!("{}", serde_json::to_string_pretty(&error_json).unwrap_or_default());
                std::process::exit(1);
            } else {
                e.exit();
            }
        }
    };
    let json_mode = is_json_mode(&cli.command);

    if let Err(err) = run(cli) {
        if json_mode {
            let msg = format!("{:#}", err);
            let code = agents::classify_error(&msg);
            let error_json = serde_json::json!({
                "error_code": code.as_str(),
                "message": msg,
            });
            println!("{}", serde_json::to_string_pretty(&error_json).unwrap_or_default());
        } else {
            eprintln!("{:#}", err);
        }
        std::process::exit(1);
    }
}

fn is_json_mode(command: &Commands) -> bool {
    match command {
        Commands::Read { json, .. } => *json,
        Commands::Compare { json, .. } => *json,
        Commands::Report { json, .. } => *json,
        Commands::List { json, .. } => *json,
        Commands::Search { json, .. } => *json,
        Commands::TrashTalk { .. } => false,
        Commands::ContextPack { .. } => false,
    }
}

fn run(cli: Cli) -> Result<()> {
    match cli.command {
        Commands::Read {
            agent,
            id,
            cwd,
            chats_dir,
            last,
            json,
        } => {
            let effective_cwd = effective_cwd(cwd);
            let last_n = last.max(1);
            let adapter = adapters::get_adapter(agent.as_str())
                .with_context(|| format!("Unsupported agent: {}", agent.as_str()))?;
            let session = adapter.read_session(
                id.as_deref(),
                &effective_cwd,
                chats_dir.as_deref(),
                last_n,
            )?;

            if json {
                let report = json!({
                    "agent": session.agent,
                    "source": session.source,
                    "content": session.content,
                    "warnings": session.warnings,
                    "session_id": session.session_id,
                    "cwd": session.cwd,
                    "timestamp": session.timestamp,
                    "message_count": session.message_count,
                    "messages_returned": session.messages_returned,
                });
                println!("{}", serde_json::to_string_pretty(&report)?);
            } else {
                for warning in &session.warnings {
                    eprintln!("{}", utils::sanitize_for_terminal(warning));
                }
                println!("SOURCE: {} Session ({})", format_agent_name(session.agent), utils::sanitize_for_terminal(&session.source));
                println!("---");
                println!("{}", utils::sanitize_for_terminal(&session.content));
            }
        }
        Commands::Compare { sources, cwd, normalize, json } => {
            let effective_cwd = effective_cwd(cwd);
            let source_specs = sources
                .iter()
                .map(|raw| report::parse_source_arg(raw))
                .collect::<Result<Vec<report::SourceSpec>>>()?;

            let request = report::ReportRequest {
                mode: "analyze".to_string(),
                task: "Compare agent outputs".to_string(),
                success_criteria: vec![
                    "Identify agreements and contradictions".to_string(),
                    "Highlight unavailable sources".to_string(),
                ],
                sources: source_specs,
                constraints: Vec::new(),
                normalize,
            };

            let result = report::build_report(&request, &effective_cwd);
            emit_report_output(&result, json)?;
        }
        Commands::Report { handoff, cwd, json } => {
            let effective_cwd = effective_cwd(cwd);
            let request = report::load_handoff(&handoff)
                .with_context(|| format!("Failed to load handoff packet from {}", handoff))?;
            let result = report::build_report(&request, &effective_cwd);
            emit_report_output(&result, json)?;
        }
        Commands::List { agent, cwd, limit, json } => {
            let normalized_cwd = cwd.map(|value| {
                utils::normalize_path(&value)
                    .map(|path| path.to_string_lossy().to_string())
                    .unwrap_or(value)
            });
            let adapter = adapters::get_adapter(agent.as_str())
                .with_context(|| format!("Unsupported agent: {}", agent.as_str()))?;
            let entries = adapter.list_sessions(normalized_cwd.as_deref(), limit)?;

            if json {
                println!("{}", serde_json::to_string_pretty(&entries)?);
            } else {
                for entry in &entries {
                    println!("{}", serde_json::to_string(entry).unwrap_or_default());
                }
            }
        }
        Commands::Search { query, agent, cwd, limit, json } => {
            let normalized_cwd = cwd.map(|value| {
                utils::normalize_path(&value)
                    .map(|path| path.to_string_lossy().to_string())
                    .unwrap_or(value)
            });
            let adapter = adapters::get_adapter(agent.as_str())
                .with_context(|| format!("Unsupported agent: {}", agent.as_str()))?;
            let entries = adapter.search_sessions(&query, normalized_cwd.as_deref(), limit)?;

            if json {
                println!("{}", serde_json::to_string_pretty(&entries)?);
            } else {
                for entry in &entries {
                    println!("{}", serde_json::to_string(entry).unwrap_or_default());
                }
            }
        }
        Commands::TrashTalk { cwd } => {
            let effective = effective_cwd(cwd);
            agents::trash_talk(&effective);
        }
        Commands::ContextPack { command } => {
            match command {
                ContextPackCommand::Build {
                    reason,
                    base,
                    head,
                    pack_dir,
                    changed_files,
                    force_snapshot,
                } => {
                    context_pack::build(context_pack::BuildOptions {
                        reason,
                        base,
                        head,
                        pack_dir,
                        changed_files,
                        force_snapshot,
                    })?;
                }
                ContextPackCommand::SyncMain {
                    local_ref,
                    local_sha,
                    remote_ref,
                    remote_sha,
                } => {
                    context_pack::sync_main(
                        &local_ref,
                        &local_sha,
                        &remote_ref,
                        &remote_sha,
                    )?;
                }
                ContextPackCommand::InstallHooks { cwd, dry_run } => {
                    let target_cwd = effective_cwd(cwd);
                    context_pack::install_hooks(&target_cwd, dry_run)?;
                }
                ContextPackCommand::Rollback { snapshot, pack_dir } => {
                    context_pack::rollback(snapshot.as_deref(), pack_dir.as_deref())?;
                }
                ContextPackCommand::CheckFreshness { base, cwd } => {
                    let target_cwd = effective_cwd(cwd);
                    context_pack::check_freshness(
                        base.as_deref().unwrap_or("origin/main"),
                        &target_cwd,
                    )?;
                }
            }
        }
    }

    Ok(())
}

fn emit_report_output(report_value: &serde_json::Value, json_output: bool) -> Result<()> {
    if json_output {
        println!("{}", serde_json::to_string_pretty(report_value)?);
    } else {
        println!("{}", utils::sanitize_for_terminal(&report::report_to_markdown(report_value)));
    }
    Ok(())
}

fn effective_cwd(cwd: Option<String>) -> String {
    cwd.unwrap_or_else(|| {
        std::env::current_dir()
            .map(|path| path.to_string_lossy().to_string())
            .unwrap_or_else(|_| ".".to_string())
    })
}

fn format_agent_name(agent: &str) -> &'static str {
    match agent {
        "codex" => "Codex",
        "gemini" => "Gemini",
        "claude" => "Claude",
        "cursor" => "Cursor",
        _ => "Unknown",
    }
}