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