Skip to main content

tracevault_cli/commands/
project.rs

1//! `tracevault project` — workspace/detached-mode project-attribution
2//! commands. Mirrors `commands::repo`'s `switch`/`status` structure, but binds
3//! the project-attribution axis (design §7/Task 7) rather than the repo axis.
4
5use crate::program::{CLI, ENV};
6use std::collections::HashSet;
7use std::path::Path;
8
9use crate::api_client::{resolve_client, ApiClient, ProjectListItem, ResolveProjectOutcome};
10use crate::resolution::{
11    capture_project_binding, capture_project_id, git_remote_url, CaptureProjectInputs,
12    ProjectSource,
13};
14use crate::session_state::{self, ProjectBinding, SessionState};
15
16/// Sub-actions for `project` (project-attribution axis).
17#[derive(clap::Subcommand)]
18pub enum ProjectCmd {
19    /// Bind project attribution to a registered project for the current
20    /// session (or, with `--user`, the session-independent user default).
21    Switch {
22        /// Exact, case-sensitive name of a registered project.
23        name: String,
24        /// Write a session-independent user-level default instead of a
25        /// session binding. Implied when no session id is available. Also
26        /// skips the current-codebase containment check (a user default
27        /// isn't tied to any one checkout).
28        #[arg(long)]
29        user: bool,
30        /// Session to target; defaults to the session id the session-start hook exported (in Amp: $AMP_CURRENT_THREAD_ID).
31        #[arg(long)]
32        session_id: Option<String>,
33        /// Who owns attribution. `explicit` stamps the named project
34        /// without a repo/project membership check and marks the session
35        /// forced — so it also binds a project this checkout is not a member
36        /// of, which an ordinary switch refuses; it says so when it does.
37        /// `switch` itself checks nothing: the requirement — a Control Plane
38        /// identity (never a `tvk_` API key) and Operator on the project —
39        /// is enforced at INGEST, which refuses the force with a 403 and
40        /// queues the event rather than re-attributing it. A persisted force
41        /// lapses after ~one working day.
42        #[arg(long, value_parser = ["derived", "explicit"], default_value = "derived")]
43        project_attribution: String,
44    },
45    /// Show the project the current session is attributed to.
46    Status {
47        /// Session to target; defaults to the session id the session-start hook exported (in Amp: $AMP_CURRENT_THREAD_ID).
48        #[arg(long)]
49        session_id: Option<String>,
50        /// What-if, display only: resolve this project name and feed it in at
51        /// the top of the precedence chain, above the session and user-default
52        /// bindings, to preview what `status` would report. It binds nothing;
53        /// use `project switch` to change what events are attributed to.
54        #[arg(long)]
55        project: Option<String>,
56    },
57}
58
59pub async fn run(
60    cmd: ProjectCmd,
61    project_root: &Path,
62    cwd: &Path,
63) -> Result<(), Box<dyn std::error::Error>> {
64    match cmd {
65        ProjectCmd::Switch {
66            name,
67            user,
68            session_id,
69            project_attribution,
70        } => {
71            switch(
72                &name,
73                user,
74                session_id.as_deref(),
75                &project_attribution,
76                project_root,
77                cwd,
78            )
79            .await
80        }
81        ProjectCmd::Status {
82            session_id,
83            project,
84        } => status(session_id.as_deref(), project.as_deref(), project_root, cwd).await,
85    }
86}
87
88/// Exact, case-sensitive name → item. Miss lists the available names.
89fn resolve_project_name<'a>(
90    items: &'a [ProjectListItem],
91    name: &str,
92) -> Result<&'a ProjectListItem, String> {
93    items.iter().find(|p| p.name == name).ok_or_else(|| {
94        let mut names: Vec<&str> = items.iter().map(|p| p.name.as_str()).collect();
95        names.sort_unstable();
96        format!(
97            "project '{name}' not found. Available: {}",
98            names.join(", ")
99        )
100    })
101}
102
103/// What a `switch` does about a project that does not contain the current
104/// checkout.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106enum CodebaseCheck {
107    /// Not performed at all: the user-level default is session-independent
108    /// and not tied to any checkout, so there is nothing to check it against.
109    Skip,
110    /// An ordinary session switch. Binding a project this checkout is not a
111    /// member of is almost always a typo, so it is an error.
112    Enforce,
113    /// `--project-attribution explicit`. Binding a project this checkout is
114    /// not a member of is the POINT of the flag — a repo deliberately shared
115    /// by two projects, or a launcher attributing work to a project the
116    /// checkout was never registered under. The requirement is a trust claim
117    /// the SERVER enforces at ingest (Operator on the project, and a Control
118    /// Plane identity), not something the client can or should adjudicate at
119    /// switch time; refusing here contradicts both the flag's help text and
120    /// the design. So: report the fact, never block on it.
121    Report,
122}
123
124/// Which [`CodebaseCheck`] a `switch` runs, from where it is persisting and
125/// whether the caller claimed attribution. The one place the rule is written
126/// down, so `switch` and its test cannot disagree about it.
127fn codebase_check_for(dest: &SwitchDest, explicit: bool) -> CodebaseCheck {
128    match (dest, explicit) {
129        // Session-independent: not tied to any checkout, nothing to check.
130        (SwitchDest::UserDefault, _) => CodebaseCheck::Skip,
131        (SwitchDest::Session(_), true) => CodebaseCheck::Report,
132        (SwitchDest::Session(_), false) => CodebaseCheck::Enforce,
133    }
134}
135
136/// Resolve `name` to a registered project (via `list_projects`) and, unless
137/// `check` is [`CodebaseCheck::Skip`], test whether that project contains the
138/// current codebase (resolved from `cwd`'s git origin remote, mirroring
139/// `resolve_path_to_binding`). Kept separate from `switch` so the
140/// client-dependent flow is unit-testable with a mock `ApiClient`, mirroring
141/// `commands::repo::resolve_switch_binding`.
142///
143/// Returns the binding plus, for [`CodebaseCheck::Report`] when the check
144/// would have failed, the informational line the caller prints. A failing
145/// check under [`CodebaseCheck::Enforce`] is still an `Err`.
146async fn resolve_switch_project(
147    name: &str,
148    client: &ApiClient,
149    check: CodebaseCheck,
150    cwd: &Path,
151) -> Result<(ProjectBinding, Option<String>), Box<dyn std::error::Error>> {
152    let items = client.list_projects().await?;
153    let matched = resolve_project_name(&items, name)
154        .map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
155    let project_id = matched.id;
156    let project_name = matched.name.clone();
157    let mut note = None;
158
159    if check != CodebaseCheck::Skip {
160        if let Some(git_url) = git_remote_url(cwd) {
161            if let Some(remote) = client.resolve_remote(&git_url).await? {
162                let codebase_repo_ids: HashSet<uuid::Uuid> = client
163                    .get_remote_repos(remote.remote_id)
164                    .await?
165                    .into_iter()
166                    .map(|r| r.id)
167                    .collect();
168                let project_repo_ids: HashSet<uuid::Uuid> = client
169                    .get_project(project_id)
170                    .await?
171                    .repos
172                    .into_iter()
173                    .map(|r| r.id)
174                    .collect();
175                if codebase_repo_ids.is_disjoint(&project_repo_ids) {
176                    match check {
177                        CodebaseCheck::Enforce => {
178                            return Err(format!(
179                                "project '{name}' does not contain the current codebase"
180                            )
181                            .into())
182                        }
183                        // Deliberate, but the user should still learn the
184                        // fact — they are just not blocked by it.
185                        CodebaseCheck::Report => note = Some(forced_non_member_note(name)),
186                        CodebaseCheck::Skip => unreachable!("guarded above"),
187                    }
188                }
189            }
190            // Codebase not registered with the server → nothing to check
191            // against; allow the switch (mirrors resolve_path_to_binding's
192            // Ok(None) for an untracked remote).
193        }
194        // No git origin remote at all (workspace mode, no checkout) → nothing
195        // to check against; allow the switch.
196    }
197
198    Ok((
199        ProjectBinding {
200            project_id: project_id.to_string(),
201            project_name,
202            updated_at: chrono::Utc::now().to_rfc3339(),
203            forced_until: None,
204        },
205        note,
206    ))
207}
208
209/// The line a forced switch prints when the project does not contain this
210/// checkout. Not a warning: with `--project-attribution explicit` this is the
211/// intended case, and the message says so — while still naming the fact, and
212/// where the requirement is actually enforced, so a user who reached it by
213/// typo is not left thinking the switch did what they meant.
214fn forced_non_member_note(name: &str) -> String {
215    format!(
216        "note: project '{name}' does not contain the current codebase — binding it anyway \
217         because --project-attribution explicit says this caller owns attribution. The \
218         server enforces that claim at ingest (Operator on the project, and a Control Plane \
219         identity — never a `tvk_` API key) and refuses it with a 403 otherwise."
220    )
221}
222
223/// Where a `project switch` should persist its binding: a specific session,
224/// or the session-independent user-level default. Mirrors
225/// `commands::repo::SwitchDest`/`switch_destination`.
226#[derive(Debug)]
227enum SwitchDest {
228    Session(String),
229    UserDefault,
230}
231
232fn switch_destination(user: bool, session_id: Option<String>) -> SwitchDest {
233    if user {
234        return SwitchDest::UserDefault;
235    }
236    match session_id {
237        Some(id) => SwitchDest::Session(id),
238        None => SwitchDest::UserDefault,
239    }
240}
241
242/// Stamp or clear the persisted force on a binding about to be saved.
243///
244/// Clearing on a plain switch is deliberate: without it, a user who forced
245/// once and later switched normally would keep forcing until the clock ran
246/// out, which is exactly the forgotten-force failure the lifetime exists to
247/// bound.
248fn apply_force(mut binding: ProjectBinding, explicit: bool) -> ProjectBinding {
249    binding.forced_until = explicit.then(|| {
250        (chrono::Utc::now()
251            + chrono::Duration::hours(crate::user_project_default::DEFAULT_FORCE_LIFETIME_HOURS))
252        .to_rfc3339()
253    });
254    binding
255}
256
257/// The state of the PERSISTED force stored on a binding — a fact about what
258/// is on disk, never a verdict about what this process will send.
259///
260/// That distinction is the whole point of the wording. The verdict is
261/// [`attribution_report`]'s first line, which is the only thing that can
262/// answer "derived or explicit?", because it is the only one that sees
263/// `TRACEVAULT_PROJECT_ATTRIBUTION` as well as this timestamp. An earlier
264/// version of this function rendered "attribution: derived (a force lapsed
265/// …; membership is checked again)", which read as a second, competing
266/// answer — and in a shell with `TRACEVAULT_PROJECT_ATTRIBUTION=explicit`
267/// and a lapsed persisted force it directly contradicted the true one while
268/// every hook in that shell sent `explicit`. Stating the fact instead makes
269/// the contradiction unrepresentable, whatever the environment says.
270///
271/// Only ever called when `forced_until.is_some()` (see
272/// [`attribution_report`]), so there is no "no force at all" arm: that case
273/// prints no line.
274///
275/// This only WORDS a verdict; it does not reach one.
276/// [`crate::session_state::force_status`] is the single parse-and-compare,
277/// shared with `commands::stream::attribution_mode`, which is the function
278/// that actually decides the header — so the line and the header cannot
279/// disagree about whether a stored force is live, lapsed or unreadable. An
280/// unparseable timestamp (hand-edited or corrupted state file) therefore
281/// fails SAFE here too, and says so.
282fn format_force_line(forced_until: &str) -> String {
283    match crate::session_state::force_status(forced_until) {
284        crate::session_state::ForceStatus::Live(until) => {
285            format!("persisted force: active until {}", until.to_rfc3339())
286        }
287        crate::session_state::ForceStatus::Lapsed(until) => {
288            format!("persisted force: lapsed {}", until.to_rfc3339())
289        }
290        crate::session_state::ForceStatus::Unreadable => format!(
291            "persisted force: unreadable timestamp ('{forced_until}'), treated as not in force"
292        ),
293    }
294}
295
296/// The attribution lines both `project status` and `project switch` print
297/// for the binding they just reported or persisted.
298///
299/// Exactly one line answers "derived or explicit?": the FIRST, the effective
300/// mode, which is the only one that sees both `TRACEVAULT_PROJECT_ATTRIBUTION`
301/// and `b`'s own `forced_until` — i.e. everything
302/// `commands::stream::attribution_mode` sees when it fills the header.
303/// [`format_force_line`] follows only when `b` carries a persisted force, and
304/// states a FACT about that stored force rather than a second verdict, so the
305/// two can never disagree.
306///
307/// Two bugs are closed by that split, both reached the same way — a second
308/// line that answered a question it had no business answering:
309///
310/// * printing the force line unconditionally, so a shell with
311///   `TRACEVAULT_PROJECT_ATTRIBUTION=explicit` and NO persisted force got
312///   "attribution mode: explicit …" followed by "attribution: derived
313///   (Visdom checks repo/project membership)" (finding 3);
314/// * guarding it on `forced_until.is_some()`, which a LAPSED force still
315///   satisfies, so the same shell with an EXPIRED persisted force got
316///   "attribution mode: explicit …" followed by "attribution: derived (a
317///   force lapsed …; membership is checked again)" (Copilot on PR #54).
318///
319/// In both cases every hook in that shell was in fact sending `explicit`.
320/// The `is_some()` guard is right and stays — a binding that was never
321/// forced has nothing to report — but the guard was never what made the
322/// output honest; the wording is.
323fn attribution_report(b: &ProjectBinding) -> Vec<String> {
324    let mode = crate::commands::stream::attribution_mode(Some(b));
325    // The gloss `format_force_line` used to carry is folded in here rather
326    // than dropped: it is the part that tells a reader what the mode MEANS,
327    // and it applies to every mode, not only to a persisted force.
328    let gloss = match mode {
329        crate::api_client::AttributionMode::Explicit => {
330            "this caller owns attribution; membership is not checked"
331        }
332        crate::api_client::AttributionMode::Derived => "Visdom checks repo/project membership",
333    };
334    let mut lines = vec![format!("attribution mode: {mode} ({gloss})")];
335    if let Some(forced_until) = b.forced_until.as_deref() {
336        lines.push(format_force_line(forced_until));
337    }
338    lines
339}
340
341/// Everything `switch` prints once the binding is persisted: what was bound
342/// where, then `codebase_note` (see [`forced_non_member_note`]) when a forced
343/// switch bound a project this checkout is not a member of, then
344/// [`attribution_report`]. Pulled out as a pure function so the wording —
345/// including the ABSENCE of a contradictory "attribution: derived" line — is
346/// assertable without capturing stdout.
347///
348/// The note sits between the two because it explains why the force on the
349/// line below it is load-bearing rather than decorative.
350fn switch_report(
351    dest: &SwitchDest,
352    b: &ProjectBinding,
353    codebase_note: Option<&str>,
354) -> Vec<String> {
355    let mut lines = match dest {
356        SwitchDest::Session(id) => {
357            vec![format!("bound session {id} to project {}", b.project_name)]
358        }
359        SwitchDest::UserDefault => vec![format!(
360            "set user-level default project {}; applies to new sessions without their own binding (the current session, if any, is unchanged — omit --user to bind this session)",
361            b.project_name
362        )],
363    };
364    lines.extend(codebase_note.map(str::to_string));
365    lines.extend(attribution_report(b));
366    lines
367}
368
369async fn switch(
370    name: &str,
371    user: bool,
372    session_id: Option<&str>,
373    project_attribution: &str,
374    project_root: &Path,
375    cwd: &Path,
376) -> Result<(), Box<dyn std::error::Error>> {
377    let client = resolve_client(project_root)?;
378    let session = crate::commands::repo::resolve_session_id(session_id).ok();
379    let dest = switch_destination(user, session);
380    let explicit = project_attribution == "explicit";
381    let check = codebase_check_for(&dest, explicit);
382    let (binding, codebase_note) = resolve_switch_project(name, &client, check, cwd).await?;
383    let binding = apply_force(binding, explicit);
384
385    match &dest {
386        SwitchDest::Session(id) => {
387            let mut state = session_state::load(id);
388            state.active_project = Some(binding.clone());
389            session_state::save(id, &state)?;
390        }
391        SwitchDest::UserDefault => {
392            crate::user_project_default::save(&binding)?;
393        }
394    }
395    for line in switch_report(&dest, &binding, codebase_note.as_deref()) {
396        println!("{line}");
397    }
398    Ok(())
399}
400
401/// The project `project status` treats as effective: exactly the capture-time
402/// chain ingest uses ([`capture_project_binding`]: `--project` flag →
403/// subagent worktree override → `TRACEVAULT_PROJECT` → session
404/// `active_project` → workspace `.visdom/tracing.toml` `project_id` → user
405/// default).
406/// Pure — `status` supplies `user_default` from `user_project_default::load()`
407/// and `env_project` from `commands::stream::env_project_binding()`, the same
408/// file and the same reader `commands::stream::capture_project` uses, so the
409/// two cannot drift (pinned by
410/// `project_status_effective_project_matches_capture_project`).
411///
412/// A binding whose stored id is not a UUID is dropped exactly as ingest drops
413/// it ([`capture_project_id`] → `None`), so the effective project is `None`
414/// and the second element carries the warning naming the tier it came from.
415fn status_effective(
416    project_flag: Option<ProjectBinding>,
417    env_project: Option<ProjectBinding>,
418    session: &SessionState,
419    worktree: Option<&str>,
420    config_project: Option<ProjectBinding>,
421    user_default: Option<ProjectBinding>,
422) -> (Option<(ProjectBinding, ProjectSource)>, Option<String>) {
423    match capture_project_binding(&CaptureProjectInputs {
424        project_flag,
425        env_project,
426        session,
427        worktree_path: worktree,
428        config_project,
429        user_default,
430    }) {
431        Some((binding, source)) if capture_project_id(&binding).is_none() => {
432            let warning = invalid_capture_id_warning(&binding, source);
433            (None, Some(warning))
434        }
435        other => (other, None),
436    }
437}
438
439/// Fill in a binding's friendly `project_name` from an already-fetched
440/// projects list, when the binding has none.
441///
442/// The UUID form of `TRACEVAULT_PROJECT` arrives nameless: it is parsed
443/// locally by `commands::stream::env_project_binding` and never looked up, so
444/// without this `status` prints a bare UUID for a tier it just named. Gating
445/// on the EMPTY NAME rather than on a particular [`ProjectSource`] keeps this
446/// to the condition actually being repaired; a binding that already has a
447/// name is untouched.
448///
449/// Cosmetic only, and it never changes WHICH project is effective — the id is
450/// not touched — so it cannot make `status` disagree with ingest.
451fn enrich_project_name(
452    effective: Option<(ProjectBinding, ProjectSource)>,
453    items: Option<&[ProjectListItem]>,
454) -> Option<(ProjectBinding, ProjectSource)> {
455    effective.map(|(mut binding, source)| {
456        if binding.project_name.is_empty() {
457            if let Some(items) = items {
458                if let Ok(id) = binding.project_id.parse::<uuid::Uuid>() {
459                    if let Some(matched) = items.iter().find(|p| p.id == id) {
460                        binding.project_name = matched.name.clone();
461                    }
462                }
463            }
464        }
465        (binding, source)
466    })
467}
468
469/// Warning for a `TRACEVAULT_PROJECT` that holds a NAME rather than a UUID.
470///
471/// Same rule as the legacy `.visdom/tracing.toml` `default_project`
472/// (`commands::migrate::legacy_default_project_notice`): resolving a name needs a `list_projects` round trip, the per-event capture
473/// path never makes one, so the variable decides nothing and attribution
474/// falls through to the next tier. `status` therefore does NOT resolve it
475/// either — reporting a name-resolved project as effective would be exactly
476/// the status/ingest disagreement this command exists to remove.
477fn env_name_form_warning(raw: &str) -> String {
478    format!(
479        "warning: {ENV}_PROJECT '{raw}' is a NAME; only the UUID form is used for attribution at capture time, so this value is ignored — export the project's id instead, or bind it with `{CLI} project switch <name>`"
480    )
481}
482
483/// Display label for a binding: the friendly name, falling back to the id.
484fn binding_label(b: &ProjectBinding) -> &str {
485    if b.project_name.is_empty() {
486        &b.project_id
487    } else {
488        &b.project_name
489    }
490}
491
492/// Pure formatter for `project status`'s effective-project line: the project
493/// ingest attributes events to, and via which precedence tier. Mirrors
494/// `commands::repo::format_status`. `None` means ingest sends events
495/// repo-scoped and leaves attribution to the server.
496fn format_status(effective: Option<(&ProjectBinding, ProjectSource)>) -> String {
497    match effective {
498        Some((b, source)) => format!("project: {} via {source}", binding_label(b)),
499        None => "no project bound locally; if a repo is bound, events are sent repo-scoped and the server deduces the project from the repo".to_string(),
500    }
501}
502
503/// Warning for a capture binding whose stored `project_id` is not a UUID:
504/// ingest drops it (`capture_project_id` → `None`), so `status` reports the
505/// session as unbound. Same rule and wording as `commands::status`'s
506/// `project_binding_check`.
507fn invalid_capture_id_warning(binding: &ProjectBinding, source: ProjectSource) -> String {
508    format!(
509        "warning: project {} — {source}, but the saved project_id is not a valid id and is dropped at capture time; run `{}` to rewrite it",
510        binding_label(binding),
511        source.rewrite_command()
512    )
513}
514
515/// Warning for `--project <name>` when no credentials resolved: the name
516/// cannot be looked up, so the override is ignored.
517fn offline_project_flag_warning(name: &str) -> String {
518    format!(
519        "warning: --project '{name}' cannot be resolved without server credentials; ignoring the override"
520    )
521}
522
523/// The name of a deduced project id, if the projects list is already in
524/// scope (fetched for `--project`). Never triggers an API call of its own:
525/// the name is cosmetic, and the id is printed when it is unknown.
526fn deduced_project_name(pid: uuid::Uuid, items: Option<&[ProjectListItem]>) -> Option<&str> {
527    items?.iter().find(|p| p.id == pid).map(|p| p.name.as_str())
528}
529
530/// Pure formatter for the server-deduction line: what the server would deduce
531/// from this repo's git remote if no local binding were set. Shown separately
532/// from the effective project because ingest never deduces client-side — it
533/// only matters when nothing is bound locally. `resolved_name` is the name of
534/// a `Resolved` project when already known (see [`deduced_project_name`]);
535/// otherwise the id is printed.
536fn format_deduction(
537    effective_is_bound: bool,
538    outcome: Result<ResolveProjectOutcome, String>,
539    resolved_name: Option<&str>,
540) -> String {
541    const PREFIX: &str = "server deduction for this repo:";
542    match outcome {
543        Ok(ResolveProjectOutcome::Resolved(pid)) => {
544            let pid = pid.to_string();
545            let label = resolved_name.unwrap_or(&pid);
546            if effective_is_bound {
547                format!("{PREFIX} {label} (not used: the local binding above wins)")
548            } else {
549                format!("{PREFIX} {label} (events will land here if a repo is bound)")
550            }
551        }
552        Ok(ResolveProjectOutcome::Ambiguous) => {
553            if effective_is_bound {
554                format!(
555                    "{PREFIX} ambiguous (multiple projects) — not used, the local binding above wins"
556                )
557            } else {
558                format!(
559                    "{PREFIX} ambiguous (multiple projects) — if a repo is bound, events will be refused until you run `{CLI} project switch <name>`"
560                )
561            }
562        }
563        Ok(ResolveProjectOutcome::None) => format!("{PREFIX} none"),
564        Err(msg) => format!("{PREFIX} unavailable ({msg})"),
565    }
566}
567
568/// Everything `project status` prints: `warnings` go to stderr, `lines`
569/// (the effective-project line, then the deduction line when shown) to
570/// stdout. Built by [`status_report`] so tests assert the exact output.
571#[derive(Debug, Default)]
572struct StatusReport {
573    warnings: Vec<String>,
574    lines: Vec<String>,
575}
576
577/// `tracevault project status`: a read-only inspector that always returns
578/// `Ok(())`. Prints the [`StatusReport`] built by [`status_report`].
579async fn status(
580    session_id: Option<&str>,
581    project_flag_name: Option<&str>,
582    project_root: &Path,
583    cwd: &Path,
584) -> Result<(), Box<dyn std::error::Error>> {
585    let report = status_report(session_id, project_flag_name, project_root, cwd).await;
586    for warning in &report.warnings {
587        eprintln!("{warning}");
588    }
589    for line in &report.lines {
590        println!("{line}");
591    }
592    Ok(())
593}
594
595/// The content of `project status`. The effective project is the
596/// capture-time chain (local, no network); the server's deduction from the
597/// git remote is shown on its own line, best-effort, as what would apply if
598/// nothing were bound locally. Never fails: every problem becomes a warning.
599async fn status_report(
600    session_id: Option<&str>,
601    project_flag_name: Option<&str>,
602    project_root: &Path,
603    cwd: &Path,
604) -> StatusReport {
605    let mut report = StatusReport::default();
606    // Session state is best-effort: if a session id resolves, load it; else
607    // warn and fall back to an empty SessionState.
608    let session = match crate::commands::repo::resolve_session_id(session_id) {
609        Ok(id) => session_state::load(&id),
610        Err(_) => {
611            report.warnings.push(
612                crate::program::say(
613                    "warning: no session id (pass --session-id or set TRACEVAULT_SESSION_ID); \
614                 showing binding without session context",
615                )
616                .to_string(),
617            );
618            SessionState::default()
619        }
620    };
621    let worktree = crate::paths::worktree_toplevel(cwd);
622    // The config at the project root, read once: its `project_id` is the
623    // workspace tier — read exactly as the hook reads it, no name lookup —
624    // and its legacy `default_project` only ever produces a notice.
625    let config = crate::config::TracevaultConfig::load(project_root);
626    let config_project = config
627        .as_ref()
628        .and_then(crate::resolution::project_from_config);
629    let user_default = crate::user_project_default::load();
630    let git_url = git_remote_url(cwd);
631
632    // `TRACEVAULT_PROJECT` enters the chain through the capture path's OWN
633    // reader, which is UUID-only: `status` must not resolve a NAME into the
634    // chain, or it would report a project ingest never attributes to. The
635    // name form gets a warning instead.
636    let env_project = crate::commands::stream::env_project_binding();
637    let env_raw = std::env::var("TRACEVAULT_PROJECT")
638        .ok()
639        .map(|raw| raw.trim().to_string())
640        .filter(|raw| !raw.is_empty());
641    if env_project.is_none() {
642        if let Some(raw) = env_raw.as_deref() {
643            report.warnings.push(env_name_form_warning(raw));
644        }
645    }
646
647    // The server is needed only to resolve a `--project` NAME, to put a
648    // friendly name on the env binding's bare UUID, and to show the
649    // deduction line; the effective project itself is computed locally.
650    let client = match resolve_client(project_root) {
651        Ok(client) => Some(client),
652        Err(e) => {
653            report.warnings.push(format!(
654                "warning: could not resolve credentials ({e}); server deduction not shown"
655            ));
656            None
657        }
658    };
659
660    let mut items: Option<Vec<ProjectListItem>> = None;
661    let project_flag = match (project_flag_name, client.as_ref()) {
662        (Some(name), Some(client)) => {
663            items = client.list_projects().await.ok();
664            let flag = items
665                .as_deref()
666                .and_then(|items| resolve_project_name(items, name).ok())
667                .map(|matched| ProjectBinding {
668                    project_id: matched.id.to_string(),
669                    project_name: matched.name.clone(),
670                    updated_at: chrono::Utc::now().to_rfc3339(),
671                    forced_until: None,
672                });
673            if flag.is_none() {
674                report.warnings.push(format!(
675                    "warning: --project '{name}' could not be resolved; ignoring the override"
676                ));
677            }
678            flag
679        }
680        (Some(name), None) => {
681            report.warnings.push(offline_project_flag_warning(name));
682            None
683        }
684        (None, _) => None,
685    };
686
687    // The UUID form of `TRACEVAULT_PROJECT` resolves to a NAMELESS binding
688    // (no lookup on the capture path), so fetch the list once here purely to
689    // print a friendly name for it. Cosmetic: the id, and therefore which
690    // project is effective, is unaffected either way.
691    if items.is_none() && env_project.is_some() {
692        if let Some(client) = client.as_ref() {
693            items = client.list_projects().await.ok();
694        }
695    }
696
697    let (effective, invalid_id_warning) = status_effective(
698        project_flag,
699        env_project,
700        &session,
701        Some(&worktree),
702        config_project.clone(),
703        user_default,
704    );
705    report.warnings.extend(invalid_id_warning);
706    let effective = enrich_project_name(effective, items.as_deref());
707
708    if let Some(notice) = config
709        .as_ref()
710        .and_then(crate::commands::migrate::legacy_default_project_notice)
711    {
712        report.warnings.push(format!("warning: {notice}"));
713    }
714
715    report
716        .lines
717        .push(format_status(effective.as_ref().map(|(b, s)| (b, *s))));
718    // The attribution mode of the binding that actually won, read off THAT
719    // binding (plus `TRACEVAULT_PROJECT_ATTRIBUTION`) — the same value
720    // `commands::stream::send_stream_event` puts in the header.
721    if let Some((b, _)) = effective.as_ref() {
722        report.lines.extend(attribution_report(b));
723    }
724    // Where this session's events actually go, through the hook's own gate
725    // (no `--project` override: the hook has none) — so a repo-less session
726    // is reported as recording project-only, exactly as ingest sends it
727    // (VIS-1255), and an unbound one as recording nothing.
728    let bound_repo = config
729        .as_ref()
730        .and_then(crate::resolution::binding_from_config);
731    report
732        .lines
733        .push(crate::commands::stream::recording_line_for(
734            &crate::commands::stream::recording_attribution_for(
735                &session,
736                &worktree,
737                bound_repo,
738                crate::user_default::load(),
739                config_project,
740            ),
741        ));
742
743    if let (Some(client), Some(url)) = (client.as_ref(), git_url.as_deref()) {
744        // Best-effort and informational: an ambiguous or failed deduction is
745        // reported, never propagated — `status` exits 0 regardless.
746        let outcome = client.resolve_project(url).await.map_err(|e| e.to_string());
747        let name = match &outcome {
748            Ok(ResolveProjectOutcome::Resolved(pid)) => {
749                deduced_project_name(*pid, items.as_deref())
750            }
751            _ => None,
752        };
753        report
754            .lines
755            .push(format_deduction(effective.is_some(), outcome, name));
756    }
757    report
758}
759
760#[cfg(test)]
761mod tests {
762    use super::*;
763    use std::io::{BufRead, BufReader, Write};
764    use std::net::TcpListener;
765    use std::thread;
766
767    #[test]
768    fn resolve_project_name_exact_match_and_miss() {
769        let items = vec![
770            ProjectListItem {
771                id: uuid::Uuid::nil(),
772                name: "payments".into(),
773            },
774            ProjectListItem {
775                id: uuid::Uuid::from_u128(2),
776                name: "web".into(),
777            },
778        ];
779        let ok = resolve_project_name(&items, "web").unwrap();
780        assert_eq!(ok.id, uuid::Uuid::from_u128(2));
781        let err = resolve_project_name(&items, "Web").unwrap_err(); // case-sensitive
782        assert!(err.contains("payments") && err.contains("web")); // lists available names
783    }
784
785    #[test]
786    fn switch_destination_user_flag_forces_user_default() {
787        assert!(matches!(
788            switch_destination(true, Some("sess-1".to_string())),
789            SwitchDest::UserDefault
790        ));
791        assert!(matches!(
792            switch_destination(true, None),
793            SwitchDest::UserDefault
794        ));
795    }
796
797    #[test]
798    fn switch_destination_session_when_present_and_no_user_flag() {
799        assert!(matches!(
800            switch_destination(false, Some("sess-1".to_string())),
801            SwitchDest::Session(id) if id == "sess-1"
802        ));
803    }
804
805    #[test]
806    fn switch_destination_user_default_when_no_session() {
807        assert!(matches!(
808            switch_destination(false, None),
809            SwitchDest::UserDefault
810        ));
811    }
812
813    #[test]
814    fn switching_with_explicit_stamps_a_lapse_time() {
815        let before = chrono::Utc::now();
816        let binding = apply_force(
817            ProjectBinding {
818                project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
819                project_name: "p".into(),
820                updated_at: before.to_rfc3339(),
821                forced_until: None,
822            },
823            true,
824        );
825        let until = chrono::DateTime::parse_from_rfc3339(
826            binding.forced_until.as_deref().expect("force is stamped"),
827        )
828        .unwrap();
829        let expected = before
830            + chrono::Duration::hours(crate::user_project_default::DEFAULT_FORCE_LIFETIME_HOURS);
831        assert!((until.timestamp() - expected.timestamp()).abs() < 5);
832    }
833
834    #[test]
835    fn switching_without_explicit_stamps_no_lapse_time() {
836        let binding = apply_force(
837            ProjectBinding {
838                project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
839                project_name: "p".into(),
840                updated_at: chrono::Utc::now().to_rfc3339(),
841                forced_until: Some("2020-01-01T00:00:00Z".into()),
842            },
843            false,
844        );
845        assert_eq!(
846            binding.forced_until, None,
847            "switching without --project-attribution explicit must CLEAR a stale force"
848        );
849    }
850
851    /// `format_force_line` reports the STATE of the stored force and never a
852    /// verdict, so no output of it may contain the words the mode line owns.
853    /// A live force says when it runs out; a lapsed one says when it did.
854    #[test]
855    fn format_force_line_distinguishes_a_live_force_from_a_lapsed_one() {
856        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
857        let live = format_force_line(&future);
858        assert!(live.contains("active until"), "got: {live}");
859        assert!(live.contains(&future), "got: {live}");
860
861        let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
862        let lapsed = format_force_line(&past);
863        assert!(lapsed.contains("lapsed"), "got: {lapsed}");
864        assert!(lapsed.contains(&past), "got: {lapsed}");
865
866        // Neither may render a mode: that is `attribution_report`'s first
867        // line, and a second answer here is what produced both contradiction
868        // bugs (see `attribution_report`'s doc comment).
869        for line in [&live, &lapsed] {
870            assert!(!line.contains("derived"), "got: {line}");
871            assert!(!line.contains("explicit"), "got: {line}");
872            assert!(!line.contains("membership"), "got: {line}");
873        }
874    }
875
876    /// Discriminates the SIGN of the lapse comparison in `format_force_line`:
877    /// a `forced_until` already in the past must report as lapsed, not as
878    /// still active.
879    #[test]
880    fn status_names_a_lapsed_force_as_lapsed_not_active() {
881        let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
882        let line = format_force_line(&past);
883        assert!(line.contains("lapsed"), "got: {line}");
884        assert!(!line.contains("active until"), "got: {line}");
885    }
886
887    /// A `forced_until` that doesn't even parse as RFC3339 (a hand-edited or
888    /// corrupted `user_project.toml`/session-state file) must fail SAFE —
889    /// reported as not in force, never as active, and never a panic. Pins
890    /// the fail-safe direction against a future refactor to `.expect(...)`.
891    ///
892    /// The second half — that the printed state agrees with
893    /// `commands::stream::attribution_mode`, the one that fills the header —
894    /// used to reconcile two independently written predicates. Both now go
895    /// through `session_state::force_status`, so it pins that neither reader
896    /// has quietly grown a second opinion around the shared one.
897    #[test]
898    fn status_names_unparseable_forced_until_as_not_in_force() {
899        let line = format_force_line("not-a-timestamp");
900        assert!(line.contains("not in force"), "got: {line}");
901        assert!(!line.contains("active until"), "got: {line}");
902
903        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
904        let mut _guard = crate::test_helpers::EnvVarGuard::new();
905        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
906        let b = ProjectBinding {
907            project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
908            project_name: "payments".into(),
909            updated_at: "".into(),
910            forced_until: Some("not-a-timestamp".into()),
911        };
912        assert_eq!(
913            crate::commands::stream::attribution_mode(Some(&b)),
914            crate::api_client::AttributionMode::Derived,
915            "the reported state and the header must agree on an unreadable force"
916        );
917    }
918
919    /// VIS-305 whole-branch review, Important finding 3: `project status`
920    /// printed the effective mode and THEN printed `format_force_line`
921    /// unconditionally, so a shell with
922    /// `TRACEVAULT_PROJECT_ATTRIBUTION=explicit` and no persisted force got
923    /// two lines that contradicted each other — "attribution mode: explicit"
924    /// immediately followed by "attribution: derived (Visdom checks
925    /// repo/project membership)" — while every hook in that shell sent
926    /// `explicit`. The lapse detail describes a PERSISTED force, so it may
927    /// only be printed when one exists.
928    #[test]
929    fn attribution_report_omits_the_lapse_line_when_there_is_no_persisted_force() {
930        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
931        let mut _guard = crate::test_helpers::EnvVarGuard::new();
932        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
933
934        let b = ProjectBinding {
935            project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
936            project_name: "payments".into(),
937            updated_at: "".into(),
938            forced_until: None,
939        };
940        let lines = attribution_report(&b);
941        assert_eq!(
942            lines.len(),
943            1,
944            "an env-only force has no lapse to report, and must not be \
945             contradicted by a `derived` line: {lines:?}"
946        );
947        assert!(
948            lines[0].starts_with("attribution mode: explicit"),
949            "got: {lines:?}"
950        );
951        assert!(
952            !lines.iter().any(|l| l.contains("derived")),
953            "got: {lines:?}"
954        );
955    }
956
957    /// The other half of the same rule: a binding that DOES carry a
958    /// persisted force still gets its lapse time, so finding 3's fix is
959    /// "print it only when it applies", not "stop printing it".
960    #[test]
961    fn attribution_report_keeps_the_lapse_line_for_a_persisted_force() {
962        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
963        let mut _guard = crate::test_helpers::EnvVarGuard::new();
964        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
965
966        let until = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
967        let b = ProjectBinding {
968            project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
969            project_name: "payments".into(),
970            updated_at: "".into(),
971            forced_until: Some(until.clone()),
972        };
973        let lines = attribution_report(&b);
974        assert_eq!(lines.len(), 2, "got: {lines:?}");
975        assert!(
976            lines[0].starts_with("attribution mode: explicit"),
977            "got: {}",
978            lines[0]
979        );
980        assert!(lines[1].contains("active until"), "got: {}", lines[1]);
981        assert!(lines[1].contains(&until), "got: {}", lines[1]);
982    }
983
984    /// A LAPSED persisted force still gets its detail line — the binding
985    /// really does carry a force, it has simply run out, and saying when is
986    /// the useful part. With no env override the mode line correctly reads
987    /// `derived`; the detail line states the lapse as a fact, and the two
988    /// agree without the detail line having to render a verdict of its own.
989    #[test]
990    fn attribution_report_reports_a_lapsed_persisted_force_as_derived() {
991        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
992        let mut _guard = crate::test_helpers::EnvVarGuard::new();
993        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
994
995        let b = ProjectBinding {
996            project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
997            project_name: "payments".into(),
998            updated_at: "".into(),
999            forced_until: Some((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()),
1000        };
1001        let lines = attribution_report(&b);
1002        assert_eq!(lines.len(), 2, "got: {lines:?}");
1003        assert!(
1004            lines[0].starts_with("attribution mode: derived"),
1005            "got: {}",
1006            lines[0]
1007        );
1008        assert!(
1009            lines[1].starts_with("persisted force: lapsed"),
1010            "got: {}",
1011            lines[1]
1012        );
1013    }
1014
1015    /// Copilot on PR #54: the `is_some()` guard is the wrong test, because a
1016    /// LAPSED force is still `is_some()`. With
1017    /// `TRACEVAULT_PROJECT_ATTRIBUTION=explicit` and a binding whose
1018    /// persisted force has expired, the report used to read
1019    ///
1020    /// ```text
1021    /// attribution mode: explicit (this caller owns attribution; ...)
1022    /// attribution: derived (a force lapsed ...; membership is checked again)
1023    /// ```
1024    ///
1025    /// — the exact contradiction `attribution_report` exists to remove, just
1026    /// reached by a different route than finding 3's. The fix is not a
1027    /// narrower guard (the lapse time is still worth printing) but wording:
1028    /// the second line states a FACT about the persisted binding, so it is
1029    /// detail under the verdict rather than a competing verdict. The
1030    /// unparseable case is the same shape and is covered too.
1031    #[test]
1032    fn a_lapsed_persisted_force_never_contradicts_an_env_force() {
1033        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1034        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1035        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
1036
1037        let lapsed = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
1038        for forced_until in [lapsed.as_str(), "not-a-timestamp"] {
1039            let b = ProjectBinding {
1040                project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
1041                project_name: "payments".into(),
1042                updated_at: "".into(),
1043                forced_until: Some(forced_until.to_string()),
1044            };
1045            let lines = attribution_report(&b);
1046            assert_eq!(lines.len(), 2, "{forced_until}: got {lines:?}");
1047            assert!(
1048                lines[0].starts_with("attribution mode: explicit"),
1049                "{forced_until}: the env force decides the mode: {lines:?}"
1050            );
1051            // The detail line may say the PERSISTED force has lapsed — that
1052            // is a true fact about the stored binding — but it must not
1053            // answer the question the mode line already answered.
1054            assert!(
1055                !lines[1].contains("derived"),
1056                "{forced_until}: the detail line must not render a competing \
1057                 verdict while the env force makes this send explicit: {lines:?}"
1058            );
1059            assert!(
1060                !lines[1].contains("membership is checked"),
1061                "{forced_until}: membership is NOT being checked here: {lines:?}"
1062            );
1063        }
1064    }
1065
1066    /// VIS-305 whole-branch review, Important finding 4: Part C fixed
1067    /// `status` and left `switch` printing the same lie with no mode line to
1068    /// offset it. In a shell with `TRACEVAULT_PROJECT_ATTRIBUTION=explicit`,
1069    /// `tracevault project switch foo` reported "attribution: derived" while
1070    /// every hook in that shell sent `explicit`. Asserts the whole rendered
1071    /// output, including the ABSENCE of the contradictory line, for both
1072    /// destinations.
1073    #[test]
1074    fn switch_report_names_the_env_force_and_never_claims_derived() {
1075        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1076        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1077        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
1078
1079        let b = ProjectBinding {
1080            project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
1081            project_name: "payments".into(),
1082            updated_at: "".into(),
1083            forced_until: None,
1084        };
1085
1086        for dest in [
1087            SwitchDest::Session("sess-1".to_string()),
1088            SwitchDest::UserDefault,
1089        ] {
1090            let lines = switch_report(&dest, &b, None);
1091            assert!(
1092                lines[0].contains("payments"),
1093                "the first line still says what was bound: {lines:?}"
1094            );
1095            assert!(
1096                lines
1097                    .iter()
1098                    .any(|l| l.starts_with("attribution mode: explicit")),
1099                "a `switch` in an explicit shell must say so: {lines:?}"
1100            );
1101            assert!(
1102                !lines.iter().any(|l| l.contains("derived")),
1103                "{dest:?}: `switch` must not claim membership is checked while \
1104                 every hook in this shell sends `explicit`: {lines:?}"
1105            );
1106        }
1107    }
1108
1109    /// `switch --project-attribution explicit` still reports the lapse it
1110    /// just stamped — the fix to finding 4 must not swallow the one piece of
1111    /// information a forced switch owes the caller.
1112    #[test]
1113    fn switch_report_names_the_lapse_it_just_stamped() {
1114        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1115        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1116        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
1117
1118        let b = apply_force(
1119            ProjectBinding {
1120                project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
1121                project_name: "payments".into(),
1122                updated_at: "".into(),
1123                forced_until: None,
1124            },
1125            true,
1126        );
1127        let lines = switch_report(&SwitchDest::Session("sess-1".to_string()), &b, None);
1128        assert_eq!(lines.len(), 3, "got: {lines:?}");
1129        assert!(
1130            lines[1].starts_with("attribution mode: explicit"),
1131            "got: {}",
1132            lines[1]
1133        );
1134        assert!(
1135            lines[2].starts_with("persisted force: active until"),
1136            "got: {}",
1137            lines[2]
1138        );
1139    }
1140
1141    fn pb(name: &str) -> ProjectBinding {
1142        ProjectBinding {
1143            project_id: format!("id-{name}"),
1144            project_name: name.into(),
1145            updated_at: "t".into(),
1146            forced_until: None,
1147        }
1148    }
1149
1150    #[test]
1151    fn format_status_unbound() {
1152        assert_eq!(
1153            format_status(None),
1154            "no project bound locally; if a repo is bound, events are sent repo-scoped and the server deduces the project from the repo"
1155        );
1156    }
1157
1158    #[test]
1159    fn format_status_project_flag() {
1160        let b = pb("web");
1161        assert_eq!(
1162            format_status(Some((&b, ProjectSource::ProjectFlag))),
1163            "project: web via --project override"
1164        );
1165    }
1166
1167    #[test]
1168    fn format_status_session_active() {
1169        let b = pb("payments");
1170        assert_eq!(
1171            format_status(Some((&b, ProjectSource::SessionActive))),
1172            "project: payments via session (project switch)"
1173        );
1174    }
1175
1176    #[test]
1177    fn format_status_falls_back_to_id_when_name_empty() {
1178        // `Deduced` can no longer be the effective tier (the capture chain
1179        // never deduces); a bound tier with an empty name still prints the id.
1180        let b = ProjectBinding {
1181            project_id: "some-id".into(),
1182            project_name: String::new(),
1183            updated_at: "".into(),
1184            forced_until: None,
1185        };
1186        assert_eq!(
1187            format_status(Some((&b, ProjectSource::UserDefault))),
1188            "project: some-id via user default (project switch --user)"
1189        );
1190    }
1191
1192    #[test]
1193    fn format_status_env() {
1194        let b = pb("payments");
1195        assert_eq!(
1196            format_status(Some((&b, ProjectSource::Env))),
1197            "project: payments via TRACEVAULT_PROJECT (environment)"
1198        );
1199    }
1200
1201    #[test]
1202    fn invalid_capture_id_warning_names_tier_and_rewrite_command() {
1203        let b = ProjectBinding {
1204            project_id: "not-a-uuid".into(),
1205            project_name: "payments".into(),
1206            updated_at: "".into(),
1207            forced_until: None,
1208        };
1209        assert_eq!(
1210            invalid_capture_id_warning(&b, ProjectSource::UserDefault),
1211            "warning: project payments — user default (project switch --user), but the saved project_id is not a valid id and is dropped at capture time; run `tracevault project switch --user <name>` to rewrite it"
1212        );
1213        assert_eq!(
1214            invalid_capture_id_warning(&b, ProjectSource::Workspace),
1215            "warning: project payments — workspace .visdom/tracing.toml, but the saved project_id is not a valid id and is dropped at capture time; run `tracevault init --workspace --project <name>` to rewrite it"
1216        );
1217    }
1218
1219    /// `status`'s own drop rule: a non-UUID binding is not effective, and the
1220    /// warning returned for it names the tier it came from.
1221    #[test]
1222    fn status_effective_drops_a_non_uuid_binding_with_a_warning_naming_the_tier() {
1223        let session = SessionState {
1224            active_project: Some(ProjectBinding {
1225                project_id: "not-a-uuid".into(),
1226                project_name: "payments".into(),
1227                updated_at: "".into(),
1228                forced_until: None,
1229            }),
1230            ..Default::default()
1231        };
1232        let (effective, warning) = status_effective(None, None, &session, None, None, None);
1233        assert!(effective.is_none(), "{effective:?}");
1234        let warning = warning.expect("a dropped binding must be explained");
1235        assert!(
1236            warning.contains("session (project switch)"),
1237            "must name the tier: {warning}"
1238        );
1239        assert!(warning.contains("payments"), "{warning}");
1240
1241        // A valid binding is effective and carries no warning.
1242        let pid = uuid::Uuid::from_u128(5);
1243        let valid = SessionState {
1244            active_project: Some(ProjectBinding {
1245                project_id: pid.to_string(),
1246                project_name: "web".into(),
1247                updated_at: "".into(),
1248                forced_until: None,
1249            }),
1250            ..Default::default()
1251        };
1252        let (effective, warning) = status_effective(None, None, &valid, None, None, None);
1253        assert_eq!(
1254            effective.map(|(b, s)| (b.project_id, s)),
1255            Some((pid.to_string(), ProjectSource::SessionActive))
1256        );
1257        assert_eq!(warning, None);
1258    }
1259
1260    /// `TRACEVAULT_PROJECT` is the `Env` rung of the SAME chain ingest runs,
1261    /// so `status_effective` must place it above session-active and the user
1262    /// default, and below `--project`. Pure: the binding is passed in, as
1263    /// `status_report` passes what `stream::env_project_binding` returned.
1264    #[test]
1265    fn status_effective_places_env_at_rung_three() {
1266        let u = uuid::Uuid::from_u128;
1267        let bind = |id: uuid::Uuid, name: &str| ProjectBinding {
1268            project_id: id.to_string(),
1269            project_name: name.into(),
1270            updated_at: "".into(),
1271            forced_until: None,
1272        };
1273        let session = SessionState {
1274            active_project: Some(bind(u(2), "session")),
1275            ..Default::default()
1276        };
1277
1278        // env beats session active and the user default
1279        let (effective, _) = status_effective(
1280            None,
1281            Some(bind(u(9), "env")),
1282            &session,
1283            None,
1284            None,
1285            Some(bind(u(3), "user")),
1286        );
1287        assert_eq!(
1288            effective.map(|(b, s)| (b.project_id, s)),
1289            Some((u(9).to_string(), ProjectSource::Env))
1290        );
1291
1292        // --project still beats env
1293        let (effective, _) = status_effective(
1294            Some(bind(u(1), "flag")),
1295            Some(bind(u(9), "env")),
1296            &session,
1297            None,
1298            None,
1299            Some(bind(u(3), "user")),
1300        );
1301        assert_eq!(
1302            effective.map(|(b, s)| (b.project_id, s)),
1303            Some((u(1).to_string(), ProjectSource::ProjectFlag))
1304        );
1305    }
1306
1307    #[test]
1308    fn offline_project_flag_warning_says_the_override_is_ignored() {
1309        assert_eq!(
1310            offline_project_flag_warning("web"),
1311            "warning: --project 'web' cannot be resolved without server credentials; ignoring the override"
1312        );
1313    }
1314
1315    /// The NAME form of `TRACEVAULT_PROJECT` is not resolved into the chain
1316    /// (that would need a per-event `list_projects` the hook never makes), so
1317    /// `status` warns instead of reporting a tier ingest ignores.
1318    #[test]
1319    fn env_name_form_warning_says_only_the_uuid_form_is_used() {
1320        let warning = env_name_form_warning("payments");
1321        assert!(warning.contains("payments"), "{warning}");
1322        assert!(warning.contains("UUID form"), "{warning}");
1323        assert!(
1324            warning.contains("not used") || warning.contains("ignored"),
1325            "{warning}"
1326        );
1327    }
1328
1329    const DEDUCED: uuid::Uuid = uuid::Uuid::from_u128(2);
1330
1331    #[test]
1332    fn format_deduction_resolved_bound() {
1333        assert_eq!(
1334            format_deduction(true, Ok(ResolveProjectOutcome::Resolved(DEDUCED)), None),
1335            format!(
1336                "server deduction for this repo: {DEDUCED} (not used: the local binding above wins)"
1337            )
1338        );
1339    }
1340
1341    #[test]
1342    fn format_deduction_resolved_unbound() {
1343        assert_eq!(
1344            format_deduction(false, Ok(ResolveProjectOutcome::Resolved(DEDUCED)), None),
1345            format!("server deduction for this repo: {DEDUCED} (events will land here if a repo is bound)")
1346        );
1347    }
1348
1349    #[test]
1350    fn format_deduction_resolved_uses_name_when_known() {
1351        let items = items();
1352        let name = deduced_project_name(DEDUCED, Some(&items));
1353        assert_eq!(name, Some("web"));
1354        assert_eq!(
1355            format_deduction(false, Ok(ResolveProjectOutcome::Resolved(DEDUCED)), name),
1356            "server deduction for this repo: web (events will land here if a repo is bound)"
1357        );
1358    }
1359
1360    #[test]
1361    fn deduced_project_name_none_without_list_or_match() {
1362        assert_eq!(deduced_project_name(DEDUCED, None), None);
1363        assert_eq!(
1364            deduced_project_name(uuid::Uuid::from_u128(999), Some(&items())),
1365            None
1366        );
1367    }
1368
1369    #[test]
1370    fn format_deduction_ambiguous_bound() {
1371        assert_eq!(
1372            format_deduction(true, Ok(ResolveProjectOutcome::Ambiguous), None),
1373            "server deduction for this repo: ambiguous (multiple projects) — not used, the local binding above wins"
1374        );
1375    }
1376
1377    #[test]
1378    fn format_deduction_ambiguous_unbound() {
1379        assert_eq!(
1380            format_deduction(false, Ok(ResolveProjectOutcome::Ambiguous), None),
1381            "server deduction for this repo: ambiguous (multiple projects) — if a repo is bound, events will be refused until you run `tracevault project switch <name>`"
1382        );
1383    }
1384
1385    #[test]
1386    fn format_deduction_none() {
1387        for bound in [true, false] {
1388            assert_eq!(
1389                format_deduction(bound, Ok(ResolveProjectOutcome::None), None),
1390                "server deduction for this repo: none"
1391            );
1392        }
1393    }
1394
1395    #[test]
1396    fn format_deduction_err() {
1397        for bound in [true, false] {
1398            assert_eq!(
1399                format_deduction(bound, Err("connection refused".into()), None),
1400                "server deduction for this repo: unavailable (connection refused)"
1401            );
1402        }
1403    }
1404
1405    #[test]
1406    fn format_status_user_default() {
1407        let b = pb("payments");
1408        assert_eq!(
1409            format_status(Some((&b, ProjectSource::UserDefault))),
1410            "project: payments via user default (project switch --user)"
1411        );
1412    }
1413
1414    /// Spawn a one-shot raw-HTTP server that returns `response` to the first
1415    /// request it accepts (mirrors `commands::repo`'s test helper).
1416    fn spawn_once(response: String) -> String {
1417        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1418        let addr = listener.local_addr().unwrap();
1419        let response: &'static str = Box::leak(response.into_boxed_str());
1420        thread::spawn(move || {
1421            if let Ok((stream, _)) = listener.accept() {
1422                let mut reader = BufReader::new(stream);
1423                let mut request_line = String::new();
1424                let _ = reader.read_line(&mut request_line);
1425                let mut stream = reader.into_inner();
1426                let _ = stream.write_all(response.as_bytes());
1427                let _ = stream.flush();
1428            }
1429        });
1430        format!("http://{addr}")
1431    }
1432
1433    /// Generalizes `spawn_once` to a listener that answers each of
1434    /// `responses` in order, one per accepted connection (the
1435    /// containment-check flow makes several sequential requests).
1436    fn spawn_n(responses: Vec<String>) -> String {
1437        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1438        let addr = listener.local_addr().unwrap();
1439        thread::spawn(move || {
1440            for response in responses {
1441                let response: &'static str = Box::leak(response.into_boxed_str());
1442                if let Ok((stream, _)) = listener.accept() {
1443                    let mut reader = BufReader::new(stream);
1444                    let mut request_line = String::new();
1445                    let _ = reader.read_line(&mut request_line);
1446                    let mut stream = reader.into_inner();
1447                    let _ = stream.write_all(response.as_bytes());
1448                    let _ = stream.flush();
1449                }
1450            }
1451        });
1452        format!("http://{addr}")
1453    }
1454
1455    fn http_200(body: &str) -> String {
1456        format!(
1457            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1458            body.len(),
1459            body
1460        )
1461    }
1462
1463    /// Happy-path flow test (mirrors `resolve_switch_binding_ok_for_registered_repo`
1464    /// in `commands/repo.rs`): mock `GET /projects`, resolve the switch's
1465    /// project binding, apply it to a (uniquely-named, cleaned-up-afterward)
1466    /// session's state, and confirm the write round-trips through the real
1467    /// `session_state::save`/`load_from` — the exact assertion the brief
1468    /// calls for.
1469    #[tokio::test]
1470    async fn project_switch_happy_path_writes_active_project_to_session_file() {
1471        let tmp = tempfile::tempdir().unwrap();
1472        crate::test_helpers::init_git_repo(tmp.path()); // no origin remote → containment check is a no-op
1473
1474        // C3: isolate `session_state::sessions_dir()` (which honors
1475        // `$XDG_STATE_HOME`) to a tempdir for the duration of this test, so
1476        // it never touches the developer's real state dir.
1477        //
1478        // Held under the env lock: other tests (`flush`'s `run_flush` test,
1479        // `status_in_the_orchestrator_configuration_names_the_user_default`)
1480        // also set XDG_STATE_HOME. Restored in a guard so a panic mid-test
1481        // still cleans up the process env.
1482        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1483        let state_tmp = tempfile::tempdir().unwrap();
1484        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1485        _guard.set("XDG_STATE_HOME", state_tmp.path());
1486
1487        let list = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"},{"id":"22222222-2222-4222-8222-222222222222","name":"web"}]"#;
1488        let base = spawn_once(http_200(list));
1489        let client = ApiClient::new(&base, Some("tok"));
1490
1491        let (binding, note) =
1492            resolve_switch_project("web", &client, CodebaseCheck::Enforce, tmp.path())
1493                .await
1494                .expect("expected Ok binding");
1495        assert_eq!(binding.project_id, "22222222-2222-4222-8222-222222222222");
1496        assert_eq!(binding.project_name, "web");
1497        assert_eq!(note, None, "no remote to check against, so nothing to note");
1498
1499        let session_id = format!("project-switch-test-{}", uuid::Uuid::new_v4());
1500        let mut state = session_state::load(&session_id);
1501        state.active_project = Some(binding.clone());
1502        session_state::save(&session_id, &state).expect("save must succeed");
1503
1504        let sessions_dir = session_state::sessions_dir().expect("sessions dir must resolve");
1505        assert!(sessions_dir.starts_with(state_tmp.path()));
1506        let loaded = session_state::load_from(&sessions_dir, &session_id);
1507        assert_eq!(loaded.active_project, Some(binding));
1508    }
1509
1510    #[tokio::test]
1511    async fn project_switch_errors_when_name_not_found() {
1512        let list = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#;
1513        let base = spawn_once(http_200(list));
1514        let client = ApiClient::new(&base, Some("tok"));
1515
1516        let err = resolve_switch_project(
1517            "web",
1518            &client,
1519            CodebaseCheck::Skip,
1520            Path::new("/nonexistent"),
1521        )
1522        .await
1523        .expect_err("expected Err for an unknown project name");
1524        let msg = err.to_string();
1525        assert!(msg.contains("not found"), "got: {msg}");
1526        assert!(msg.contains("payments"), "got: {msg}");
1527    }
1528
1529    #[tokio::test]
1530    async fn project_switch_errors_when_project_does_not_contain_codebase() {
1531        let tmp = tempfile::tempdir().unwrap();
1532        crate::test_helpers::init_git_repo(tmp.path());
1533        let ok = std::process::Command::new("git")
1534            .args([
1535                "-C",
1536                &tmp.path().to_string_lossy(),
1537                "remote",
1538                "add",
1539                "origin",
1540                "git@github.com:org/repo.git",
1541            ])
1542            .status()
1543            .expect("git remote add failed")
1544            .success();
1545        assert!(ok, "git remote add must succeed");
1546
1547        let list =
1548            r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
1549        let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
1550        let remote = format!(
1551            r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
1552        );
1553        let codebase_repo_id = "55555555-5555-4555-8555-555555555555";
1554        let detail = format!(
1555            r#"{{"id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_url":"https://github.com/org/repo.git","clone_status":"ready","clone_error":null,"last_fetched_at":null,"repo_count":1,"created_at":"2026-01-01T00:00:00Z","repos":[{{"id":"{codebase_repo_id}","name":"repo"}}]}}"#
1556        );
1557        let project_detail = r#"{"repos":[{"id":"66666666-6666-4666-8666-666666666666"}]}"#;
1558        let base = spawn_n(vec![
1559            http_200(&list),
1560            http_200(&remote),
1561            http_200(&detail),
1562            http_200(project_detail),
1563        ]);
1564        let client = ApiClient::new(&base, Some("tok"));
1565
1566        let err = resolve_switch_project("payments", &client, CodebaseCheck::Enforce, tmp.path())
1567            .await
1568            .expect_err("expected Err: project doesn't contain the current codebase");
1569        assert!(
1570            err.to_string()
1571                .contains("does not contain the current codebase"),
1572            "got: {err}"
1573        );
1574    }
1575
1576    /// Copilot on PR #54: `--project-attribution explicit` was refused for
1577    /// exactly the projects it exists to bind. `check_codebase` was derived
1578    /// from the destination alone, so inside any instrumented session (the
1579    /// default whenever `TRACEVAULT_SESSION_ID` is set) `resolve_switch_project`
1580    /// errored on a project that does not contain this checkout — a repo
1581    /// deliberately shared by two projects, say. That contradicts the flag's
1582    /// own help text and the design, which puts the requirement on the
1583    /// SERVER at ingest.
1584    ///
1585    /// Same mock traffic as
1586    /// `project_switch_errors_when_project_does_not_contain_codebase` — the
1587    /// check genuinely runs and genuinely fails — but under
1588    /// `CodebaseCheck::Report` it must bind anyway AND say so, so a user who
1589    /// got here by typo still learns the fact.
1590    #[tokio::test]
1591    async fn explicit_attribution_binds_a_non_member_project_and_says_so() {
1592        let tmp = tempfile::tempdir().unwrap();
1593        crate::test_helpers::init_git_repo(tmp.path());
1594        let ok = std::process::Command::new("git")
1595            .args([
1596                "-C",
1597                &tmp.path().to_string_lossy(),
1598                "remote",
1599                "add",
1600                "origin",
1601                "git@github.com:org/repo.git",
1602            ])
1603            .status()
1604            .expect("git remote add failed")
1605            .success();
1606        assert!(ok, "git remote add must succeed");
1607
1608        let list =
1609            r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
1610        let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
1611        let remote = format!(
1612            r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
1613        );
1614        let codebase_repo_id = "55555555-5555-4555-8555-555555555555";
1615        let detail = format!(
1616            r#"{{"id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_url":"https://github.com/org/repo.git","clone_status":"ready","clone_error":null,"last_fetched_at":null,"repo_count":1,"created_at":"2026-01-01T00:00:00Z","repos":[{{"id":"{codebase_repo_id}","name":"repo"}}]}}"#
1617        );
1618        let project_detail = r#"{"repos":[{"id":"66666666-6666-4666-8666-666666666666"}]}"#;
1619        let base = spawn_n(vec![
1620            http_200(&list),
1621            http_200(&remote),
1622            http_200(&detail),
1623            http_200(project_detail),
1624        ]);
1625        let client = ApiClient::new(&base, Some("tok"));
1626
1627        let (binding, note) =
1628            resolve_switch_project("payments", &client, CodebaseCheck::Report, tmp.path())
1629                .await
1630                .expect("a forced switch must not be blocked by the containment check");
1631        assert_eq!(binding.project_id, "11111111-1111-4111-8111-111111111111");
1632
1633        let note = note.expect("the user must still be told the project is not a member");
1634        assert!(
1635            note.contains("does not contain the current codebase"),
1636            "the fact must be stated: {note}"
1637        );
1638        assert!(
1639            note.contains("--project-attribution explicit"),
1640            "must say what made it deliberate: {note}"
1641        );
1642        assert!(
1643            note.contains("Operator") && note.contains("ingest"),
1644            "must say where the requirement is actually enforced: {note}"
1645        );
1646
1647        // It reads as a note, not a refusal: the switch succeeded.
1648        assert!(
1649            !note.starts_with("error"),
1650            "this is informational, not a failure: {note}"
1651        );
1652    }
1653
1654    /// The other direction, and the reason `Report` is opt-in: without the
1655    /// flag an ordinary session switch still `Enforce`s, so a typo'd project
1656    /// name that happens to exist is caught exactly as before (the erroring
1657    /// half is `project_switch_errors_when_project_does_not_contain_codebase`).
1658    /// Calls the same [`codebase_check_for`] `switch` calls, so the mapping
1659    /// cannot drift away from this test.
1660    #[test]
1661    fn only_an_explicit_session_switch_downgrades_the_containment_check() {
1662        let session = SwitchDest::Session("s".into());
1663        assert_eq!(
1664            codebase_check_for(&session, true),
1665            CodebaseCheck::Report,
1666            "--project-attribution explicit must not be blocked"
1667        );
1668        assert_eq!(
1669            codebase_check_for(&session, false),
1670            CodebaseCheck::Enforce,
1671            "an ordinary session switch keeps erroring"
1672        );
1673        // The user-level default is not tied to a checkout either way.
1674        assert_eq!(
1675            codebase_check_for(&SwitchDest::UserDefault, true),
1676            CodebaseCheck::Skip
1677        );
1678        assert_eq!(
1679            codebase_check_for(&SwitchDest::UserDefault, false),
1680            CodebaseCheck::Skip
1681        );
1682    }
1683
1684    /// Regression for C2: a no-session, non-`--user` `switch` resolves to
1685    /// `SwitchDest::UserDefault` (mirroring `switch_destination`'s
1686    /// no-session fallback), so the codebase-containment check must be
1687    /// skipped even though `--user` wasn't passed. `cwd` has a git origin
1688    /// remote, but `check_codebase` being correctly derived from the
1689    /// destination (not from `!user`) means `resolve_switch_project` never
1690    /// calls out to `resolve_remote`/`get_project` to check it — the mock
1691    /// server below only ever answers one request (`list_projects`). If the
1692    /// gating regressed back to `!user`, the second HTTP call this test
1693    /// deliberately can't serve (mirrors `spawn_once`'s one-shot listener,
1694    /// which closes after the first `accept()`) would fail fast, and the
1695    /// switch would error instead of succeeding.
1696    ///
1697    /// Credentials are supplied two ways at once: a `.visdom/tracing.toml`
1698    /// in `cwd`, and `TRACEVAULT_SERVER_URL`/`_API_KEY` env vars pinned (via
1699    /// the guard below) at the same mock server/values. The env vars sit
1700    /// above the config file in `resolve_credentials`'s precedence, so
1701    /// without pinning them explicitly, an ambient shell that already
1702    /// exports `TRACEVAULT_SERVER_URL` (etc.) would leak in and point this
1703    /// test's client at the wrong server — deterministic in CI (which
1704    /// doesn't set them) but flaky on a developer machine that has them
1705    /// exported. The guard's `set` calls make the test's behavior
1706    /// independent of the ambient environment. `_env_lock` (taken below)
1707    /// also serializes this against `status_reports_ambiguous_deduction_as_
1708    /// informational_not_fatal`, which touches the same vars.
1709    /// `XDG_CONFIG_HOME` is redirected so this doesn't read the developer's
1710    /// real `credentials.json` (which could otherwise short-circuit
1711    /// `resolve_credentials` before the config file/env vars are consulted,
1712    /// and race for real on a machine with actual Visdom credentials)
1713    /// and so the resulting user-default write lands in a tempdir, not
1714    /// `~/.config`. `user_project_default`'s own real-path round-trip test
1715    /// mutates the same var, so both hold `test_helpers::lock_env_mutation()`
1716    /// for their duration.
1717    #[tokio::test]
1718    async fn switch_without_session_or_user_flag_skips_codebase_check() {
1719        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1720        let tmp = tempfile::tempdir().unwrap();
1721        crate::test_helpers::init_git_repo(tmp.path());
1722        let ok = std::process::Command::new("git")
1723            .args([
1724                "-C",
1725                &tmp.path().to_string_lossy(),
1726                "remote",
1727                "add",
1728                "origin",
1729                "git@github.com:org/repo.git",
1730            ])
1731            .status()
1732            .expect("git remote add failed")
1733            .success();
1734        assert!(ok, "git remote add must succeed");
1735
1736        let list =
1737            r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
1738        let base = spawn_once(http_200(&list));
1739
1740        let config_dir = tmp.path().join(".visdom");
1741        std::fs::create_dir_all(&config_dir).unwrap();
1742        std::fs::write(
1743            config_dir.join("tracing.toml"),
1744            format!("agent = \"claude-code\"\nserver_url = \"{base}\"\napi_key = \"tok\"\n"),
1745        )
1746        .unwrap();
1747
1748        // SAFETY: test-scoped env mutation, restored in a guard so a panic
1749        // in `switch` still cleans up the process env. `_env_lock` (taken
1750        // above) also covers `resolve_credentials`'s *reads* of
1751        // TRACEVAULT_SERVER_URL/_API_KEY: those env vars sit above
1752        // `.visdom/tracing.toml` in precedence, so if the developer's
1753        // ambient shell happens to already export them (e.g. pointing at a
1754        // real server), `resolve_credentials` would pick those up instead of
1755        // this test's config file and the request would go to the wrong
1756        // place — deterministic in CI (which doesn't set them) but flaky
1757        // locally. Pin them explicitly at this test's own mock server so
1758        // behavior doesn't depend on the ambient environment, mirroring the
1759        // precedent in `status_reports_ambiguous_deduction_as_informational_
1760        // not_fatal`. `_env_lock` (taken above) also serializes this against
1761        // that test and any other test in the crate touching the same vars.
1762        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1763        _guard.remove("TRACEVAULT_SESSION_ID");
1764        _guard.remove("AMP_CURRENT_THREAD_ID");
1765        _guard.set("XDG_CONFIG_HOME", tmp.path());
1766        _guard.set("TRACEVAULT_SERVER_URL", &base);
1767        _guard.set("TRACEVAULT_API_KEY", "tok");
1768
1769        let result = switch("payments", false, None, "derived", tmp.path(), tmp.path()).await;
1770        assert!(
1771            result.is_ok(),
1772            "expected a no-session, non-`--user` switch to skip the codebase check: {result:?}"
1773        );
1774
1775        let saved = crate::user_project_default::load();
1776        assert_eq!(
1777            saved.map(|b| b.project_name),
1778            Some("payments".to_string()),
1779            "no-session switch must fall back to the user-level default binding"
1780        );
1781    }
1782
1783    fn items() -> Vec<ProjectListItem> {
1784        vec![
1785            ProjectListItem {
1786                id: uuid::Uuid::from_u128(1),
1787                name: "payments".into(),
1788            },
1789            ProjectListItem {
1790                id: uuid::Uuid::from_u128(2),
1791                name: "web".into(),
1792            },
1793        ]
1794    }
1795
1796    /// A nameless binding at a given tier. The UUID form of
1797    /// `TRACEVAULT_PROJECT` is the one such tier that can be EFFECTIVE (the
1798    /// capture path parses the id locally and never looks the name up);
1799    /// `Deduced` is nameless too, but only ever reaches the separate
1800    /// deduction line, which has [`deduced_project_name`] of its own.
1801    fn nameless(id: uuid::Uuid, source: ProjectSource) -> (ProjectBinding, ProjectSource) {
1802        (
1803            ProjectBinding {
1804                project_id: id.to_string(),
1805                project_name: String::new(),
1806                updated_at: "".into(),
1807                forced_until: None,
1808            },
1809            source,
1810        )
1811    }
1812
1813    /// Small finding 8: the UUID form of `TRACEVAULT_PROJECT` never goes
1814    /// through a name lookup, so its binding arrives nameless and the
1815    /// operator would see a bare UUID on the effective line.
1816    #[test]
1817    fn enrich_project_name_fills_in_name_when_id_found_in_list() {
1818        let effective = Some(nameless(uuid::Uuid::from_u128(2), ProjectSource::Env));
1819        let (b, source) = enrich_project_name(effective, Some(&items())).unwrap();
1820        assert_eq!(b.project_name, "web");
1821        assert_eq!(source, ProjectSource::Env);
1822    }
1823
1824    #[test]
1825    fn enrich_project_name_leaves_empty_when_no_list_available() {
1826        let effective = Some(nameless(uuid::Uuid::from_u128(2), ProjectSource::Env));
1827        let (b, _source) = enrich_project_name(effective, None).unwrap();
1828        assert_eq!(b.project_name, "");
1829    }
1830
1831    #[test]
1832    fn enrich_project_name_leaves_empty_when_id_not_in_list() {
1833        let effective = Some(nameless(uuid::Uuid::from_u128(999), ProjectSource::Env));
1834        let (b, _source) = enrich_project_name(effective, Some(&items())).unwrap();
1835        assert_eq!(b.project_name, "");
1836    }
1837
1838    #[test]
1839    fn enrich_project_name_leaves_a_populated_name_untouched() {
1840        // A binding that already has a friendly name must pass through
1841        // unchanged, whatever its tier — enrichment repairs an EMPTY name
1842        // and nothing else.
1843        let b = pb("payments");
1844        let effective = Some((b.clone(), ProjectSource::SessionActive));
1845        let (out, source) = enrich_project_name(effective, Some(&items())).unwrap();
1846        assert_eq!(out, b);
1847        assert_eq!(source, ProjectSource::SessionActive);
1848    }
1849
1850    #[test]
1851    fn enrich_project_name_passes_through_none() {
1852        assert!(enrich_project_name(None, Some(&items())).is_none());
1853    }
1854
1855    /// VIS-316 pin: the project `project status` reports as effective is the
1856    /// project ingest attributes events to. For each configuration, the id
1857    /// `status` would treat as effective (`status_effective`, the function
1858    /// `status` itself calls, including its non-UUID drop rule) must equal `commands::stream::capture_project`. Both sides read
1859    /// the user default through `user_project_default::load()`, from a
1860    /// `user_project.toml` written under a temp config dir (`XDG_CONFIG_HOME`
1861    /// on Linux, `HOME` for macOS's `dirs::config_dir()`), with the env lock
1862    /// held for the whole test. Each case also asserts the expected id, so
1863    /// the equality can't pass vacuously with both sides `None`.
1864    #[tokio::test]
1865    async fn project_status_effective_project_matches_capture_project() {
1866        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1867        let tmp = tempfile::tempdir().unwrap();
1868        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1869        _guard.set("XDG_CONFIG_HOME", tmp.path());
1870        _guard.set("HOME", tmp.path());
1871
1872        let u = uuid::Uuid::from_u128;
1873        let bind = |id: String| ProjectBinding {
1874            project_id: id,
1875            project_name: "n".into(),
1876            updated_at: "".into(),
1877            forced_until: None,
1878        };
1879        let worktree = "/wt";
1880        let subagent_session = {
1881            let mut s = SessionState {
1882                active_project: Some(bind(u(2).to_string())),
1883                ..Default::default()
1884            };
1885            s.subagent_projects
1886                .insert(worktree.into(), bind(u(1).to_string()));
1887            s
1888        };
1889        let active_session = SessionState {
1890            active_project: Some(bind(u(2).to_string())),
1891            ..Default::default()
1892        };
1893        let bad_active_session = SessionState {
1894            active_project: Some(bind("not-a-uuid".into())),
1895            ..Default::default()
1896        };
1897
1898        // (label, session, user default written to user_project.toml,
1899        //  TRACEVAULT_PROJECT, expected id)
1900        type Case = (
1901            &'static str,
1902            SessionState,
1903            Option<String>,
1904            Option<String>,
1905            Option<uuid::Uuid>,
1906        );
1907        let cases: Vec<Case> = vec![
1908            (
1909                "(a) subagent override + session active + user default",
1910                subagent_session,
1911                Some(u(3).to_string()),
1912                None,
1913                Some(u(1)),
1914            ),
1915            (
1916                "(b) session active + user default",
1917                active_session.clone(),
1918                Some(u(3).to_string()),
1919                None,
1920                Some(u(2)),
1921            ),
1922            (
1923                "(c) user default only",
1924                SessionState::default(),
1925                Some(u(3).to_string()),
1926                None,
1927                Some(u(3)),
1928            ),
1929            ("(d) nothing", SessionState::default(), None, None, None),
1930            (
1931                "(e) user default with a non-UUID project_id",
1932                SessionState::default(),
1933                Some("not-a-uuid".into()),
1934                None,
1935                None,
1936            ),
1937            (
1938                "(f) non-UUID session active shadows a valid user default",
1939                bad_active_session,
1940                Some(u(3).to_string()),
1941                None,
1942                None,
1943            ),
1944            // The `Env` rung is part of the SAME shared chain, so it has to
1945            // be covered here too or `status` and ingest could drift on it.
1946            (
1947                "(g) TRACEVAULT_PROJECT (UUID) outranks session active and the user default",
1948                active_session.clone(),
1949                Some(u(3).to_string()),
1950                Some(u(4).to_string()),
1951                Some(u(4)),
1952            ),
1953            // A NAME in TRACEVAULT_PROJECT is not a tier on either side:
1954            // both must fall through to the session's active binding.
1955            (
1956                "(h) TRACEVAULT_PROJECT (NAME) is ignored by both",
1957                active_session,
1958                Some(u(3).to_string()),
1959                Some("payments".into()),
1960                Some(u(2)),
1961            ),
1962        ];
1963        // The workspace `.visdom/tracing.toml` `project_id` tier
1964        // (VIS-1256): same shared chain, so it is pinned here too. Each case
1965        // adds the config's `project_id` as a sixth column.
1966        let session_active = || SessionState {
1967            active_project: Some(bind(u(2).to_string())),
1968            ..Default::default()
1969        };
1970        // (label, session, user default, TRACEVAULT_PROJECT, workspace
1971        //  config project_id, expected id)
1972        type WorkspaceCase = (
1973            &'static str,
1974            SessionState,
1975            Option<String>,
1976            Option<String>,
1977            Option<String>,
1978            Option<uuid::Uuid>,
1979        );
1980        let workspace_cases: Vec<WorkspaceCase> = vec![
1981            (
1982                "(i) workspace config outranks the user default",
1983                SessionState::default(),
1984                Some(u(3).to_string()),
1985                None,
1986                Some(u(5).to_string()),
1987                Some(u(5)),
1988            ),
1989            (
1990                "(j) session active (project switch) outranks the workspace config",
1991                session_active(),
1992                Some(u(3).to_string()),
1993                None,
1994                Some(u(5).to_string()),
1995                Some(u(2)),
1996            ),
1997            (
1998                "(k) TRACEVAULT_PROJECT (UUID) outranks the workspace config",
1999                SessionState::default(),
2000                None,
2001                Some(u(4).to_string()),
2002                Some(u(5).to_string()),
2003                Some(u(4)),
2004            ),
2005            (
2006                "(l) a non-UUID workspace project_id is dropped by both, shadowing the user default",
2007                SessionState::default(),
2008                Some(u(3).to_string()),
2009                None,
2010                Some("not-a-uuid".into()),
2011                None,
2012            ),
2013        ];
2014        let cases = cases
2015            .into_iter()
2016            .map(|(label, session, user, env, expected)| {
2017                (label, session, user, env, None, expected)
2018            })
2019            .chain(workspace_cases);
2020
2021        for (label, session, user_default, env_project, config_project, expected) in cases {
2022            match &user_default {
2023                Some(id) => crate::user_project_default::save(&bind(id.clone())).unwrap(),
2024                None => crate::user_project_default::clear().unwrap(),
2025            }
2026            match &env_project {
2027                Some(v) => _guard.set("TRACEVAULT_PROJECT", v),
2028                None => _guard.remove("TRACEVAULT_PROJECT"),
2029            }
2030            // Read the way both callers read it: through `project_from_config`.
2031            let config_project = config_project.and_then(|id| {
2032                crate::resolution::project_from_config(&crate::config::TracevaultConfig {
2033                    project_id: Some(id),
2034                    ..Default::default()
2035                })
2036            });
2037            let status_pid = status_effective(
2038                None,
2039                crate::commands::stream::env_project_binding(),
2040                &session,
2041                Some(worktree),
2042                config_project.clone(),
2043                crate::user_project_default::load(),
2044            )
2045            .0
2046            .and_then(|(b, _)| capture_project_id(&b));
2047            let ingest_pid =
2048                crate::commands::stream::capture_project(&session, Some(worktree), config_project);
2049            assert_eq!(
2050                status_pid, ingest_pid,
2051                "{label}: status and ingest disagree"
2052            );
2053            assert_eq!(status_pid, expected, "{label}");
2054        }
2055        crate::user_project_default::clear().unwrap();
2056    }
2057
2058    /// F1: `status` returns `Ok` when the `/projects/resolve` deduction
2059    /// answers 409 (ambiguous) — the deduction is informational, never fatal.
2060    #[tokio::test]
2061    async fn status_reports_ambiguous_deduction_as_informational_not_fatal() {
2062        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2063        let tmp = tempfile::tempdir().unwrap();
2064        crate::test_helpers::init_git_repo(tmp.path());
2065        let ok = std::process::Command::new("git")
2066            .args([
2067                "-C",
2068                &tmp.path().to_string_lossy(),
2069                "remote",
2070                "add",
2071                "origin",
2072                "git@github.com:org/repo.git",
2073            ])
2074            .status()
2075            .expect("git remote add failed")
2076            .success();
2077        assert!(ok, "git remote add must succeed");
2078
2079        // One 409 for `status`, one for `status_report`.
2080        let conflict = "HTTP/1.1 409 Conflict\r\nContent-Type: application/json\r\nContent-Length: 20\r\nConnection: close\r\n\r\n{\"error\":\"multiple\"}";
2081        let base = spawn_n(vec![conflict.to_string(), conflict.to_string()]);
2082
2083        // Env mutation under `_env_lock`, restored by the guard even if
2084        // `status` panics. The config dir (and so any user default) is
2085        // isolated to the tempdir, and no ambient session id leaks in.
2086        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2087        _guard.set("TRACEVAULT_SERVER_URL", &base);
2088        _guard.set("TRACEVAULT_API_KEY", "tok");
2089        _guard.set("XDG_CONFIG_HOME", tmp.path());
2090        _guard.set("HOME", tmp.path());
2091        _guard.remove("TRACEVAULT_SESSION_ID");
2092        _guard.remove("AMP_CURRENT_THREAD_ID");
2093        // `status_effective` takes `TRACEVAULT_PROJECT` at a rung ABOVE the
2094        // "nothing is bound" state this test asserts, and an env-sourced
2095        // binding also triggers an extra `list_projects` call this mock does
2096        // not stage — an ambient export would make the test fail, or pass,
2097        // for the wrong reason.
2098        _guard.remove("TRACEVAULT_PROJECT");
2099        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2100
2101        let result = status(None, None, tmp.path(), tmp.path()).await;
2102        assert!(
2103            result.is_ok(),
2104            "status must degrade gracefully on an ambiguous deduction, not propagate the error: {result:?}"
2105        );
2106
2107        let report = status_report(None, None, tmp.path(), tmp.path()).await;
2108        assert_eq!(
2109            report.lines,
2110            vec![
2111                format_status(None),
2112                crate::commands::stream::recording_line(None),
2113                format_deduction(false, Ok(ResolveProjectOutcome::Ambiguous), None),
2114            ],
2115            "the ambiguous deduction is reported on its own line"
2116        );
2117    }
2118
2119    /// VIS-316 orchestrator configuration: the container sets a machine-wide
2120    /// user default B before the session exists, the session itself binds
2121    /// nothing, and the server would deduce A from the git remote. `status`
2122    /// must name B (what ingest uses) as effective, and show A only as an
2123    /// unused deduction.
2124    #[tokio::test]
2125    async fn status_in_the_orchestrator_configuration_names_the_user_default() {
2126        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2127        let tmp = tempfile::tempdir().unwrap();
2128        let repo = tmp.path().join("repo");
2129        std::fs::create_dir_all(&repo).unwrap();
2130        crate::test_helpers::init_git_repo(&repo);
2131        let ok = std::process::Command::new("git")
2132            .args([
2133                "-C",
2134                &repo.to_string_lossy(),
2135                "remote",
2136                "add",
2137                "origin",
2138                "git@github.com:org/repo.git",
2139            ])
2140            .status()
2141            .expect("git remote add failed")
2142            .success();
2143        assert!(ok, "git remote add must succeed");
2144
2145        let deduced_a = uuid::Uuid::from_u128(0xA);
2146        let base = spawn_once(http_200(&format!(r#"{{"project_id":"{deduced_a}"}}"#)));
2147
2148        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2149        _guard.set("TRACEVAULT_SERVER_URL", &base);
2150        _guard.set("TRACEVAULT_API_KEY", "tok");
2151        _guard.set("XDG_CONFIG_HOME", tmp.path());
2152        _guard.set("HOME", tmp.path());
2153        _guard.set("XDG_STATE_HOME", tmp.path().join("state"));
2154        _guard.remove("TRACEVAULT_SESSION_ID");
2155        _guard.remove("AMP_CURRENT_THREAD_ID");
2156        // Both would change which project is effective / which mode is
2157        // reported, and the env binding would also trigger a `list_projects`
2158        // call this one-shot mock does not stage.
2159        _guard.remove("TRACEVAULT_PROJECT");
2160        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2161
2162        let default_b = ProjectBinding {
2163            project_id: uuid::Uuid::from_u128(0xB).to_string(),
2164            project_name: "project-b".into(),
2165            updated_at: "".into(),
2166            forced_until: None,
2167        };
2168        crate::user_project_default::save(&default_b).unwrap();
2169
2170        let report = status_report(None, None, &repo, &repo).await;
2171
2172        assert_eq!(
2173            report.lines,
2174            vec![
2175                "project: project-b via user default (project switch --user)".to_string(),
2176                "attribution mode: derived (Visdom checks repo/project membership)"
2177                    .to_string(),
2178                // No repo binds this checkout (no config, no session), so
2179                // ingest sends repo-less to B — and status says so (VIS-1255).
2180                crate::commands::stream::recording_line(Some(
2181                    &crate::commands::stream::Attribution::ProjectOnly {
2182                        project_id: uuid::Uuid::from_u128(0xB),
2183                    }
2184                )),
2185                format!(
2186                    "server deduction for this repo: {deduced_a} (not used: the local binding above wins)"
2187                ),
2188            ]
2189        );
2190    }
2191
2192    /// A3, UUID form, through the whole report: `TRACEVAULT_PROJECT` set to
2193    /// a UUID resolves at the `Env` rung, and the one `list_projects` call
2194    /// the env binding triggers is used to put its friendly name on the line
2195    /// (small finding 8 — otherwise a bare UUID is printed). `spawn_once`'s
2196    /// listener only ever answers one request, so a regression that fell
2197    /// through to the `/projects/resolve` deduction would fail on the
2198    /// missing listener as well as on the line itself.
2199    #[tokio::test]
2200    async fn status_reports_env_uuid_as_the_effective_tier_with_its_name() {
2201        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2202        let tmp = tempfile::tempdir().unwrap();
2203
2204        let uuid = "11111111-1111-4111-8111-111111111111";
2205        let list = format!(r#"[{{"id":"{uuid}","name":"payments"}}]"#);
2206        let base = spawn_once(http_200(&list));
2207
2208        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2209        _guard.set("XDG_CONFIG_HOME", tmp.path());
2210        _guard.set("HOME", tmp.path());
2211        _guard.set("TRACEVAULT_SERVER_URL", &base);
2212        _guard.set("TRACEVAULT_API_KEY", "tok");
2213        _guard.set("TRACEVAULT_PROJECT", uuid);
2214        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2215        _guard.remove("TRACEVAULT_SESSION_ID");
2216        _guard.remove("AMP_CURRENT_THREAD_ID");
2217
2218        let report = status_report(None, None, tmp.path(), tmp.path()).await;
2219        assert_eq!(
2220            report.lines[0], "project: payments via TRACEVAULT_PROJECT (environment)",
2221            "got: {:?}",
2222            report.lines
2223        );
2224        assert!(
2225            report
2226                .warnings
2227                .iter()
2228                .all(|w| !w.contains("TRACEVAULT_PROJECT")),
2229            "the UUID form is honoured at capture time and needs no caveat: {:?}",
2230            report.warnings
2231        );
2232    }
2233
2234    /// A3, name form: unlike our earlier design, `status` does NOT resolve a
2235    /// NAME in `TRACEVAULT_PROJECT` into the chain. VIS-316's rule is that
2236    /// `project status` reports what ingest does, and the capture path is
2237    /// UUID-only (a name would need a per-event `list_projects`), so a
2238    /// resolved name would be a project no event is attributed to. The value
2239    /// is reported as an ignored tier instead, and the session's own binding
2240    /// stays effective.
2241    #[tokio::test]
2242    async fn status_warns_that_an_env_name_is_not_used_and_falls_through() {
2243        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2244        let tmp = tempfile::tempdir().unwrap();
2245
2246        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2247        _guard.set("XDG_CONFIG_HOME", tmp.path());
2248        _guard.set("HOME", tmp.path());
2249        _guard.set("XDG_STATE_HOME", tmp.path().join("state"));
2250        _guard.remove("TRACEVAULT_SERVER_URL");
2251        _guard.remove("TRACEVAULT_API_KEY");
2252        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2253        _guard.set("TRACEVAULT_PROJECT", "payments");
2254
2255        let session_id = "vis305-env-name-form";
2256        let pid = uuid::Uuid::from_u128(0x5E);
2257        crate::session_state::save(
2258            session_id,
2259            &SessionState {
2260                active_project: Some(ProjectBinding {
2261                    project_id: pid.to_string(),
2262                    project_name: "session-project".into(),
2263                    updated_at: "".into(),
2264                    forced_until: None,
2265                }),
2266                ..Default::default()
2267            },
2268        )
2269        .unwrap();
2270
2271        let report = status_report(Some(session_id), None, tmp.path(), tmp.path()).await;
2272        assert_eq!(
2273            report.lines[0], "project: session-project via session (project switch)",
2274            "a NAME must not become the effective tier: {:?}",
2275            report.lines
2276        );
2277        assert!(
2278            report
2279                .warnings
2280                .iter()
2281                .any(|w| w.contains("TRACEVAULT_PROJECT") && w.contains("UUID form")),
2282            "the ignored NAME must be explained: {:?}",
2283            report.warnings
2284        );
2285    }
2286
2287    /// A3, item 3: with credentials unresolved (no client at all — the `Err`
2288    /// arm of `resolve_client`), `status` must still honour the UUID form of
2289    /// `TRACEVAULT_PROJECT`, which needs no server call. The friendly name
2290    /// is simply unavailable, so the id is printed.
2291    #[tokio::test]
2292    async fn status_reports_env_uuid_even_without_a_client() {
2293        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2294        let tmp = tempfile::tempdir().unwrap();
2295
2296        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2297        _guard.set("XDG_CONFIG_HOME", tmp.path());
2298        _guard.set("HOME", tmp.path());
2299        _guard.remove("TRACEVAULT_SERVER_URL");
2300        _guard.remove("TRACEVAULT_API_KEY");
2301        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2302        let uuid = "33333333-3333-4333-8333-333333333333";
2303        _guard.set("TRACEVAULT_PROJECT", uuid);
2304
2305        let report = status_report(None, None, tmp.path(), tmp.path()).await;
2306        assert_eq!(
2307            report.lines[0],
2308            format!("project: {uuid} via TRACEVAULT_PROJECT (environment)"),
2309            "got: {:?}",
2310            report.lines
2311        );
2312    }
2313
2314    /// VIS-305 Part C review, small finding 3: `project status` must report
2315    /// the EFFECTIVE attribution mode, not just the winning binding's own
2316    /// `forced_until`. `TRACEVAULT_PROJECT_ATTRIBUTION=explicit` drives
2317    /// `explicit` on its own, with no persisted force anywhere — a status
2318    /// line built from `format_force_line` alone would show "derived" here,
2319    /// which is exactly the lie item 3 flags: every hook in this shell is
2320    /// actually sending `explicit`.
2321    #[tokio::test]
2322    async fn status_reports_explicit_via_env_even_when_the_binding_itself_is_not_forced() {
2323        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2324        let tmp = tempfile::tempdir().unwrap();
2325
2326        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2327        _guard.set("XDG_CONFIG_HOME", tmp.path());
2328        _guard.set("HOME", tmp.path());
2329        _guard.remove("TRACEVAULT_SERVER_URL");
2330        _guard.remove("TRACEVAULT_API_KEY");
2331        let uuid = "44444444-4444-4444-8444-444444444444";
2332        _guard.set("TRACEVAULT_PROJECT", uuid);
2333        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2334
2335        let report = status_report(None, None, tmp.path(), tmp.path()).await;
2336        assert_eq!(
2337            report.lines,
2338            vec![
2339                format!("project: {uuid} via TRACEVAULT_PROJECT (environment)"),
2340                "attribution mode: explicit (this caller owns attribution; membership is not checked)".to_string(),
2341                crate::commands::stream::recording_line(Some(
2342                    &crate::commands::stream::Attribution::ProjectOnly {
2343                        project_id: uuid::Uuid::parse_str(uuid).unwrap(),
2344                    }
2345                )),
2346            ],
2347            "the EFFECTIVE mode must reflect TRACEVAULT_PROJECT_ATTRIBUTION even when \
2348             the winning binding has no force of its own, and the lapse line must NOT \
2349             appear (there is no persisted force to lapse)"
2350        );
2351    }
2352}