tracevault-cli 0.21.0

CLI tool for Visdom Trace - AI code tracing and attribution
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
//! `tracevault repo` — workspace/detached-mode repo binding commands.

use std::path::Path;

use crate::api_client::{resolve_credentials, ApiClient};
use crate::resolution::{
    binding_from_config, effective_binding, org_slug_for, resolve_path_to_binding, BindingSource,
    ResolveInputs,
};
use crate::session_state::{self, RepoBinding, SessionState};

/// Sub-actions for `tracevault repo` (workspace/detached mode).
#[derive(clap::Subcommand)]
pub enum RepoCmd {
    /// Bind tracing to the repo at <path> for the current session and print
    /// its policies.
    Switch {
        /// Path to a checkout of a registered repo.
        path: String,
        /// Session to target; defaults to $TRACEVAULT_SESSION_ID.
        #[arg(long)]
        session_id: Option<String>,
    },
    /// Show the repo the current session is bound to.
    Status {
        /// Session to target; defaults to $TRACEVAULT_SESSION_ID.
        #[arg(long)]
        session_id: Option<String>,
        /// One-off: resolve this checkout path instead of the session binding.
        #[arg(long)]
        path: Option<String>,
    },
    /// Clear the current session's binding.
    Reset {
        /// Session to target; defaults to $TRACEVAULT_SESSION_ID.
        #[arg(long)]
        session_id: Option<String>,
    },
}

/// Resolve the current session id: the explicit flag wins, else
/// `$TRACEVAULT_SESSION_ID` (set by the SessionStart hook of `init --global`).
pub fn resolve_session_id(explicit: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
    if let Some(s) = explicit {
        return Ok(s.to_string());
    }
    std::env::var("TRACEVAULT_SESSION_ID")
        .ok()
        .filter(|s| !s.is_empty())
        .ok_or_else(|| {
            "no session id available: pass --session-id or set TRACEVAULT_SESSION_ID \
             (installed by `tracevault init --global`)"
                .into()
        })
}

pub async fn run(
    cmd: RepoCmd,
    project_root: &Path,
    cwd: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    match cmd {
        RepoCmd::Status { session_id, path } => {
            status(session_id.as_deref(), path.as_deref(), project_root, cwd).await
        }
        RepoCmd::Switch { path, session_id } => {
            switch(&path, session_id.as_deref(), project_root).await
        }
        RepoCmd::Reset { session_id } => reset(session_id.as_deref()),
    }
}

/// Resolve a path to a binding for `repo switch`, turning "unregistered" into
/// a clear error (switch should fail loudly, unlike the best-effort `--path`
/// status override).
async fn resolve_switch_binding(
    path: &Path,
    org_slug: &str,
    client: &ApiClient,
) -> Result<RepoBinding, Box<dyn std::error::Error>> {
    resolve_path_to_binding(path, org_slug, client)
        .await?
        .ok_or_else(|| {
            format!(
                "repo at {} is not registered with TraceVault (org {org_slug}); nothing to bind",
                path.display()
            )
            .into()
        })
}

/// Apply a switch to session state (session-level active binding). Pure.
fn apply_switch(state: &mut SessionState, binding: RepoBinding) {
    state.active = Some(binding);
}

/// Clear the session's workspace binding (session-level reset). Pure.
fn apply_reset(state: &mut SessionState) {
    *state = SessionState::default();
}

fn reset(session_id: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
    let id = resolve_session_id(session_id)?;
    let mut state = session_state::load(&id);
    apply_reset(&mut state);
    session_state::save(&id, &state)?;
    // NOTE: subagent worktree-scoped reset-to-parent is handled in sub-plan C.
    println!("cleared workspace repo binding for session {id}");
    Ok(())
}

async fn switch(
    path: &str,
    session_id: Option<&str>,
    project_root: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    let id = resolve_session_id(session_id)?;
    let org_slug = org_slug_for(project_root)
        .ok_or("no org configured: set TRACEVAULT_ORG_SLUG, log in, or run inside a bound repo")?;

    let (server_url, token) = resolve_credentials(project_root);
    let server_url = server_url.ok_or("not logged in / no server_url; run `tracevault login`")?;
    let client = ApiClient::new(&server_url, token.as_deref());

    let binding = resolve_switch_binding(Path::new(path), &org_slug, &client).await?;

    // Validate the repo id BEFORE persisting anything: a malformed repo_id
    // must not leave a persisted session binding behind.
    let repo_uuid = binding.repo_id.parse::<uuid::Uuid>().map_err(|e| {
        format!(
            "server returned an invalid repo id {:?}: {e}",
            binding.repo_id
        )
    })?;

    // NOTE: subagent worktree-override writes are handled in sub-plan C.
    let mut state = session_state::load(&id);
    apply_switch(&mut state, binding.clone());
    session_state::save(&id, &state)?;

    println!(
        "bound session {id} to repo {} (org {})",
        binding.repo_id, binding.org_slug
    );

    // The binding was already saved above — that's the primary effect of
    // `switch`. A failure to fetch policies afterward shouldn't make the
    // whole command report as an error.
    match client
        .get_agent_instructions(&binding.org_slug, &repo_uuid)
        .await
    {
        Ok(policies) => println!("{}", policies.content),
        Err(e) => eprintln!("warning: bound, but could not fetch policies: {e}"),
    }
    Ok(())
}

/// Resolve a `--path <path>` override into a live `RepoBinding`, if possible.
/// Best-effort: prints a clear message and returns `None` on any failure
/// (missing org slug / credentials, or a server error) rather than failing
/// the whole `status` inspector.
async fn resolve_repo_flag(
    repo_flag_path: Option<&str>,
    project_root: &Path,
) -> Option<RepoBinding> {
    let path = repo_flag_path?;

    let Some(org_slug) = org_slug_for(project_root) else {
        eprintln!(
            "--path {path}: no org slug configured (set TRACEVAULT_ORG_SLUG, log in, or bind \
             the repo); showing binding without the --path override"
        );
        return None;
    };

    let (server_url, token) = resolve_credentials(project_root);
    let Some(server_url) = server_url else {
        eprintln!(
            "--path {path}: no server URL configured (run `tracevault login`); showing binding \
             without the --path override"
        );
        return None;
    };

    let client = ApiClient::new(&server_url, token.as_deref());
    match resolve_path_to_binding(Path::new(path), &org_slug, &client).await {
        Ok(Some(binding)) => Some(binding),
        Ok(None) => {
            eprintln!(
                "--path {path}: no registered repo found for this path's git remote; showing \
                 binding without the --path override"
            );
            None
        }
        Err(e) => {
            eprintln!(
                "--path {path}: failed to resolve ({e}); showing binding without the --path \
                 override"
            );
            None
        }
    }
}

/// Pure formatter for `repo status`'s output: which repo is bound, and via
/// which precedence tier. Kept separate from I/O so it can be unit-tested.
fn format_status(binding: Option<(&RepoBinding, BindingSource)>) -> String {
    match binding {
        Some((b, source)) => format!(
            "bound to repo {} (org {}) via {source}",
            b.repo_id, b.org_slug
        ),
        None => {
            "not bound to any repo (workspace mode; run `tracevault repo switch <path>`)".into()
        }
    }
}

async fn status(
    session_id: Option<&str>,
    repo_flag_path: Option<&str>,
    project_root: &Path,
    cwd: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    // Session state is best-effort: if a session id resolves, load it; else
    // warn and fall back to an empty SessionState rather than silently
    // reporting "not bound" without the user knowing why.
    let session = match resolve_session_id(session_id) {
        Ok(id) => session_state::load(&id),
        Err(_) => {
            eprintln!(
                "warning: no session id (pass --session-id or set TRACEVAULT_SESSION_ID); \
                 showing binding without session context"
            );
            SessionState::default()
        }
    };
    let worktree = crate::paths::worktree_toplevel(cwd);
    let bound = crate::config::TracevaultConfig::load(project_root)
        .as_ref()
        .and_then(binding_from_config);

    // A --path override on status resolves live (needs org_slug + server).
    let repo_flag = resolve_repo_flag(repo_flag_path, project_root).await;

    let effective = effective_binding(ResolveInputs {
        repo_flag,
        session: &session,
        worktree_path: Some(&worktree),
        bound,
    });
    println!(
        "{}",
        format_status(effective.as_ref().map(|(b, s)| (b, *s)))
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{BufRead, BufReader, Write};
    use std::net::TcpListener;
    use std::thread;

    #[test]
    fn resolve_session_id_prefers_explicit() {
        assert_eq!(resolve_session_id(Some("sess-x")).unwrap(), "sess-x");
    }

    #[test]
    fn resolve_session_id_errors_when_absent() {
        // No explicit id and (in this test process) no env var set → error.
        // Guard against a leaked env var from another test by checking the
        // message only when the var is genuinely absent.
        if std::env::var("TRACEVAULT_SESSION_ID").is_err() {
            assert!(resolve_session_id(None).is_err());
        }
    }

    fn binding(id: &str) -> RepoBinding {
        RepoBinding {
            org_slug: "org".into(),
            repo_id: id.into(),
            git_url: None,
            updated_at: "t".into(),
        }
    }

    #[test]
    fn apply_switch_sets_session_active() {
        let mut state = SessionState::default();
        apply_switch(&mut state, binding("new-repo"));
        assert_eq!(state.active.unwrap().repo_id, "new-repo");
    }

    #[test]
    fn apply_reset_clears_active_and_subagents() {
        let mut state = SessionState {
            active: Some(binding("r")),
            subagents: std::collections::HashMap::from([("/wt/a".to_string(), binding("r2"))]),
            ..Default::default()
        };
        apply_reset(&mut state);
        assert_eq!(state, SessionState::default());
    }

    #[test]
    fn apply_switch_overwrites_existing_active() {
        let mut state = SessionState {
            active: Some(binding("old-repo")),
            subagents: Default::default(),
            ..Default::default()
        };
        apply_switch(&mut state, binding("new-repo"));
        assert_eq!(state.active.unwrap().repo_id, "new-repo");
    }

    #[test]
    fn format_status_none() {
        assert_eq!(
            format_status(None),
            "not bound to any repo (workspace mode; run `tracevault repo switch <path>`)"
        );
    }

    #[test]
    fn format_status_repo_flag() {
        let b = binding("r1");
        assert_eq!(
            format_status(Some((&b, BindingSource::RepoFlag))),
            "bound to repo r1 (org org) via --path override"
        );
    }

    #[test]
    fn format_status_subagent() {
        let b = binding("r2");
        assert_eq!(
            format_status(Some((&b, BindingSource::Subagent))),
            "bound to repo r2 (org org) via subagent worktree override"
        );
    }

    #[test]
    fn format_status_session_active() {
        let b = binding("r3");
        assert_eq!(
            format_status(Some((&b, BindingSource::SessionActive))),
            "bound to repo r3 (org org) via session (repo switch)"
        );
    }

    #[test]
    fn format_status_bound() {
        let b = binding("r4");
        assert_eq!(
            format_status(Some((&b, BindingSource::Bound))),
            "bound to repo r4 (org org) via bound .tracevault/config.toml"
        );
    }

    fn add_origin_remote(dir: &std::path::Path, url: &str) {
        let ok = std::process::Command::new("git")
            .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
            .status()
            .expect("git remote add failed")
            .success();
        assert!(ok, "git remote add must succeed");
    }

    /// Spawn a one-shot raw-HTTP server that returns `response` to the first
    /// request it accepts (mirrors `tests/resolve_repo_test.rs`).
    fn spawn_once(response: &'static str) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        thread::spawn(move || {
            if let Ok((stream, _)) = listener.accept() {
                let mut reader = BufReader::new(stream);
                let mut request_line = String::new();
                let _ = reader.read_line(&mut request_line);
                let mut stream = reader.into_inner();
                let _ = stream.write_all(response.as_bytes());
                let _ = stream.flush();
            }
        });
        format!("http://{addr}")
    }

    #[tokio::test]
    async fn resolve_switch_binding_ok_for_registered_repo() {
        let tmp = tempfile::tempdir().unwrap();
        crate::test_helpers::init_git_repo(tmp.path());
        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");

        let repo_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
        let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
        let resp = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            body.len(),
            body
        );
        let base = spawn_once(Box::leak(resp.into_boxed_str()));
        let client = ApiClient::new(&base, Some("tok"));

        let got = resolve_switch_binding(tmp.path(), "org", &client)
            .await
            .expect("expected Ok binding");
        assert_eq!(got.repo_id, repo_id);
        assert_eq!(got.org_slug, "org");
    }

    #[tokio::test]
    async fn resolve_switch_binding_errors_for_unregistered_repo() {
        let tmp = tempfile::tempdir().unwrap();
        crate::test_helpers::init_git_repo(tmp.path());
        add_origin_remote(tmp.path(), "git@github.com:org/unregistered.git");

        let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
        let base = spawn_once(resp);
        let client = ApiClient::new(&base, Some("tok"));

        let err = resolve_switch_binding(tmp.path(), "org", &client)
            .await
            .expect_err("expected Err for unregistered repo");
        assert!(
            err.to_string().contains("not registered"),
            "unexpected error message: {err}"
        );
    }
}