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