diff --git a/cli/src/cli_schema.rs b/cli/src/cli_schema.rs index c5348c670..93627f5b1 100644 --- a/cli/src/cli_schema.rs +++ b/cli/src/cli_schema.rs @@ -199,6 +199,12 @@ pub enum Commands { /// Install an optional workflow by slug; repeat for several (default: none) #[arg(long = "workflow", value_name = "SLUG")] workflow: Vec, + + #[arg( + long, + help = "Ask every saved setup answer again, using the saved values as defaults (interactive only)" + )] + reconfigure: bool, }, #[command(about = DOCTOR_CLAP_ABOUT, hide = !DOCTOR_SHOW_IN_TOP_LEVEL_HELP)] diff --git a/cli/src/services/auth_command/mod.rs b/cli/src/services/auth_command/mod.rs index adcd58a98..48e33741c 100644 --- a/cli/src/services/auth_command/mod.rs +++ b/cli/src/services/auth_command/mod.rs @@ -58,6 +58,12 @@ impl TelemetryProvisioningResult { } } +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct LoginReport { + pub(crate) rendered: String, + pub(crate) telemetry: TelemetryProvisioningResult, +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum AuthSubcommand { Login { format: AuthFormat }, @@ -149,16 +155,57 @@ where if !telemetry_enabled || destination_conflict { return Err(telemetry_headers_unavailable()); } - let Some(working_dir) = working_dir.filter(|_| auth_db_probe()) else { + let Some(working_dir) = working_dir else { return Err(telemetry_headers_unavailable()); }; - let credential = run_with_deadline(CREDENTIAL_LOOKUP_DEADLINE, async move { + let credential = authorized_repository_credential_with( + working_dir, + auth_db_probe, + resolve_repository, + lookup, + ) + .await; + render_telemetry_headers(Ok(credential)) +} + +pub(crate) async fn repository_telemetry_authorized(repository_root: &Path) -> bool { + authorized_repository_credential_with( + repository_root.to_path_buf(), + managed_telemetry::auth_db_present, + repository_id_for, + telemetry_credential_storage::load_repository_telemetry_credential, + ) + .await + .is_some() +} + +pub(crate) async fn authorized_repository_credential_with( + working_dir: PathBuf, + auth_db_probe: P, + resolve_repository: R, + lookup: L, +) -> Option +where + P: FnOnce() -> bool, + R: FnOnce(&Path) -> Option + Send + 'static, + L: FnOnce(String) -> Fut + Send + 'static, + Fut: Future< + Output = Result< + Option, + TokenStorageError, + >, + > + Send + + 'static, +{ + if !auth_db_probe() { + return None; + } + run_with_deadline(CREDENTIAL_LOOKUP_DEADLINE, async move { let repository_id = resolve_repository(&working_dir)?; lookup(repository_id).await.ok().flatten() }) .await - .flatten(); - render_telemetry_headers(Ok(credential)) + .flatten() } pub(crate) fn render_telemetry_headers( @@ -178,11 +225,18 @@ fn telemetry_headers_unavailable() -> CliError { CliError::runtime(anyhow!(TELEMETRY_HEADERS_UNAVAILABLE)) } -fn resolve_current_auth_config() -> Result { - let cwd = std::env::current_dir() +fn current_auth_working_dir() -> Result { + std::env::current_dir() .context("failed to determine current directory for auth config resolution") - .map_err(unexpected_auth_command_error)?; - config::resolve_auth_runtime_config(&cwd).map_err(unexpected_auth_command_error) + .map_err(unexpected_auth_command_error) +} + +fn resolve_current_auth_config() -> Result { + resolve_auth_config_in(¤t_auth_working_dir()?) +} + +fn resolve_auth_config_in(working_dir: &Path) -> Result { + config::resolve_auth_runtime_config(working_dir).map_err(unexpected_auth_command_error) } fn ensure_auth_allowed(policy: &ResolvedAccessPolicy) -> Result<(), CliError> { @@ -199,8 +253,18 @@ fn ensure_auth_allowed(policy: &ResolvedAccessPolicy) -> Result<(), CliError> { } pub async fn run_login(format: AuthFormat) -> Result { + let working_dir = current_auth_working_dir()?; + run_login_in(&working_dir, format) + .await + .map(|report| report.rendered) +} + +pub(crate) async fn run_login_in( + working_dir: &Path, + format: AuthFormat, +) -> Result { let client = reqwest::Client::new(); - let auth_config = resolve_current_auth_config()?; + let auth_config = resolve_auth_config_in(working_dir)?; let client_id = auth_config.workos_client_id.value.unwrap_or_default(); let control_plane = AuthenticatedControlPlaneClient::new( client.clone(), @@ -221,15 +285,29 @@ pub async fn run_login(format: AuthFormat) -> Result { |stored_tokens| async move { maybe_renew_stored_credentials(client, client_id, stored_tokens).await }, - || async move { provision_telemetry_credential(control_plane).await }, + || async move { provision_telemetry_credential(control_plane, working_dir).await }, |format| async move { match format { AuthFormat::Text => { - run_text_login(client, client_id, control_plane, telemetry_enabled).await + run_text_login( + client, + client_id, + control_plane, + working_dir, + telemetry_enabled, + ) + .await } AuthFormat::Json => { - run_login_json(client, client_id, format, control_plane, telemetry_enabled) - .await + run_login_json( + client, + client_id, + format, + control_plane, + working_dir, + telemetry_enabled, + ) + .await } } }, @@ -244,7 +322,7 @@ async fn run_login_with( renew: R, provision: P, device_login: D, -) -> Result +) -> Result where T: FnOnce() -> TF, TF: Future, TokenStorageError>>, @@ -253,7 +331,7 @@ where P: FnOnce() -> PF, PF: Future, D: FnOnce(AuthFormat) -> DF, - DF: Future>, + DF: Future>, { ensure_auth_allowed(policy)?; let stored_tokens = load_tokens().await.map_err(login_storage_error)?; @@ -370,20 +448,25 @@ async fn run_login_with_stored_credentials( renew: R, provision: P, device_login: D, -) -> Result +) -> Result where R: FnOnce(StoredTokens) -> RF, RF: Future, CliError>>, P: FnOnce() -> PF, PF: Future, D: FnOnce(AuthFormat) -> DF, - DF: Future>, + DF: Future>, { if let Some(stored_tokens) = stored_tokens { if let Some(renewed_tokens) = renew(stored_tokens).await? { let telemetry = provision().await; - return render_login_refresh_result_with_telemetry(&renewed_tokens, format, telemetry) - .map_err(unexpected_auth_command_error); + let rendered = + render_login_refresh_result_with_telemetry(&renewed_tokens, format, telemetry) + .map_err(unexpected_auth_command_error)?; + return Ok(LoginReport { + rendered, + telemetry, + }); } } @@ -427,34 +510,47 @@ where async fn provision_telemetry_credential( client: &AuthenticatedControlPlaneClient, + working_dir: &Path, ) -> TelemetryProvisioningResult { if client.issue_and_save_telemetry_credential().await.is_err() { return TelemetryProvisioningResult::Unavailable; } - enroll_current_repository_if_unbound().await; + enroll_repository_if_unbound(working_dir).await; TelemetryProvisioningResult::Issued } -async fn enroll_current_repository_if_unbound() { - let Some(repository_id) = std::env::current_dir() - .ok() - .and_then(|working_dir| repository_id_for(&working_dir)) - else { +async fn enroll_repository_if_unbound(working_dir: &Path) { + enroll_repository_if_unbound_with(working_dir, repository_id_for, |repository_id| { + telemetry_credential_storage::bind_repository_telemetry( + repository_id, + telemetry_credential_storage::RepositoryBindingMode::EnrollIfUnbound, + ) + }) + .await; +} + +async fn enroll_repository_if_unbound_with( + working_dir: &Path, + repository_id_for: I, + bind: B, +) where + I: FnOnce(&Path) -> Option, + B: FnOnce(String) -> BF, + BF: Future>, +{ + let Some(repository_id) = repository_id_for(working_dir) else { return; }; - let _ = telemetry_credential_storage::bind_repository_telemetry( - repository_id, - telemetry_credential_storage::RepositoryBindingMode::EnrollIfUnbound, - ) - .await; + let _ = bind(repository_id).await; } async fn run_text_login( client: &reqwest::Client, client_id: &str, control_plane: &AuthenticatedControlPlaneClient, + working_dir: &Path, telemetry_enabled: bool, -) -> Result { +) -> Result { let authorization = auth::request_device_authorization(client, auth::WORKOS_DEFAULT_BASE_URL, client_id) .await @@ -474,10 +570,10 @@ async fn run_text_login( let stored_tokens = save_new_session_tokens(&token).await?; let telemetry = provision_if_enabled(telemetry_enabled, || { - provision_telemetry_credential(control_plane) + provision_telemetry_credential(control_plane, working_dir) }) .await; - render_login_result_with_telemetry( + let rendered = render_login_result_with_telemetry( &DeviceAuthFlowResult { authorization, stored_tokens, @@ -485,7 +581,11 @@ async fn run_text_login( AuthFormat::Text, telemetry, ) - .map_err(unexpected_auth_command_error) + .map_err(unexpected_auth_command_error)?; + Ok(LoginReport { + rendered, + telemetry, + }) } async fn run_login_json( @@ -493,8 +593,9 @@ async fn run_login_json( client_id: &str, format: AuthFormat, control_plane: &AuthenticatedControlPlaneClient, + working_dir: &Path, telemetry_enabled: bool, -) -> Result { +) -> Result { let authorization = auth::request_device_authorization(client, auth::WORKOS_DEFAULT_BASE_URL, client_id) .await @@ -512,10 +613,10 @@ async fn run_login_json( let stored_tokens = save_new_session_tokens(&token).await?; let telemetry = provision_if_enabled(telemetry_enabled, || { - provision_telemetry_credential(control_plane) + provision_telemetry_credential(control_plane, working_dir) }) .await; - render_login_result_with_telemetry( + let rendered = render_login_result_with_telemetry( &DeviceAuthFlowResult { authorization, stored_tokens, @@ -523,7 +624,11 @@ async fn run_login_json( format, telemetry, ) - .map_err(unexpected_auth_command_error) + .map_err(unexpected_auth_command_error)?; + Ok(LoginReport { + rendered, + telemetry, + }) } fn write_login_prompt(authorization: &auth::DeviceAuthorizationResponse) -> Result<()> { @@ -1043,6 +1148,83 @@ mod tests { assert_eq!(headers, r#"{"Authorization":"Bearer tok-scoped"}"#); } + #[tokio::test] + async fn repository_readiness_lookup_fails_closed_unless_repository_is_authorized() { + enum Lookup { + Authorized, + Unauthorized, + AccessFailure, + Hangs, + } + + let cases = [ + ( + "authorized repository", + true, + Some("repo-a"), + Lookup::Authorized, + true, + ), + ( + "auth.db absent", + false, + Some("repo-a"), + Lookup::Authorized, + false, + ), + ( + "missing repository identity", + true, + None, + Lookup::Authorized, + false, + ), + ( + "missing, expired, or foreign-bound credential", + true, + Some("repo-a"), + Lookup::Unauthorized, + false, + ), + ( + "non-interactive access failure", + true, + Some("repo-a"), + Lookup::AccessFailure, + false, + ), + ("lookup timeout", true, Some("repo-a"), Lookup::Hangs, false), + ]; + + for (case, auth_db, repository, lookup, expected) in cases { + let started = std::time::Instant::now(); + let credential = authorized_repository_credential_with( + PathBuf::from("/workspace/repo"), + || auth_db, + move |dir: &Path| { + assert_eq!(dir, Path::new("/workspace/repo")); + repository.map(str::to_string) + }, + move |repository_id: String| async move { + assert_eq!(repository_id, "repo-a"); + match lookup { + Lookup::Authorized => Ok(Some(telemetry_credential("tok-scoped"))), + Lookup::Unauthorized => Ok(None), + Lookup::AccessFailure => Err(storage_failure()), + Lookup::Hangs => std::future::pending().await, + } + }, + ) + .await; + + assert_eq!(credential.is_some(), expected, "{case}"); + assert!( + started.elapsed() < CREDENTIAL_LOOKUP_DEADLINE * 2, + "{case}: lookup exceeded deadline" + ); + } + } + #[test] fn telemetry_headers_policy_follows_auth_and_invalid_config() { let dir = tempfile::tempdir().unwrap(); @@ -1123,6 +1305,13 @@ mod tests { device_auth_result().stored_tokens } + fn device_login_report() -> LoginReport { + LoginReport { + rendered: "device-login-complete".to_string(), + telemetry: TelemetryProvisioningResult::Issued, + } + } + #[tokio::test] async fn stored_credentials_are_provisioned_only_after_renewal_completes() { let original = stored_tokens(); @@ -1154,6 +1343,8 @@ mod tests { .expect("stored login should succeed"); assert_eq!(*events.lock().unwrap(), ["renewal-complete", "provision"]); + assert_eq!(output.telemetry, TelemetryProvisioningResult::Issued); + let output = output.rendered; assert!(output.contains("\"renewed\": true")); assert!(output.contains("\"status\": \"issued\"")); } @@ -1166,12 +1357,12 @@ mod tests { None, |_stored| async { unreachable!("there are no stored credentials") }, || async { unreachable!("device login owns provisioning") }, - |_format| async { Ok("device-login-complete".to_string()) }, + |_format| async { Ok(device_login_report()) }, ) .await .expect("device login should succeed"); - assert_eq!(output, "device-login-complete"); + assert_eq!(output, device_login_report()); } #[test] @@ -1365,9 +1556,10 @@ mod tests { }) }, || async { TelemetryProvisioningResult::Issued }, - |_format| async { Ok("device-login-complete".to_string()) }, + |_format| async { Ok(device_login_report()) }, ) - .await; + .await + .map(|report| report.rendered); let reads = storage_reads.load(std::sync::atomic::Ordering::SeqCst); match (mode, stored) { @@ -1404,6 +1596,8 @@ mod tests { .await .expect("renewed login should succeed"); + assert_eq!(output.telemetry, TelemetryProvisioningResult::Disabled); + let output = output.rendered; assert!(output.contains("\"status\": \"disabled\"")); assert!(output.contains(TELEMETRY_PROVISIONING_DISABLED)); } @@ -1584,4 +1778,54 @@ mod tests { ); assert!(output.contains("\"credentials_removed\": true")); } + + #[tokio::test] + async fn login_report_carries_issued_telemetry_when_policy_enables_it() { + for mode in [AuthMode::Optional, AuthMode::Mandatory] { + let report = run_login_with( + AuthFormat::Text, + &global_policy(mode, true), + || async { Ok(Some(stored_tokens())) }, + |tokens| async move { Ok(Some(tokens)) }, + || async { TelemetryProvisioningResult::Issued }, + |_format| async { panic!("renewed credentials must not use device login") }, + ) + .await + .expect("renewed login should succeed"); + + assert_eq!(report.telemetry, TelemetryProvisioningResult::Issued); + } + } + + #[tokio::test] + async fn repository_enrollment_uses_the_supplied_working_directory() { + let working_dir = Path::new("/tmp/sce-login-working-dir"); + let looked_up = std::sync::Mutex::new(None); + let bound = std::sync::Mutex::new(None); + let looked_up = &looked_up; + let bound = &bound; + + enroll_repository_if_unbound_with( + working_dir, + |dir| { + *looked_up.lock().unwrap() = Some(dir.to_path_buf()); + Some("repo-id".to_string()) + }, + |repository_id| async move { + *bound.lock().unwrap() = Some(repository_id); + Ok(true) + }, + ) + .await; + + assert_eq!(looked_up.lock().unwrap().as_deref(), Some(working_dir),); + assert_eq!(bound.lock().unwrap().as_deref(), Some("repo-id")); + + enroll_repository_if_unbound_with( + working_dir, + |_dir| None, + |_repository_id| async { panic!("unresolved repository must not bind") }, + ) + .await; + } } diff --git a/cli/src/services/command_registry.rs b/cli/src/services/command_registry.rs index bc8ff9023..331ebbe6e 100644 --- a/cli/src/services/command_registry.rs +++ b/cli/src/services/command_registry.rs @@ -137,6 +137,7 @@ pub fn default_runtime_command(name: &str) -> Option { hooks_repo_path: None, context_only: false, optional_workflows: None, + reconfigure: false, }, }, )), diff --git a/cli/src/services/config/resolver.rs b/cli/src/services/config/resolver.rs index eba25bdfe..7a7fe8d63 100644 --- a/cli/src/services/config/resolver.rs +++ b/cli/src/services/config/resolver.rs @@ -979,7 +979,7 @@ where Ok(None) } -fn resolve_default_global_config_path() -> Result { +pub(crate) fn resolve_default_global_config_path() -> Result { Ok(resolve_sce_default_locations()?.global_config_file()) } diff --git a/cli/src/services/error.rs b/cli/src/services/error.rs index a786fedea..92441cf34 100644 --- a/cli/src/services/error.rs +++ b/cli/src/services/error.rs @@ -57,6 +57,7 @@ pub enum UserError { AuthStorageUnavailable(AuthStorageFailure), LoginAuthStorageUnavailable(AuthStorageFailure), AuthDisabledByConfig(AuthPolicyConfigFile), + SetupLoginRequired, UnexpectedFailure, } @@ -84,6 +85,7 @@ impl UserError { | Self::AuthStorageUnavailable(_) | Self::LoginAuthStorageUnavailable(_) | Self::AuthDisabledByConfig(_) + | Self::SetupLoginRequired | Self::UnexpectedFailure => FailureClass::Runtime, } } @@ -97,6 +99,7 @@ impl UserError { "auth.storage_unavailable" } Self::AuthDisabledByConfig(_) => "auth.disabled_by_config", + Self::SetupLoginRequired => "auth.setup_login_required", Self::UnexpectedFailure => "general.unexpected_failure", } } @@ -123,6 +126,7 @@ impl UserError { *failure, ), Self::AuthDisabledByConfig(file) => auth_disabled_by_config_message(*file), + Self::SetupLoginRequired => SETUP_LOGIN_REQUIRED_MESSAGE, Self::UnexpectedFailure => { "An unexpected error occurred. Check the log files for more details." } @@ -166,6 +170,10 @@ enum AuthStorageOperation { Login, } +const SETUP_LOGIN_REQUIRED_MESSAGE: &str = "Local SCE setup completed, but the SCE login required by `auth.mode: mandatory` did not succeed. + +To finish setup, run `sce auth login`, then rerun `sce setup`."; + const MACOS_AUTH_STORAGE_UNAVAILABLE: &str = "Authentication storage is unavailable. SCE could not access its encryption key in macOS Keychain. @@ -489,6 +497,33 @@ mod tests { } } + #[test] + fn setup_login_required_has_stable_runtime_catalog_mapping_and_keeps_its_source() { + let error = CliError::user_with_source( + UserError::SetupLoginRequired, + anyhow::anyhow!("device flow expired"), + ); + + assert_eq!(error.class(), FailureClass::Runtime); + assert_eq!(error.code(), "SCE-ERR-RUNTIME"); + assert_eq!( + UserError::SetupLoginRequired.key(), + "auth.setup_login_required" + ); + assert_eq!( + error.to_string(), + "Local SCE setup completed, but the SCE login required by `auth.mode: mandatory` did not succeed.\n\nTo finish setup, run `sce auth login`, then rerun `sce setup`." + ); + let CliError::User { + source: Some(source), + .. + } = &error + else { + panic!("expected a user error with a source"); + }; + assert_eq!(source.to_string(), "device flow expired"); + } + #[test] fn not_git_repository_has_stable_runtime_catalog_mapping() { let error = CliError::User { diff --git a/cli/src/services/parse/command_runtime.rs b/cli/src/services/parse/command_runtime.rs index 38d9999fb..7f745f796 100644 --- a/cli/src/services/parse/command_runtime.rs +++ b/cli/src/services/parse/command_runtime.rs @@ -292,6 +292,7 @@ fn convert_clap_command(command: cli_schema::Commands) -> Result convert_setup_command(services::setup::SetupCliOptions { target: [ (opencode, services::setup::SetupTarget::OpenCode), @@ -307,6 +308,7 @@ fn convert_clap_command(command: cli_schema::Commands) -> Result Ok(convert_doctor_command(fix, format)), cli_schema::Commands::Hooks { subcommand } => convert_hooks_subcommand(subcommand), @@ -580,6 +582,46 @@ mod tests { } } + #[test] + fn setup_reconfigure_parses_to_interactive_reconfigure_request() { + let RuntimeCommand::Setup(command) = parse(&["sce", "setup", "--reconfigure"]) else { + panic!("expected setup command"); + }; + + assert_eq!( + command.request.config_mode, + Some(services::setup::SetupMode::Interactive) + ); + assert!(command.request.reconfigure); + } + + #[test] + fn setup_reconfigure_with_a_target_fails_validation() { + let error = parse_runtime_command( + ["sce", "setup", "--claude", "--reconfigure"].map(String::from), + &CommandRegistry::default(), + None, + ) + .err() + .expect("reconfigure with a target should fail"); + + assert_eq!( + error.to_string(), + "Option '--reconfigure' cannot be used with '--claude'. Try: run 'sce setup --reconfigure' alone to change saved setup answers interactively." + ); + } + + #[test] + fn setup_help_lists_the_reconfigure_flag() { + let help = + cli_schema::render_help_for_path(&["setup"]).expect("setup help should be renderable"); + + assert!( + help.contains("--reconfigure"), + "setup help should list --reconfigure, got: {help}" + ); + } + #[test] fn sync_parses_to_sync_request_with_default_text_format() { let command = parse(&["sce", "sync"]); diff --git a/cli/src/services/setup/access_preferences.rs b/cli/src/services/setup/access_preferences.rs new file mode 100644 index 000000000..7a548b566 --- /dev/null +++ b/cli/src/services/setup/access_preferences.rs @@ -0,0 +1,540 @@ +use std::{ + fmt, fs, io, + path::{Path, PathBuf}, +}; + +use anyhow::Context; +use serde_json::{Map, Value}; + +use crate::services::agent_trace::sce_config_schema_url; +use crate::services::config::schema::{parse_file_config, CONFIG_SCHEMA_DECLARATION_KEY}; +use crate::services::config::{AuthMode, ConfigPathSource}; + +use super::atomic_write::write_atomically; + +const AUTH_KEY: &str = "auth"; +const AUTH_MODE_KEY: &str = "mode"; +const TELEMETRY_KEY: &str = "telemetry"; +const TELEMETRY_ENABLED_KEY: &str = "enabled"; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum GlobalAccessPreferences { + Missing, + Valid { + auth_mode: Option, + telemetry_enabled: Option, + }, + Invalid, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum GlobalWriteOutcome { + Unchanged, + Written, +} + +#[derive(Debug)] +pub(crate) enum GlobalAccessPreferencesError { + InvalidGlobalConfig { path: PathBuf, reason: String }, + ConcurrentModification { path: PathBuf }, + SymlinkManaged { path: PathBuf }, + Io(anyhow::Error), +} + +impl fmt::Display for GlobalAccessPreferencesError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidGlobalConfig { path, reason } => write!( + f, + "Global SCE config '{}' is invalid and was left unchanged: {reason}", + path.display() + ), + Self::ConcurrentModification { path } => write!( + f, + "Global SCE config '{}' changed while setup was updating it and was left unchanged.", + path.display() + ), + Self::SymlinkManaged { path } => write!( + f, + "Global SCE config '{}' is a symlink and was left unchanged; SCE cannot modify a symlink-managed global config. Update the file's source directly (for example, your Nix or Home Manager configuration).", + path.display() + ), + Self::Io(error) => write!(f, "{error:#}"), + } + } +} + +impl std::error::Error for GlobalAccessPreferencesError {} + +pub(crate) fn read_global_access_preferences( + path: &Path, +) -> anyhow::Result { + let Some(bytes) = read_optional(path)? else { + return Ok(GlobalAccessPreferences::Missing); + }; + let Ok(raw) = String::from_utf8(bytes) else { + return Ok(GlobalAccessPreferences::Invalid); + }; + let Ok(config) = parse_file_config(&raw, path, ConfigPathSource::DefaultDiscoveredGlobal) + else { + return Ok(GlobalAccessPreferences::Invalid); + }; + + Ok(GlobalAccessPreferences::Valid { + auth_mode: config.auth_mode.map(|setting| setting.value), + telemetry_enabled: config.telemetry_enabled.map(|setting| setting.value), + }) +} + +pub(crate) fn persist_global_access_preferences( + path: &Path, + auth_mode: Option, + telemetry_enabled: Option, +) -> Result { + persist_global_access_preferences_with(path, auth_mode, telemetry_enabled, read_optional) +} + +fn persist_global_access_preferences_with( + path: &Path, + auth_mode: Option, + telemetry_enabled: Option, + reread: R, +) -> Result +where + R: FnOnce(&Path) -> anyhow::Result>>, +{ + if auth_mode.is_none() && telemetry_enabled.is_none() { + return Ok(GlobalWriteOutcome::Unchanged); + } + + let original = read_optional(path).map_err(GlobalAccessPreferencesError::Io)?; + let original_value = match &original { + Some(bytes) => parse_global_config(path, bytes)?, + None => Value::Object(Map::from_iter([( + CONFIG_SCHEMA_DECLARATION_KEY.to_string(), + Value::String(sce_config_schema_url()), + )])), + }; + + let mut updated_value = original_value.clone(); + let object = updated_value + .as_object_mut() + .ok_or_else(|| invalid_global_config(path, "expected a top-level JSON object"))?; + if let Some(mode) = auth_mode { + set_nested_value( + object, + AUTH_KEY, + AUTH_MODE_KEY, + Value::String(mode.as_str().to_string()), + ); + } + if let Some(enabled) = telemetry_enabled { + set_nested_value( + object, + TELEMETRY_KEY, + TELEMETRY_ENABLED_KEY, + Value::Bool(enabled), + ); + } + + if original.is_some() && updated_value == original_value { + return Ok(GlobalWriteOutcome::Unchanged); + } + + let mut serialized = serde_json::to_string_pretty(&updated_value) + .context("Failed to serialize global SCE config") + .map_err(GlobalAccessPreferencesError::Io)?; + serialized.push('\n'); + parse_file_config(&serialized, path, ConfigPathSource::DefaultDiscoveredGlobal) + .map_err(|error| invalid_global_config(path, &format!("{error:#}")))?; + + let current = reread(path).map_err(GlobalAccessPreferencesError::Io)?; + if current != original { + return Err(GlobalAccessPreferencesError::ConcurrentModification { + path: path.to_path_buf(), + }); + } + if is_symlink(path).map_err(GlobalAccessPreferencesError::Io)? { + return Err(GlobalAccessPreferencesError::SymlinkManaged { + path: path.to_path_buf(), + }); + } + + write_atomically(path, serialized.as_bytes()).map_err(GlobalAccessPreferencesError::Io)?; + Ok(GlobalWriteOutcome::Written) +} + +fn parse_global_config(path: &Path, bytes: &[u8]) -> Result { + let raw = std::str::from_utf8(bytes) + .map_err(|_| invalid_global_config(path, "file is not valid UTF-8"))?; + parse_file_config(raw, path, ConfigPathSource::DefaultDiscoveredGlobal) + .map_err(|error| invalid_global_config(path, &format!("{error:#}")))?; + serde_json::from_str(raw).map_err(|error| invalid_global_config(path, &error.to_string())) +} + +fn set_nested_value(object: &mut Map, section: &str, key: &str, value: Value) { + let entry = object + .entry(section.to_string()) + .or_insert_with(|| Value::Object(Map::new())); + if !entry.is_object() { + *entry = Value::Object(Map::new()); + } + if let Some(section_object) = entry.as_object_mut() { + section_object.insert(key.to_string(), value); + } +} + +fn invalid_global_config(path: &Path, reason: &str) -> GlobalAccessPreferencesError { + GlobalAccessPreferencesError::InvalidGlobalConfig { + path: path.to_path_buf(), + reason: reason.to_string(), + } +} + +fn is_symlink(path: &Path) -> anyhow::Result { + match fs::symlink_metadata(path) { + Ok(metadata) => Ok(metadata.file_type().is_symlink()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error) + .with_context(|| format!("Failed to inspect global SCE config '{}'", path.display())), + } +} + +fn read_optional(path: &Path) -> anyhow::Result>> { + match fs::read(path) { + Ok(bytes) => Ok(Some(bytes)), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error) + .with_context(|| format!("Failed to read global SCE config '{}'", path.display())), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn read_json(path: &Path) -> Value { + serde_json::from_slice(&fs::read(path).unwrap()).unwrap() + } + + fn write_json(path: &Path, value: &Value) { + fs::write(path, serde_json::to_vec_pretty(value).unwrap()).unwrap(); + } + + #[test] + fn access_preferences_writer_sets_only_requested_keys() { + struct Case { + name: &'static str, + initial: Option, + auth_mode: Option, + telemetry_enabled: Option, + expected: Value, + } + + let schema = sce_config_schema_url(); + let cases = [ + Case { + name: "missing file", + initial: None, + auth_mode: Some(AuthMode::Optional), + telemetry_enabled: Some(false), + expected: json!({ + "$schema": schema, + "auth": {"mode": "optional"}, + "telemetry": {"enabled": false} + }), + }, + Case { + name: "empty object", + initial: Some(json!({})), + auth_mode: None, + telemetry_enabled: Some(true), + expected: json!({"telemetry": {"enabled": true}}), + }, + Case { + name: "unrelated keys preserved", + initial: Some(json!({ + "log_level": "debug", + "agent_trace": {"auto_sync": true}, + "policies": {"attribution_hooks": {"enabled": false}} + })), + auth_mode: Some(AuthMode::Mandatory), + telemetry_enabled: None, + expected: json!({ + "log_level": "debug", + "agent_trace": {"auto_sync": true}, + "policies": {"attribution_hooks": {"enabled": false}}, + "auth": {"mode": "mandatory"} + }), + }, + Case { + name: "explicit values replaced", + initial: Some(json!({ + "auth": {"mode": "disabled"}, + "telemetry": {"enabled": true} + })), + auth_mode: Some(AuthMode::Optional), + telemetry_enabled: Some(false), + expected: json!({ + "auth": {"mode": "optional"}, + "telemetry": {"enabled": false} + }), + }, + ]; + + for case in cases { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("sce").join("config.json"); + if let Some(initial) = &case.initial { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + write_json(&path, initial); + } + + let outcome = + persist_global_access_preferences(&path, case.auth_mode, case.telemetry_enabled) + .unwrap(); + + assert_eq!(outcome, GlobalWriteOutcome::Written, "{}", case.name); + assert_eq!(read_json(&path), case.expected, "{}", case.name); + assert!( + fs::read_to_string(&path).unwrap().ends_with("}\n"), + "{}", + case.name + ); + assert_eq!( + read_global_access_preferences(&path).unwrap(), + GlobalAccessPreferences::Valid { + auth_mode: case.auth_mode, + telemetry_enabled: case.telemetry_enabled, + }, + "{}", + case.name + ); + } + } + + #[test] + fn access_preferences_writer_is_idempotent_on_rerun() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.json"); + + persist_global_access_preferences(&path, Some(AuthMode::Optional), Some(true)).unwrap(); + let first = fs::read(&path).unwrap(); + + let outcome = + persist_global_access_preferences(&path, Some(AuthMode::Optional), Some(true)).unwrap(); + + assert_eq!(outcome, GlobalWriteOutcome::Unchanged); + assert_eq!(fs::read(&path).unwrap(), first); + } + + #[test] + fn access_preferences_writer_without_answers_never_creates_file() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.json"); + + let outcome = persist_global_access_preferences(&path, None, None).unwrap(); + + assert_eq!(outcome, GlobalWriteOutcome::Unchanged); + assert!(!path.exists()); + } + + #[cfg(unix)] + #[test] + fn access_preferences_writer_preserves_existing_mode_and_creates_private_file() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let existing = dir.path().join("existing.json"); + write_json(&existing, &json!({})); + fs::set_permissions(&existing, fs::Permissions::from_mode(0o644)).unwrap(); + let created = dir.path().join("created.json"); + + persist_global_access_preferences(&existing, Some(AuthMode::Optional), None).unwrap(); + persist_global_access_preferences(&created, Some(AuthMode::Optional), None).unwrap(); + + assert_eq!( + fs::metadata(&existing).unwrap().permissions().mode() & 0o777, + 0o644 + ); + assert_eq!( + fs::metadata(&created).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + + #[test] + fn access_preferences_writer_refuses_invalid_files_without_touching_them() { + let cases: [(&str, &[u8]); 4] = [ + ("invalid json", b"{not json"), + ("schema invalid mode", br#"{"auth":{"mode":"required"}}"#), + ("unknown top-level key", br#"{"surprise":true}"#), + ("not utf8", &[0xff, 0xfe, 0x00]), + ]; + + for (name, bytes) in cases { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.json"); + fs::write(&path, bytes).unwrap(); + + let error = + persist_global_access_preferences(&path, Some(AuthMode::Optional), Some(true)) + .unwrap_err(); + + assert!( + matches!( + error, + GlobalAccessPreferencesError::InvalidGlobalConfig { .. } + ), + "{name}: {error}" + ); + assert_eq!(fs::read(&path).unwrap(), bytes, "{name}"); + assert_eq!( + read_global_access_preferences(&path).unwrap(), + GlobalAccessPreferences::Invalid, + "{name}" + ); + } + } + + #[test] + fn access_preferences_writer_detects_concurrent_modification_before_rename() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.json"); + write_json(&path, &json!({"log_level": "info"})); + let concurrent = br#"{"log_level":"debug"}"#.to_vec(); + + let error = persist_global_access_preferences_with( + &path, + Some(AuthMode::Optional), + Some(true), + |reread_path| { + fs::write(reread_path, &concurrent).unwrap(); + read_optional(reread_path) + }, + ) + .unwrap_err(); + + assert!(matches!( + error, + GlobalAccessPreferencesError::ConcurrentModification { .. } + )); + assert_eq!(fs::read(&path).unwrap(), concurrent); + } + + #[cfg(unix)] + #[test] + fn access_preferences_writer_reports_io_error_for_read_only_directory() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let config_dir = dir.path().join("sce"); + fs::create_dir_all(&config_dir).unwrap(); + let path = config_dir.join("config.json"); + let original = br#"{"log_level":"info"}"#.to_vec(); + fs::write(&path, &original).unwrap(); + fs::set_permissions(&config_dir, fs::Permissions::from_mode(0o555)).unwrap(); + + let result = persist_global_access_preferences(&path, Some(AuthMode::Optional), None); + + fs::set_permissions(&config_dir, fs::Permissions::from_mode(0o755)).unwrap(); + assert!(matches!(result, Err(GlobalAccessPreferencesError::Io(_)))); + assert_eq!(fs::read(&path).unwrap(), original); + } + + #[cfg(unix)] + #[test] + fn access_preferences_writer_refuses_to_replace_symlinked_global_config() { + use std::os::unix::fs::{symlink, PermissionsExt}; + + let original = br#"{"log_level":"info"}"#.to_vec(); + for (name, target_exists, target_mode) in [ + ("valid target", true, 0o644), + ("read-only target", true, 0o444), + ("dangling target", false, 0o644), + ] { + let dir = tempfile::tempdir().unwrap(); + let target = dir.path().join("store").join("config.json"); + fs::create_dir_all(target.parent().unwrap()).unwrap(); + if target_exists { + fs::write(&target, &original).unwrap(); + fs::set_permissions(&target, fs::Permissions::from_mode(target_mode)).unwrap(); + } + let path = dir.path().join("config.json"); + symlink(&target, &path).unwrap(); + + let error = + persist_global_access_preferences(&path, Some(AuthMode::Optional), Some(true)) + .unwrap_err(); + + assert!( + matches!(error, GlobalAccessPreferencesError::SymlinkManaged { .. }), + "{name}: {error}" + ); + assert!( + error + .to_string() + .contains("Update the file's source directly"), + "{name}" + ); + assert!( + fs::symlink_metadata(&path) + .unwrap() + .file_type() + .is_symlink(), + "{name}" + ); + assert_eq!(fs::read_link(&path).unwrap(), target, "{name}"); + if target_exists { + assert_eq!(fs::read(&target).unwrap(), original, "{name}"); + } else { + assert!(!target.exists(), "{name}"); + } + assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2, "{name}"); + } + } + + #[cfg(unix)] + #[test] + fn access_preferences_writer_leaves_symlinked_global_config_alone_when_unchanged() { + use std::os::unix::fs::symlink; + + let dir = tempfile::tempdir().unwrap(); + let target = dir.path().join("target.json"); + let current = br#"{"auth":{"mode":"optional"},"telemetry":{"enabled":true}}"#.to_vec(); + fs::write(&target, ¤t).unwrap(); + let path = dir.path().join("config.json"); + symlink(&target, &path).unwrap(); + + let outcome = + persist_global_access_preferences(&path, Some(AuthMode::Optional), Some(true)).unwrap(); + + assert_eq!(outcome, GlobalWriteOutcome::Unchanged); + assert!(fs::symlink_metadata(&path) + .unwrap() + .file_type() + .is_symlink()); + assert_eq!(fs::read(&target).unwrap(), current); + } + + #[test] + fn access_preferences_reader_distinguishes_missing_and_absent_keys() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.json"); + + assert_eq!( + read_global_access_preferences(&path).unwrap(), + GlobalAccessPreferences::Missing + ); + + write_json(&path, &json!({"log_level": "info"})); + assert_eq!( + read_global_access_preferences(&path).unwrap(), + GlobalAccessPreferences::Valid { + auth_mode: None, + telemetry_enabled: None, + } + ); + } +} diff --git a/cli/src/services/setup/atomic_write.rs b/cli/src/services/setup/atomic_write.rs new file mode 100644 index 000000000..ac27defb6 --- /dev/null +++ b/cli/src/services/setup/atomic_write.rs @@ -0,0 +1,46 @@ +use std::{ + fs, + path::{Path, PathBuf}, +}; + +use anyhow::{Context, Result}; + +const NEW_FILE_MODE: u32 = 0o600; +const TEMP_SUFFIX: &str = ".sce-tmp"; + +pub(super) fn write_atomically(path: &Path, bytes: &[u8]) -> Result<()> { + let parent = path + .parent() + .with_context(|| format!("Settings path '{}' has no parent directory", path.display()))?; + fs::create_dir_all(parent) + .with_context(|| format!("Failed to create '{}'", parent.display()))?; + + let mut temp_name = path.as_os_str().to_os_string(); + temp_name.push(TEMP_SUFFIX); + let temp_path = PathBuf::from(temp_name); + + fs::write(&temp_path, bytes) + .with_context(|| format!("Failed to write '{}'", temp_path.display()))?; + apply_mode(path, &temp_path)?; + fs::rename(&temp_path, path).with_context(|| { + let _ = fs::remove_file(&temp_path); + format!("Failed to replace '{}'", path.display()) + }) +} + +#[cfg(unix)] +pub(super) fn apply_mode(target: &Path, temp_path: &Path) -> Result<()> { + use std::os::unix::fs::PermissionsExt; + + let mode = match fs::metadata(target) { + Ok(metadata) => metadata.permissions().mode() & 0o7777, + Err(_) => NEW_FILE_MODE, + }; + fs::set_permissions(temp_path, fs::Permissions::from_mode(mode)) + .with_context(|| format!("Failed to set permissions on '{}'", temp_path.display())) +} + +#[cfg(not(unix))] +pub(super) fn apply_mode(_target: &Path, _temp_path: &Path) -> Result<()> { + Ok(()) +} diff --git a/cli/src/services/setup/claude_telemetry.rs b/cli/src/services/setup/claude_telemetry.rs index 8d7abcf09..0bbe7ffb8 100644 --- a/cli/src/services/setup/claude_telemetry.rs +++ b/cli/src/services/setup/claude_telemetry.rs @@ -5,6 +5,7 @@ use std::{ use anyhow::{Context, Result}; +use super::atomic_write::write_atomically; use super::config_merge::{ merge_claude_telemetry_settings, ClaudeTelemetryMergeOutcome, ClaudeTelemetrySkipReason, }; @@ -15,13 +16,13 @@ const CLAUDE_USER_DIR_NAME: &str = ".claude"; const LINUX_MANAGED_SETTINGS_PATH: &str = "/etc/claude-code/managed-settings.json"; const MACOS_MANAGED_SETTINGS_PATH: &str = "/Library/Application Support/ClaudeCode/managed-settings.json"; -const NEW_SETTINGS_FILE_MODE: u32 = 0o600; -const TEMP_SUFFIX: &str = ".sce-tmp"; const CONFIGURED_LINE: &str = "Claude telemetry: configured in user-level Claude settings for native OpenTelemetry export."; -const AUTH_PENDING_LINE: &str = - "Claude telemetry: authentication pending for this repository; run 'sce auth login' in this repository to start exporting."; +const NOT_READY_LINE: &str = + "Claude telemetry: not ready for this repository; no valid SCE telemetry credential is authorized for it, so Claude will not export. Run 'sce auth login' in this repository with the SCE account it is enrolled under."; +const NOT_CHECKED_LINE: &str = + "Claude telemetry: configured; repository authorization was not checked during non-interactive setup."; const SKIPPED_HELPER_LINE: &str = "Claude telemetry: skipped; existing Claude settings define a different otelHeadersHelper."; const SKIPPED_DISABLED_LINE: &str = @@ -91,15 +92,25 @@ pub(crate) fn install_claude_telemetry( } } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum RepositoryAuthorization { + Authorized, + Unauthorized, + NotChecked, +} + pub(crate) fn format_claude_telemetry_report( outcome: &ClaudeTelemetryInstallOutcome, - authentication_pending: bool, + authorization: RepositoryAuthorization, ) -> String { match outcome { - ClaudeTelemetryInstallOutcome::Configured if authentication_pending => { - format!("{CONFIGURED_LINE}\n{AUTH_PENDING_LINE}") - } - ClaudeTelemetryInstallOutcome::Configured => CONFIGURED_LINE.to_string(), + ClaudeTelemetryInstallOutcome::Configured => match authorization { + RepositoryAuthorization::Authorized => CONFIGURED_LINE.to_string(), + RepositoryAuthorization::Unauthorized => { + format!("{CONFIGURED_LINE}\n{NOT_READY_LINE}") + } + RepositoryAuthorization::NotChecked => NOT_CHECKED_LINE.to_string(), + }, ClaudeTelemetryInstallOutcome::SkippedConflict(reason) => { skipped_conflict_line(*reason).to_string() } @@ -129,43 +140,6 @@ fn read_optional(path: &Path) -> Result>> { } } -fn write_atomically(path: &Path, bytes: &[u8]) -> Result<()> { - let parent = path - .parent() - .with_context(|| format!("Settings path '{}' has no parent directory", path.display()))?; - fs::create_dir_all(parent) - .with_context(|| format!("Failed to create '{}'", parent.display()))?; - - let mut temp_name = path.as_os_str().to_os_string(); - temp_name.push(TEMP_SUFFIX); - let temp_path = PathBuf::from(temp_name); - - fs::write(&temp_path, bytes) - .with_context(|| format!("Failed to write '{}'", temp_path.display()))?; - apply_mode(path, &temp_path)?; - fs::rename(&temp_path, path).with_context(|| { - let _ = fs::remove_file(&temp_path); - format!("Failed to replace '{}'", path.display()) - }) -} - -#[cfg(unix)] -fn apply_mode(target: &Path, temp_path: &Path) -> Result<()> { - use std::os::unix::fs::PermissionsExt; - - let mode = match fs::metadata(target) { - Ok(metadata) => metadata.permissions().mode() & 0o7777, - Err(_) => NEW_SETTINGS_FILE_MODE, - }; - fs::set_permissions(temp_path, fs::Permissions::from_mode(mode)) - .with_context(|| format!("Failed to set permissions on '{}'", temp_path.display())) -} - -#[cfg(not(unix))] -fn apply_mode(_target: &Path, _temp_path: &Path) -> Result<()> { - Ok(()) -} - #[cfg(test)] mod tests { use super::*; @@ -309,20 +283,27 @@ mod tests { ) ); assert_eq!(fs::read(&settings).unwrap(), original); - let report = format_claude_telemetry_report(&outcome, false); + let report = + format_claude_telemetry_report(&outcome, RepositoryAuthorization::Unauthorized); assert!(report.contains("explicitly disable telemetry")); assert!(!report.contains("configured")); } #[test] - fn claude_telemetry_report_marks_authentication_pending_without_helper_name() { - let pending = - format_claude_telemetry_report(&ClaudeTelemetryInstallOutcome::Configured, true); - let ready = - format_claude_telemetry_report(&ClaudeTelemetryInstallOutcome::Configured, false); - - assert!(pending.contains("authentication pending")); - assert!(!ready.contains("authentication pending")); + fn claude_telemetry_report_marks_unready_repository_without_helper_name() { + let report = |authorization| { + format_claude_telemetry_report( + &ClaudeTelemetryInstallOutcome::Configured, + authorization, + ) + }; + let pending = report(RepositoryAuthorization::Unauthorized); + let not_checked = report(RepositoryAuthorization::NotChecked); + + assert!(pending.contains("not ready for this repository")); + assert_eq!(report(RepositoryAuthorization::Authorized), CONFIGURED_LINE); + assert_eq!(not_checked, NOT_CHECKED_LINE); + assert!(!not_checked.contains("not ready")); assert!(!pending.contains("telemetry-headers")); } } diff --git a/cli/src/services/setup/command.rs b/cli/src/services/setup/command.rs index 74eaca0c5..1846477fc 100644 --- a/cli/src/services/setup/command.rs +++ b/cli/src/services/setup/command.rs @@ -1,14 +1,39 @@ +use std::future::Future; +use std::path::{Path, PathBuf}; + use anyhow::Context; use crate::app::ContextWithRepoRoot; -use crate::services::error::{CliError, UserError}; +use crate::services::auth_command::{self, AuthFormat, LoginReport}; +use crate::services::config::{AuthMode, ResolvedAccessPolicy, ValueSource}; +use crate::services::error::{AuthPolicyConfigFile, CliError, UserError}; use crate::services::lifecycle::{ lifecycle_providers, RequiredHookInstallStatus, RequiredHooksInstallOutcome, }; -use crate::services::{config, setup}; +use crate::services::setup::access_preferences::{ + persist_global_access_preferences, read_global_access_preferences, + GlobalAccessPreferencesError, GlobalWriteOutcome, +}; +use crate::services::{config, managed_telemetry, setup}; const CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE: &str = "Claude telemetry: skipped; SCE telemetry is disabled by config."; +const SCE_ACCESS_HEADING: &str = "SCE access:"; +const SAVED_ACCESS_SCOPE: &str = "applies to all repositories on this machine"; +const AUTH_LOGOUT_HINT_LINE: &str = + "- SCE login: stored SCE credentials remain on this machine; run 'sce auth logout' to remove them."; +const GLOBAL_ACCESS_WRITE_REMEDIATION: &str = "No repository files were changed. Run 'sce config validate' to check the file, then rerun 'sce setup'."; +const GLOBAL_ACCESS_SYMLINK_REMEDIATION: &str = + "No repository files were changed. Rerun 'sce setup' after updating the config source."; +const SETUP_LOGIN_DISABLED_LINE: &str = + "SCE login: skipped; SCE authentication is disabled by config."; +const SETUP_LOGIN_NOT_REQUESTED_LINE: &str = + "SCE login: not requested; run 'sce auth login' to log in or refresh credentials."; +const SETUP_LOGIN_DECLINED_LINE: &str = "SCE login: skipped; run 'sce auth login' to log in."; +const SETUP_LOGIN_FAILED_PREFIX: &str = "SCE login: failed: "; +const SETUP_LOGIN_RETRY_LINE: &str = "Run 'sce auth login' to retry."; +const RECONFIGURE_HINT_LINE: &str = + "- Run 'sce setup --reconfigure' to change saved setup answers."; pub struct SetupCommand { pub request: setup::SetupRequest, @@ -25,33 +50,16 @@ impl SetupCommand { let repository_root = resolve_setup_repository(&setup_start_path)?; - let setup_dispatch = if self.request.context_only { - None - } else if let Some(mode) = self.request.config_mode { - let optional_workflow_defaults = match &self.request.optional_workflows { - Some(selection) => selection.clone(), - None => setup::persisted_optional_workflows(&repository_root), - }; - - match setup::resolve_setup_dispatch( - mode, - &setup::InquireSetupTargetPrompter, - &optional_workflow_defaults, - &setup::persisted_integration_targets(&repository_root), - setup::persisted_setup_confirmations(&repository_root), - ) - .map_err(unexpected_failure)? - { - setup::SetupDispatch::Cancelled => { - return Ok(setup::setup_cancelled_text()); - } - dispatch @ setup::SetupDispatch::Proceed { .. } => Some(dispatch), - } - } else { - None + let (setup_dispatch, interactive_access) = match self.prepare_dispatch(&repository_root)? { + PreparedSetup::Cancelled => return Ok(setup::setup_cancelled_text()), + PreparedSetup::Ready { + dispatch, + interactive_access, + } => (dispatch, interactive_access), }; let claude_telemetry_selected = dispatch_targets_claude(setup_dispatch.as_ref()); + let authorization_check = RepositoryAuthorizationCheck::for_mode(self.request.config_mode); let mut sections = Vec::new(); @@ -85,6 +93,8 @@ impl SetupCommand { optional_workflows: prompted_optional_workflows, agent_trace_auto_sync, attribution_hooks_enabled, + login_intent, + .. }) = setup_dispatch { let optional_workflows = prompted_optional_workflows @@ -102,13 +112,377 @@ impl SetupCommand { .map_err(unexpected_failure)?; sections.push(setup_message); + if let Some((access_save, auth_db_present)) = &interactive_access { + let (access_section, policy) = setup_access_report( + &repository_root, + access_save, + resolve_access_policy, + *auth_db_present, + )?; + sections.push(access_section); + + let login_status = + run_setup_login_step(setup_login_action(&policy, login_intent), || { + auth_command::run_login_in(&repository_root, AuthFormat::Text) + }) + .await?; + sections.push(render_setup_login_section(&login_status)); + } + if claude_telemetry_selected { - sections.push(claude_telemetry_report(&repository_root)); + sections.push(claude_telemetry_report(&repository_root, authorization_check).await); } } Ok(sections.join("\n\n")) } + + fn prepare_dispatch(&self, repository_root: &Path) -> Result { + if self.request.context_only { + return Ok(PreparedSetup::Ready { + dispatch: None, + interactive_access: None, + }); + } + let Some(mode) = self.request.config_mode else { + return Ok(PreparedSetup::Ready { + dispatch: None, + interactive_access: None, + }); + }; + + let optional_workflow_defaults = match &self.request.optional_workflows { + Some(selection) => selection.clone(), + None => setup::persisted_optional_workflows(repository_root), + }; + + if mode != setup::SetupMode::Interactive { + let dispatch = setup::resolve_setup_dispatch( + mode, + &setup::InquireSetupTargetPrompter, + &optional_workflow_defaults, + &setup::persisted_integration_targets(repository_root), + setup::persisted_setup_confirmations(repository_root), + setup::SetupAccessGate::default(), + false, + ) + .map_err(unexpected_failure)?; + + return Ok(match dispatch { + setup::SetupDispatch::Cancelled => PreparedSetup::Cancelled, + dispatch @ setup::SetupDispatch::Proceed { .. } => PreparedSetup::Ready { + dispatch: Some(dispatch), + interactive_access: None, + }, + }); + } + + let global_config_path = + config::resolver::resolve_default_global_config_path().map_err(unexpected_failure)?; + let auth_db_present = managed_telemetry::auth_db_present(); + + Ok( + match prepare_interactive_setup( + repository_root, + &setup::InquireSetupTargetPrompter, + &optional_workflow_defaults, + &global_config_path, + resolve_access_policy, + auth_db_present, + self.request.reconfigure, + )? { + InteractiveSetup::Cancelled => PreparedSetup::Cancelled, + InteractiveSetup::Ready { + dispatch, + access_save, + } => PreparedSetup::Ready { + dispatch: Some(dispatch), + interactive_access: Some((access_save, auth_db_present)), + }, + }, + ) + } +} + +enum PreparedSetup { + Cancelled, + Ready { + dispatch: Option, + interactive_access: Option<(SetupAccessSave, bool)>, + }, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +struct SetupAccessSave { + global_config_path: PathBuf, + auth_mode: Option, + telemetry_enabled: Option, + outcome: GlobalWriteOutcome, + prompts_suppressed: bool, +} + +#[derive(Debug)] +enum InteractiveSetup { + Cancelled, + Ready { + dispatch: setup::SetupDispatch, + access_save: SetupAccessSave, + }, +} + +fn resolve_access_policy(repository_root: &Path) -> anyhow::Result { + config::resolve_auth_runtime_config(repository_root).map(|config| config.access_policy) +} + +fn prepare_interactive_setup( + repository_root: &Path, + prompter: &P, + optional_workflow_defaults: &[String], + global_config_path: &Path, + resolve_policy: R, + auth_db_present: bool, + reconfigure: bool, +) -> Result +where + P: setup::SetupTargetPrompter, + R: Fn(&Path) -> anyhow::Result, +{ + let policy = resolve_policy(repository_root).map_err(unexpected_failure)?; + let global_preferences = + read_global_access_preferences(global_config_path).map_err(unexpected_failure)?; + let persisted_confirmations = setup::persisted_setup_confirmations(repository_root) + .with_global_access_preferences(global_preferences); + + let dispatch = setup::resolve_setup_dispatch( + setup::SetupMode::Interactive, + prompter, + optional_workflow_defaults, + &setup::persisted_integration_targets(repository_root), + persisted_confirmations, + setup::SetupAccessGate::from_policy(&policy, auth_db_present), + reconfigure, + ) + .map_err(unexpected_failure)?; + + let (auth_mode, telemetry_enabled, prompts_suppressed) = match &dispatch { + setup::SetupDispatch::Cancelled => return Ok(InteractiveSetup::Cancelled), + setup::SetupDispatch::Proceed { + auth_mode, + telemetry_enabled, + prompts_suppressed, + .. + } => (*auth_mode, *telemetry_enabled, *prompts_suppressed), + }; + + let access_save = SetupAccessSave { + prompts_suppressed, + ..persist_setup_access_preferences(global_config_path, auth_mode, telemetry_enabled)? + }; + + Ok(InteractiveSetup::Ready { + dispatch, + access_save, + }) +} + +fn persist_setup_access_preferences( + global_config_path: &Path, + auth_mode: Option, + telemetry_enabled: Option, +) -> Result { + let outcome = + persist_global_access_preferences(global_config_path, auth_mode, telemetry_enabled) + .map_err(|source| global_access_write_failure(global_config_path, &source))?; + + Ok(SetupAccessSave { + global_config_path: global_config_path.to_path_buf(), + auth_mode, + telemetry_enabled, + outcome, + prompts_suppressed: false, + }) +} + +fn global_access_write_failure( + global_config_path: &Path, + source: &GlobalAccessPreferencesError, +) -> CliError { + let remediation = match source { + GlobalAccessPreferencesError::SymlinkManaged { .. } => GLOBAL_ACCESS_SYMLINK_REMEDIATION, + _ => GLOBAL_ACCESS_WRITE_REMEDIATION, + }; + CliError::runtime(anyhow::anyhow!( + "Failed to save SCE access preferences to the global SCE config '{}'.\n{source}\n{remediation}", + global_config_path.display() + )) +} + +fn setup_access_report( + repository_root: &Path, + access_save: &SetupAccessSave, + resolve_policy: R, + auth_db_present: bool, +) -> Result<(String, ResolvedAccessPolicy), CliError> +where + R: Fn(&Path) -> anyhow::Result, +{ + let policy = resolve_policy(repository_root).map_err(unexpected_failure)?; + let section = render_setup_access_section(access_save, &policy, auth_db_present); + + Ok((section, policy)) +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum SetupLoginSkip { + AuthDisabled, + NotOffered, + Declined, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum SetupLoginAction { + Skip(SetupLoginSkip), + Run { required: bool }, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +enum SetupLoginStatus { + Skipped(SetupLoginSkip), + Authenticated(LoginReport), + Failed(UserError), +} + +fn setup_login_action( + policy: &ResolvedAccessPolicy, + intent: setup::SetupLoginIntent, +) -> SetupLoginAction { + if !policy.auth_allowed() { + return SetupLoginAction::Skip(SetupLoginSkip::AuthDisabled); + } + if policy.auth_mode.value == AuthMode::Mandatory { + return SetupLoginAction::Run { required: true }; + } + match intent { + setup::SetupLoginIntent::Requested => SetupLoginAction::Run { required: false }, + setup::SetupLoginIntent::Declined => SetupLoginAction::Skip(SetupLoginSkip::Declined), + setup::SetupLoginIntent::NotOffered => SetupLoginAction::Skip(SetupLoginSkip::NotOffered), + } +} + +async fn run_setup_login_step( + action: SetupLoginAction, + login: L, +) -> Result +where + L: FnOnce() -> LF, + LF: Future>, +{ + let required = match action { + SetupLoginAction::Skip(skip) => return Ok(SetupLoginStatus::Skipped(skip)), + SetupLoginAction::Run { required } => required, + }; + + match login().await { + Ok(report) => Ok(SetupLoginStatus::Authenticated(report)), + Err(error) if required => Err(CliError::user_with_source( + UserError::SetupLoginRequired, + error, + )), + Err(CliError::User { error, .. }) => Ok(SetupLoginStatus::Failed(error)), + Err(CliError::Internal { .. }) => { + Ok(SetupLoginStatus::Failed(UserError::UnexpectedFailure)) + } + } +} + +fn render_setup_login_section(status: &SetupLoginStatus) -> String { + match status { + SetupLoginStatus::Skipped(SetupLoginSkip::AuthDisabled) => { + SETUP_LOGIN_DISABLED_LINE.to_string() + } + SetupLoginStatus::Skipped(SetupLoginSkip::NotOffered) => { + SETUP_LOGIN_NOT_REQUESTED_LINE.to_string() + } + SetupLoginStatus::Skipped(SetupLoginSkip::Declined) => { + SETUP_LOGIN_DECLINED_LINE.to_string() + } + SetupLoginStatus::Authenticated(report) => report.rendered.clone(), + SetupLoginStatus::Failed(error) => format!( + "{SETUP_LOGIN_FAILED_PREFIX}{}\n{SETUP_LOGIN_RETRY_LINE}", + error.message() + ), + } +} + +fn render_setup_access_section( + access_save: &SetupAccessSave, + policy: &ResolvedAccessPolicy, + auth_db_present: bool, +) -> String { + let global_config_path = access_save.global_config_path.display(); + let mut lines = vec![SCE_ACCESS_HEADING.to_string()]; + + let saved_values = [ + access_save + .auth_mode + .map(|mode| ("auth.mode", mode.as_str().to_string())), + access_save + .telemetry_enabled + .map(|enabled| ("telemetry.enabled", enabled.to_string())), + ]; + if access_save.outcome == GlobalWriteOutcome::Written { + lines.extend(saved_values.into_iter().flatten().map(|(key, saved)| { + format!( + "- {key}: {saved} (saved to global SCE config '{global_config_path}'; {SAVED_ACCESS_SCOPE})" + ) + })); + } else { + lines.push(format!( + "- saved access preferences: unchanged (global SCE config '{global_config_path}')" + )); + } + + lines.push(format!( + "- effective auth.mode: {} ({})", + policy.auth_mode.value.as_str(), + format_policy_source(policy.auth_mode.source) + )); + lines.push(match policy.telemetry.disabled_reason() { + Some(reason) => format!( + "- effective telemetry: disabled (reason: {})", + reason.as_str() + ), + None => "- effective telemetry: enabled".to_string(), + }); + + if let Some(file) = setup::SetupAccessGate::from_policy(policy, auth_db_present).auth_locked_by + { + lines.push(format!("- {}", auth_locked_by_line(file))); + } + if !policy.auth_allowed() && auth_db_present { + lines.push(AUTH_LOGOUT_HINT_LINE.to_string()); + } + if access_save.prompts_suppressed { + lines.push(RECONFIGURE_HINT_LINE.to_string()); + } + + lines.join("\n") +} + +fn format_policy_source(source: ValueSource) -> String { + match source.config_source() { + Some(config_source) => format!( + "source: {}, config_source: {}", + source.as_str(), + config_source.as_str() + ), + None => format!("source: {}", source.as_str()), + } +} + +fn auth_locked_by_line(file: AuthPolicyConfigFile) -> &'static str { + let message = UserError::AuthDisabledByConfig(file).message(); + message.lines().next().unwrap_or(message) } fn dispatch_targets_claude(dispatch: Option<&setup::SetupDispatch>) -> bool { @@ -119,7 +493,25 @@ fn dispatch_targets_claude(dispatch: Option<&setup::SetupDispatch>) -> bool { ) } -fn claude_telemetry_report(repository_root: &std::path::Path) -> String { +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RepositoryAuthorizationCheck { + Verify, + Skip, +} + +impl RepositoryAuthorizationCheck { + fn for_mode(config_mode: Option) -> Self { + match config_mode { + Some(setup::SetupMode::Interactive) => Self::Verify, + Some(setup::SetupMode::NonInteractive(_)) | None => Self::Skip, + } + } +} + +async fn claude_telemetry_report( + repository_root: &std::path::Path, + authorization_check: RepositoryAuthorizationCheck, +) -> String { let telemetry_enabled = config::resolve_auth_runtime_config(repository_root) .is_ok_and(|config| config.access_policy.telemetry_enabled()); @@ -127,16 +519,26 @@ fn claude_telemetry_report(repository_root: &std::path::Path) -> String { telemetry_enabled, setup::claude_telemetry::resolve_claude_settings_path().as_deref(), &setup::claude_telemetry::managed_claude_settings_path(), + authorization_check, + || auth_command::repository_telemetry_authorized(repository_root), ) + .await } -fn render_claude_telemetry_section( +async fn render_claude_telemetry_section( telemetry_enabled: bool, settings_path: Option<&std::path::Path>, managed_settings_path: &std::path::Path, -) -> String { + authorization_check: RepositoryAuthorizationCheck, + repository_authorized: A, +) -> String +where + A: FnOnce() -> AF, + AF: Future, +{ use setup::claude_telemetry::{ format_claude_telemetry_report, install_claude_telemetry, ClaudeTelemetryInstallOutcome, + RepositoryAuthorization, }; if !telemetry_enabled { @@ -148,9 +550,18 @@ fn render_claude_telemetry_section( .unwrap_or(ClaudeTelemetryInstallOutcome::SkippedInvalid), None => ClaudeTelemetryInstallOutcome::SkippedInvalid, }; - let authentication_pending = installed == ClaudeTelemetryInstallOutcome::Configured; + let authorization = match (&installed, authorization_check) { + (ClaudeTelemetryInstallOutcome::Configured, RepositoryAuthorizationCheck::Verify) => { + if repository_authorized().await { + RepositoryAuthorization::Authorized + } else { + RepositoryAuthorization::Unauthorized + } + } + _ => RepositoryAuthorization::NotChecked, + }; - format_claude_telemetry_report(&installed, authentication_pending) + format_claude_telemetry_report(&installed, authorization) } fn resolve_setup_repository(start_path: &std::path::Path) -> Result { @@ -217,14 +628,36 @@ mod tests { use serde_json::Value; use super::*; + use crate::services::auth_command::TelemetryProvisioningResult; + use crate::services::config::AuthMode; use crate::services::setup::{ resolve_setup_dispatch, resolve_setup_request, ConcreteSetupTarget, - PersistedSetupConfirmations, SetupCliOptions, SetupDispatch, SetupMode, SetupTarget, - SetupTargetPrompter, + PersistedSetupConfirmations, SetupAccessGate, SetupCliOptions, SetupDispatch, SetupMode, + SetupTarget, SetupTargetPrompter, }; struct FakePrompter { targets: Option>, + auth_mode: Option, + telemetry_consent: bool, + } + + impl FakePrompter { + fn with_targets(targets: Option>) -> Self { + Self { + targets, + auth_mode: None, + telemetry_consent: false, + } + } + + fn answering(auth_mode: AuthMode, telemetry_consent: bool) -> Self { + Self { + targets: Some(vec![ConcreteSetupTarget::OpenCode]), + auth_mode: Some(auth_mode), + telemetry_consent, + } + } } impl SetupTargetPrompter for FakePrompter { @@ -239,11 +672,23 @@ mod tests { Ok(Some(Vec::new())) } - fn prompt_agent_trace_auto_sync(&self) -> Result> { + fn prompt_agent_trace_auto_sync(&self, _default: bool) -> Result> { Ok(Some(false)) } - fn prompt_attribution_hooks_enabled(&self) -> Result> { + fn prompt_attribution_hooks_enabled(&self, _default: bool) -> Result> { + Ok(Some(false)) + } + + fn prompt_auth_mode(&self, default: AuthMode) -> Result> { + Ok(Some(self.auth_mode.unwrap_or(default))) + } + + fn prompt_telemetry_consent(&self, _default: bool) -> Result> { + Ok(Some(self.telemetry_consent)) + } + + fn prompt_login(&self) -> Result> { Ok(Some(false)) } } @@ -251,55 +696,204 @@ mod tests { fn dispatch_for(mode: SetupMode, prompted: Option>) -> SetupDispatch { resolve_setup_dispatch( mode, - &FakePrompter { targets: prompted }, + &FakePrompter::with_targets(prompted), &[], &[], PersistedSetupConfirmations::default(), + SetupAccessGate::default(), + false, ) .expect("dispatch should resolve") } + fn render_claude_telemetry( + telemetry_enabled: bool, + settings_path: &Path, + managed_settings_path: &Path, + authorization_check: RepositoryAuthorizationCheck, + repository_authorized: Option, + ) -> (String, bool) { + let looked_up = std::cell::Cell::new(false); + let report = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(render_claude_telemetry_section( + telemetry_enabled, + Some(settings_path), + managed_settings_path, + authorization_check, + || { + looked_up.set(true); + async move { + repository_authorized.expect("repository authorization lookup must not run") + } + }, + )); + (report, looked_up.get()) + } + fn run_claude_telemetry_stage( + request_mode: Option, dispatch: Option<&SetupDispatch>, telemetry_enabled: bool, root: &Path, ) -> Option { + let authorization_check = RepositoryAuthorizationCheck::for_mode(request_mode); + let authorized = + (authorization_check == RepositoryAuthorizationCheck::Verify).then_some(false); dispatch_targets_claude(dispatch).then(|| { - render_claude_telemetry_section( + render_claude_telemetry( telemetry_enabled, - Some(&root.join("settings.json")), + &root.join("settings.json"), &root.join("managed.json"), + authorization_check, + authorized, ) + .0 }) } + const CLAUDE_CONFIGURED_LINE: &str = + "Claude telemetry: configured in user-level Claude settings for native OpenTelemetry export."; + const CLAUDE_NOT_READY_LINE: &str = "Claude telemetry: not ready for this repository; no valid SCE telemetry credential is authorized for it, so Claude will not export. Run 'sce auth login' in this repository with the SCE account it is enrolled under."; + const CLAUDE_NOT_CHECKED_LINE: &str = "Claude telemetry: configured; repository authorization was not checked during non-interactive setup."; + #[test] - fn setup_claude_telemetry_reports_skip_without_repository_enrollment() { - let dir = tempfile::tempdir().unwrap(); - let settings = dir.path().join("settings.json"); - fs::write(&settings, r#"{"otelHeadersHelper":"my-helper"}"#).unwrap(); + fn setup_claude_telemetry_readiness_follows_repository_authorization() { + use RepositoryAuthorizationCheck::{Skip, Verify}; - let report = render_claude_telemetry_section( - true, - Some(&settings), - &dir.path().join("managed.json"), - ); + let configured_not_ready = format!("{CLAUDE_CONFIGURED_LINE}\n{CLAUDE_NOT_READY_LINE}"); + let conflict = Some(r#"{"otelHeadersHelper":"my-helper"}"#); + let conflict_line = "Claude telemetry: skipped; existing Claude settings define a different otelHeadersHelper."; + let invalid_line = "Claude telemetry: skipped; existing Claude settings could not be parsed and were left unchanged."; + let cases = [ + ( + "interactive authorized", + Verify, + true, + None, + Some(true), + CLAUDE_CONFIGURED_LINE, + ), + ( + "interactive unauthorized", + Verify, + true, + None, + Some(false), + configured_not_ready.as_str(), + ), + ( + "non-interactive not checked", + Skip, + true, + None, + None, + CLAUDE_NOT_CHECKED_LINE, + ), + ( + "interactive telemetry disabled", + Verify, + false, + None, + None, + CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE, + ), + ( + "non-interactive telemetry disabled", + Skip, + false, + None, + None, + CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE, + ), + ( + "interactive settings conflict", + Verify, + true, + conflict, + None, + conflict_line, + ), + ( + "non-interactive settings conflict", + Skip, + true, + conflict, + None, + conflict_line, + ), + ( + "interactive invalid settings", + Verify, + true, + Some("{not json"), + None, + invalid_line, + ), + ( + "non-interactive invalid settings", + Skip, + true, + Some("{not json"), + None, + invalid_line, + ), + ]; + + for (name, check, telemetry_enabled, existing, authorized, expected) in cases { + let dir = tempfile::tempdir().unwrap(); + let settings = dir.path().join("settings.json"); + if let Some(existing) = existing { + fs::write(&settings, existing).unwrap(); + } + + let (report, looked_up) = render_claude_telemetry( + telemetry_enabled, + &settings, + &dir.path().join("managed.json"), + check, + authorized, + ); - assert!(report.contains("skipped")); - assert!(!report.contains("authentication pending")); + assert_eq!(report, expected, "{name}"); + assert_eq!(looked_up, authorized.is_some(), "{name}"); + assert!(!report.contains("Bearer"), "{name}"); + } } #[test] - fn setup_claude_telemetry_defers_repository_enrollment_to_auth_login() { - let dir = tempfile::tempdir().unwrap(); + fn setup_repository_authorization_is_checked_only_for_interactive_setup() { + let request_mode = |target, non_interactive| { + resolve_setup_request(SetupCliOptions { + target, + non_interactive, + ..SetupCliOptions::default() + }) + .unwrap() + .config_mode + }; - let report = render_claude_telemetry_section( - true, - Some(&dir.path().join("settings.json")), - &dir.path().join("managed.json"), + assert_eq!( + RepositoryAuthorizationCheck::for_mode(request_mode(None, false)), + RepositoryAuthorizationCheck::Verify + ); + for target in [SetupTarget::Claude, SetupTarget::All] { + for non_interactive in [true, false] { + assert_eq!( + RepositoryAuthorizationCheck::for_mode(request_mode( + Some(target), + non_interactive + )), + RepositoryAuthorizationCheck::Skip, + "{target:?} non_interactive={non_interactive}" + ); + } + } + assert_eq!( + RepositoryAuthorizationCheck::for_mode(None), + RepositoryAuthorizationCheck::Skip ); - - assert!(report.contains("authentication pending")); } fn assert_installed(root: &Path) { @@ -319,25 +913,44 @@ mod tests { SetupMode::Interactive, Some(vec![ConcreteSetupTarget::Claude]), ); - for dispatch in [ - dispatch_for(SetupMode::NonInteractive(SetupTarget::Claude), None), - dispatch_for(SetupMode::NonInteractive(SetupTarget::All), None), - interactive, + let configured_not_ready = format!("{CLAUDE_CONFIGURED_LINE}\n{CLAUDE_NOT_READY_LINE}"); + for (mode, dispatch, expected) in [ + ( + SetupMode::NonInteractive(SetupTarget::Claude), + dispatch_for(SetupMode::NonInteractive(SetupTarget::Claude), None), + CLAUDE_NOT_CHECKED_LINE, + ), + ( + SetupMode::NonInteractive(SetupTarget::All), + dispatch_for(SetupMode::NonInteractive(SetupTarget::All), None), + CLAUDE_NOT_CHECKED_LINE, + ), + ( + SetupMode::Interactive, + interactive, + configured_not_ready.as_str(), + ), ] { let dir = tempfile::tempdir().unwrap(); - assert!(run_claude_telemetry_stage(Some(&dispatch), true, dir.path()).is_some()); + assert_eq!( + run_claude_telemetry_stage(Some(mode), Some(&dispatch), true, dir.path()) + .as_deref(), + Some(expected), + "{mode:?}" + ); assert_installed(dir.path()); } } #[test] fn setup_claude_telemetry_skips_install_when_telemetry_is_disabled_by_config() { + let mode = Some(SetupMode::NonInteractive(SetupTarget::Claude)); let dispatch = dispatch_for(SetupMode::NonInteractive(SetupTarget::Claude), None); let dir = tempfile::tempdir().unwrap(); assert_eq!( - run_claude_telemetry_stage(Some(&dispatch), false, dir.path()).as_deref(), + run_claude_telemetry_stage(mode, Some(&dispatch), false, dir.path()).as_deref(), Some(CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE) ); assert_untouched(dir.path()); @@ -346,7 +959,7 @@ mod tests { let existing = br#"{"env":{"FOO":"bar"},"model":"opus"}"#; fs::write(dir.path().join("settings.json"), existing).unwrap(); assert_eq!( - run_claude_telemetry_stage(Some(&dispatch), false, dir.path()).as_deref(), + run_claude_telemetry_stage(mode, Some(&dispatch), false, dir.path()).as_deref(), Some("Claude telemetry: skipped; SCE telemetry is disabled by config.") ); assert_eq!( @@ -354,11 +967,8 @@ mod tests { existing ); - let report = run_claude_telemetry_stage(Some(&dispatch), true, dir.path()).unwrap(); - assert_eq!( - report, - "Claude telemetry: configured in user-level Claude settings for native OpenTelemetry export.\nClaude telemetry: authentication pending for this repository; run 'sce auth login' in this repository to start exporting." - ); + let report = run_claude_telemetry_stage(mode, Some(&dispatch), true, dir.path()).unwrap(); + assert_eq!(report, CLAUDE_NOT_CHECKED_LINE); assert_installed(dir.path()); let parsed: Value = serde_json::from_slice(&fs::read(dir.path().join("settings.json")).unwrap()).unwrap(); @@ -424,19 +1034,639 @@ mod tests { assert_eq!(hooks_only.config_mode, None); assert!(bootstrap.context_only); + let opencode = SetupMode::NonInteractive(SetupTarget::OpenCode); let dispatches = [ - Some(dispatch_for( - SetupMode::NonInteractive(SetupTarget::OpenCode), - None, - )), - Some(dispatch_for(SetupMode::Interactive, None)), - None, + (Some(opencode), Some(dispatch_for(opencode, None))), + ( + Some(SetupMode::Interactive), + Some(dispatch_for(SetupMode::Interactive, None)), + ), + (hooks_only.config_mode, None), + (bootstrap.config_mode, None), ]; - for dispatch in &dispatches { + for (mode, dispatch) in &dispatches { let dir = tempfile::tempdir().unwrap(); - assert!(run_claude_telemetry_stage(dispatch.as_ref(), true, dir.path()).is_none()); + assert!( + run_claude_telemetry_stage(*mode, dispatch.as_ref(), true, dir.path()).is_none() + ); assert_untouched(dir.path()); } } + + struct AccessFixture { + _dir: tempfile::TempDir, + repo: std::path::PathBuf, + global: std::path::PathBuf, + } + + impl AccessFixture { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let repo = dir.path().join("repo"); + fs::create_dir_all(repo.join(".git")).unwrap(); + let global = dir.path().join("global").join("config.json"); + fs::create_dir_all(global.parent().unwrap()).unwrap(); + Self { + _dir: dir, + repo, + global, + } + } + + fn write_repo_config(&self, json: &str) { + fs::create_dir_all(self.repo.join(".sce")).unwrap(); + fs::write(self.repo.join(".sce").join("config.json"), json).unwrap(); + } + + fn resolve_policy(&self) -> impl Fn(&Path) -> Result + '_ { + move |root| { + config::resolver::resolve_auth_runtime_config_with( + root, + |_| None, + |path| fs::read_to_string(path).map_err(anyhow::Error::from), + Path::exists, + || Ok(self.global.clone()), + ) + .map(|config| config.access_policy) + } + } + + fn prepare(&self, prompter: &FakePrompter) -> Result { + self.prepare_with(prompter, false) + } + + fn prepare_with( + &self, + prompter: &FakePrompter, + reconfigure: bool, + ) -> Result { + prepare_interactive_setup( + &self.repo, + prompter, + &[], + &self.global, + self.resolve_policy(), + false, + reconfigure, + ) + } + + fn report(&self, access_save: &SetupAccessSave, auth_db_present: bool) -> String { + setup_access_report( + &self.repo, + access_save, + self.resolve_policy(), + auth_db_present, + ) + .unwrap() + .0 + } + + fn policy(&self) -> ResolvedAccessPolicy { + self.resolve_policy()(&self.repo).unwrap() + } + } + + fn ready(setup: Result) -> (SetupDispatch, SetupAccessSave) { + match setup.expect("interactive setup should prepare") { + InteractiveSetup::Ready { + dispatch, + access_save, + } => (dispatch, access_save), + InteractiveSetup::Cancelled => panic!("interactive setup should not cancel"), + } + } + + fn read_json_file(path: &Path) -> Value { + serde_json::from_slice(&fs::read(path).unwrap()).unwrap() + } + + #[test] + fn interactive_setup_saves_access_answers_only_to_the_global_config() { + let fixture = AccessFixture::new(); + fs::write(&fixture.global, "{\"log_level\": \"debug\"}\n").unwrap(); + + let (dispatch, access_save) = + ready(fixture.prepare(&FakePrompter::answering(AuthMode::Mandatory, true))); + + let global = read_json_file(&fixture.global); + assert_eq!(global["auth"]["mode"], "mandatory"); + assert_eq!(global["telemetry"]["enabled"], true); + assert_eq!(global["log_level"], "debug"); + assert_eq!(access_save.outcome, GlobalWriteOutcome::Written); + + let SetupDispatch::Proceed { + targets, + target_persistence, + agent_trace_auto_sync, + attribution_hooks_enabled, + .. + } = dispatch + else { + panic!("dispatch should proceed"); + }; + setup::persist_integration_targets( + &fixture.repo, + &targets, + target_persistence, + &[], + agent_trace_auto_sync, + attribution_hooks_enabled, + ) + .unwrap(); + + let repository = read_json_file(&fixture.repo.join(".sce").join("config.json")); + let repository = repository.as_object().unwrap(); + assert!(!repository.contains_key("auth")); + assert!(!repository.contains_key("telemetry")); + } + + #[test] + fn interactive_setup_rerun_leaves_the_global_config_bytes_unchanged() { + let fixture = AccessFixture::new(); + let prompter = FakePrompter::answering(AuthMode::Optional, false); + + ready(fixture.prepare(&prompter)); + let first = fs::read(&fixture.global).unwrap(); + + let (_, rerun) = ready(fixture.prepare(&prompter)); + assert_eq!( + rerun, + SetupAccessSave { + global_config_path: fixture.global.clone(), + auth_mode: None, + telemetry_enabled: None, + outcome: GlobalWriteOutcome::Unchanged, + prompts_suppressed: true, + } + ); + assert_eq!(fs::read(&fixture.global).unwrap(), first); + + let repeated = persist_setup_access_preferences( + &fixture.global, + Some(AuthMode::Optional), + Some(false), + ) + .unwrap(); + assert_eq!(repeated.outcome, GlobalWriteOutcome::Unchanged); + assert_eq!(fs::read(&fixture.global).unwrap(), first); + } + + #[test] + fn interactive_setup_skips_access_writes_when_the_global_config_is_invalid() { + let fixture = AccessFixture::new(); + let invalid = b"{\"auth\": {\"mode\": \"sometimes\"}}\n"; + fs::write(&fixture.global, invalid).unwrap(); + + let (dispatch, access_save) = + ready(fixture.prepare(&FakePrompter::answering(AuthMode::Mandatory, true))); + + assert!(matches!( + dispatch, + SetupDispatch::Proceed { + auth_mode: None, + telemetry_enabled: None, + .. + } + )); + assert_eq!(access_save.outcome, GlobalWriteOutcome::Unchanged); + assert_eq!(fs::read(&fixture.global).unwrap(), invalid); + } + + #[cfg(unix)] + #[test] + fn interactive_setup_aborts_before_repository_writes_when_the_global_config_is_read_only() { + use std::os::unix::fs::PermissionsExt; + + let fixture = AccessFixture::new(); + let global_dir = fixture.global.parent().unwrap().to_path_buf(); + fs::set_permissions(&global_dir, fs::Permissions::from_mode(0o555)).unwrap(); + + let result = fixture.prepare(&FakePrompter::answering(AuthMode::Optional, true)); + fs::set_permissions(&global_dir, fs::Permissions::from_mode(0o755)).unwrap(); + + let error = result.expect_err("read-only global config should abort setup"); + let message = error.to_string(); + assert!(message.starts_with(&format!( + "Failed to save SCE access preferences to the global SCE config '{}'.\n", + fixture.global.display() + ))); + assert!(message.ends_with(GLOBAL_ACCESS_WRITE_REMEDIATION)); + assert_eq!(error.code(), "SCE-ERR-RUNTIME"); + assert!(!fixture.global.exists()); + assert!(!fixture.repo.join("context").exists()); + assert!(!fixture.repo.join(".sce").exists()); + } + + #[cfg(unix)] + #[test] + fn interactive_setup_aborts_before_repository_writes_when_the_global_config_is_a_symlink() { + let fixture = AccessFixture::new(); + let target = fixture.global.with_file_name("managed.json"); + let original = b"{\"log_level\": \"info\"}\n"; + fs::write(&target, original).unwrap(); + std::os::unix::fs::symlink(&target, &fixture.global).unwrap(); + + let error = fixture + .prepare(&FakePrompter::answering(AuthMode::Optional, true)) + .expect_err("symlinked global config should abort setup"); + + let message = error.to_string(); + assert!(message.contains("is a symlink and was left unchanged")); + assert!(message.ends_with(GLOBAL_ACCESS_SYMLINK_REMEDIATION)); + assert!(!message.contains("sce config validate")); + assert_eq!(fs::read_link(&fixture.global).unwrap(), target); + assert_eq!(fs::read(&target).unwrap(), original); + assert!(!fixture.repo.join("context").exists()); + assert!(!fixture.repo.join(".sce").exists()); + } + + #[test] + fn setup_access_write_refuses_an_invalid_global_config_with_a_fixed_message() { + let fixture = AccessFixture::new(); + fs::write(&fixture.global, "{not json").unwrap(); + + let error = persist_setup_access_preferences(&fixture.global, None, Some(true)) + .expect_err("invalid global config should not be overwritten"); + + let message = error.to_string(); + assert!(message.starts_with(&format!( + "Failed to save SCE access preferences to the global SCE config '{}'.\nGlobal SCE config '{}' is invalid and was left unchanged: ", + fixture.global.display(), + fixture.global.display() + ))); + assert!(message.ends_with(&format!("\n{GLOBAL_ACCESS_WRITE_REMEDIATION}"))); + assert_eq!(fs::read(&fixture.global).unwrap(), b"{not json"); + } + + #[test] + fn setup_access_section_reports_repository_opt_out_after_global_consent() { + let fixture = AccessFixture::new(); + fixture.write_repo_config(r#"{"telemetry":{"enabled":false}}"#); + + let (_, access_save) = + ready(fixture.prepare(&FakePrompter::answering(AuthMode::Optional, true))); + + assert_eq!( + fixture.report(&access_save, false), + format!( + "SCE access:\n\ + - auth.mode: optional (saved to global SCE config '{path}'; applies to all repositories on this machine)\n\ + - telemetry.enabled: true (saved to global SCE config '{path}'; applies to all repositories on this machine)\n\ + - effective auth.mode: optional (source: config_file, config_source: default_discovered_global)\n\ + - effective telemetry: disabled (reason: repository_opt_out)", + path = fixture.global.display() + ) + ); + } + + #[test] + fn setup_access_section_renders_exact_lines() { + let unchanged = |fixture: &AccessFixture| SetupAccessSave { + global_config_path: fixture.global.clone(), + auth_mode: None, + telemetry_enabled: None, + outcome: GlobalWriteOutcome::Unchanged, + prompts_suppressed: false, + }; + + let fixture = AccessFixture::new(); + fs::write( + &fixture.global, + r#"{"auth":{"mode":"optional"},"telemetry":{"enabled":true}}"#, + ) + .unwrap(); + assert_eq!( + fixture.report(&unchanged(&fixture), true), + format!( + "SCE access:\n\ + - saved access preferences: unchanged (global SCE config '{}')\n\ + - effective auth.mode: optional (source: config_file, config_source: default_discovered_global)\n\ + - effective telemetry: enabled", + fixture.global.display() + ) + ); + + let fixture = AccessFixture::new(); + let access_save = + persist_setup_access_preferences(&fixture.global, Some(AuthMode::Disabled), None) + .unwrap(); + assert_eq!( + fixture.report(&access_save, true), + format!( + "SCE access:\n\ + - auth.mode: disabled (saved to global SCE config '{}'; applies to all repositories on this machine)\n\ + - effective auth.mode: disabled (source: config_file, config_source: default_discovered_global)\n\ + - effective telemetry: disabled (reason: auth_disabled)\n\ + {AUTH_LOGOUT_HINT_LINE}", + fixture.global.display() + ) + ); + assert!(!fixture + .report(&access_save, false) + .contains("sce auth logout")); + + let fixture = AccessFixture::new(); + fixture.write_repo_config(r#"{"auth":{"mode":"disabled"}}"#); + assert_eq!( + fixture.report(&unchanged(&fixture), false), + format!( + "SCE access:\n\ + - saved access preferences: unchanged (global SCE config '{}')\n\ + - effective auth.mode: disabled (source: config_file, config_source: default_discovered_local)\n\ + - effective telemetry: disabled (reason: auth_disabled)\n\ + - Authentication is disabled by `auth.mode: disabled` in the repository SCE config (`.sce/config.json`).", + fixture.global.display() + ) + ); + } + + #[test] + fn setup_access_section_hints_reconfigure_when_saved_answers_suppressed_prompts() { + let fixture = AccessFixture::new(); + let prompter = FakePrompter::answering(AuthMode::Optional, false); + ready(fixture.prepare(&prompter)); + + let (_, rerun) = ready(fixture.prepare(&prompter)); + assert_eq!( + fixture.report(&rerun, false), + format!( + "SCE access:\n\ + - saved access preferences: unchanged (global SCE config '{}')\n\ + - effective auth.mode: optional (source: config_file, config_source: default_discovered_global)\n\ + - effective telemetry: disabled (reason: user_opt_out)\n\ + - Run 'sce setup --reconfigure' to change saved setup answers.", + fixture.global.display() + ) + ); + + let (_, reconfigured) = ready(fixture.prepare_with(&prompter, true)); + assert!(!reconfigured.prompts_suppressed); + assert!(!fixture + .report(&reconfigured, false) + .contains(RECONFIGURE_HINT_LINE)); + } + + #[test] + fn reconfigure_rewrites_saved_global_answers() { + let fixture = AccessFixture::new(); + ready(fixture.prepare(&FakePrompter::answering(AuthMode::Disabled, false))); + assert_eq!(read_json_file(&fixture.global)["auth"]["mode"], "disabled"); + + let (rerun, _) = + ready(fixture.prepare(&FakePrompter::answering(AuthMode::Mandatory, true))); + assert!(matches!( + rerun, + SetupDispatch::Proceed { + auth_mode: None, + telemetry_enabled: None, + .. + } + )); + assert_eq!(read_json_file(&fixture.global)["auth"]["mode"], "disabled"); + + let (dispatch, access_save) = + ready(fixture.prepare_with(&FakePrompter::answering(AuthMode::Mandatory, true), true)); + assert!(matches!( + dispatch, + SetupDispatch::Proceed { + auth_mode: Some(AuthMode::Mandatory), + telemetry_enabled: Some(true), + .. + } + )); + assert_eq!(access_save.outcome, GlobalWriteOutcome::Written); + let global = read_json_file(&fixture.global); + assert_eq!(global["auth"]["mode"], "mandatory"); + assert_eq!(global["telemetry"]["enabled"], true); + } + + const LOGIN_RENDERED: &str = "Logged in to SCE.\nTelemetry credential provisioned."; + + fn login_success(telemetry: TelemetryProvisioningResult) -> SetupLoginStatus { + SetupLoginStatus::Authenticated(LoginReport { + rendered: LOGIN_RENDERED.to_string(), + telemetry, + }) + } + + fn policy_for(global: Option<&str>, repository: Option<&str>) -> ResolvedAccessPolicy { + let fixture = AccessFixture::new(); + if let Some(global) = global { + fs::write(&fixture.global, global).unwrap(); + } + if let Some(repository) = repository { + fixture.write_repo_config(repository); + } + fixture.policy() + } + + fn run_login_step(action: SetupLoginAction, login: F) -> Result + where + F: FnOnce() -> Result, + { + tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(run_setup_login_step(action, || async move { login() })) + } + + fn login_must_not_run() -> Result { + panic!("login must not be invoked") + } + + #[test] + fn setup_login_action_covers_every_effective_mode_and_intent() { + use crate::services::setup::SetupLoginIntent::{Declined, NotOffered, Requested}; + + let optional = policy_for(Some(r#"{"auth":{"mode":"optional"}}"#), None); + let mandatory = policy_for(Some(r#"{"auth":{"mode":"mandatory"}}"#), None); + let disabled = policy_for(Some(r#"{"auth":{"mode":"disabled"}}"#), None); + let repository_mandatory = policy_for( + Some(r#"{"auth":{"mode":"optional"}}"#), + Some(r#"{"auth":{"mode":"mandatory"}}"#), + ); + let repository_disabled = policy_for( + Some(r#"{"auth":{"mode":"mandatory"}}"#), + Some(r#"{"auth":{"mode":"disabled"}}"#), + ); + let default = policy_for(None, None); + + let auth_disabled = SetupLoginAction::Skip(SetupLoginSkip::AuthDisabled); + let required = SetupLoginAction::Run { required: true }; + for (policy, intent, expected) in [ + ( + &optional, + Requested, + SetupLoginAction::Run { required: false }, + ), + ( + &optional, + Declined, + SetupLoginAction::Skip(SetupLoginSkip::Declined), + ), + ( + &optional, + NotOffered, + SetupLoginAction::Skip(SetupLoginSkip::NotOffered), + ), + ( + &default, + Requested, + SetupLoginAction::Run { required: false }, + ), + ( + &default, + NotOffered, + SetupLoginAction::Skip(SetupLoginSkip::NotOffered), + ), + (&mandatory, Requested, required), + (&mandatory, Declined, required), + (&mandatory, NotOffered, required), + (&repository_mandatory, Declined, required), + (&repository_mandatory, NotOffered, required), + (&disabled, Requested, auth_disabled), + (&disabled, Declined, auth_disabled), + (&disabled, NotOffered, auth_disabled), + (&repository_disabled, Requested, auth_disabled), + (&repository_disabled, NotOffered, auth_disabled), + ] { + assert_eq!( + setup_login_action(policy, intent), + expected, + "{:?} {intent:?}", + policy.auth_mode + ); + } + } + + #[test] + fn setup_login_step_never_invokes_login_when_skipped() { + for skip in [ + SetupLoginSkip::AuthDisabled, + SetupLoginSkip::Declined, + SetupLoginSkip::NotOffered, + ] { + let status = run_login_step(SetupLoginAction::Skip(skip), login_must_not_run).unwrap(); + assert_eq!(status, SetupLoginStatus::Skipped(skip)); + } + } + + #[test] + fn setup_login_step_reports_optional_failure_as_successful_setup() { + let status = run_login_step(SetupLoginAction::Run { required: false }, || { + Err(CliError::user_with_source( + UserError::NotAuthenticated, + anyhow::anyhow!("device code expired"), + )) + }) + .unwrap(); + assert_eq!( + status, + SetupLoginStatus::Failed(UserError::NotAuthenticated) + ); + assert_eq!( + render_setup_login_section(&status), + format!( + "SCE login: failed: {}\nRun 'sce auth login' to retry.", + UserError::NotAuthenticated.message() + ) + ); + + let status = run_login_step(SetupLoginAction::Run { required: false }, || { + Err(CliError::runtime(anyhow::anyhow!( + "access_token=secret-value leaked in a diagnostic" + ))) + }) + .unwrap(); + assert_eq!( + status, + SetupLoginStatus::Failed(UserError::UnexpectedFailure) + ); + assert!(!render_setup_login_section(&status).contains("secret-value")); + } + + #[test] + fn setup_login_step_fails_mandatory_login_with_setup_login_required() { + let error = run_login_step(SetupLoginAction::Run { required: true }, || { + Err(CliError::user_with_source( + UserError::NotAuthenticated, + anyhow::anyhow!("device code expired"), + )) + }) + .unwrap_err(); + + let CliError::User { + error: user_error, + source: Some(source), + } = &error + else { + panic!("expected a user error with the login error as source"); + }; + assert_eq!(*user_error, UserError::SetupLoginRequired); + assert_eq!(user_error.key(), "auth.setup_login_required"); + assert_eq!(error.code(), "SCE-ERR-RUNTIME"); + assert_eq!(source.to_string(), UserError::NotAuthenticated.message()); + } + + #[test] + fn setup_login_step_includes_login_text_for_mandatory_and_accepted_optional_login() { + for required in [true, false] { + let status = run_login_step(SetupLoginAction::Run { required }, || { + Ok(LoginReport { + rendered: LOGIN_RENDERED.to_string(), + telemetry: TelemetryProvisioningResult::Issued, + }) + }) + .unwrap(); + assert_eq!(status, login_success(TelemetryProvisioningResult::Issued)); + assert_eq!(render_setup_login_section(&status), LOGIN_RENDERED); + } + } + + #[test] + fn setup_login_section_renders_exact_skip_lines_without_credentials() { + for (skip, expected) in [ + ( + SetupLoginSkip::AuthDisabled, + "SCE login: skipped; SCE authentication is disabled by config.", + ), + ( + SetupLoginSkip::Declined, + "SCE login: skipped; run 'sce auth login' to log in.", + ), + ( + SetupLoginSkip::NotOffered, + "SCE login: not requested; run 'sce auth login' to log in or refresh credentials.", + ), + ] { + assert_eq!( + render_setup_login_section(&SetupLoginStatus::Skipped(skip)), + expected + ); + } + + let tokens = crate::services::token_storage::StoredTokens { + access_token: "secret-access-token-value".to_string(), + token_type: "Bearer".to_string(), + expires_in: 3600, + refresh_token: "secret-refresh-token-value".to_string(), + scope: None, + stored_at_unix_seconds: 1, + }; + let rendered = auth_command::render_login_refresh_result_with_telemetry( + &tokens, + AuthFormat::Text, + TelemetryProvisioningResult::Issued, + ) + .unwrap(); + let output = render_setup_login_section(&SetupLoginStatus::Authenticated(LoginReport { + rendered, + telemetry: TelemetryProvisioningResult::Issued, + })); + assert!(output.contains("Authentication succeeded.")); + assert!(!output.contains("secret-access-token-value")); + assert!(!output.contains("secret-refresh-token-value")); + } } diff --git a/cli/src/services/setup/mod.rs b/cli/src/services/setup/mod.rs index 0834ff93f..536968fa6 100644 --- a/cli/src/services/setup/mod.rs +++ b/cli/src/services/setup/mod.rs @@ -5,9 +5,13 @@ use std::{ path::{Path, PathBuf}, }; +use crate::services::config::{AuthMode, ConfigPathSource, ResolvedAccessPolicy, ValueSource}; +use crate::services::error::AuthPolicyConfigFile; use crate::services::style::{label, success, value}; use crate::services::{default_paths, default_paths::RepoPaths}; +pub(crate) mod access_preferences; +mod atomic_write; pub(crate) mod claude_telemetry; pub mod command; pub(crate) mod config_merge; @@ -228,11 +232,16 @@ pub enum SetupDispatch { optional_workflows: Option>, agent_trace_auto_sync: Option, attribution_hooks_enabled: Option, + auth_mode: Option, + telemetry_enabled: Option, + login_intent: SetupLoginIntent, + prompts_suppressed: bool, }, Cancelled, } #[derive(Clone, Debug, Default, Eq, PartialEq)] +#[allow(clippy::struct_excessive_bools)] pub struct SetupCliOptions { pub target: Option, pub non_interactive: bool, @@ -241,6 +250,7 @@ pub struct SetupCliOptions { pub bootstrap_context: bool, pub workflows: Vec, + pub reconfigure: bool, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -251,9 +261,18 @@ pub struct SetupRequest { pub context_only: bool, pub optional_workflows: Option>, + pub reconfigure: bool, } pub fn resolve_setup_request(options: SetupCliOptions) -> Result { + if options.reconfigure { + if let Some(conflict) = reconfigure_conflicting_option(&options) { + bail!( + "Option '--reconfigure' cannot be used with '{conflict}'. Try: run 'sce setup --reconfigure' alone to change saved setup answers interactively." + ); + } + } + if options.repo_path.is_some() && !options.hooks { bail!( "Option '--repo' requires '--hooks'. Try: run 'sce setup --hooks --repo ' or remove '--repo'." @@ -289,6 +308,7 @@ pub fn resolve_setup_request(options: SetupCliOptions) -> Result { hooks_repo_path: None, context_only: true, optional_workflows: None, + reconfigure: false, }); } @@ -315,9 +335,34 @@ pub fn resolve_setup_request(options: SetupCliOptions) -> Result { hooks_repo_path: options.repo_path, context_only: false, optional_workflows, + reconfigure: options.reconfigure, }) } +fn reconfigure_conflicting_option(options: &SetupCliOptions) -> Option<&'static str> { + if let Some(target) = options.target { + return Some(setup_target_flag(target)); + } + [ + (options.non_interactive, "--non-interactive"), + (options.hooks, "--hooks"), + (options.repo_path.is_some(), "--repo"), + (options.bootstrap_context, "--bootstrap-context"), + ] + .into_iter() + .find_map(|(present, flag)| present.then_some(flag)) +} + +fn setup_target_flag(target: SetupTarget) -> &'static str { + match target { + SetupTarget::OpenCode => "--opencode", + SetupTarget::Claude => "--claude", + SetupTarget::Pi => "--pi", + SetupTarget::Codex => "--codex", + SetupTarget::All => "--all", + } +} + fn validate_optional_workflow_slugs(raw_slugs: &[String]) -> Result> { let mut selected: Vec = Vec::new(); @@ -428,6 +473,34 @@ pub fn persisted_optional_workflows(repository_root: &Path) -> Vec { pub struct PersistedSetupConfirmations { pub agent_trace_auto_sync: Option, pub attribution_hooks_enabled: Option, + pub auth_mode: Option, + pub telemetry_enabled: Option, + pub global_config_invalid: bool, +} + +impl PersistedSetupConfirmations { + pub(crate) fn with_global_access_preferences( + self, + preferences: access_preferences::GlobalAccessPreferences, + ) -> Self { + use access_preferences::GlobalAccessPreferences; + + match preferences { + GlobalAccessPreferences::Missing => self, + GlobalAccessPreferences::Valid { + auth_mode, + telemetry_enabled, + } => Self { + auth_mode, + telemetry_enabled, + ..self + }, + GlobalAccessPreferences::Invalid => Self { + global_config_invalid: true, + ..self + }, + } + } } pub fn persisted_setup_confirmations(repository_root: &Path) -> PersistedSetupConfirmations { @@ -440,14 +513,44 @@ pub fn persisted_setup_confirmations(repository_root: &Path) -> PersistedSetupCo attribution_hooks_enabled: config .attribution_hooks_enabled .map(|setting| setting.value), + ..PersistedSetupConfirmations::default() + } +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct SetupAccessGate { + pub auth_locked_by: Option, + pub mandatory_locked: bool, + pub auth_db_present: bool, +} + +impl SetupAccessGate { + pub(crate) fn from_policy(policy: &ResolvedAccessPolicy, auth_db_present: bool) -> Self { + let auth_locked_by = policy + .auth_disabled_config_file() + .filter(|file| *file != AuthPolicyConfigFile::Global); + + Self { + auth_locked_by, + mandatory_locked: policy.auth_mode.value == AuthMode::Mandatory + && policy.auth_mode.source + != ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal), + auth_db_present, + } } } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SetupLoginIntent { + NotOffered, + Declined, + Requested, +} + fn persisted_file_config( repository_root: &Path, ) -> Option { use crate::services::config::schema::parse_file_config; - use crate::services::config::ConfigPathSource; let config_path = RepoPaths::new(repository_root).sce_config_file(); let raw = fs::read_to_string(&config_path).ok()?; @@ -912,8 +1015,11 @@ pub trait SetupTargetPrompter { defaults: &[ConcreteSetupTarget], ) -> Result>>; fn prompt_optional_workflows(&self, defaults: &[String]) -> Result>>; - fn prompt_agent_trace_auto_sync(&self) -> Result>; - fn prompt_attribution_hooks_enabled(&self) -> Result>; + fn prompt_agent_trace_auto_sync(&self, default: bool) -> Result>; + fn prompt_attribution_hooks_enabled(&self, default: bool) -> Result>; + fn prompt_auth_mode(&self, default: AuthMode) -> Result>; + fn prompt_telemetry_consent(&self, default: bool) -> Result>; + fn prompt_login(&self) -> Result>; } #[derive(Clone, Copy, Debug, Default)] @@ -931,12 +1037,24 @@ impl SetupTargetPrompter for InquireSetupTargetPrompter { prompt::prompt_optional_workflows(defaults) } - fn prompt_agent_trace_auto_sync(&self) -> Result> { - prompt::prompt_agent_trace_auto_sync() + fn prompt_agent_trace_auto_sync(&self, default: bool) -> Result> { + prompt::prompt_agent_trace_auto_sync(default) } - fn prompt_attribution_hooks_enabled(&self) -> Result> { - prompt::prompt_attribution_hooks_enabled() + fn prompt_attribution_hooks_enabled(&self, default: bool) -> Result> { + prompt::prompt_attribution_hooks_enabled(default) + } + + fn prompt_auth_mode(&self, default: AuthMode) -> Result> { + prompt::prompt_auth_mode(default) + } + + fn prompt_telemetry_consent(&self, default: bool) -> Result> { + prompt::prompt_telemetry_consent(default) + } + + fn prompt_login(&self) -> Result> { + prompt::prompt_login() } } @@ -961,6 +1079,8 @@ pub fn resolve_setup_dispatch

( optional_workflow_defaults: &[String], configured_targets: &[ConcreteSetupTarget], persisted_confirmations: PersistedSetupConfirmations, + access_gate: SetupAccessGate, + reconfigure: bool, ) -> Result where P: SetupTargetPrompter, @@ -977,31 +1097,48 @@ where return Ok(SetupDispatch::Cancelled); }; - let Some(agent_trace_auto_sync) = - persisted_confirmations.agent_trace_auto_sync.map_or_else( - || prompter.prompt_agent_trace_auto_sync(), - |value| Ok(Some(value)), - )? + let Some(agent_trace_auto_sync) = persisted_or_prompted( + persisted_confirmations.agent_trace_auto_sync, + reconfigure, + |default| prompter.prompt_agent_trace_auto_sync(default), + )? + else { + return Ok(SetupDispatch::Cancelled); + }; + + let Some(attribution_hooks_enabled) = persisted_or_prompted( + persisted_confirmations.attribution_hooks_enabled, + reconfigure, + |default| prompter.prompt_attribution_hooks_enabled(default), + )? else { return Ok(SetupDispatch::Cancelled); }; - let Some(attribution_hooks_enabled) = persisted_confirmations - .attribution_hooks_enabled - .map_or_else( - || prompter.prompt_attribution_hooks_enabled(), - |value| Ok(Some(value)), - )? + let Some(access) = resolve_setup_access_choices( + prompter, + persisted_confirmations, + access_gate, + reconfigure, + )? else { return Ok(SetupDispatch::Cancelled); }; + let behavior_prompts_suppressed = !reconfigure + && (persisted_confirmations.agent_trace_auto_sync.is_some() + || persisted_confirmations.attribution_hooks_enabled.is_some()); + Ok(SetupDispatch::Proceed { targets, target_persistence: TargetPersistence::Replace, optional_workflows: Some(optional_workflows), agent_trace_auto_sync: Some(agent_trace_auto_sync), attribution_hooks_enabled: Some(attribution_hooks_enabled), + auth_mode: access.auth_mode, + telemetry_enabled: access.telemetry_enabled, + login_intent: access.login_intent, + prompts_suppressed: behavior_prompts_suppressed || access.prompts_suppressed, }) } SetupMode::NonInteractive(target) => Ok(SetupDispatch::Proceed { @@ -1010,17 +1147,909 @@ where optional_workflows: None, agent_trace_auto_sync: None, attribution_hooks_enabled: None, + auth_mode: None, + telemetry_enabled: None, + login_intent: SetupLoginIntent::NotOffered, + prompts_suppressed: false, }), } } +const FIRST_RUN_BEHAVIOR_DEFAULT: bool = true; + +fn persisted_or_prompted( + persisted: Option, + reconfigure: bool, + prompt: F, +) -> Result> +where + F: FnOnce(bool) -> Result>, +{ + match persisted { + Some(value) if !reconfigure => Ok(Some(value)), + persisted => prompt(persisted.unwrap_or(FIRST_RUN_BEHAVIOR_DEFAULT)), + } +} + +const FIRST_RUN_AUTH_MODE_DEFAULT: AuthMode = AuthMode::Optional; +const FIRST_RUN_TELEMETRY_CONSENT_DEFAULT: bool = false; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct SetupAccessChoices { + auth_mode: Option, + telemetry_enabled: Option, + login_intent: SetupLoginIntent, + prompts_suppressed: bool, +} + +fn resolve_setup_access_choices

( + prompter: &P, + persisted: PersistedSetupConfirmations, + gate: SetupAccessGate, + reconfigure: bool, +) -> Result> +where + P: SetupTargetPrompter, +{ + let mut choices = SetupAccessChoices { + auth_mode: None, + telemetry_enabled: None, + login_intent: SetupLoginIntent::NotOffered, + prompts_suppressed: false, + }; + + if gate.auth_locked_by.is_some() { + return Ok(Some(choices)); + } + + let global_writable = !persisted.global_config_invalid; + + if global_writable && (reconfigure || persisted.auth_mode.is_none()) { + let default = persisted.auth_mode.unwrap_or(FIRST_RUN_AUTH_MODE_DEFAULT); + let Some(mode) = prompter.prompt_auth_mode(default)? else { + return Ok(None); + }; + choices.auth_mode = Some(mode); + } else if global_writable { + choices.prompts_suppressed = true; + } + + let prospective_mode = + choices + .auth_mode + .or(persisted.auth_mode) + .unwrap_or(if gate.mandatory_locked { + AuthMode::Mandatory + } else { + AuthMode::Optional + }); + + if prospective_mode == AuthMode::Disabled { + return Ok(Some(choices)); + } + + if global_writable && (reconfigure || persisted.telemetry_enabled.is_none()) { + let default = persisted + .telemetry_enabled + .unwrap_or(FIRST_RUN_TELEMETRY_CONSENT_DEFAULT); + let Some(consent) = prompter.prompt_telemetry_consent(default)? else { + return Ok(None); + }; + choices.telemetry_enabled = Some(consent); + } else if global_writable { + choices.prompts_suppressed = true; + } + + let access_prompted = choices.auth_mode.is_some() || choices.telemetry_enabled.is_some(); + let login_offered = prospective_mode == AuthMode::Optional + && !gate.mandatory_locked + && (access_prompted || !gate.auth_db_present); + + if login_offered { + let Some(accepted) = prompter.prompt_login()? else { + return Ok(None); + }; + choices.login_intent = if accepted { + SetupLoginIntent::Requested + } else { + SetupLoginIntent::Declined + }; + } + + Ok(Some(choices)) +} + pub fn setup_cancelled_text() -> String { value("Setup cancelled. No files were changed.") } #[cfg(test)] mod tests { + use std::cell::RefCell; + use super::*; + use crate::services::config::{ResolvedValue, TelemetryDisabledReason, TelemetryPolicyState}; + + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + enum PromptCall { + Targets, + Workflows, + AutoSync(bool), + Attribution(bool), + AuthMode(AuthMode), + Telemetry(bool), + Login, + } + + struct RecordingPrompter { + calls: RefCell>, + auth_mode: Option, + telemetry: Option, + login: Option, + } + + impl RecordingPrompter { + fn answering( + auth_mode: Option, + telemetry: Option, + login: Option, + ) -> Self { + Self { + calls: RefCell::new(Vec::new()), + auth_mode, + telemetry, + login, + } + } + + fn record(&self, call: PromptCall) { + self.calls.borrow_mut().push(call); + } + + fn access_calls(&self) -> Vec { + self.calls + .borrow() + .iter() + .copied() + .filter(|call| { + matches!( + call, + PromptCall::AuthMode(_) | PromptCall::Telemetry(_) | PromptCall::Login + ) + }) + .collect() + } + } + + impl SetupTargetPrompter for RecordingPrompter { + fn prompt_targets( + &self, + _defaults: &[ConcreteSetupTarget], + ) -> Result>> { + self.record(PromptCall::Targets); + Ok(Some(vec![ConcreteSetupTarget::Claude])) + } + + fn prompt_optional_workflows(&self, _defaults: &[String]) -> Result>> { + self.record(PromptCall::Workflows); + Ok(Some(Vec::new())) + } + + fn prompt_agent_trace_auto_sync(&self, default: bool) -> Result> { + self.record(PromptCall::AutoSync(default)); + Ok(Some(true)) + } + + fn prompt_attribution_hooks_enabled(&self, default: bool) -> Result> { + self.record(PromptCall::Attribution(default)); + Ok(Some(true)) + } + + fn prompt_auth_mode(&self, default: AuthMode) -> Result> { + self.record(PromptCall::AuthMode(default)); + Ok(self.auth_mode) + } + + fn prompt_telemetry_consent(&self, default: bool) -> Result> { + self.record(PromptCall::Telemetry(default)); + Ok(self.telemetry) + } + + fn prompt_login(&self) -> Result> { + self.record(PromptCall::Login); + Ok(self.login) + } + } + + fn interactive_dispatch( + prompter: &RecordingPrompter, + persisted: PersistedSetupConfirmations, + gate: SetupAccessGate, + ) -> SetupDispatch { + resolve_setup_dispatch( + SetupMode::Interactive, + prompter, + &[], + &[], + persisted, + gate, + false, + ) + .expect("dispatch should resolve") + } + + fn access_values( + dispatch: &SetupDispatch, + ) -> (Option, Option, SetupLoginIntent) { + match dispatch { + SetupDispatch::Proceed { + auth_mode, + telemetry_enabled, + login_intent, + .. + } => (*auth_mode, *telemetry_enabled, *login_intent), + SetupDispatch::Cancelled => panic!("dispatch was cancelled"), + } + } + + #[test] + fn first_interactive_run_asks_access_prompts_after_existing_prompts_with_defaults() { + let prompter = + RecordingPrompter::answering(Some(AuthMode::Optional), Some(true), Some(true)); + + let dispatch = interactive_dispatch( + &prompter, + PersistedSetupConfirmations::default(), + SetupAccessGate::default(), + ); + + assert_eq!( + *prompter.calls.borrow(), + vec![ + PromptCall::Targets, + PromptCall::Workflows, + PromptCall::AutoSync(true), + PromptCall::Attribution(true), + PromptCall::AuthMode(AuthMode::Optional), + PromptCall::Telemetry(false), + PromptCall::Login, + ] + ); + assert_eq!( + access_values(&dispatch), + ( + Some(AuthMode::Optional), + Some(true), + SetupLoginIntent::Requested + ) + ); + } + + type AccessValues = (Option, Option, SetupLoginIntent); + type AccessCase = ( + &'static str, + Option, + PersistedSetupConfirmations, + SetupAccessGate, + Vec, + AccessValues, + ); + + fn persisted_access( + auth_mode: Option, + telemetry_enabled: Option, + global_config_invalid: bool, + ) -> PersistedSetupConfirmations { + PersistedSetupConfirmations { + auth_mode, + telemetry_enabled, + global_config_invalid, + ..PersistedSetupConfirmations::default() + } + } + + fn access_gate( + auth_locked_by: Option, + mandatory_locked: bool, + auth_db_present: bool, + ) -> SetupAccessGate { + SetupAccessGate { + auth_locked_by, + mandatory_locked, + auth_db_present, + } + } + + fn assert_access_cases(cases: Vec) { + for (name, auth_answer, persisted, gate, expected_calls, expected_values) in cases { + let prompter = RecordingPrompter::answering( + auth_answer, + expected_values.1.or(Some(true)), + Some(expected_values.2 != SetupLoginIntent::Declined), + ); + + let dispatch = interactive_dispatch(&prompter, persisted, gate); + + assert_eq!(prompter.access_calls(), expected_calls, "{name}"); + assert_eq!(access_values(&dispatch), expected_values, "{name}"); + } + } + + #[test] + fn access_mode_and_telemetry_prompts_follow_persisted_values_locks_and_selected_mode() { + use AuthMode::{Disabled, Mandatory, Optional}; + use PromptCall::{AuthMode as Mode, Login, Telemetry}; + use SetupLoginIntent::{Declined, NotOffered}; + + assert_access_cases(vec![ + ( + "persisted globals suppress mode and telemetry; auth.db present skips login", + Some(Optional), + persisted_access(Some(Optional), Some(true), false), + access_gate(None, false, true), + vec![], + (None, None, NotOffered), + ), + ( + "persisted mode with telemetry unanswered asks telemetry then login", + None, + persisted_access(Some(Optional), None, false), + access_gate(None, false, true), + vec![Telemetry(false), Login], + (None, Some(false), Declined), + ), + ( + "selected disabled skips telemetry and login", + Some(Disabled), + PersistedSetupConfirmations::default(), + access_gate(None, false, false), + vec![Mode(Optional)], + (Some(Disabled), None, NotOffered), + ), + ( + "persisted global disabled skips every access prompt", + None, + persisted_access(Some(Disabled), None, false), + access_gate(None, false, false), + vec![], + (None, None, NotOffered), + ), + ( + "repository lock skips mode, telemetry, and login", + Some(Mandatory), + PersistedSetupConfirmations::default(), + access_gate(Some(AuthPolicyConfigFile::Repository), false, false), + vec![], + (None, None, NotOffered), + ), + ( + "explicit config lock skips mode, telemetry, and login", + Some(Optional), + PersistedSetupConfirmations::default(), + access_gate(Some(AuthPolicyConfigFile::ConfigEnv), false, false), + vec![], + (None, None, NotOffered), + ), + ( + "invalid global skips mode and telemetry", + Some(Optional), + persisted_access(None, None, true), + access_gate(None, false, true), + vec![], + (None, None, NotOffered), + ), + ]); + } + + #[test] + fn login_offer_follows_mode_auth_db_and_prompts_asked_this_run() { + use AuthMode::{Mandatory, Optional}; + use PromptCall::{AuthMode as Mode, Login, Telemetry}; + use SetupLoginIntent::{Declined, NotOffered, Requested}; + + assert_access_cases(vec![ + ( + "persisted globals without auth.db still offer login", + Some(Optional), + persisted_access(Some(Optional), Some(false), false), + access_gate(None, false, false), + vec![Login], + (None, None, Declined), + ), + ( + "selected mandatory skips login", + Some(Mandatory), + PersistedSetupConfirmations::default(), + access_gate(None, false, false), + vec![Mode(Optional), Telemetry(false)], + (Some(Mandatory), Some(false), NotOffered), + ), + ( + "effective mandatory skips login after an optional answer", + Some(Optional), + PersistedSetupConfirmations::default(), + access_gate(None, true, false), + vec![Mode(Optional), Telemetry(false)], + (Some(Optional), Some(false), NotOffered), + ), + ( + "invalid global offers login when auth.db is absent", + Some(Optional), + persisted_access(None, None, true), + access_gate(None, false, false), + vec![Login], + (None, None, Requested), + ), + ( + "answers asked this run offer login even with auth.db present", + Some(Optional), + PersistedSetupConfirmations::default(), + access_gate(None, false, true), + vec![Mode(Optional), Telemetry(false), Login], + (Some(Optional), Some(true), Requested), + ), + ]); + } + + #[test] + fn cancelling_any_access_prompt_cancels_setup() { + let cases = [ + RecordingPrompter::answering(None, Some(true), Some(true)), + RecordingPrompter::answering(Some(AuthMode::Optional), None, Some(true)), + RecordingPrompter::answering(Some(AuthMode::Optional), Some(true), None), + ]; + + for (index, prompter) in cases.iter().enumerate() { + let dispatch = interactive_dispatch( + prompter, + PersistedSetupConfirmations::default(), + SetupAccessGate::default(), + ); + + assert_eq!(dispatch, SetupDispatch::Cancelled); + assert_eq!(prompter.access_calls().len(), index + 1); + } + } + + #[test] + fn telemetry_default_ignores_claude_target_and_auth_db() { + for auth_db_present in [false, true] { + let prompter = + RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(false)); + + interactive_dispatch( + &prompter, + PersistedSetupConfirmations { + agent_trace_auto_sync: Some(true), + ..PersistedSetupConfirmations::default() + }, + SetupAccessGate { + auth_db_present, + ..SetupAccessGate::default() + }, + ); + + assert!(prompter + .calls + .borrow() + .contains(&PromptCall::Telemetry(false))); + } + } + + #[test] + fn non_interactive_targets_prompt_nothing_and_carry_no_access_values() { + for target in [ + SetupTarget::OpenCode, + SetupTarget::Claude, + SetupTarget::Pi, + SetupTarget::Codex, + SetupTarget::All, + ] { + let prompter = + RecordingPrompter::answering(Some(AuthMode::Mandatory), Some(true), Some(true)); + + let dispatch = resolve_setup_dispatch( + SetupMode::NonInteractive(target), + &prompter, + &[], + &[], + PersistedSetupConfirmations::default(), + SetupAccessGate::default(), + false, + ) + .unwrap(); + + assert!(prompter.calls.borrow().is_empty()); + assert_eq!( + access_values(&dispatch), + (None, None, SetupLoginIntent::NotOffered) + ); + } + } + + fn reconfigure_dispatch( + prompter: &RecordingPrompter, + persisted: PersistedSetupConfirmations, + gate: SetupAccessGate, + ) -> SetupDispatch { + resolve_setup_dispatch( + SetupMode::Interactive, + prompter, + &[], + &[], + persisted, + gate, + true, + ) + .expect("dispatch should resolve") + } + + fn prompts_suppressed(dispatch: &SetupDispatch) -> bool { + match dispatch { + SetupDispatch::Proceed { + prompts_suppressed, .. + } => *prompts_suppressed, + SetupDispatch::Cancelled => panic!("dispatch was cancelled"), + } + } + + fn persisted_answers( + agent_trace_auto_sync: bool, + attribution_hooks_enabled: bool, + auth_mode: AuthMode, + telemetry_enabled: bool, + ) -> PersistedSetupConfirmations { + PersistedSetupConfirmations { + agent_trace_auto_sync: Some(agent_trace_auto_sync), + attribution_hooks_enabled: Some(attribution_hooks_enabled), + auth_mode: Some(auth_mode), + telemetry_enabled: Some(telemetry_enabled), + global_config_invalid: false, + } + } + + #[test] + fn reconfigure_asks_every_persisted_prompt_with_the_persisted_defaults() { + let prompter = + RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(true)); + + let dispatch = reconfigure_dispatch( + &prompter, + persisted_answers(false, true, AuthMode::Mandatory, true), + access_gate(None, false, true), + ); + + assert_eq!( + *prompter.calls.borrow(), + vec![ + PromptCall::Targets, + PromptCall::Workflows, + PromptCall::AutoSync(false), + PromptCall::Attribution(true), + PromptCall::AuthMode(AuthMode::Mandatory), + PromptCall::Telemetry(true), + PromptCall::Login, + ] + ); + assert_eq!( + access_values(&dispatch), + ( + Some(AuthMode::Optional), + Some(false), + SetupLoginIntent::Requested + ) + ); + assert!(!prompts_suppressed(&dispatch)); + } + + #[test] + fn reconfigure_uses_a_persisted_global_disabled_as_the_auth_mode_cursor() { + let prompter = + RecordingPrompter::answering(Some(AuthMode::Disabled), Some(true), Some(true)); + + let dispatch = reconfigure_dispatch( + &prompter, + persisted_answers(true, false, AuthMode::Disabled, false), + access_gate(None, false, false), + ); + + assert_eq!( + *prompter.calls.borrow(), + vec![ + PromptCall::Targets, + PromptCall::Workflows, + PromptCall::AutoSync(true), + PromptCall::Attribution(false), + PromptCall::AuthMode(AuthMode::Disabled), + ] + ); + assert_eq!( + access_values(&dispatch), + (Some(AuthMode::Disabled), None, SetupLoginIntent::NotOffered) + ); + } + + #[test] + fn reconfigure_keeps_the_lock_and_invalid_global_gates() { + use AuthMode::Optional; + use PromptCall::{Attribution, AutoSync, Targets, Workflows}; + + let cases = [ + ( + "repository lock skips access prompts", + persisted_answers(true, true, Optional, true), + access_gate(Some(AuthPolicyConfigFile::Repository), false, false), + ), + ( + "explicit lock skips access prompts", + persisted_answers(true, true, Optional, true), + access_gate(Some(AuthPolicyConfigFile::ConfigFlag), false, false), + ), + ( + "invalid global skips mode and telemetry", + PersistedSetupConfirmations { + agent_trace_auto_sync: Some(true), + attribution_hooks_enabled: Some(true), + global_config_invalid: true, + ..PersistedSetupConfirmations::default() + }, + access_gate(None, true, true), + ), + ]; + + for (name, persisted, gate) in cases { + let prompter = + RecordingPrompter::answering(Some(AuthMode::Disabled), Some(false), Some(true)); + + let dispatch = reconfigure_dispatch(&prompter, persisted, gate); + + assert_eq!( + *prompter.calls.borrow(), + vec![Targets, Workflows, AutoSync(true), Attribution(true)], + "{name}" + ); + assert_eq!( + access_values(&dispatch), + (None, None, SetupLoginIntent::NotOffered), + "{name}" + ); + } + } + + #[test] + fn reconfigure_from_a_global_mandatory_offers_login_for_optional() { + let global_mandatory = ResolvedAccessPolicy { + auth_mode: ResolvedValue { + value: AuthMode::Mandatory, + source: ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal), + }, + telemetry_enabled: ResolvedValue { + value: false, + source: ValueSource::Default, + }, + telemetry: TelemetryPolicyState::Disabled(TelemetryDisabledReason::NotEnabled), + background_cloud_allowed: true, + }; + let prompter = + RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(true)); + + let dispatch = reconfigure_dispatch( + &prompter, + persisted_answers(true, true, AuthMode::Mandatory, false), + SetupAccessGate::from_policy(&global_mandatory, true), + ); + + assert_eq!( + prompter.access_calls(), + vec![ + PromptCall::AuthMode(AuthMode::Mandatory), + PromptCall::Telemetry(false), + PromptCall::Login, + ] + ); + assert_eq!( + access_values(&dispatch), + ( + Some(AuthMode::Optional), + Some(false), + SetupLoginIntent::Requested + ) + ); + } + + #[test] + fn persisted_answers_mark_prompts_suppressed_only_without_reconfigure() { + let first_run = interactive_dispatch( + &RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(false)), + PersistedSetupConfirmations::default(), + SetupAccessGate::default(), + ); + assert!(!prompts_suppressed(&first_run)); + + let suppressed_cases = [ + PersistedSetupConfirmations { + agent_trace_auto_sync: Some(true), + ..PersistedSetupConfirmations::default() + }, + PersistedSetupConfirmations { + attribution_hooks_enabled: Some(false), + ..PersistedSetupConfirmations::default() + }, + persisted_access(Some(AuthMode::Disabled), None, false), + persisted_access(None, Some(false), false), + ]; + for persisted in suppressed_cases { + let rerun = interactive_dispatch( + &RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(false)), + persisted, + SetupAccessGate::default(), + ); + assert!(prompts_suppressed(&rerun), "{persisted:?}"); + } + + let locked = interactive_dispatch( + &RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(false)), + persisted_access(None, None, true), + access_gate(Some(AuthPolicyConfigFile::Repository), false, false), + ); + assert!(!prompts_suppressed(&locked)); + + let reconfigured = reconfigure_dispatch( + &RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(false)), + persisted_answers(true, true, AuthMode::Optional, true), + SetupAccessGate::default(), + ); + assert!(!prompts_suppressed(&reconfigured)); + } + + #[test] + fn reconfigure_request_rejects_every_non_interactive_combination() { + let reconfigure = |options: SetupCliOptions| { + resolve_setup_request(SetupCliOptions { + reconfigure: true, + ..options + }) + }; + let message = |flag: &str| { + format!( + "Option '--reconfigure' cannot be used with '{flag}'. Try: run 'sce setup --reconfigure' alone to change saved setup answers interactively." + ) + }; + + let mut cases: Vec<(SetupCliOptions, &str)> = [ + (SetupTarget::OpenCode, "--opencode"), + (SetupTarget::Claude, "--claude"), + (SetupTarget::Pi, "--pi"), + (SetupTarget::Codex, "--codex"), + (SetupTarget::All, "--all"), + ] + .into_iter() + .map(|(target, flag)| { + ( + SetupCliOptions { + target: Some(target), + ..SetupCliOptions::default() + }, + flag, + ) + }) + .collect(); + cases.extend([ + ( + SetupCliOptions { + non_interactive: true, + ..SetupCliOptions::default() + }, + "--non-interactive", + ), + ( + SetupCliOptions { + hooks: true, + ..SetupCliOptions::default() + }, + "--hooks", + ), + ( + SetupCliOptions { + hooks: true, + repo_path: Some(PathBuf::from("repo")), + ..SetupCliOptions::default() + }, + "--hooks", + ), + ( + SetupCliOptions { + repo_path: Some(PathBuf::from("repo")), + ..SetupCliOptions::default() + }, + "--repo", + ), + ( + SetupCliOptions { + bootstrap_context: true, + ..SetupCliOptions::default() + }, + "--bootstrap-context", + ), + ]); + + for (options, flag) in cases { + let error = reconfigure(options.clone()) + .expect_err("reconfigure combination should be rejected"); + assert_eq!(error.to_string(), message(flag), "{options:?}"); + } + + let request = reconfigure(SetupCliOptions::default()).expect("reconfigure alone is valid"); + assert_eq!(request.config_mode, Some(SetupMode::Interactive)); + assert!(request.reconfigure); + assert!(request.install_hooks); + + let plain = resolve_setup_request(SetupCliOptions::default()).unwrap(); + assert!(!plain.reconfigure); + } + + #[test] + fn access_gate_locks_only_for_repository_or_explicit_disabled() { + let policy = |mode, source| ResolvedAccessPolicy { + auth_mode: ResolvedValue { + value: mode, + source, + }, + telemetry_enabled: ResolvedValue { + value: false, + source: ValueSource::Default, + }, + telemetry: TelemetryPolicyState::Disabled(TelemetryDisabledReason::NotEnabled), + background_cloud_allowed: false, + }; + let local = ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal); + let global = ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal); + + let cases = [ + ( + policy(AuthMode::Disabled, local), + Some(AuthPolicyConfigFile::Repository), + false, + ), + ( + policy( + AuthMode::Disabled, + ValueSource::ConfigFile(ConfigPathSource::Flag), + ), + Some(AuthPolicyConfigFile::ConfigFlag), + false, + ), + ( + policy( + AuthMode::Disabled, + ValueSource::ConfigFile(ConfigPathSource::Env), + ), + Some(AuthPolicyConfigFile::ConfigEnv), + false, + ), + (policy(AuthMode::Disabled, global), None, false), + (policy(AuthMode::Mandatory, local), None, true), + (policy(AuthMode::Mandatory, global), None, false), + ( + policy(AuthMode::Optional, ValueSource::Default), + None, + false, + ), + ]; + + for (policy, locked_by, mandatory) in cases { + let gate = SetupAccessGate::from_policy(&policy, true); + + assert_eq!( + gate, + SetupAccessGate { + auth_locked_by: locked_by, + mandatory_locked: mandatory, + auth_db_present: true, + } + ); + } + } #[test] fn sce_info_assets_install_only_for_claude_and_exclude_development_files() { diff --git a/cli/src/services/setup/prompt.rs b/cli/src/services/setup/prompt.rs index fd867bc9c..979852d17 100644 --- a/cli/src/services/setup/prompt.rs +++ b/cli/src/services/setup/prompt.rs @@ -1,8 +1,9 @@ use anyhow::{bail, Result}; use inquire::list_option::ListOption; use inquire::validator::Validation; -use inquire::{Confirm, InquireError, MultiSelect}; +use inquire::{Confirm, InquireError, MultiSelect, Select}; +use crate::services::config::AuthMode; use crate::services::style::{prompt_label, prompt_value_with_color_policy}; use super::{ConcreteSetupTarget, OptionalWorkflow, SetupPromptTarget}; @@ -77,20 +78,95 @@ pub(super) fn prompt_optional_workflows(defaults: &[String]) -> Result Result> { +pub(super) fn prompt_agent_trace_auto_sync(default: bool) -> Result> { prompt_confirmation( "Automatically sync Agent Traces?\n(Requires an SCE account. Sends Agent Traces from supported AI coding tools\nto SCE servers so they can be stored and viewed in your account.)", + default, ) } -pub(super) fn prompt_attribution_hooks_enabled() -> Result> { +pub(super) fn prompt_attribution_hooks_enabled(default: bool) -> Result> { prompt_confirmation( "Record SCE involvement in Git commits?\n(Adds SCE metadata to commits created or assisted by SCE.)", + default, ) } -fn prompt_confirmation(label: &str) -> Result> { - match Confirm::new(label).with_default(true).prompt() { +const AUTH_MODE_PROMPT_TITLE: &str = "SCE account mode for this machine"; + +const AUTH_MODE_PROMPT_ROWS: [AuthMode; 3] = + [AuthMode::Optional, AuthMode::Mandatory, AuthMode::Disabled]; + +const AUTH_MODE_OPTIONAL_LABEL: &str = + "Optional: use SCE locally and log in when you want SCE cloud features"; +const AUTH_MODE_MANDATORY_LABEL: &str = "Mandatory: require an SCE login when setting up"; +const AUTH_MODE_DISABLED_LABEL: &str = + "Disabled: local only; no SCE login, cloud sync, or telemetry"; + +const TELEMETRY_CONSENT_PROMPT_LABEL: &str = "Share SCE telemetry?\n(Sends SCE usage telemetry to SCE servers using your SCE login. If Claude is\nselected, also configures Claude Code's native telemetry export. Separate from\nAgent Trace sync. Applies to all repositories on this machine.)"; + +const LOGIN_PROMPT_LABEL: &str = "Log in to SCE now?\n(Opens a device login in your browser. An existing login on this machine is\nreused. You can log in later with 'sce auth login'.)"; + +const LOGIN_PROMPT_DEFAULT: bool = true; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) struct AuthModeRow(pub(super) AuthMode); + +impl std::fmt::Display for AuthModeRow { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", auth_mode_row_label(self.0)) + } +} + +pub(super) fn auth_mode_row_label(mode: AuthMode) -> &'static str { + match mode { + AuthMode::Optional => AUTH_MODE_OPTIONAL_LABEL, + AuthMode::Mandatory => AUTH_MODE_MANDATORY_LABEL, + AuthMode::Disabled => AUTH_MODE_DISABLED_LABEL, + } +} + +pub(super) fn auth_mode_prompt_rows() -> Vec { + AUTH_MODE_PROMPT_ROWS + .iter() + .copied() + .map(AuthModeRow) + .collect() +} + +pub(super) fn auth_mode_prompt_default_index(default: AuthMode) -> usize { + AUTH_MODE_PROMPT_ROWS + .iter() + .position(|mode| *mode == default) + .unwrap_or(0) +} + +pub(super) fn auth_mode_prompt_title() -> String { + prompt_label(AUTH_MODE_PROMPT_TITLE) +} + +pub(super) fn prompt_auth_mode(default: AuthMode) -> Result> { + let selection = Select::new(&auth_mode_prompt_title(), auth_mode_prompt_rows()) + .with_starting_cursor(auth_mode_prompt_default_index(default)) + .prompt(); + + interactive_prompt_result(selection.map(|row| row.0)) +} + +pub(super) fn prompt_telemetry_consent(default: bool) -> Result> { + prompt_confirmation(TELEMETRY_CONSENT_PROMPT_LABEL, default) +} + +pub(super) fn prompt_login() -> Result> { + prompt_confirmation(LOGIN_PROMPT_LABEL, LOGIN_PROMPT_DEFAULT) +} + +fn prompt_confirmation(label: &str, default: bool) -> Result> { + interactive_prompt_result(Confirm::new(label).with_default(default).prompt()) +} + +fn interactive_prompt_result(result: Result) -> Result> { + match result { Ok(value) => Ok(Some(value)), Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => Ok(None), Err(InquireError::NotTTY) => bail!( @@ -189,3 +265,79 @@ pub(super) fn setup_prompt_target_label_with_color_policy( prompt_value_with_color_policy(label, color_enabled) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn auth_mode_rows_map_to_modes_in_fixed_order_with_fixed_labels() { + let rows = auth_mode_prompt_rows(); + let mapped: Vec<(AuthMode, String)> = + rows.iter().map(|row| (row.0, row.to_string())).collect(); + + assert_eq!( + mapped, + vec![ + ( + AuthMode::Optional, + "Optional: use SCE locally and log in when you want SCE cloud features" + .to_string() + ), + ( + AuthMode::Mandatory, + "Mandatory: require an SCE login when setting up".to_string() + ), + ( + AuthMode::Disabled, + "Disabled: local only; no SCE login, cloud sync, or telemetry".to_string() + ), + ] + ); + } + + #[test] + fn auth_mode_default_cursor_points_at_the_default_row() { + let rows = auth_mode_prompt_rows(); + + for mode in [AuthMode::Optional, AuthMode::Mandatory, AuthMode::Disabled] { + let index = auth_mode_prompt_default_index(mode); + assert_eq!(rows[index].0, mode); + } + assert_eq!(auth_mode_prompt_default_index(AuthMode::Optional), 0); + } + + #[test] + fn new_prompt_labels_and_defaults_are_fixed() { + assert_eq!( + TELEMETRY_CONSENT_PROMPT_LABEL, + "Share SCE telemetry?\n(Sends SCE usage telemetry to SCE servers using your SCE login. If Claude is\nselected, also configures Claude Code's native telemetry export. Separate from\nAgent Trace sync. Applies to all repositories on this machine.)" + ); + assert_eq!( + LOGIN_PROMPT_LABEL, + "Log in to SCE now?\n(Opens a device login in your browser. An existing login on this machine is\nreused. You can log in later with 'sce auth login'.)" + ); + assert_eq!(AUTH_MODE_PROMPT_TITLE, "SCE account mode for this machine"); + } + + #[test] + fn interactive_prompt_result_maps_cancel_and_not_tty_like_existing_prompts() { + assert_eq!( + interactive_prompt_result(Ok(AuthMode::Mandatory)).unwrap(), + Some(AuthMode::Mandatory) + ); + assert_eq!( + interactive_prompt_result::(Err(InquireError::OperationCanceled)).unwrap(), + None + ); + assert_eq!( + interactive_prompt_result::(Err(InquireError::OperationInterrupted)).unwrap(), + None + ); + let error = interactive_prompt_result::(Err(InquireError::NotTTY)).unwrap_err(); + assert_eq!( + error.to_string(), + "Interactive setup requires a TTY. Re-run with '--non-interactive' and one of '--opencode', '--claude', '--pi', '--codex', or '--all'." + ); + } +} diff --git a/cli/src/services/telemetry_credential_storage.rs b/cli/src/services/telemetry_credential_storage.rs index a26069acf..d1a833cc9 100644 --- a/cli/src/services/telemetry_credential_storage.rs +++ b/cli/src/services/telemetry_credential_storage.rs @@ -954,6 +954,46 @@ mod tests { assert_eq!(repository_token(&db, REPOSITORY_A).await, None); } + #[tokio::test] + async fn repository_readiness_follows_binding_rather_than_credential_issuance() { + let (_guard, db) = open_db().await; + log_in_as(&db, USER_A, WORKSPACE_A, "tok-a").await; + assert!( + bind_repository_with(&db, now(), REPOSITORY_A, RepositoryBindingMode::Enroll) + .await + .expect("bind should succeed") + ); + + log_in_as(&db, USER_B, WORKSPACE_B, "tok-b").await; + assert!( + !bind_repository_with( + &db, + now(), + REPOSITORY_A, + RepositoryBindingMode::EnrollIfUnbound + ) + .await + .expect("bind should succeed"), + "issued credential must not take over a repository bound to another identity" + ); + assert!(load_with(&db, now()) + .await + .expect("load should succeed") + .into_valid() + .is_some()); + assert_eq!(repository_token(&db, REPOSITORY_A).await, None); + + seed_session(&db, USER_A, WORKSPACE_A).await; + save_with(&db, &credential("tok-a-existing", FAR_FUTURE)) + .await + .expect("save should succeed"); + assert_eq!( + repository_token(&db, REPOSITORY_A).await, + Some("tok-a-existing".to_string()), + "already-authorized repository is ready without a new enrollment" + ); + } + #[tokio::test] async fn incomplete_identity_is_never_saved() { let (_guard, db) = open_db().await; diff --git a/context/architecture.md b/context/architecture.md index 04d0118b4..1cac1bd2b 100644 --- a/context/architecture.md +++ b/context/architecture.md @@ -69,8 +69,9 @@ The repository includes a new placeholder Rust binary crate at `cli/`. - `cli/src/services/local_db/mod.rs` provides `LocalDb = TursoDb` with zero local migrations; inherited construction, `execute`, `query`, and `query_map` operations are async and use the shared adapter retry policies. - `cli/src/services/auth_db/mod.rs` provides the encrypted auth DB spec and `AuthDb` type alias over `EncryptedTursoDb`. `AuthDbSpec` resolves `/sce/auth.db` through the shared default-path seam and embeds ordered auth migrations. Auth DB lifecycle setup/doctor integration is wired through `AuthDbLifecycle`; auth command/token-storage reads/writes are directed through `token_storage.rs`. - `cli/src/services/agent_trace_db/mod.rs` owns the shared Agent Trace insert payloads, SQL constants, and typed row helpers (diff-trace/intersection/Agent Trace/message/part) plus `ensure_schema_ready_for_hooks()` consumed by the repository adapter. `cli/src/services/agent_trace_db/repository.rs` defines the sole `RepositoryAgentTraceDb` adapter over `TursoDb` with one fresh `agent-trace-repository/001_repository_schema.sql` baseline for `diff_traces` (including `payload_type`), `post_commit_patch_intersections`, `agent_traces`, `messages`, `parts`, indexes, and triggers, `repository_metadata` validation, no trace-table `checkout_id` columns, `agent_traces.agent_trace_id NOT NULL UNIQUE`, and `recent_diff_trace_patches(cutoff_time_ms, end_time_ms)` using the inclusive chronological parser without checkout filtering; structured-row reconstruction applies the persisted row `model_id` to every hunk and the persisted canonical `session_id` to every touched line before downstream combination and intersection. Active hook runtime, setup/lifecycle storage, and `sce sync` resolve through `agent_trace_storage` and use `RepositoryAgentTraceDb`. The checkout-scoped `AgentTraceDb`/`AgentTraceDbSpec` adapter, its `agent_trace_db_path()`/`agent_trace_db_path_for_checkout()` helpers, the 15-file `cli/migrations/agent-trace/` chain, and the former `sce trace --legacy` surface were removed by the `retire-legacy-agent-trace-db` plan. -- `cli/src/services/setup/mod.rs` defines the setup command contract (`SetupMode`, `SetupTarget`, `SetupRequest`, CLI flag parser/validator), an `inquire`-backed interactive target prompter (`InquireSetupTargetPrompter`), setup dispatch outcomes (proceed/cancelled), additive durable-context bootstrap (`bootstrap_context_baseline` for standalone `--bootstrap-context` and every normal successful setup path), and compile-time embedded asset access (`EmbeddedAsset`, target-scoped iterators, required-hook asset iterators/lookups). It also owns the install-time optional-workflow seam: the `OptionalWorkflow` type plus the build-generated `OPTIONAL_WORKFLOWS` catalog, a per-target `WorkflowAssetLayout` built from the existing `default_paths` command/skill directory constants (`command`/`commands`/`prompts` plus `skills`), and `iter_embedded_assets_for_setup_target_with_selection(target, selection)`, which yields every embedded asset except the `{command_dir}/{command_slug}.md` file and `{skills_dir}/{skill_slug}/` subtree of each optional workflow the selection omits. Membership is derived from the catalog's slugs rather than an enumerated file list, so a new optional workflow needs no Rust change. This filtered iterator is the only way embedded assets are enumerated; setup installs through it and doctor inspects through it, so there is no unfiltered enumeration path that could reintroduce an unselected workflow. The non-interactive selection flows through the repeatable `--workflow ` flag into `SetupRequest.optional_workflows: Option>` (`None` meaning the flag was absent); `validate_optional_workflow_slugs` checks each slug against `OPTIONAL_WORKFLOWS` during request resolution, before any write, and `run_setup_for_mode` resolves `None` to the persisted `integrations.optional_workflows` (exported as `persisted_optional_workflows`) before installing through the filtered iterator and persisting the resolved selection. The interactive selection flows through the same seam: `SetupTargetPrompter` carries `prompt_target` plus `prompt_optional_workflows(defaults)` (returning `None` for a cancelled prompt), `SetupDispatch::Proceed { mode, optional_workflows }` carries a prompted selection alongside the resolved mode, and `resolve_setup_dispatch(mode, prompter, defaults)` runs the workflow prompt only after an interactive target prompt, mapping either cancellation to `SetupDispatch::Cancelled`. The prompt module builds its `inquire::MultiSelect` from `optional_workflow_prompt_inputs(catalog, defaults)`, which returns `None` for an empty catalog (skipping the prompt) and otherwise catalog-ordered rows plus the indices to pre-check, ignoring ids absent from the catalog. `setup/command.rs` therefore resolves the repository root before dispatch, mapping the setup domain's typed positive non-Git classification to `setup.not_git_repository` and other resolution failures to `general.unexpected_failure`, so a non-Git directory fails before any prompt without CLI-layer string matching. For repository builds, `cli/build.rs` validates the `SCE_CLI_GENERATED_INPUT_DIR` payload and canonical-input inventories, copies the payload into Cargo `OUT_DIR/pkl-generated`, stages `cli/assets/hooks/**` under `OUT_DIR/static`, requires the staged `config/optional-workflows.json`, and generates both the setup manifest and the optional-workflow catalog (`optional_workflows.rs`, rejecting a manifest whose `schemaVersion` is not 1 or whose entries lack a non-empty `id`/`title`/`description`/`commandSlug`/`skillSlug`) in `OUT_DIR`; focused internal seams separate install-flow from prompt-flow logic; `cli/src/services/setup/command.rs` owns the `SetupCommand` payload used by the static `RuntimeCommand` enum and executes against any context implementing repo-root scoping. Its install engine/orchestrator (`install_assets_for_concrete_target_with_rename`) installs each embedded asset individually: it stages the asset's content next to its final destination and swaps it into place by renaming the staging file directly over the destination — never unlinking the destination first, since `fs::rename` already replaces an existing file atomically — with deterministic recovery guidance naming the failing asset's path on swap failure (the pre-existing destination content, if any, is untouched) and no backup artifact creation; it never removes an integration target directory as a whole, so files a repository owns inside `.opencode`/`.claude`/`.pi` — including nested inside an SCE-owned subdirectory such as `skills/` or `commands/` — survive a setup run; Codex has no single target directory this way, since `CODEX_EMBEDDED_ASSETS` relative paths already carry their own `.agents/`/`.codex/` prefix and `InstallTargetPaths::codex_target_dir()` resolves to the repository root itself, but the same per-asset stage/atomic-swap and never-delete-what-it-did-not-author guarantees still apply file by file. For the three assets that are merge targets — the Claude target's `settings.json`, the OpenCode target's `opencode.json`, and Codex's user-owned `.codex/hooks.json` — the content staged is not always the embedded asset's bytes. Claude and OpenCode use `cli/src/services/setup/config_merge.rs`, while Codex uses the shared `cli/src/services/codex_hook_config.rs` service for structural validation and canonical-registration merging. For the Claude and OpenCode targets, the content staged is the result of `cli/src/services/setup/config_merge.rs::merge_or_create_claude_settings`/`merge_or_create_opencode_config(existing_bytes, generated_bytes, source_path)`: each returns the generated document verbatim when no file exists yet, otherwise parses the existing file as JSON (a parse failure is a hard error naming `source_path`, and nothing is written) and merges it with a pure per-shape function that copies `$schema` from the generated document and preserves every other key from the existing file untouched. `merge_claude_settings` replaces, per hook event key the generated document declares, only the entries whose command contains the ownership marker `run-sce-or-show-install-guidance.sh`, preserving every event key and non-SCE hook entry from the existing file. `merge_opencode_config` merges the `plugin` array as a set: existing entries whose path starts with the ownership marker `./plugins/sce-` are dropped structurally — so a stale plugin path an older or renamed catalog once installed is still recognized and pruned even after the current generated document stops declaring it — and the generated document's `plugin` entries are appended after the surviving entries. Codex's merge validates the document shape and recognizes ownership by the generated helper path plus one of two trailing command contracts — `sce hooks codex` or `sce hooks codex-mutation-scope` — attributing each handler to whichever it matches; it replaces stale or duplicate handlers with exactly one current handler per registration (the four `sce hooks codex` registrations plus six additive `sce hooks codex-mutation-scope` registrations, within that mutation-scope set, `PreToolUse` and `PostToolUse` use matcher `^(Bash|apply_patch)$`, while `Stop`, `Interrupt`, `SubagentStop`, and `SessionEnd` are appended in unmatched groups after the existing groups so an already-trusted handler keeps its `(event, matcher, group index, handler index)` identity and computed Codex trust key), touching only the matching command's handlers and preserving unrelated valid Codex fields, groups, and handlers. After that per-asset install loop, `prune_stale_assets_for_concrete_target` deletes every path the full embedded catalog for the concrete target claims but the resolved selection did not install (a deselected optional workflow, or an asset a newer catalog renamed or dropped), and `remove_empty_ancestor_directories` removes any parent directory left empty by that deletion, stopping at the target root or at a directory that still holds something such as a user file. It formats deterministic completion messaging; required-hook install orchestration (`install_required_git_hooks`, backed by the rename-injectable `install_required_git_hooks_with_rename`) is a third content-computation seam alongside the two JSON merge targets: `install_single_required_hook_with_rename` computes the bytes to stage with `cli/src/services/setup/hook_merge.rs::merge_or_create_hook(existing_bytes, canonical_bytes, hook_name)` rather than writing `hook_asset.bytes` verbatim — a foreign hook (no SCE managed block, no legacy guidance-URL marker) is kept as an exact byte prefix with the canonical block appended after it, an SCE-owned hook has only its block spliced in place or left unchanged, and a legacy pre-marker hook is replaced wholesale — then follows the same per-file stage/atomic-swap choreography as config-asset install: the staging file is renamed directly over the existing hook without unlinking it first, so a rename failure leaves the prior hook's bytes and executable bit intact, with deterministic recovery guidance on swap failure. `Installed`/`Updated`/`Skipped` are decided against the merged bytes plus the executable bit rather than the canonical asset's raw bytes, so an already-current foreign-plus-block hook reports `Skipped`; `RequiredHookInstallResult.unreachable_block_advisory` is set, and rendered as a named advisory line in setup's hook output, when an appended block follows a foreign hook's zero-indent `exec`/`exit` and so would never run. After the Git gate, setup always ensures the context baseline; context-only requests return there, while normal modes derive a repo-root-scoped context before aggregating static lifecycle provider `setup` dispatch across providers (config → local_db → auth_db → agent_trace_db → hooks when requested), so setup providers consume only repo-root access from the scoped context. +- `cli/src/services/setup/mod.rs` defines the setup command contract (`SetupMode`, `SetupTarget`, `SetupRequest`, CLI flag parser/validator), an `inquire`-backed interactive target prompter (`InquireSetupTargetPrompter`), setup dispatch outcomes (proceed/cancelled), additive durable-context bootstrap (`bootstrap_context_baseline` for standalone `--bootstrap-context` and every normal successful setup path), and compile-time embedded asset access (`EmbeddedAsset`, target-scoped iterators, required-hook asset iterators/lookups). It also owns the install-time optional-workflow seam: the `OptionalWorkflow` type plus the build-generated `OPTIONAL_WORKFLOWS` catalog, a per-target `WorkflowAssetLayout` built from the existing `default_paths` command/skill directory constants (`command`/`commands`/`prompts` plus `skills`), and `iter_embedded_assets_for_setup_target_with_selection(target, selection)`, which yields every embedded asset except the `{command_dir}/{command_slug}.md` file and `{skills_dir}/{skill_slug}/` subtree of each optional workflow the selection omits. Membership is derived from the catalog's slugs rather than an enumerated file list, so a new optional workflow needs no Rust change. This filtered iterator is the only way embedded assets are enumerated; setup installs through it and doctor inspects through it, so there is no unfiltered enumeration path that could reintroduce an unselected workflow. The non-interactive selection flows through the repeatable `--workflow ` flag into `SetupRequest.optional_workflows: Option>` (`None` meaning the flag was absent); `validate_optional_workflow_slugs` checks each slug against `OPTIONAL_WORKFLOWS` during request resolution, before any write, and `run_setup_for_mode` resolves `None` to the persisted `integrations.optional_workflows` (exported as `persisted_optional_workflows`) before installing through the filtered iterator and persisting the resolved selection. The interactive selection flows through the same seam: `SetupTargetPrompter` carries `prompt_targets(defaults)`, `prompt_optional_workflows(defaults)`, the two behavior confirmations `prompt_agent_trace_auto_sync(default)` / `prompt_attribution_hooks_enabled(default)` (dispatch passes `true`), and the access prompts `prompt_auth_mode(default)` (an `inquire::Select` with fixed Optional/Mandatory/Disabled rows), `prompt_telemetry_consent(default)`, and `prompt_login()` (Yes default), which dispatch does not call yet; every method returns `None` for a cancelled prompt and fails with the fixed TTY guidance on `NotTTY`, `SetupDispatch::Proceed { mode, optional_workflows }` carries a prompted selection alongside the resolved mode, and `resolve_setup_dispatch(mode, prompter, defaults)` runs the workflow prompt only after an interactive target prompt, mapping either cancellation to `SetupDispatch::Cancelled`. The prompt module builds its `inquire::MultiSelect` from `optional_workflow_prompt_inputs(catalog, defaults)`, which returns `None` for an empty catalog (skipping the prompt) and otherwise catalog-ordered rows plus the indices to pre-check, ignoring ids absent from the catalog. `setup/command.rs` therefore resolves the repository root before dispatch, mapping the setup domain's typed positive non-Git classification to `setup.not_git_repository` and other resolution failures to `general.unexpected_failure`, so a non-Git directory fails before any prompt without CLI-layer string matching. For repository builds, `cli/build.rs` validates the `SCE_CLI_GENERATED_INPUT_DIR` payload and canonical-input inventories, copies the payload into Cargo `OUT_DIR/pkl-generated`, stages `cli/assets/hooks/**` under `OUT_DIR/static`, requires the staged `config/optional-workflows.json`, and generates both the setup manifest and the optional-workflow catalog (`optional_workflows.rs`, rejecting a manifest whose `schemaVersion` is not 1 or whose entries lack a non-empty `id`/`title`/`description`/`commandSlug`/`skillSlug`) in `OUT_DIR`; focused internal seams separate install-flow from prompt-flow logic; `cli/src/services/setup/command.rs` owns the `SetupCommand` payload used by the static `RuntimeCommand` enum and executes against any context implementing repo-root scoping. Its install engine/orchestrator (`install_assets_for_concrete_target_with_rename`) installs each embedded asset individually: it stages the asset's content next to its final destination and swaps it into place by renaming the staging file directly over the destination — never unlinking the destination first, since `fs::rename` already replaces an existing file atomically — with deterministic recovery guidance naming the failing asset's path on swap failure (the pre-existing destination content, if any, is untouched) and no backup artifact creation; it never removes an integration target directory as a whole, so files a repository owns inside `.opencode`/`.claude`/`.pi` — including nested inside an SCE-owned subdirectory such as `skills/` or `commands/` — survive a setup run; Codex has no single target directory this way, since `CODEX_EMBEDDED_ASSETS` relative paths already carry their own `.agents/`/`.codex/` prefix and `InstallTargetPaths::codex_target_dir()` resolves to the repository root itself, but the same per-asset stage/atomic-swap and never-delete-what-it-did-not-author guarantees still apply file by file. For the three assets that are merge targets — the Claude target's `settings.json`, the OpenCode target's `opencode.json`, and Codex's user-owned `.codex/hooks.json` — the content staged is not always the embedded asset's bytes. Claude and OpenCode use `cli/src/services/setup/config_merge.rs`, while Codex uses the shared `cli/src/services/codex_hook_config.rs` service for structural validation and canonical-registration merging. For the Claude and OpenCode targets, the content staged is the result of `cli/src/services/setup/config_merge.rs::merge_or_create_claude_settings`/`merge_or_create_opencode_config(existing_bytes, generated_bytes, source_path)`: each returns the generated document verbatim when no file exists yet, otherwise parses the existing file as JSON (a parse failure is a hard error naming `source_path`, and nothing is written) and merges it with a pure per-shape function that copies `$schema` from the generated document and preserves every other key from the existing file untouched. `merge_claude_settings` replaces, per hook event key the generated document declares, only the entries whose command contains the ownership marker `run-sce-or-show-install-guidance.sh`, preserving every event key and non-SCE hook entry from the existing file. `merge_opencode_config` merges the `plugin` array as a set: existing entries whose path starts with the ownership marker `./plugins/sce-` are dropped structurally — so a stale plugin path an older or renamed catalog once installed is still recognized and pruned even after the current generated document stops declaring it — and the generated document's `plugin` entries are appended after the surviving entries. Codex's merge validates the document shape and recognizes ownership by the generated helper path plus one of two trailing command contracts — `sce hooks codex` or `sce hooks codex-mutation-scope` — attributing each handler to whichever it matches; it replaces stale or duplicate handlers with exactly one current handler per registration (the four `sce hooks codex` registrations plus six additive `sce hooks codex-mutation-scope` registrations, within that mutation-scope set, `PreToolUse` and `PostToolUse` use matcher `^(Bash|apply_patch)$`, while `Stop`, `Interrupt`, `SubagentStop`, and `SessionEnd` are appended in unmatched groups after the existing groups so an already-trusted handler keeps its `(event, matcher, group index, handler index)` identity and computed Codex trust key), touching only the matching command's handlers and preserving unrelated valid Codex fields, groups, and handlers. After that per-asset install loop, `prune_stale_assets_for_concrete_target` deletes every path the full embedded catalog for the concrete target claims but the resolved selection did not install (a deselected optional workflow, or an asset a newer catalog renamed or dropped), and `remove_empty_ancestor_directories` removes any parent directory left empty by that deletion, stopping at the target root or at a directory that still holds something such as a user file. It formats deterministic completion messaging; required-hook install orchestration (`install_required_git_hooks`, backed by the rename-injectable `install_required_git_hooks_with_rename`) is a third content-computation seam alongside the two JSON merge targets: `install_single_required_hook_with_rename` computes the bytes to stage with `cli/src/services/setup/hook_merge.rs::merge_or_create_hook(existing_bytes, canonical_bytes, hook_name)` rather than writing `hook_asset.bytes` verbatim — a foreign hook (no SCE managed block, no legacy guidance-URL marker) is kept as an exact byte prefix with the canonical block appended after it, an SCE-owned hook has only its block spliced in place or left unchanged, and a legacy pre-marker hook is replaced wholesale — then follows the same per-file stage/atomic-swap choreography as config-asset install: the staging file is renamed directly over the existing hook without unlinking it first, so a rename failure leaves the prior hook's bytes and executable bit intact, with deterministic recovery guidance on swap failure. `Installed`/`Updated`/`Skipped` are decided against the merged bytes plus the executable bit rather than the canonical asset's raw bytes, so an already-current foreign-plus-block hook reports `Skipped`; `RequiredHookInstallResult.unreachable_block_advisory` is set, and rendered as a named advisory line in setup's hook output, when an appended block follows a foreign hook's zero-indent `exec`/`exit` and so would never run. After the Git gate, setup always ensures the context baseline; context-only requests return there, while normal modes derive a repo-root-scoped context before aggregating static lifecycle provider `setup` dispatch across providers (config → local_db → auth_db → agent_trace_db → hooks when requested), so setup providers consume only repo-root access from the scoped context. - `cli/src/services/setup/mod.rs` keeps those responsibilities inside one file for now, but the current ownership split is explicit: the inline `install` module owns repository-path normalization, staging/swap install behavior, required-hook installation, and filesystem safety guards, while the inline `prompt` module owns interactive target selection and prompt styling. +- `cli/src/services/setup/access_preferences.rs` owns the reader and the atomic writer for setup's global access preferences (`auth.mode`, `telemetry.enabled` in the global user config only), over the shared temp-file-plus-rename helper in `setup/atomic_write.rs`. `setup/command.rs` calls it after dispatch and before any repository write, and re-resolves the policy for the `SCE access` report and for the setup login step (`setup_login_action` / `run_setup_login_step`, which reuses `auth_command::run_login_in` rather than a separate login path); precedence stays in `config/resolver.rs` (see `context/cli/access-policy.md#setup`). - `cli/src/services/security.rs` provides shared security utilities for deterministic secret redaction (`redact_sensitive_text`) and directory write-permission probes (`ensure_directory_is_writable`) used by app/setup/observability surfaces. - `cli/src/services/doctor/mod.rs` owns the current doctor request/report surface while focused submodules (`doctor/inspect.rs`, `doctor/render.rs`, `doctor/fixes.rs`, `doctor/types.rs`) split report fact collection, rendering, manual fix reporting, and doctor-owned domain types into smaller seams; `cli/src/services/doctor/command.rs` owns the `DoctorCommand` payload used by the static `RuntimeCommand` enum and executes against any context implementing repo-root scoping. Runtime doctor execution resolves a repository root, derives a scoped context, requests the shared static lifecycle provider catalog with hooks included for service-owned `diagnose` and `fix` behavior, adapts lifecycle-owned health/fix records into doctor-owned problem/fix records, and then renders stable text/JSON problem records with category/severity/fixability/remediation fields plus deterministic fix-result reporting in fix mode. Agent Trace database inspection is no longer a doctor-adjacent command surface; doctor owns repository-scoped DB health and checkout identity facts, while `sce sync` owns control-plane synchronization. Report fact collection preserves environment/repository/hook/integration display data and adds a non-launching `post_commit_auto_sync` fact based on canonical post-commit managed-block currency plus resolved `agent_trace.auto_sync` source/value; this fact does not launch `sce sync`, and existing hook problem/remediation/readiness semantics remain authoritative. Service-owned lifecycle providers own config validation, local DB and repository-scoped Agent Trace DB readiness/bootstrap, and hook rollout diagnosis/repair. Integration inspection in `doctor/inspect.rs` is scoped twice over: `resolve_doctor_integration_targets` picks which targets to inspect, and `persisted_optional_workflows` (reused from setup) resolves which optional workflows the repository selected, which the OpenCode/Claude/Pi/Codex child collectors apply through `iter_embedded_assets_for_setup_target_with_selection`. An unselected optional workflow therefore contributes no expected children at all, so no row and no missing/mismatch problem can be produced for it, while a selected one keeps the unchanged presence and content-hash checks. Codex's collector (`collect_codex_integration_groups`) is the one exception to the single-target-directory shape the other three share: since `CODEX_EMBEDDED_ASSETS` relative paths already carry their own `.agents/`/`.codex/` prefix, it resolves its integration root through `InstallTargetPaths::codex_target_dir()` (the repository root itself) rather than a `RepoPaths` per-target subdirectory, and splits assets into `Skills` (`.agents/skills/` prefix) and `Hooks` (`.codex/` prefix) groups instead of Pi's `Extensions`/`Prompts`/`Skills` split. Its `.codex/hooks.json` reporting is per-registration rather than one whole-file child: `codex_hook_config::diagnose_document` classifies each required registration — the four `sce hooks codex` registrations plus the six `sce hooks codex-mutation-scope` ones, the latter reported under distinct `#(mutation-scope)` rows — as `PresentAndCurrent`/`Missing`/`Stale` (or the whole document as `Malformed` when it cannot be structurally validated) without writing anything, so unrelated user handlers never create a false whole-document mismatch. For a structurally current registration, `codex_hook_trust` separately reads (never writes) Codex's own durable `$CODEX_HOME/config.toml` hook-trust state — reproducing upstream's `hook_hash`/`hook_key`/`hook_trust_status` exactly — and reports `Trusted`/`Untrusted`/`Modified`/`Disabled`/`Unknown`, and `codex_hook_policy` probes Codex's effective hook-discovery policy once per invocation; only a structurally current registration that is trusted *and* policy-allowed renders healthy. `sce doctor --fix` repairs a structurally unhealthy `.codex/hooks.json` through the existing merge-install path, but a registration that is current yet not-yet-trusted or policy-blocked is never "fixed", since SCE cannot grant Codex hook trust or change managed policy. - `cli/src/services/version/mod.rs` defines the version command parser/rendering contract (`parse_version_request`, `render_version`) with deterministic text output and stable JSON runtime-identification fields; `cli/src/services/version/command.rs` owns the `VersionCommand` payload used by the static `RuntimeCommand` enum. diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md index 65fac6afa..80ea03c5e 100644 --- a/context/cli/access-policy.md +++ b/context/cli/access-policy.md @@ -4,7 +4,7 @@ This file describes how the CLI turns the per-layer `auth.mode` and `telemetry.enabled` config values into one effective access policy (`ResolvedAccessPolicy`). Key syntax and schema validation are in [config precedence contract](config-precedence-contract.md). The precedence model is recorded in [ADR: consent-gated access policy precedence](../decisions/2026-10-20-consent-gated-access-policy-precedence.md). -Status: the resolver computes and exposes the policy, and `sce config show` / `validate` report it (see [Reporting](#reporting)). Managed telemetry startup, `sce doctor`'s managed-telemetry and auto-sync health, the hidden `sce auth telemetry-headers` helper, `sce auth login` / `whoami`, `sce sync`, and post-commit auto-sync enforce the policy (see [Enforcement](#enforcement)). Setup does not enforce it yet. +Status: the resolver computes and exposes the policy, and `sce config show` / `validate` report it (see [Reporting](#reporting)). Managed telemetry startup, `sce doctor`'s managed-telemetry and auto-sync health, the hidden `sce auth telemetry-headers` helper, `sce auth login` / `whoami`, `sce sync`, and post-commit auto-sync enforce the policy (see [Enforcement](#enforcement)). Interactive `sce setup` is the writer for the user layer's access keys (see [Setup](#setup)). ## Terms @@ -21,6 +21,7 @@ Status: the resolver computes and exposes the policy, and `sce config show` / `v - `telemetry`: the effective state, `TelemetryPolicyState` (`Enabled`, or `Disabled(reason)`). - `background_cloud_allowed`. - **Degraded:** at least one default-discovered file was skipped as invalid. +- **Setup global access preferences** (`GlobalAccessPreferences`): the `auth.mode` / `telemetry.enabled` values in the global user config that interactive setup reads to suppress its access prompts and writes from new answers. Read as `Missing`, `Valid { auth_mode, telemetry_enabled }` (an absent key means not asked yet), or `Invalid`. See [Setup](#setup). ## Repository discovery @@ -116,6 +117,12 @@ Each string is a `WARNING_*` constant in `resolver.rs`. The skipped file's own e The note documents a coverage limit: telemetry opt-out does not remove Claude-native telemetry settings already written to user-level Claude settings. +## Setup + +Interactive `sce setup` saves its auth-mode and telemetry-consent answers only to the global user config (the user layer), before any repository write. It never writes them to the repository or explicit layers ([ADR](../decisions/2026-10-21-setup-writes-access-answers-to-user-layer-only.md)). Setup does not change this resolver's precedence: after the install it re-resolves the policy and reports the effective state, so repository and explicit restrictions still win. A saved global value suppresses its prompt on reruns and changes only through `sce setup --reconfigure`, which shows it as the default. The write, its failure handling, and the `SCE access` report are described in [setup local bootstrap: global access preferences](../sce/setup-repo-local-config-bootstrap.md#global-access-preferences). + +Setup then enforces the re-resolved mode with a login step: it never logs in under effective `disabled`, logs in under `optional` only when the user accepted the login offer, and always logs in under `mandatory`. A failed mandatory login exits with `auth.setup_login_required`. See [setup login](../sce/setup-repo-local-config-bootstrap.md#setup-login). + ## Exposure `ResolvedAuthRuntimeConfig`, `ResolvedHookRuntimeConfig`, and `ResolvedObservabilityRuntimeConfig` each carry `access_policy`, cloned from the same resolution that produced the rest of the projection. No consumer resolves config a second time to get the policy. diff --git a/context/cli/cli-command-surface.md b/context/cli/cli-command-surface.md index 2979b4a4b..3eecf9f74 100644 --- a/context/cli/cli-command-surface.md +++ b/context/cli/cli-command-surface.md @@ -62,6 +62,10 @@ Record SCE involvement in Git commits? The confirmations are independent and default to Yes, so Enter persists `true`; an explicit `n` changes only its corresponding value. Successful target setup records the answers at `agent_trace.auto_sync` and `policies.attribution_hooks.enabled` in repo-local `.sce/config.json` while retaining the existing JSON merge and newline behavior. +After those confirmations, interactive setup asks the SCE access prompts (account mode, telemetry consent, login offer), saves the answers to the global user config, and, after the install, runs `sce auth login` from the repository root when the effective mode requires it or the user accepted. A failed mandatory login exits with `auth.setup_login_required`. See [setup local bootstrap: setup login](../sce/setup-repo-local-config-bootstrap.md#setup-login). + +Saved answers skip their prompts on reruns. `sce setup --reconfigure` asks all four saved answers again (auto-sync, attribution, account mode, telemetry consent) with the saved values as defaults; it is interactive-only and fails validation alongside a target flag, `--non-interactive`, `--hooks`, `--repo`, or `--bootstrap-context`. See [setup local bootstrap: reconfigure](../sce/setup-repo-local-config-bootstrap.md#reconfigure). + Non-interactive target setup never prompts. A missing config receives explicit `true` values for both behaviors; an existing config's explicit values and omissions remain unchanged by the non-interactive behavior-selection path. The auto-sync resolver remains config-file-only with omitted fallback `false`, and attribution retains its `SCE_ATTRIBUTION_HOOKS_DISABLED` precedence, `SCE_DISABLED` kill switch, and staged-diff AI-overlap gate. See [setup local bootstrap](../sce/setup-repo-local-config-bootstrap.md), [config precedence](config-precedence-contract.md), and [hook routing](../sce/agent-trace-hooks-command-routing.md). ## Nix installability surface @@ -105,7 +109,7 @@ An interactive `setup` run instead resolves the selection through an `inquire` m `setup` now also exposes compile-time embedded config assets for OpenCode/Claude/Pi/Codex targets, sourced from the generated `config/.opencode/**`, `config/.claude/**`, `config/.pi/**`, and (via a build-time staging merge of `config/.agents/**` + `config/.codex/**`) `config/codex-target/**` trees via `cli/build.rs` with normalized forward-slash relative paths and target-scoped iteration APIs; the embedded asset set includes the OpenCode bash-policy plugin wrapper plus Claude settings `PreToolUse` Bash policy hook, both delegating to the Rust `sce policy bash` path. `setup` additionally includes a repository-root install engine (`install_embedded_setup_assets`) that installs each embedded asset individually into `.opencode/`/`.claude/`/`.pi/` — stage next to the final destination, remove only that destination file if present, swap into place, with deterministic recovery guidance naming the failing asset's path on swap failure — never removing an integration target directory as a whole, while treating bash-policy enforcement files as first-class SCE-managed assets. Codex is the one target whose embedded relative paths already carry their own output-root prefix (`.agents/...`, `.codex/...`), so its destination root is the repository root itself rather than a single `.codex/`-style subdirectory. Its generated hook command resolves that repository root at invocation time, so Codex events from nested cwd and repositories with spaces reach the installed helper safely; Git-root failure is a silent successful no-op, while the helper preserves missing-CLI stderr guidance and STDIN forwarding. See [setup non-destructive per-asset install policy](../sce/setup-no-backup-policy-seam.md) for the full contract, including the pending pruning gap for deselected/stale assets. `setup` now executes end-to-end and prints deterministic completion details including selected target(s) and per-target install count. -`setup` with a selected Claude target also merges Claude-native OpenTelemetry settings into user-level Claude `settings.json` (`$CLAUDE_CONFIG_DIR` else `~/.claude`) and prints a fixed telemetry line (configured, authentication pending, skipped on conflict/malformed JSON, or skipped because the effective access policy does not enable telemetry, in which case settings are untouched) without failing repository setup; see [telemetry credential](../sce/telemetry-credential.md). The hidden auth helper is intentionally not part of the public command listing. +`setup` with a selected Claude target also merges Claude-native OpenTelemetry settings into user-level Claude `settings.json` (`$CLAUDE_CONFIG_DIR` else `~/.claude`) and prints a fixed telemetry line (configured, configured but not ready for this repository when interactive setup finds no valid credential bound to it, configured with repository authorization not checked for non-interactive and target-flag runs, which never read authentication storage, skipped on conflict/malformed JSON, or skipped because the effective access policy does not enable telemetry, in which case settings are untouched) without failing repository setup; see [telemetry credential](../sce/telemetry-credential.md). The hidden auth helper is intentionally not part of the public command listing. `doctor` now executes end-to-end with explicit diagnosis and repair-intent surfaces: `sce doctor` stays read-only and `sce doctor --fix` selects repair-intent mode. The former Agent Trace database inspection routes are unavailable; doctor owns repository-scoped Agent Trace DB health (checkout-identity diagnostics were removed by the `remove-checkout-id` plan; see `context/cli/checkout-identity.md`). The current `doctor` runtime aggregates `ServiceLifecycle::diagnose` and `ServiceLifecycle::fix` calls across all registered service providers (`config`, `local_db`, `auth_db`, `agent_trace_db`, `hooks`) plus integration checks, covering state-root resolution, global and repo-local `sce/config.json` readability/schema validation, local DB and repository-scoped Agent Trace DB path/health, DB-parent readiness barriers, the repo hook rollout slice when a repository target is detected, and post-commit Agent Trace auto-sync readiness derived from canonical managed-block currency plus resolved configuration. The readiness fact reports enabled/current, explicit disabled, not-ready, and not-applicable states in text and JSON without launching synchronization; Claude's inventory is only `Plugins`, `Commands`, and `Skills`, while OpenCode retains `Agents`. Fix mode delegates to each provider's `fix` implementation, which reuses the canonical setup hook install flow to repair missing/stale/non-executable required hooks and missing hooks directories, and it can bootstrap missing canonical database parent directories when the resolved paths match canonical owned locations. `sce sync [--format text|json]` is the implemented user-invocable synchronization command: it synchronizes the current repository's Agent Trace DB with the control-plane ingestion API; local DB and Agent Trace DB bootstrap continue to happen through `setup`, and DB health/repair continues to happen through `doctor`. Under `auth.mode: disabled`, `sce sync` fails with `auth.disabled_by_config` before storage or credential access (see [effective access policy](access-policy.md#enforcement)). See [agent-trace-sync-command.md](agent-trace-sync-command.md) and [sync-command.md](sync-command.md). diff --git a/context/cli/config-precedence-contract.md b/context/cli/config-precedence-contract.md index 0d9a5672e..93a2c0a44 100644 --- a/context/cli/config-precedence-contract.md +++ b/context/cli/config-precedence-contract.md @@ -100,6 +100,7 @@ When a default-discovered global or repo-local config file exists but fails JSON - `auth` must be an object when present and allows only `mode`, one of `disabled|optional|mandatory` (schema default `optional`); `AuthMode` in `cli/src/services/config/types.rs` owns parsing. - `telemetry` must be an object when present and allows only `enabled`, a boolean (schema default `false`). It is consent for SCE-managed export and is independent of the `otel` destination block. +- Interactive `sce setup` writes `auth.mode` and `telemetry.enabled` to the global config only, and only for answers given in that run. It never adds `auth` or `telemetry` to repo-local or explicit files. See [setup local bootstrap: global access preferences](../sce/setup-repo-local-config-bootstrap.md#global-access-preferences). - Both sections are accepted in global, repo-local, and explicit config files and parse per layer with their `ConfigPathSource` (`FileConfig.auth_mode` / `FileConfig.telemetry_enabled`). Invalid modes, non-boolean `enabled` (including the string `"true"`), unknown sub-keys, and non-object sections fail generated-schema validation with `/auth...` or `/telemetry...` pointers. The resolver captures both values per layer (user = global; repository = repo-local; explicit = `--config` / `SCE_CONFIG_FILE`) and resolves them into the effective access policy with consent-gated precedence and fixed contradiction warnings; see [effective access policy](access-policy.md). `sce config show` reports both values plus the effective telemetry state, and the consumers listed in the access-policy contract enforce them. - `otel` must be an object when present and allows optional `endpoint`, `protocol`, `traces_endpoint`, `metrics_endpoint`, and `logs_endpoint`; `protocol` accepts only `http/protobuf` and the endpoint fields are non-empty strings. The block and each field are config-file only (global-before-local per-key merge) and omission never removes the code-owned managed OTLP defaults in `cli/src/services/managed_telemetry.rs` (`https://otel.crocoderlab.dev`, `http/protobuf`, and `/v1/traces`, `/v1/metrics`, `/v1/logs` paths); `show` reports each as `otel.` with `source: default` when unset. The metrics endpoint is reserved for a later pipeline. @@ -163,7 +164,7 @@ When a default-discovered global or repo-local config file exists but fails JSON ## Setup-written behavior values -Interactive setup is the only selection path for these two behavior values. After target selection, it persists the independent confirmation results at `agent_trace.auto_sync` and `policies.attribution_hooks.enabled`; Enter accepts each Yes default, and `n` changes only that key. A non-interactive target run supplies no values, so it preserves both keys when present and preserves their omission when absent. Creating a missing repo-local config is the exception: setup bootstraps both values as explicit `true`. +Interactive setup is the only selection path for these two behavior values. After target selection, it persists the independent confirmation results at `agent_trace.auto_sync` and `policies.attribution_hooks.enabled`; Enter accepts each Yes default, and `n` changes only that key. A non-interactive target run supplies no values, so it preserves both keys when present and preserves their omission when absent. Creating a missing repo-local config is the exception: setup bootstraps both values as explicit `true`. A persisted value skips its prompt on later interactive runs; `sce setup --reconfigure` asks again with the persisted value as the default, and does the same for the setup-written global `auth.mode` and `telemetry.enabled`. These setup writes do not add a resolver layer. `agent_trace.auto_sync` remains config-file-only with global-before-local merge and omitted fallback `false`; attribution remains enabled by default, with `SCE_ATTRIBUTION_HOOKS_DISABLED` overriding `policies.attribution_hooks.enabled`. `SCE_DISABLED`, staged-diff AI-overlap evidence, and all other hook semantics remain owned by the hook runtime. diff --git a/context/context-map.md b/context/context-map.md index 267047db4..7f8dc9e63 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -87,7 +87,7 @@ Feature/domain context: - `context/sce/setup-githooks-hook-asset-packaging.md` (compile-time `sce setup --hooks` required-hook template packaging contract, including all-hook non-blocking missing-`sce` install guidance, available-CLI argument forwarding, post-commit-only origin remote lookup plus remote-URL forwarding/fallback behavior, setup-service accessor surface, and current validation posture) - `context/sce/setup-githooks-install-flow.md` (setup-service required-hook install orchestration with git-truth hooks-path resolution, managed-block merge content computation that preserves foreign hook content, per-hook installed/updated/skipped outcomes decided against the merged content, the unreachable-block advisory, and atomic-swap replacement with recovery guidance) - `context/sce/setup-githooks-cli-ux.md` (T04 composable `sce setup` target+`--hooks` / `--repo` command-surface contract, option compatibility validation, and deterministic setup/hook output semantics) -- `context/sce/setup-repo-local-config-bootstrap.md` (setup local bootstrap behavior: Git-root and named-remote preflights before prompts/context/lifecycle/hooks/assets, shared degraded handling for invalid default-discovered repo-local config with byte-preserving skip of integration persistence, explicit-config fatality, additive durable-context baseline via `sce setup --bootstrap-context` and every normal setup path, repo-local `.sce/config.json` create-if-missing via config lifecycle, additive `integrations.target` persistence after successful target installs, `integrations.optional_workflows` selection persistence with prompt-over-flag-over-persisted precedence, plus lifecycle-owned local DB initialization before hooks/config asset dispatch) +- `context/sce/setup-repo-local-config-bootstrap.md` (setup local bootstrap behavior: Git-root and named-remote preflights before prompts/context/lifecycle/hooks/assets, shared degraded handling for invalid default-discovered repo-local config with byte-preserving skip of integration persistence, explicit-config fatality, additive durable-context baseline via `sce setup --bootstrap-context` and every normal setup path, repo-local `.sce/config.json` create-if-missing via config lifecycle, additive `integrations.target` persistence after successful target installs, `integrations.optional_workflows` selection persistence with prompt-over-flag-over-persisted precedence, plus lifecycle-owned local DB initialization before hooks/config asset dispatch, and interactive global-only `auth.mode` / `telemetry.enabled` persistence before any repository write with the re-resolved `SCE access` report, the interactive setup login step decided by the effective auth mode with `auth.setup_login_required` on mandatory failure, and interactive-only `sce setup --reconfigure` re-asking every saved answer with the saved value as the default) - `context/sce/cli-security-hardening-contract.md` (T06 CLI redaction contract, setup `--repo` canonicalization/validation, and setup write-permission probe behavior) - `context/sce/agent-trace-post-rewrite-local-remap-ingestion.md` (current post-rewrite no-op baseline plus historical remap-ingestion reference) - `context/sce/agent-trace-rewrite-trace-transformation.md` (current post-rewrite no-op baseline plus historical rewrite-transformation reference) @@ -148,6 +148,7 @@ Supporting repo docs: Recent decision records: +- `context/decisions/2026-10-21-setup-writes-access-answers-to-user-layer-only.md` (interactive setup writes `auth.mode` / `telemetry.enabled` only to the global user config, atomically and before any repository write, never to repository or explicit config files; resolver precedence unchanged) - `context/decisions/2026-10-02-claude-background-bash-untracked.md` (effective Claude background-admission decision; supersedes `context/decisions/2026-10-01-claude-background-admission-requires-proven-lifecycle.md`, which is retained unmodified as history: permits Claude-managed `Bash(run_in_background=true)` natively with no mutation scope, adapter attempt, lifecycle tracking, or mutation-attribution guarantee, accepting that an untracked background process may contaminate a concurrent tracked scope's attribution; lifecycle completion remains unproven, background `PowerShell` stays denied, and the Claude adapter implements the decision) - `context/decisions/2026-09-07-split-auto-sync-defaults.md` (newly bootstrapped repo-local config explicitly opts into Agent Trace auto-sync while omitted runtime values remain disabled) - `context/decisions/2026-09-10-claude-bridge-seeding-on-diff-trace.md` (moves bridge-derived Claude model-state seeding from the model-less `SessionStart` path — structurally unable to read its own lazily created transcript — to the diff-trace state miss, amends attribution precedence to `direct > exact transcript > exact state > bridge-derived chain state > NULL`, accepts one exact-scope state write on that resolution path, and selects the newest chain observation by `observed_at_ms` rather than the chain origin or the newest sibling transcript; supersedes the trigger point and selection rule of the 2026-09-08 decision) diff --git a/context/decisions/2026-10-21-setup-writes-access-answers-to-user-layer-only.md b/context/decisions/2026-10-21-setup-writes-access-answers-to-user-layer-only.md new file mode 100644 index 000000000..adbb99f4e --- /dev/null +++ b/context/decisions/2026-10-21-setup-writes-access-answers-to-user-layer-only.md @@ -0,0 +1,69 @@ +# Decision: Setup writes access-policy answers to the user layer only + +Date: 2026-10-21 +Status: Accepted +Plan: `context/plans/setup-auth-telemetry-consent.md` +Task: `T01, T05` + +## Context + +Interactive `sce setup` asks for the SCE auth mode and for telemetry consent. Those answers must be saved somewhere the resolver reads as a policy layer. SCE credentials (`auth.db` and its OS credential-store key) are per-user and per-machine. The repository `.sce/config.json` is committed and shared with a team. Older SCE binaries skip a whole config file that holds keys they reject. Under the [consent-gated precedence](2026-10-20-consent-gated-access-policy-precedence.md), only the user side can grant telemetry consent, and a repository `true` grants nothing. + +## Decision + +Interactive `sce setup` writes `auth.mode` and `telemetry.enabled` only to the global user config (`${config_root}/sce/config.json`, the user policy layer). It never writes them to the repository `.sce/config.json` or to an explicit `--config` / `SCE_CONFIG_FILE` file. + +How the write behaves: + +- It records explicit answers only. A key the user was not asked about stays absent. +- It is atomic: a sibling temp file, then a rename. The existing file mode is kept, and a new file gets `0o600`. +- It uses best-effort optimistic concurrency: the file's bytes are re-read before the rename, and the write is refused if they changed. +- It never overwrites a global file that is invalid. +- It runs before any repository write. If it fails, setup aborts with no repository files changed. + +Resolver precedence (`resolve_access_policy`) is unchanged by this decision. + +## Rationale + +- Consent and the choice to use credentials belong to the person on the machine, which matches where credentials live. +- Writing a restriction into the shared repository file would amount to team-policy authoring through a personal setup run. It could also make older binaries ignore that repository's whole config. +- A user-layer-only write keeps the existing precedence intact. Repository and explicit restrictions (`auth.mode: disabled`, `telemetry.enabled: false`) still win, and setup cannot grant consent through the repository. +- Writing globally before any repository write means a failed consent write leaves nothing half-done. + +## Alternatives considered + +- **Write the answers to the repository `.sce/config.json`.** Not selected. The file is shared and committed, a repository `true` cannot grant consent, and older binaries reject the keys. +- **Offer a fourth, repository-scoped restriction choice in setup.** Not selected. It would change shared files and break older binaries. The plan keeps this as an open question rather than shipping it. + +## Compatibility and risks + +- A global `auth.mode: disabled` chosen during setup in one repository applies to every repository on the machine. The setup report states this scope ("applies to all repositories on this machine"). +- The concurrency check is optimistic, not a lock. Two writers that race between the re-read and the rename can still collide. +- The first rewrite does not preserve key order in the global file. + +## Guardrails + +- Setup never writes `auth` or `telemetry` keys into the repository config. +- Setup never lifts a global prohibition silently: a persisted global value suppresses its prompt on reruns. +- Setup never overwrites an invalid global config. When the global config is invalid at read time, the access prompts are skipped. +- The resolver's precedence is not recomputed or duplicated in setup. + +## Consequences + +- The effective policy that setup reports comes from re-resolution, so a repository opt-out can still disable telemetry after the user consents. +- Unattended consent requires deliberately editing the global config. No non-interactive consent flags exist. + +## Follow-up + +- None. + +## References + +- Plan: [`setup-auth-telemetry-consent`](../plans/setup-auth-telemetry-consent.md) +- Task: `T01`, `T05` +- Current-state context: [`access-policy.md`](../cli/access-policy.md) +- Current-state context: [`setup-repo-local-config-bootstrap.md`](../sce/setup-repo-local-config-bootstrap.md) +- Current-state context: [`config-precedence-contract.md`](../cli/config-precedence-contract.md) +- Evidence: [`access_preferences.rs`](../../cli/src/services/setup/access_preferences.rs) +- Evidence: [`command.rs`](../../cli/src/services/setup/command.rs) +- Related decision: [`Consent-gated precedence for the effective access policy`](2026-10-20-consent-gated-access-policy-precedence.md) diff --git a/context/glossary.md b/context/glossary.md index dc52f3b97..68daf0505 100644 --- a/context/glossary.md +++ b/context/glossary.md @@ -1,5 +1,5 @@ # Glossary -- CLI execution terminology: [command dispatch, runtime dependencies and telemetry](cli/execution-glossary.md). Auth mode, policy layer (user/repository), effective access policy, and the `auth.disabled_by_config` rejection: [effective access policy](cli/access-policy.md). +- CLI execution terminology: [command dispatch, runtime dependencies and telemetry](cli/execution-glossary.md). Auth mode, policy layer (user/repository), effective access policy, setup global access preferences, and the `auth.disabled_by_config` rejection: [effective access policy](cli/access-policy.md). Setup login step and `auth.setup_login_required`: [setup login](sce/setup-repo-local-config-bootstrap.md#setup-login). - `pkl-check-generated`: Flake app exposed as `nix run .#pkl-check-generated`; canonical ephemeral-generation check that rejects committed target/schema/mirror outputs, evaluates exact workflow metadata, the generated artifact contract, semantic layout/path/inventory/content/parity/observational checks, and the optional-workflow manifest's content against the catalog, requires the shared helper-composition rule and SCE-scoped workflow prohibitions, enforces ordered catalog-derived OpenCode skill permissions plus explicit-permission artifact integrity, rejects stale sibling-package references or unresolved internalization tokens in workflow entrypoint `SKILL.md` documents, proves contract failures through checked-in negative fixtures, and delegates deterministic generation plus payload/input inventories to the generated-input producer while preserving its established inventory report. - `repo-level verification preference`: Current repository guidance that contributor-facing validation/check flows should prefer `nix flake check`; direct Cargo verification commands are secondary and used only when explicitly requested or for narrow targeted debugging, while `cargo fmt` remains the explicit autofix path. Required quick checks after each completed task in this repo are `nix run .#pkl-check-generated` and `nix flake check`. - disposable plan lifecycle: Policy where `context/plans/` holds active execution artifacts only; completed plans are disposable and durable outcomes must be reflected in current-state context files and/or `context/decisions/`. @@ -107,7 +107,7 @@ - `CLI generated migration manifest`: Build-time Rust source at `OUT_DIR/generated_migrations.rs` written by `cli/build.rs` from immediate `cli/migrations//*.sql` directories after staging SQL under `OUT_DIR/static/migrations`; constants are named from the database directory (for example `AGENT_TRACE_REPOSITORY_MIGRATIONS`, `AUTH_MIGRATIONS`), sorted by the numeric filename prefix before `_`, and embed staged SQL via `include_str!`. - `sync command deferral` (historical): Former plan/state note that a user-invocable sync command was deferred to `0.4.0`; superseded first by nested `sce trace sync` and now by top-level `sce sync` (see `context/cli/sync-command.md`). Local DB bootstrap and setup-time repository-scoped Agent Trace DB initialization still flow through lifecycle providers aggregated by the setup command, hook runtime still keeps a lazy repository Agent Trace DB fallback for repositories where setup has not run or schema metadata is incomplete, and DB health/repair still flows through the doctor surface. - `CLI bounded resilience wrapper`: Shared policy in `cli/src/services/resilience.rs` (`RetryPolicy`, async `run_with_retry` and non-cancelling `run_with_retry_elapsed`) that applies deterministic retries/timeouts/capped backoff to transient operations, emits retry observability events, and returns actionable terminal failure guidance. Async database construction and operations use `run_with_retry`; there is no synchronous variant. -- `setup service orchestration`: Setup execution logic in `cli/src/services/setup/command.rs` that resolves the repository root, always ensures the durable-context baseline, then for normal modes derives a repo-root-scoped `AppContext` from the runtime command context, dispatches `setup` through the static lifecycle provider catalog (config → local_db → auth_db → agent_trace_db → hooks when requested), handles interactive target selection for config asset installation, and emits deterministic success messaging per target. +- `setup service orchestration`: Setup execution logic in `cli/src/services/setup/command.rs` that resolves the repository root, saves interactive access answers to the global config, always ensures the durable-context baseline, then for normal modes derives a repo-root-scoped `AppContext` from the runtime command context, dispatches `setup` through the static lifecycle provider catalog (config → local_db → auth_db → agent_trace_db → hooks when requested), handles interactive target selection for config asset installation, and emits deterministic success messaging per target. - `setup target flags` and `setup mode contract`: Mutually-exclusive `sce setup` target selectors (`--opencode`, `--claude`, `--pi`, `--codex`, `--all`) force non-interactive `SetupMode::NonInteractive(SetupTarget)` when exactly one is provided; otherwise `SetupMode::Interactive` is the default. `--all` expands to opencode+claude+pi+codex and replaced the removed `--both` flag. - `setup interactive target prompt`: `inquire::Select` flow in `cli/src/services/setup/mod.rs` (`InquireSetupTargetPrompter`) that presents OpenCode, Claude, Pi, Codex, and All (OpenCode + Claude + Pi + Codex) when `sce setup` runs without target flags. - `setup dispatch outcome`: Execution model in `cli/src/services/setup/mod.rs` (`SetupDispatch`) where setup either proceeds with a selected/non-interactive target or exits as cancelled without file changes. Interactive dispatch also carries independent `agent_trace.auto_sync` and `policies.attribution_hooks.enabled` booleans from Yes-default confirmations; non-interactive dispatch carries neither, allowing persistence to preserve existing keys and omissions. diff --git a/context/overview.md b/context/overview.md index b495ab3ad..b0364eb47 100644 --- a/context/overview.md +++ b/context/overview.md @@ -57,7 +57,7 @@ The generated `/next-task` workflow persists task-level context-synchronization - **Observability:** config-resolved logging with tracing, explicit config-file/default `log_to_file` control, suppression of normal logger records on `stderr` when file logging is enabled, error-only logger routing to `stderr` when file logging is disabled, and optional dated/session-partitioned `log_dir` / `SCE_LOG_DIR` files with retention (see `context/sce/cli-observability-contract.md`). - **Config precedence:** `flags > env > config file > defaults` (see `context/cli/config-precedence-contract.md`); invalid default-discovered config remains degradable for ordinary startup, while setup and Agent Trace storage fail closed before side effects or fallback identity selection. The config-file-only `agent_trace.auto_sync` setting resolves omitted values to `false`, while setup explicitly writes `true` into a newly created repo-local config; source metadata feeds the post-commit trigger and doctor readiness boundaries. Its asynchronous post-commit behavior and doctor capability reporting are documented in `context/cli/agent-trace-auto-sync.md`. - **Attribution hooks:** enabled by default, gated by staged-diff AI-overlap preflight; `SCE_ATTRIBUTION_HOOKS_DISABLED` opt-out (see `context/sce/agent-trace-commit-msg-coauthor-policy.md`). -- **Setup behavior choices:** interactive setup asks independent Yes-default confirmations for post-commit Agent Trace auto-sync and commit-attribution trailers, persists the answers under `agent_trace.auto_sync` and `policies.attribution_hooks.enabled`, and leaves existing behavior keys/omissions untouched during non-interactive setup. The runtime resolver and hook contracts remain authoritative (see `context/sce/setup-repo-local-config-bootstrap.md`). +- **Setup behavior choices:** interactive setup asks independent Yes-default confirmations for post-commit Agent Trace auto-sync and commit-attribution trailers, persists the answers under `agent_trace.auto_sync` and `policies.attribution_hooks.enabled`, and leaves existing behavior keys/omissions untouched during non-interactive setup. Interactive setup also asks for the SCE auth mode and telemetry consent, saves those answers only to the global user config before any repository write, and reports the re-resolved effective access policy in an `SCE access` section. It then runs `sce auth login` from the repository root when the effective mode is `mandatory` or the user accepted the `optional` login offer, never under `disabled`; a failed mandatory login exits with `auth.setup_login_required`. Saved answers skip their prompts on reruns; interactive-only `sce setup --reconfigure` asks them all again with the saved values as defaults. The runtime resolver and hook contracts remain authoritative (see `context/sce/setup-repo-local-config-bootstrap.md`). - **Install channels:** repo-flake Nix, Cargo, npm, and source-built Flatpak (`dev.crocoder.sce`); Homebrew deferred (see `context/sce/cli-first-install-channels-contract.md`). The CLI crate currently depends on `anyhow`, `chrono`, `clap`, `clap_complete`, `dirs`, `hmac`, `indicatif`, `inquire`, `jsonschema`, `keyring-core`, `murmur3`, `owo-colors`, `rand`, `reqwest`, `serde`, `serde_json`, `sha2`, `tokio`, `tracing`, `turso`, and `uuid`, with target-specific keyring backend dependencies for Linux/FreeBSD, macOS, and Windows. `quint-connect` is the CLI's first dev-only dependency, added for the in-progress `mutation-cursor-quint-connect` model-based-testing harness. @@ -73,7 +73,7 @@ Agent Trace lifecycle setup now resolves repository storage and initializes `` flag names the selection for a run, an omitted flag reuses the selection persisted in `integrations.optional_workflows`, and the resolved selection filters the installed target assets and is written back to repo-local config. Interactive runs ask for the selection instead: a multi-select prompt follows target selection with every row unchecked on a first run and pre-checked from the persisted selection afterwards, cancelling it exits non-destructively like the target prompt, and the prompt is skipped when the catalog marks no workflow optional. `brownfield` is currently the only optional workflow, so a default run installs the five core workflows and no brownfield assets. `sce doctor` scopes its integration checks to that same recorded selection, so it never reports an unselected optional workflow's files as missing. For repository generation consumers, `config/pkl/generator-inputs.txt` declares the canonical Pkl/plugin input set and `scripts/produce-cli-generated-input.sh` owns its discovery, two-pass `config/pkl/generate.pkl` evaluation, determinism comparison, payload/input inventories, in-flight input-mutation rejection, atomic handoff publication, and staging cleanup. `scripts/run-cli-cargo.sh` creates a fresh temporary destination, delegates generation to that producer, invokes the requested Cargo workflow with `SCE_CLI_GENERATED_INPUT_DIR`, and removes the handoff after Cargo success, failure, or handled signals. `config/pkl/check-generated.sh` delegates the same production mechanics while retaining contract and path assertions. The root flake also runs `codex-hook-command`, which generates the Codex assets and verifies root, nested-cwd, spaced-path, stdin-forwarding, and fail-open invocation behavior against a stub `sce`. `scripts/prepare-cli-generated-assets.sh` moves the producer-validated Pkl payload and checksums into the unchanged package fallback, adds hooks, migrations, and the Agent Trace schema, and appends only those static checksums to the combined inventory. The root flake's pre-Cargo `cliGeneratedInput` derivation invokes the same producer from a declarative source containing the producer plus its declared inputs. `cli/build.rs` rejects missing, incomplete, modified, or stale repository handoffs, copies the validated payload into Cargo `OUT_DIR/pkl-generated`, stages static inputs under `OUT_DIR/static`, and writes setup-asset, optional-workflow-catalog, and migration Rust manifests into `OUT_DIR`; it never invokes Pkl. Published crates carry the ignored packaging-only fallback, and unpacked downstream builds validate and copy it into their own `OUT_DIR` without requiring Pkl or parent repository paths. -The setup service also provides repository-root install orchestration: it resolves the repository root, ensures the additive durable-context baseline, then for normal modes derives a repo-root-scoped `AppContext` from the runtime command context, aggregates `ServiceLifecycle::setup` calls across lifecycle providers (config → local_db → auth_db → agent_trace_db → hooks when requested), handles interactive or flag-based target selection for config asset installation, and reports deterministic completion details (selected target(s) and installed file counts). Setup installs config assets (`.opencode`/`.claude`/`.pi`) per file: each embedded asset is staged and swapped into its own destination path, creating parent directories as needed, without removing or recreating the target directory as a whole, so files a repository owns inside an SCE-managed target directory survive a setup run untouched. Two assets are merge targets rather than verbatim writes: Claude's `.claude/settings.json` and OpenCode's `.opencode/opencode.json`. For each, setup JSON-merges the generated document into the user's existing file rather than overwriting it, and fails deterministically without writing if the existing file is not valid JSON; a missing file is still created from the generated document verbatim. Claude's merge replaces only SCE-owned hook entries (identified by a command containing `run-sce-or-show-install-guidance.sh`) and the `$schema` key while preserving every other key and hook entry untouched. OpenCode's merge replaces the `$schema` key and merges the `plugin` array as a set: any entry shaped like an SCE plugin path (`./plugins/sce-*`) is dropped, structurally, so a path an older or renamed catalog once installed is still recognized and pruned, and the generated document's canonical plugin entries are appended after the surviving user entries. Required-hook install uses the same per-file stage/atomic-swap choreography as config-asset install — the staging file is renamed directly over an existing hook without unlinking it first, so a rename failure leaves the prior hook untouched. Both flows return deterministic recovery guidance (recover from version control) on swap failure, without creating backup artifacts. After installing, config install prunes stale SCE-owned assets: it deletes every path the full embedded catalog for the target claims but the current selection did not install (a deselected optional workflow, or an asset a newer catalog renamed or dropped), then removes any parent directory left empty by that deletion, leaving a directory intact if a user file still lives inside it. The setup command gates all modes on an existing git repository before any writes. Internally, `cli/src/services/setup/mod.rs`now separates install-flow logic from interactive prompt logic through focused support seams. +The setup service also provides repository-root install orchestration: it resolves the repository root, saves interactive access answers to the global config, ensures the additive durable-context baseline, then for normal modes derives a repo-root-scoped `AppContext` from the runtime command context, aggregates `ServiceLifecycle::setup` calls across lifecycle providers (config → local_db → auth_db → agent_trace_db → hooks when requested), handles interactive or flag-based target selection for config asset installation, and reports deterministic completion details (selected target(s) and installed file counts). Setup installs config assets (`.opencode`/`.claude`/`.pi`) per file: each embedded asset is staged and swapped into its own destination path, creating parent directories as needed, without removing or recreating the target directory as a whole, so files a repository owns inside an SCE-managed target directory survive a setup run untouched. Two assets are merge targets rather than verbatim writes: Claude's `.claude/settings.json` and OpenCode's `.opencode/opencode.json`. For each, setup JSON-merges the generated document into the user's existing file rather than overwriting it, and fails deterministically without writing if the existing file is not valid JSON; a missing file is still created from the generated document verbatim. Claude's merge replaces only SCE-owned hook entries (identified by a command containing `run-sce-or-show-install-guidance.sh`) and the `$schema` key while preserving every other key and hook entry untouched. OpenCode's merge replaces the `$schema` key and merges the `plugin` array as a set: any entry shaped like an SCE plugin path (`./plugins/sce-*`) is dropped, structurally, so a path an older or renamed catalog once installed is still recognized and pruned, and the generated document's canonical plugin entries are appended after the surviving user entries. Required-hook install uses the same per-file stage/atomic-swap choreography as config-asset install — the staging file is renamed directly over an existing hook without unlinking it first, so a rename failure leaves the prior hook untouched. Both flows return deterministic recovery guidance (recover from version control) on swap failure, without creating backup artifacts. After installing, config install prunes stale SCE-owned assets: it deletes every path the full embedded catalog for the target claims but the current selection did not install (a deselected optional workflow, or an asset a newer catalog renamed or dropped), then removes any parent directory left empty by that deletion, leaving a directory intact if a user file still lives inside it. The setup command gates all modes on an existing git repository before any writes. Internally, `cli/src/services/setup/mod.rs`now separates install-flow logic from interactive prompt logic through focused support seams. The CLI now also applies baseline security hardening for reliability-driven automation: diagnostics/logging paths use deterministic secret redaction,`sce setup --hooks --repo ` canonicalizes and validates repository paths before execution, and setup write flows run explicit directory write-permission probes before staging/swap operations. The config service now provides deterministic runtime config resolution with explicit precedence (`flags > env > config file > defaults`), strict config-file validation (`$schema`, `log_level`, `log_format`, `log_to_file`, `log_dir`, `workos_client_id`, and nested `policies.bash`, `policies.attribution_hooks.enabled`, plus `policies.database_retry` with per-DB `connection_open`/`query` retry policy specs and Agent Trace-only `agent_trace_db.busy_timeout_ms`/`contention_deadline_ms`), deterministic default discovery/merge of global+local config files (`${config*root}/sce/config.json`then`.sce/config.json`with local override, where`config_root` comes from the shared default-path seam with XDG/`dirs::config_dir()` config-root resolution), defaults for the resolved observability value set (`log_level=error`, `log_format=text`, `log_dir=/sce/logs`), shared auth-key resolution with optional baked defaults starting at `workos_client_id`, first-class bash-policy preset/custom parsing with deterministic conflict and duplicate-prefix validation, custom-policy `satisfied_by`wrapper exemption (a policy does not fire when the matched command was unwrapped from a declared wrapper such as`nix shell nixpkgs#ripgrep`), and a canonical Pkl-authored `sce/config.json`JSON Schema generated beneath Cargo`OUT_DIR`and embedded by`cli/src/services/config/mod.rs`for both`sce config validate`and doctor-time config checks. Runtime startup config loading keeps parity with that schema by accepting its`$schema`declaration in repo-local and global config files, so startup commands such as`sce version`no longer fail before dispatch on that field; the canonical declaration is versioned as`"https://sce.crocoder.dev/v/config.json"` using the CLI release version; this schema URL is separate from the `https://sce.crocoderlab.dev` baked default used by `sce sync` for control-plane ingestion. App-runtime observability now consumes flat logging keys through the shared resolver, so env values still override config-file values while config files provide deterministic fallback for `log_dir`; positive-integer `log_file_retention_limit` uses config-file/default precedence, defaults to `10`, and controls creation-triggered cleanup for primary and v2 log files; `sce config show` reports resolved observability/auth/policy values with provenance, while `sce config validate` is now a trimmed validation surface that reports only pass/fail plus validation errors or warnings in text and JSON modes. The canonical preset catalog and matching contract live in `config/pkl/base/bash-policy-presets.pkl` and `context/sce/bash-tool-policy-enforcement-contract.md`. Invalid default-discovered config files now also degrade gracefully at startup: `sce` keeps running with degraded observability defaults, logs `sce.config.invalid_config` warnings, and reserves hard failures for explicit `--config` / `SCE_CONFIG_FILE` targets or other truly invalid runtime observability inputs. diff --git a/context/plans/setup-auth-telemetry-consent.md b/context/plans/setup-auth-telemetry-consent.md new file mode 100644 index 000000000..ce1930c26 --- /dev/null +++ b/context/plans/setup-auth-telemetry-consent.md @@ -0,0 +1,663 @@ +# Plan: setup-auth-telemetry-consent + +## Change summary + +Interactive `sce setup` gains three steps: it asks for the auth mode (`disabled | optional | mandatory`, default `optional`), it asks for explicit SCE telemetry consent (default No), and it logs the user in. Login is offered under `optional`, required under `mandatory`, and skipped under `disabled`. Both answers are saved to the **global user config** (the user layer of the access policy) by an atomic writer with optimistic concurrency. They are never written to the repository's `.sce/config.json`. Login reuses the existing `sce auth login` path. It runs after the answers are saved, so telemetry credential provisioning sees the new consent. On reruns, saved answers suppress the prompts. A new interactive-only `sce setup --reconfigure` flag asks every saved setup answer again, with the saved value as the default. Non-interactive, hooks-only, and context-only setup keep their current behavior: no new prompts, no access-policy writes, no login, and no credential-store access. + +This extends the existing setup prompt seam (`SetupTargetPrompter` → `resolve_setup_dispatch` → `SetupCommand::execute`) and the access-policy work from `auth-telemetry-policy-config` and `remove-telemetry-readiness-marker`. It does not touch the resolver's precedence. It completes the "future interface" that `auth-telemetry-policy-config` recorded: a setup step writes `auth.mode` and `telemetry.enabled` into the global config, and `resolve_access_policy` stays unchanged. It also addresses that plan's open question about existing logged-in users silently losing managed export. + +## Design + +### Problem + +Since `auth-telemetry-policy-config`, managed SCE telemetry is off unless the user hand-edits `telemetry.enabled: true` into `${config_root}/sce/config.json`. `auth.mode` can also only be set by editing JSON. Setup asks about Agent Trace auto-sync ("Requires an SCE account") but never offers login. `mandatory` therefore has no flow that actually produces an authenticated install. The Claude-native telemetry stage tells users to "run 'sce auth login'" even when they are already in an interactive session that could do it. + +### Current implementation findings + +- **CLI parsing.** `cli/src/cli_schema.rs` `Commands::Setup` has these flags: `--opencode|--claude|--pi|--codex|--all` (mutually exclusive), `--non-interactive`, `--hooks`, `--repo` (requires `--hooks`), `--bootstrap-context`, and repeatable `--workflow`. `cli/src/services/parse/command_runtime.rs` maps them into `SetupCliOptions` and calls `convert_setup_command`. +- **`SetupCliOptions` → `SetupRequest`** (`cli/src/services/setup/mod.rs` `resolve_setup_request`). It produces one of three shapes: + - `config_mode: Some(SetupMode::Interactive)`: no target and no `--hooks`. `install_hooks` is forced true. + - `Some(SetupMode::NonInteractive(target))`: a target flag was given. + - `None`: hooks-only (`--hooks`) or `context_only` (`--bootstrap-context`, which must be used alone). + - Interactive mode always runs from the current working directory, because `--repo` requires `--hooks`. +- **Prompt seam.** `trait SetupTargetPrompter` has four methods: `prompt_targets`, `prompt_optional_workflows`, `prompt_agent_trace_auto_sync`, and `prompt_attribution_hooks_enabled`. `InquireSetupTargetPrompter` implements it by delegating to `cli/src/services/setup/prompt.rs`, which uses `inquire` `MultiSelect`/`Confirm` with a Yes default. Cancel maps to `Ok(None)`; `NotTTY` maps to a fixed `bail!`. This is the only prompt seam. The test fake `FakePrompter` lives in `setup/command.rs` tests. +- **`resolve_setup_dispatch(mode, prompter, optional_workflow_defaults, configured_targets, PersistedSetupConfirmations)`.** + - Interactive mode prompts for targets, then workflows. For each of `agent_trace_auto_sync` and `attribution_hooks_enabled`, it reuses the persisted value instead of prompting when one exists. Any `None` answer returns `SetupDispatch::Cancelled`. + - Non-interactive mode returns `Proceed` with `TargetPersistence::Merge` and no behavior values. + - Persisted answers can never be changed through setup today. The only way to change them is to edit JSON. +- **`PersistedSetupConfirmations`** (`Copy`, `Default`) is read by `persisted_setup_confirmations(repository_root)` from the repository-local file only, through `persisted_file_config`. That function returns `None` for a missing or invalid file. +- **`SetupCommand::execute`** (`setup/command.rs`) runs these steps in order: + 1. `resolve_setup_repository`: Git gate, plus a remote preflight through `resolve_agent_trace_storage_runtime_config`. An unreadable global config or an invalid explicit config already fails here. + 2. Dispatch, with all prompts. Cancellation returns "Setup cancelled. No files were changed." + 3. `bootstrap_context_baseline`. + 4. The lifecycle providers Config → LocalDb → AuthDb → AgentTraceDb → [Hooks]. `AuthDbLifecycle::setup` only creates the auth DB parent directory; it never opens `auth.db` or resolves the Keychain key. + 5. `run_setup_for_targets`: asset install, then `persist_integration_targets`. + 6. When Claude is selected, `claude_telemetry_report`. This resolves policy through `config::resolve_auth_runtime_config(repository_root)`, installs only when telemetry is `Enabled`, and always prints `AUTH_PENDING_LINE` after a fresh configure. +- **`persist_integration_targets`.** + - It skips an invalid repository-local file and returns `Ok(())`. + - It bootstraps the file when it is missing. + - It round-trips the file through `serde_json::Value`, which does not preserve key order because the `preserve_order` feature is off. + - It writes with a non-atomic `fs::write`. +- **`cli/src/services/setup/claude_telemetry.rs`.** `write_atomically` writes a sibling temp file, then renames it, preserving the existing file mode or using `0o600` for a new file. This is the existing safe-write utility to reuse. +- **Access policy** (`cli/src/services/config/resolver.rs`). + - `resolve_runtime_config_with` records the per-layer `AccessPolicyLayer` and then calls the pure `resolve_access_policy(user, repository, explicit, degraded)`. + - The global path comes from the private `resolve_default_global_config_path()`. + - `ResolvedAccessPolicy` (`config/types.rs`) exposes `auth_mode: ResolvedValue` with its deciding source, `telemetry: TelemetryPolicyState`, `telemetry_enabled()`, `auth_allowed()`, and `auth_disabled_config_file()`. + - `AuthMode` and its `as_str`/`parse` are `pub(crate)`. + - `schema::parse_file_config(raw, path, ConfigPathSource)` yields `FileConfig.auth_mode` / `telemetry_enabled` as `Option>`, so "key absent" and "explicit value" are already distinguishable. +- **Login** (`cli/src/services/auth_command/mod.rs`). + - `run_login(format)` resolves policy from `current_dir` and runs `ensure_auth_allowed`. It loads stored tokens with `CredentialAccess::Interactive`, which opens or creates `auth.db` and resolves the Keychain key. + - If the stored tokens renew, it provisions (only when telemetry is `Enabled`) and renders the refresh result. Otherwise it runs the WorkOS device flow (`write_login_prompt` prints straight to stdout), saves the tokens, and provisions. + - Provisioning calls `enroll_current_repository_if_unbound()`, which reads `current_dir` again. + - It returns a rendered `String`, so the `TelemetryProvisioningResult` is not visible to callers. + - The text output contains no tokens. +- **Credential storage.** Only `auth.db` is encrypted (`EncryptedTursoDb`). `managed_telemetry::auth_db_present()` is a file-existence check that never touches the Keychain. +- **`mandatory` enforcement today.** The only effect is that an unauthenticated `sce auth whoami` fails with `auth.not_authenticated`. Hooks, auto-sync, and startup never block or log in. Setup is not admitted to managed telemetry startup (`app.rs` returns no span kind for `setup`). +- **Errors** (`cli/src/services/error.rs`). `UserError::{NotAuthenticated, AuthStorageUnavailable, LoginAuthStorageUnavailable, AuthDisabledByConfig(AuthPolicyConfigFile), UnexpectedFailure}` have fixed keys and messages. Setup maps most failures to `UnexpectedFailure` with a source. +- **No readiness marker remains** (`remove-telemetry-readiness-marker` is validated). This plan must not reintroduce one. + +### Interactive prompt sequence + +The existing prompts keep their position and wording. The new prompts come after them, and every prompt is answered before any file is written. + +1. `Select setup targets` (existing `MultiSelect`). +2. `Select optional workflows` (existing). +3. `Automatically sync Agent Traces?` (existing; asked only when no value is persisted, unless `--reconfigure`). +4. `Record SCE involvement in Git commits?` (existing; same rule). +5. **New `Select` prompt, `SCE account mode for this machine`.** It is asked when no global `auth.mode` is persisted, unless `--reconfigure`, and is skipped by the gates below. The cursor starts on `optional` on a first run, or on the persisted value with `--reconfigure`. The rows are, in this order: + - `Optional: use SCE locally and log in when you want SCE cloud features` + - `Mandatory: require an SCE login when setting up` + - `Disabled: local only; no SCE login, cloud sync, or telemetry` +6. **New `Confirm` prompt, telemetry consent.** It is asked only when the selected or persisted mode is not `disabled` and no global `telemetry.enabled` is persisted, unless `--reconfigure`. The default is No on a first run, or the persisted value with `--reconfigure`. Label: + ``` + Share SCE telemetry? + (Sends SCE usage telemetry to SCE servers using your SCE login. If Claude is + selected, also configures Claude Code's native telemetry export. Separate from + Agent Trace sync. Applies to all repositories on this machine.) + ``` +7. **New `Confirm` prompt, login offer.** It is asked only when the prospective mode is `optional` (selected, persisted, or effective) and one of these holds: prompts 5 or 6 were asked in this run, or `auth_db_present()` is false. The default is Yes. Label: + ``` + Log in to SCE now? + (Opens a device login in your browser. An existing login on this machine is + reused. You can log in later with 'sce auth login'.) + ``` + +Gates on prompts 5–7. They are computed from data that is already loaded, with no credential access: + +- **Effective `auth.mode` is `disabled` with a repository or explicit deciding source** (`auth_disabled_config_file()` is `Repository`, `ConfigFlag`, or `ConfigEnv`): prompts 5–7 are skipped. Setup cannot lift that restriction. The report names the deciding file through the existing `auth_disabled_by_config_message` wording. +- **The global config exists but is invalid:** prompts 5 and 6 are skipped, because the answers could not be saved. Prompt 7 follows the normal rule. +- **The effective mode is already `mandatory`** (any layer), **or prompt 5 selected `mandatory`:** prompt 7 is skipped, because login will be required. +- **Prompt 5 selected `disabled`:** prompts 6 and 7 are skipped. The global `telemetry.enabled` value is left untouched, and it stays ineffective because policy reports `auth_disabled`. + +Cancelling at any prompt (Esc or Ctrl-C) returns `SetupDispatch::Cancelled` before any write, so the existing "Setup cancelled. No files were changed." stays true. + +The telemetry prompt never takes its default from: the Claude target, an existing `auth.db`, `agent_trace.auto_sync`, an old telemetry credential, or existing Claude settings. Its only inputs are the persisted global value and the first-run default `false`. + +### Configuration ownership and persistence + +| Choice | Written to | Never written to | Rationale | +|---|---|---|---| +| `auth.mode` | Global user config `${config_root}/sce/config.json` (`resolve_default_global_config_path`) | Repository `.sce/config.json`, explicit `--config` / `SCE_CONFIG_FILE` files | Credentials (`auth.db`, Keychain) are per-user per-machine. The repository file is committed and shared, so writing a restriction there would be team-policy authoring, and older binaries skip the whole file when it holds keys they reject. This matches the `auth-telemetry-policy-config` future interface. | +| `telemetry.enabled` | Global user config | Repository and explicit files | Only the user side can grant consent. A repository `true` grants nothing, so setup must never produce one. | +| Agent Trace auto-sync, attribution | Repository config (unchanged) | n/a | Existing behavior. | + +- **The resolver's precedence is not changed.** The writer changes only the user layer, so the following still hold: + - A repository or explicit `auth.mode: disabled` still wins (`disabled > mandatory > optional`). + - A repository or explicit `telemetry.enabled: false` still restricts telemetry. + - Global `true` in a repository that opted out stays `repository_opt_out`. +- **Setup never lifts a global prohibition silently.** A persisted global `disabled` suppresses prompt 5 on reruns. It changes only through `--reconfigure`, which shows the current value as the default. Any write to global `auth.mode` is reported as `auth.mode: (saved to global SCE config ''; applies to all repositories on this machine)`. +- **The writer records explicit choices only.** Declining telemetry writes `telemetry.enabled: false` and accepting writes `true`. Choosing a mode writes `auth.mode`, including an explicit `optional`. A key that is absent stays absent until the user answers. + - **States distinguished at read time** (`GlobalAccessPreferences`): global file missing, key absent (meaning "not asked yet"), explicit `false`, explicit `true`, and global file invalid (degraded: no prompt, no write). + - **States read from the resolved policy:** repository restriction (`RepositoryOptOut`, repository-sourced `AuthDisabled`), auth-disabled effective state, and degraded config (`InvalidConfig`). + - The report shows the effective state with its reason, never the saved value alone. +- **Safe write algorithm.** `persist_global_access_preferences` reuses the setup safe-write helper: + 1. Read the file's bytes. A missing file starts as `{"$schema": }`. An unreadable file is an error. + 2. Parse with `parse_file_config(.., DefaultDiscoveredGlobal)`. On failure, refuse to write and return a typed `InvalidGlobalConfig` error. The invalid file is never overwritten. + 3. Mutate only `auth.mode` and/or `telemetry.enabled` in the `serde_json::Value`, preserving every other key and nested key. + 4. Serialize as pretty JSON plus a trailing newline, then validate the new bytes with `parse_file_config` before writing. + 5. If the bytes are unchanged, return `Unchanged` and do not write (idempotence). + 6. Re-read the file. If its bytes differ from step 1, return a `ConcurrentModification` error and do not write. + 7. Create the parent directory, then call `write_atomically`: a sibling temp file, the existing mode or `0o600`, then rename. + - **Guarantees and limits:** the rename is atomic on one filesystem, and the step 6 check is best-effort optimistic concurrency, not a lock. + - Schema unknown keys never reach step 3, because the schema rejects them at step 2. + - Key order changes on the first rewrite, as with the existing repository writer. +- **Failure handling.** An invalid, unreadable, read-only, or concurrently modified global file fails setup before any repository write, with a fixed message naming the file and suggesting `sce config validate` and a rerun. Consent is never reported when the write did not succeed. + +### Decision matrix + +The "Effective" column is computed by re-resolving `resolve_auth_runtime_config(repository_root)` after the global write. "Login" is decided from the effective mode, not from the prompt answer. + +| Selected mode | Telemetry answer | Global write | Effective (no other layers) | Login behavior | Telemetry provisioning | +|---|---|---|---|---|---| +| disabled | not asked | `auth.mode: disabled` (telemetry untouched) | auth disabled, telemetry `auth_disabled` | Never. No `auth.db` or Keychain access. If `auth.db` exists, one line hints `sce auth logout`. | none | +| disabled | (true not offerable) | n/a | n/a | n/a | the conflict cannot be entered, because prompt 6 is skipped | +| optional | false | `optional`, `false` | telemetry `user_opt_out` | Offered. Declining or failing is reported, and setup succeeds. | `disabled` | +| optional | true | `optional`, `true` | telemetry enabled | Offered. On success, provisioning runs inside login. | Issued only after successful login. If login is declined, consent stays saved and a later explicit `sce auth login` provisions. | +| mandatory | false | `mandatory`, `false` | telemetry `user_opt_out` | Required: renew stored credentials, otherwise the device flow. Failure is a nonzero setup exit. | `disabled` | +| mandatory | true | `mandatory`, `true` | telemetry enabled | Required. | Issued after successful login. | + +Rows with other layers present. In each, the precedence comes from the resolver and is not recomputed by setup. + +| Other layers | Setup behavior | +|---|---| +| Repository or explicit `auth.mode: disabled` | Prompts 5–7 skipped, no global write for access keys, no login. Report: auth disabled by ``. | +| Repository `auth.mode: mandatory`, user answers `optional` | Global `optional` is written. Effective `mandatory` (repository), so login is required. | +| Repository `telemetry.enabled: false`, user answers Yes | Global `true` is written. Effective `repository_opt_out`. Login provisioning reports `disabled`. Report: `telemetry: disabled (reason: repository_opt_out)`. | +| Repository `telemetry.enabled: true`, user answers No | Global `false` is written. Effective `user_opt_out`. The repository cannot grant. | +| Global config invalid | Prompts 5–6 skipped. Effective telemetry `invalid_config`. Login follows the effective mode. | +| `SCE_CONFIG_FILE` with `telemetry.enabled: false` | Global consent is written. Effective `user_opt_out` (explicit). Reported as such. | + +### Non-interactive and partial setup contract + +| Invocation | New prompts | Access-key writes | Login / credential store | Unchanged behavior | +|---|---|---|---|---| +| `sce setup` (interactive) | Yes (per the gates) | Global only | Per the matrix | Targets, workflows, behavior prompts, hooks | +| `sce setup --reconfigure` | All persisted answers asked again, with persisted defaults | Global only | Per the matrix | Same as interactive | +| `sce setup --{opencode,claude,pi,codex,all} --non-interactive` (also without `--non-interactive`, which is the same mode) | None | None | None. Never prompts, never runs the device flow, never opens `auth.db` | Asset install, target merge, Claude telemetry gated by the existing effective policy | +| `sce setup --hooks [--repo]` | None | None | None | Hook install | +| `sce setup --bootstrap-context` | None | None | None | Context baseline only | + +No new non-interactive consent or mode flags are added. Unattended consent must be granted by deliberately editing the global config, which already works. The new `--reconfigure` is rejected with a fixed validation message when combined with a target flag, `--non-interactive`, `--hooks`, `--repo`, or `--bootstrap-context`. + +### Setup lifecycle order + +1. Resolve the repository and run the preflights (existing). +2. Read persisted state: + - repository confirmations, targets, and workflows (existing); + - global access preferences (new, file read only); + - the effective policy via `resolve_auth_runtime_config(repository_root)` (new, config only); + - `auth_db_present()` (file existence only). +3. Dispatch: all prompts. Cancellation means no writes. +4. **Persist the global access preferences.** This is the first write. Failure aborts with nothing changed in the repository. +5. Context baseline (existing). +6. Lifecycle providers (existing; no credential access). +7. Target assets and repository config (existing). +8. Re-resolve the effective policy, then run the **login step**: + - skip when not applicable; + - under optional, run login if the user accepted; + - under mandatory, run login. + Login reads the policy written in step 4, so provisioning sees the new consent. +9. Claude-native telemetry stage (existing gate). The "not ready for this repository" line is shown unless the repository has a valid, unexpired credential bound to the credential's identity (PR #339 review fix; this replaces the earlier `TelemetryProvisioningResult::Issued` gate). Non-interactive and target-flag runs skip the authorization check entirely and report `Claude telemetry: configured; repository authorization was not checked during non-interactive setup.`, so they never open `auth.db` or the OS credential store (PR #339 review fix). +10. Report: an `SCE access` section with the saved values (or "unchanged"), the effective auth mode and telemetry state with reason from step 8's resolution, and the login outcome from the actual login result. + +Why this order: + +- Prompts come before writes, which preserves the cancellation contract. +- The global write comes before repository writes, so a failed consent write leaves nothing half-done. +- Login comes after persistence, which provisioning requires. +- Login comes after asset installation, so a slow or failed device flow does not leave the repository uninstalled. +- The Claude stage comes after login, so its report reflects the real provisioning. + +Atomicity and recovery: + +- **Atomic:** the global config write (temp file plus rename). +- **Not transactional across steps:** there is no rollback. +- **Rerun-safe:** every step is resumable on rerun, because each step is idempotent. Saved answers suppress prompts, asset install is idempotent, and login renews or reuses credentials. + +| Failure | Outcome | +|---|---| +| Cancel at any prompt | `Setup cancelled. No files were changed.` (exit 0, existing) | +| Optional login declined | Success. Line: `SCE login: skipped; run 'sce auth login' to log in.` | +| Optional login fails (WorkOS unavailable, device flow expired or denied, Keychain unavailable) | Success. Line: `SCE login: failed: `, followed by the retry hint. | +| Mandatory login fails | Nonzero exit with new `UserError::SetupLoginRequired` (key `auth.setup_login_required`, runtime class). Fixed message: local setup completed; run `sce auth login`, then rerun `sce setup`. The underlying login error is kept as the source. | +| Global config write fails | Nonzero exit before any repository write, with a fixed message naming the file. | +| Repository config write fails | Existing behavior ("Setup assets were installed … but failed to update repo-local config"). The global answers stay saved, and a rerun does not ask them again. | +| Claude settings conflict | Existing skip lines (unchanged). | +| Already authenticated | Optional: offered only when answers were asked this run or `auth.db` is absent. Mandatory: renew without the device flow. | +| Stored credentials expired or unrenewable | `run_login` already falls back to the device flow. | + +## Acceptance criteria + +- [x] AC1: On a first interactive run with no global access keys, setup asks the existing four prompts unchanged, then the auth-mode `Select` (cursor on `optional`), telemetry consent (default No), and, under `optional`, the login offer (default Yes). Cancelling any prompt writes no file and prints `Setup cancelled. No files were changed.` + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup::` dispatch tests using a recording `FakePrompter` that assert the call order, the defaults passed, and the cancellation result at each new prompt. +- [x] AC2: Setup writes `auth.mode` and `telemetry.enabled` only to the global config. The repository `.sce/config.json` never gains `auth` or `telemetry` keys from setup. Unrelated global keys are preserved. A second identical run does not rewrite the file. Existing file mode is preserved, and a new file is `0o600`. + - Validate: table-driven tests for `persist_global_access_preferences` (missing file, empty object, unrelated keys, explicit values, idempotent rerun, mode preservation) and an execute-level test asserting the bytes of the repository config. +- [x] AC3: An invalid, unreadable, or concurrently modified global config is never overwritten. An invalid one causes the access prompts to be skipped. A write failure aborts setup before any repository write and never reports consent. + - Validate: writer tests for invalid JSON, schema-invalid file, read-only directory, and a changed-bytes race (injected re-read), plus a dispatch test for the invalid-global gate. +- [x] AC4: A repository or explicit `auth.mode: disabled` skips all access prompts and login. A repository `telemetry.enabled: false` keeps telemetry disabled after the user consents. A repository `telemetry.enabled: true` never enables telemetry without global consent. A repository `mandatory` forces the login to be required. + - Validate: table-driven tests for the dispatch gate and the login-action decision built from `resolve_auth_runtime_config_with` over temp global, repository, and explicit files. +- [x] AC5: The login step is skipped under effective `disabled` without calling any credential-store or login closure. Under `optional` it runs only after the user accepts, and declining or failing leaves setup successful. Under `mandatory` it always runs, and failure exits nonzero with `auth.setup_login_required`. Telemetry is provisioned only when the re-resolved policy is `Enabled`. + - Validate: `setup_login_action` table test and a generic execute-step test with login closures that panic when called. Use the existing `auth_command` provisioning tests to cover `Disabled` versus `Issued`. +- [x] AC6: On rerun, persisted global and repository answers suppress their prompts. `sce setup --reconfigure` asks all of them again, with the persisted values as defaults. `--reconfigure` combined with a target flag, `--non-interactive`, `--hooks`, `--repo`, or `--bootstrap-context` fails validation. + - Validate: `resolve_setup_request` and `resolve_setup_dispatch` tests; a `cli_schema`/parse test for the flag. +- [x] AC7: Non-interactive target runs, `--hooks`, and `--bootstrap-context` produce byte-identical output to today. They ask no new prompts, write no access keys, and never invoke login or credential storage. + - Validate: the existing setup command tests stay green, plus a dispatch test asserting `Proceed` carries no access values and `SetupLoginIntent::NotOffered` for every `SetupMode::NonInteractive` target. +- [x] AC8: The setup report states the effective auth mode, the effective telemetry state with its reason (from re-resolution, not from the saved value), and the actual login outcome, and contains no token or credential value. `sce auth login` output stays byte-identical. + - Validate: exact-output render tests for the `SCE access` section; the existing `auth_command` render tests stay green; a test asserting the login report text contains no `access_token` / `refresh_token` values. +- [x] AC9: The Claude-native telemetry report omits the "not ready" line only when the repository is locally authorized (valid credential bound to this repository's identity), whether or not this run issued a credential. The check runs only during interactive setup; non-interactive and target-flag runs report authorization as not checked and never access authentication storage. (Revised by the PR #339 review fixes.) + - Validate: `render_claude_telemetry_section` tests in `cli/src/services/setup/command.rs`, `repository_readiness_lookup_fails_closed_unless_repository_is_authorized`, `repository_readiness_follows_binding_rather_than_credential_issuance`. + +### Full validation + +- `nix flake check` +- `nix run .#pkl-check-generated` (only if schema or Pkl inputs change; none are planned) + +### Context sync + +- `context/cli/access-policy.md`: the "Setup does not enforce it yet" status; a setup enforcement bullet; setup as the user-layer writer. +- `context/cli/config-precedence-contract.md`: setup-written global access values, and `--reconfigure` on the setup-written behavior values. +- `context/sce/setup-repo-local-config-bootstrap.md`: prompt sequence, rerun suppression, `--reconfigure`. +- `context/cli/cli-command-surface.md`: `sce setup --reconfigure`, the login step in setup, `auth.setup_login_required`. +- `context/sce/telemetry-credential.md`: setup consent prompt, provisioning through setup login, the Claude pending line. +- `context/sce/cli-error-code-taxonomy.md`: the new error key. +- `context/glossary.md`: "setup access preferences", if introduced. +- `context/context-map.md` +- A decision record for "setup writes access-policy answers to the user layer only". + +## Task context synchronization lifecycle + +Persist this field in every plan; this is durable plan state, not chat state: + +- **Task context synchronization:** every task carries `pending | synced | blocked`. + A completed task must be `synced` before another task can start or the plan can + finish. +- For `blocked`, record **Blocker**, **Required action**, and **Retry condition** + beside the status. Never infer `synced` from conversation history; write every + lifecycle transition to the plan file. + +## Constraints and non-goals + +- **In scope:** + - `cli/src/cli_schema.rs` and `cli/src/services/parse/command_runtime.rs` (the `--reconfigure` flag) + - `cli/src/services/setup/{mod,prompt,command,claude_telemetry}.rs` + - a new `cli/src/services/setup/access_preferences.rs` + - `cli/src/services/config/{resolver,mod}.rs` (visibility of `resolve_default_global_config_path` / `AuthMode` re-export only) + - `cli/src/services/auth_command/mod.rs` (login report refactor) + - `cli/src/services/error.rs` (one `UserError` variant) + - the context files listed under Context sync +- **Out of scope:** + - `auth.db` schema or migrations + - restoring `telemetry-ready.json` or any marker + - Keychain ACLs and code signing + - Linux Secret Service changes + - Claude-native settings cleanup or reconciliation + - resolver precedence changes or rewrites + - new credential caches + - new agent integrations + - making the repository-config writer `persist_integration_targets` atomic + - non-interactive consent or mode flags + - a general `sce config set` command +- **Constraints:** + - Policy is resolved only through `resolve_auth_runtime_config` / `resolve_access_policy`, with no duplicate precedence logic in setup. + - No `dyn`, boxed futures, or a new prompt framework. Static generics and closures are used for test seams, matching `run_login_with`. + - Fixed, deterministic user-facing strings. + - No secrets in output. + - `sce auth login` and non-interactive setup outputs stay byte-identical. + - No new dependencies. `inquire::Select` is already in the `inquire` crate. + - Rust 2021, `anyhow` with context, rustfmt, clippy clean. + - No code comments (user preference). +- **Non-goal:** a general preferences framework, per-repository auth-mode authoring by setup, or changing what `mandatory` means for hooks and background work. Hooks never log in or block. + +## Assumptions + +- `auth.mode` set through setup is a per-user, per-machine preference stored in the global config. The prompt title and report say "this machine" or "all repositories". This rests on the `auth-telemetry-policy-config` future interface and on the per-user `auth.db`. +- Answering "No" to telemetry writes an explicit global `false`. This disables managed telemetry in every repository on the machine, consistent with consent being user-level. `--reconfigure` reverses it. +- The new prompts follow the existing four rather than reordering them, so the "Automatically sync Agent Traces?" prompt still comes before the auth-mode prompt. The existing resolver warning covers auto-sync being enabled together with auth `disabled`. +- The login offer defaults to Yes. Pressing Enter on a prompt labelled "Log in to SCE now?" counts as an explicit user action for Keychain access. +- Login inside setup uses the setup repository root as its working directory. Interactive setup always runs from the current directory, and the resolver discovers the same Git root from any subdirectory. +- A failed mandatory login exits nonzero without rolling back the installed assets or the saved answers. Every step is idempotent on rerun. + +## Task stack + +- [x] T01: `Add an atomic global-config writer for setup access preferences` (status:done) + - Task ID: T01 + - Scope: In: + - New `cli/src/services/setup/access_preferences.rs` with `GlobalAccessPreferences` (`Missing | Valid { auth_mode: Option, telemetry_enabled: Option } | Invalid`), `read_global_access_preferences(path)`, and `persist_global_access_preferences(path, auth_mode: Option, telemetry_enabled: Option) -> Result`. Typed errors: `InvalidGlobalConfig`, `ConcurrentModification`, I/O with context. + - Move `write_atomically` and `apply_mode` from `claude_telemetry.rs` to setup-module scope (`pub(super)`), unchanged in behavior, with `claude_telemetry.rs` using the moved helper. + - Make `resolver::resolve_default_global_config_path` `pub(crate)` and re-export `AuthMode` through `config`. + - Out: prompts, dispatch, `execute` wiring, login. + - Dependencies: none + - Done when: + - The writer follows the safe-write algorithm in Design: it preserves unrelated keys, refuses invalid files without touching them, validates the output with `parse_file_config`, skips the write for unchanged bytes, detects changed bytes before the rename, and preserves the file mode (`0o600` for a new file). + - Claude telemetry install tests are unchanged and green. + - Any temporary `#[allow(dead_code)]` on the new items is listed in the completion record for T05 to remove. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml access_preferences`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_telemetry` + - Completed: 2026-10-21 + - Files changed: + - `cli/src/services/setup/access_preferences.rs` (new) + - `cli/src/services/setup/atomic_write.rs` (new) + - `cli/src/services/setup/claude_telemetry.rs` + - `cli/src/services/setup/mod.rs` + - `cli/src/services/config/resolver.rs` + - Result: + - Added `GlobalAccessPreferences { Missing, Valid { auth_mode, telemetry_enabled }, Invalid }`, `read_global_access_preferences`, `persist_global_access_preferences -> Result`, and a private `persist_global_access_preferences_with` that injects the pre-rename re-read for tests. + - Moved `write_atomically` and `apply_mode` verbatim into `setup/atomic_write.rs` (`pub(super)`). `claude_telemetry.rs` now imports `write_atomically` from there. + - `resolve_default_global_config_path` is now `pub(crate)`. + - `AuthMode` was already reachable as `config::AuthMode` through `pub use types::*`, so no new re-export was added. + - Deviations and assumptions: + - "Unchanged" compares parsed JSON values rather than raw bytes. A file whose values already match is not rewritten, even if its formatting differs. + - Calling the writer with no answers returns `Unchanged` and never creates a file. + - Temporary dead-code allowances for T05 to remove: `#[allow(dead_code)]` on `pub(crate) mod access_preferences;` in `cli/src/services/setup/mod.rs`. + - Verify outcomes: + - `access_preferences`: passed (8 tests). Coverage: missing file, empty object, unrelated keys, explicit values, idempotent rerun, no-answer no-op, mode preservation (0o644) and new-file 0o600, invalid JSON / schema-invalid / unknown key / non-UTF-8 left untouched, injected concurrent modification, read-only directory I/O error, reader missing vs. absent keys. + - `claude_telemetry`: passed (14 tests, unchanged). + - Additional check: `clippy --all-targets -- --deny warnings` is clean. + - Context impact: internal (new crate-private setup helper; no user-visible behavior, CLI surface, or contract change until T04/T05 wire it in) + - Context synchronization: synced + +- [x] T02: `Return a typed login report from auth login with an explicit working directory` (status:done) + - Task ID: T02 + - Scope: In: + - In `cli/src/services/auth_command/mod.rs`, add `pub(crate) struct LoginReport { rendered: String, telemetry: TelemetryProvisioningResult }` and `pub(crate) async fn run_login_in(working_dir: &Path, format: AuthFormat) -> Result`. + - `run_login_in` resolves policy from `working_dir` and passes `working_dir` to repository enrollment, replacing the `current_dir` reads in `enroll_current_repository_if_unbound`. + - `run_login(format)` becomes `current_dir` + `run_login_in(..).map(|r| r.rendered)`. + - `run_login_with`, `run_login_with_stored_credentials`, `run_text_login`, and `run_login_json` return `LoginReport`. + - Out: setup wiring, any change to WorkOS, renewal, credential persistence, or provisioning logic. + - Dependencies: none + - Done when: `sce auth login` text and JSON output are byte-identical, existing auth_command tests pass unchanged, and new tests assert that `LoginReport.telemetry` is `Disabled` when policy telemetry is off and `Issued` when the provisioning closure issues, and that enrollment receives the supplied working directory. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml auth_command` + - Completed: 2026-10-21 + - Files changed: + - `cli/src/services/auth_command/mod.rs` + - Result: + - Added `pub(crate) struct LoginReport { rendered, telemetry }` with `pub(crate)` fields and `pub(crate) async fn run_login_in(working_dir, format) -> Result`. + - `run_login` now reads `current_dir` (same error context as before) and returns `run_login_in(..).rendered`; render functions are untouched, so `sce auth login` text/JSON output is byte-identical. + - `run_login_with`, `run_login_with_stored_credentials`, `run_text_login`, and `run_login_json` return `LoginReport`; the stored-credential refresh path carries its provisioning result into the report. + - `provision_telemetry_credential` takes the working directory; `enroll_current_repository_if_unbound` was replaced by `enroll_repository_if_unbound(working_dir)` over a generic seam `enroll_repository_if_unbound_with(working_dir, repository_id_for, bind)`. + - Policy resolution goes through new `resolve_auth_config_in(working_dir)`; `resolve_current_auth_config` delegates to it. + - Deviations and assumptions: + - Existing tests needed mechanical type adaptation only (`.rendered` / `device_login_report()` fixture); their assertions are unchanged. + - Verify outcomes: + - `auth_command`: passed (21 tests, including new `login_report_carries_issued_telemetry_when_policy_enables_it` and `repository_enrollment_uses_the_supplied_working_directory`; `LoginReport.telemetry == Disabled` asserted in `login_skips_provisioning_unless_telemetry_is_enabled`). + - Additional check: `clippy --all-targets -- --deny warnings` is clean. + - Context impact: internal (crate-private login API seam for setup; no user-visible CLI behavior or output change until T06 wires it in) + - Context synchronization: synced + +- [x] T03: `Add auth-mode, telemetry-consent, and login-offer prompts to the setup prompt seam` (status:done) + - Task ID: T03 + - Scope: In: + - In `cli/src/services/setup/prompt.rs`, add `prompt_auth_mode(default: AuthMode)` using `inquire::Select` with the three fixed rows and the cursor on the default, `prompt_telemetry_consent(default: bool)`, and `prompt_login()` (default Yes) with the fixed labels from Design. + - Give `prompt_agent_trace_auto_sync` and `prompt_attribution_hooks_enabled` a `default: bool` parameter. Current callers pass `true`. + - Extend `trait SetupTargetPrompter` and `InquireSetupTargetPrompter`. + - Cancel and `NotTTY` handling match the existing prompts. + - Update `FakePrompter` in `setup/command.rs` tests to compile. + - Out: dispatch logic, persistence, login. + - Dependencies: T01 (`AuthMode` re-export) + - Done when: the new prompt functions exist with exact label constants and defaults, the auth-mode row mapping is covered by a pure test (row index ↔ `AuthMode`, default cursor), and existing prompt behavior and wording are unchanged. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup::` + - Completed: 2026-10-21 + - Files changed: + - `cli/src/services/setup/prompt.rs` + - `cli/src/services/setup/mod.rs` + - `cli/src/services/setup/command.rs` + - Result: + - `prompt.rs` adds `prompt_auth_mode(default: AuthMode)` (`inquire::Select` over `AUTH_MODE_PROMPT_ROWS` = Optional, Mandatory, Disabled, with `with_starting_cursor(auth_mode_prompt_default_index(default))` and title `prompt_label("SCE account mode for this machine")`), `prompt_telemetry_consent(default: bool)`, and `prompt_login()` (`LOGIN_PROMPT_DEFAULT = true`). Every row label and confirm label is a fixed constant matching Design. + - `prompt_agent_trace_auto_sync` and `prompt_attribution_hooks_enabled` take `default: bool`. Their wording is unchanged, and `resolve_setup_dispatch` passes `true`. + - Cancel/Interrupt → `Ok(None)` and `NotTTY` → the existing fixed bail now go through one shared `interactive_prompt_result` helper, used by both `Confirm` and `Select`. + - `SetupTargetPrompter` and `InquireSetupTargetPrompter` gain `prompt_auth_mode`, `prompt_telemetry_consent`, and `prompt_login`. The test `FakePrompter` in `setup/command.rs` implements them. + - Deviations and assumptions: + - The new trait methods and prompt functions have no callers until T04, so they carry temporary dead-code allowances. + - Temporary dead-code allowances for T04 to remove when it wires dispatch: `#[allow(dead_code)]` on the trait methods `prompt_auth_mode`, `prompt_telemetry_consent`, and `prompt_login` in `cli/src/services/setup/mod.rs`, and on `auth_mode_prompt_title`, `prompt_auth_mode`, `prompt_telemetry_consent`, and `prompt_login` in `cli/src/services/setup/prompt.rs`. + - Verify outcomes: + - `setup::`: passed (71 tests). This includes the new `prompt::tests` (row index ↔ `AuthMode` order and labels, the default cursor for every mode, fixed telemetry/login/title labels, and Cancel/Interrupt/NotTTY mapping). + - Additional check: `clippy --all-targets -- --deny warnings` is clean. + - Context impact: internal (crate-private prompt seam additions; no user-visible behavior change until T04 wires dispatch) + - Context synchronization: synced + +- [x] T04: `Resolve access-policy choices and login intent in setup dispatch` (status:done) + - Task ID: T04 + - Scope: In: + - In `cli/src/services/setup/mod.rs`, extend `PersistedSetupConfirmations` with `auth_mode: Option`, `telemetry_enabled: Option`, and `global_config_invalid: bool`. + - Add `SetupAccessGate` (computed from the current `ResolvedAccessPolicy` and `auth_db_present`): `auth_locked_by: Option` for repository or explicit disabled, `effective_mandatory: bool`, `auth_db_present: bool`. + - Add `enum SetupLoginIntent { NotOffered, Declined, Requested }`. + - Add `auth_mode: Option`, `telemetry_enabled: Option`, and `login_intent: SetupLoginIntent` to `SetupDispatch::Proceed`. + - `resolve_setup_dispatch` takes the gate and applies the prompt sequence and gates from Design. + - Non-interactive returns `None`, `None`, `NotOffered`. + - In `setup/command.rs`, build the gate from `config::resolve_auth_runtime_config(&repository_root)`, `read_global_access_preferences`, and `managed_telemetry::auth_db_present()`, then pass it in. The new `Proceed` fields are carried but not yet persisted. + - Out: writing the global config, login execution, `--reconfigure`. + - Dependencies: T01, T03 + - Done when: table-driven dispatch tests with a recording `FakePrompter` cover: + - a first run, which asks all prompts in order with the right defaults; + - persisted global values, which suppress prompts 5 and 6; + - selected `disabled`, which skips 6 and 7; + - selected or effective `mandatory`, which skips 7; + - repository or explicit `disabled`, which skips 5–7; + - an invalid global config, which skips 5 and 6; + - the `auth_db_present` and prompts-asked rules for prompt 7; + - cancellation at prompts 5, 6, and 7, which returns `Cancelled`; + - every non-interactive target, which prompts nothing and returns `NotOffered`; + - a telemetry default of `false` whatever the Claude target selection or `auth_db_present` value. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup::` + - Completed: 2026-10-21 + - Files changed: + - `cli/src/services/setup/mod.rs` + - `cli/src/services/setup/command.rs` + - `cli/src/services/setup/prompt.rs` + - Result: + - `PersistedSetupConfirmations` gains `auth_mode`, `telemetry_enabled`, and `global_config_invalid`, filled from `GlobalAccessPreferences` by `with_global_access_preferences`. The repository reader leaves them at their defaults. + - Added `SetupAccessGate { auth_locked_by, effective_mandatory, auth_db_present }` with `from_policy(&ResolvedAccessPolicy, auth_db_present)`. `auth_locked_by` keeps only `Repository`, `ConfigFlag`, and `ConfigEnv` sources of an effective `disabled`. + - Added `SetupLoginIntent { NotOffered, Declined, Requested }`. `SetupDispatch::Proceed` carries `auth_mode`, `telemetry_enabled`, and `login_intent`. + - `resolve_setup_dispatch` takes the gate. A private `resolve_setup_access_choices` applies prompts 5–7 after the existing four, using the Design gates. Cancelling returns `Cancelled`. Non-interactive dispatch returns `None`, `None`, `NotOffered`. + - `SetupCommand::execute` builds the gate and the global preferences only for `SetupMode::Interactive`, via `resolve_auth_runtime_config`, `resolve_default_global_config_path` + `read_global_access_preferences`, and `managed_telemetry::auth_db_present()`. Non-interactive runs use a default gate and read nothing new. The new `Proceed` fields are not yet persisted. + - Removed T03's temporary `#[allow(dead_code)]` allowances from the trait methods in `mod.rs` and the prompt functions in `prompt.rs`. + - Deviations and assumptions: + - `Proceed` carries only values answered in this run. A prompt suppressed by a persisted value yields `None`, so T05 writes only explicit new answers. + - The prospective mode for the prompt 6/7 gates is chosen in this order: the selected answer, then the persisted global value, then the effective mode (`mandatory` when `effective_mandatory`, otherwise `optional`). + - `effective_mandatory` is computed before the global write. T07 must account for it when `--reconfigure` changes a global `mandatory`. + - T01's module-level `#[allow(dead_code)]` on `access_preferences` stays for T05, because the writer is still unused. + - Verify outcomes: + - `setup::`: passed (78 tests). These include the new `setup::tests` dispatch tests with a recording prompter: + - first-run order and defaults + - mode and telemetry gates (persisted, selected and persisted `disabled`, repository and explicit lock, invalid global) + - login gates (`auth_db_present`, prompts asked this run, selected and effective `mandatory`) + - cancellation at prompts 5, 6, and 7 + - every non-interactive target returning `NotOffered` + - a telemetry default of `false` + - the `SetupAccessGate::from_policy` lock sources + - Additional check: `clippy --all-targets -- --deny warnings` is clean. + - Context impact: internal, interim. Interactive setup now asks prompts 5–7, but their answers are not persisted or acted on until T05/T06. The report output is unchanged, and non-interactive, hooks-only, and context-only behavior is unchanged. Durable context for the prompt sequence belongs with T05–T07 per the plan's Context sync list. + - Context synchronization: synced + +- [x] T05: `Persist global access preferences in setup and report the effective policy` (status:done) + - Task ID: T05 + - Scope: In: + - In `SetupCommand::execute`, call `persist_global_access_preferences` right after dispatch and before `bootstrap_context_baseline`, only when `Proceed` carries an access value. + - A write failure returns a `CliError` with a fixed message naming the global file, the `sce config validate` hint, and "no repository files were changed". + - After the target install, re-resolve `resolve_auth_runtime_config(&repository_root)` and render a fixed `SCE access` section: + - saved or unchanged values with the global path; + - `auth.mode: (source: …)`; + - `telemetry: enabled` or `telemetry: disabled (reason: )`; + - the `sce auth logout` hint under effective `disabled` when `auth_db_present()`; + - the deciding-file line when auth is locked by the repository or an explicit file. + - The section appears only for interactive runs. + - Remove T01's temporary dead-code allowances. + - Out: login execution, `--reconfigure`. + - Dependencies: T01, T04 + - Done when: + - Execute-level tests with temp global and repository files (injected global path, `resolve_auth_runtime_config_with`) prove the following: + - answers land only in the global file; + - the repository config gains no `auth`/`telemetry` keys; + - a rerun with identical answers leaves the global bytes unchanged; + - a read-only or invalid global file aborts before `context/` or `.sce/` are created; + - a repository `telemetry.enabled: false` with global consent reports `disabled (reason: repository_opt_out)`. + - Exact-output tests cover the `SCE access` section. + - Non-interactive output is byte-identical. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup::` + - Completed: 2026-10-21 + - Files changed: + - `cli/src/services/setup/command.rs` + - `cli/src/services/setup/mod.rs` + - Result: + - `SetupCommand::execute` now resolves dispatch through `prepare_dispatch`. For interactive runs it calls `prepare_interactive_setup`, which resolves the policy, reads the global preferences, runs dispatch, and then calls `persist_setup_access_preferences`. All of this happens before `bootstrap_context_baseline`, so the global write is setup's first write. + - The policy resolver, global path, and `auth_db_present` are injected. In production these are `resolve_auth_runtime_config`, `resolve_default_global_config_path`, and `managed_telemetry::auth_db_present()`. Non-interactive dispatch is unchanged and reads nothing new. + - A writer failure returns a runtime `CliError` with a fixed three-line message: `Failed to save SCE access preferences to the global SCE config ''.`, the writer error, then `No repository files were changed. Run 'sce config validate' to check the file, then rerun 'sce setup'.` + - After the target install, `setup_access_report` re-resolves the policy and `render_setup_access_section` adds the `SCE access:` section, for interactive runs only. It shows: + - the saved values with the global path and the "applies to all repositories on this machine" scope, or `saved access preferences: unchanged (global SCE config '')` + - `effective auth.mode: (source: …, config_source: …)`, using the `sce config show` source vocabulary + - `effective telemetry: enabled` or `effective telemetry: disabled (reason: )` + - the first line of the `auth_disabled_by_config` message when a repository or explicit file locks auth + - the `sce auth logout` hint under effective `disabled` when `auth.db` exists + - Removed `interactive_access_inputs` and T01's `#[allow(dead_code)]` on `access_preferences`. + - Deviations and assumptions: + - The effective lines are labelled `effective auth.mode` and `effective telemetry`, so they cannot be confused with the saved `auth.mode` / `telemetry.enabled` lines. + - A global config that is already invalid at read time does not abort setup. Per the Design gate, prompts 5 and 6 are skipped and no write is attempted. Setup aborts only when the write itself fails (an unwritable directory, a file that became invalid, or a concurrent modification). The writer-level invalid-file refusal is covered by `setup_access_write_refuses_an_invalid_global_config_with_a_fixed_message`. + - The `SCE access` section sits between the target-install section and the Claude telemetry stage. T06 inserts login after the re-resolution and adds the login outcome. + - The write-failure error is a plain runtime `CliError` (`SCE-ERR-RUNTIME`), not a new `UserError` variant. + - Verify outcomes: + - `setup::`: passed (85 tests). The new `command::tests` cover: + - answers land only in the global file, unrelated global keys are preserved, and the repository config gets no `auth` or `telemetry` keys + - a rerun, and identical answers, leave the global bytes unchanged + - an invalid global file skips the access writes and stays untouched + - a read-only global directory aborts before `context/` or `.sce/` exists + - an invalid global file is refused with the fixed message + - repository opt-out combined with global consent reports `disabled (reason: repository_opt_out)` + - exact-output `SCE access` sections (saved, unchanged, logout hint, repository lock) + - Existing non-interactive and Claude telemetry setup tests are unchanged and green. + - Additional check: `clippy --all-targets -- --deny warnings` is clean. + - Context impact: user-visible. Interactive `sce setup` now writes `auth.mode` / `telemetry.enabled` to the global config before any repository write, fails with a fixed message when that write fails, and prints a new `SCE access` section. Affected areas: setup lifecycle and prompt docs (`context/sce/setup-repo-local-config-bootstrap.md`), access policy (`context/cli/access-policy.md`), and config precedence (`context/cli/config-precedence-contract.md`). + - Context synchronization: synced + +- [x] T06: `Run optional or mandatory login from interactive setup through auth login` (status:done) + - Task ID: T06 + - Scope: In: + - In `setup/command.rs`, add a pure `setup_login_action(policy: &ResolvedAccessPolicy, intent: SetupLoginIntent) -> SetupLoginAction { Skip(SetupLoginSkip), Run { required: bool } }`. + - Add a generic step `run_setup_login_step(action, login: L) -> Result`. In production it calls `auth_command::run_login_in(&repository_root, AuthFormat::Text)`. + - Wire the step after the target install and re-resolution, and before the Claude telemetry stage. + - Add `UserError::SetupLoginRequired` (key `auth.setup_login_required`, runtime class, fixed message) in `cli/src/services/error.rs`, keeping the login error as the source. + - Render login status lines for skipped, declined, failed (fixed `UserError` message only), and the authenticated `LoginReport.rendered`. + - Pass `LoginReport.telemetry == Issued` into `render_claude_telemetry_section` to drop `AUTH_PENDING_LINE`. + - Out: changes to login internals, hooks, non-interactive modes. + - Dependencies: T02, T05 + - Done when: table tests cover the following: + - `setup_login_action` covers every pairing of effective mode with intent; + - step tests with closures that panic when called prove disabled, declined, and not-offered never invoke login; + - optional failure is a successful setup with the failure line; + - mandatory failure returns `auth.setup_login_required`; + - mandatory success and optional acceptance include the login text; + - the Claude report omits the pending line only when `Issued`; + - the setup output contains no token values. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup::`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml error` + - Completed: 2026-10-21 + - Files changed: + - `cli/src/services/setup/command.rs` + - `cli/src/services/error.rs` + - Result: + - Added `SetupLoginSkip { AuthDisabled, NotOffered, Declined }`, `SetupLoginAction { Skip(SetupLoginSkip), Run { required } }`, and `SetupLoginStatus { Skipped, Authenticated(LoginReport), Failed(UserError) }` to `setup/command.rs`. + - Pure `setup_login_action(policy, intent)` decides from the re-resolved effective policy: + - effective `disabled` → `Skip(AuthDisabled)` + - effective `mandatory` → `Run { required: true }`, whatever the intent + - optional + `Requested` → `Run { required: false }` + - optional + `Declined` / `NotOffered` → the matching skip + - Generic `run_setup_login_step(action, login)` invokes the closure only for `Run`. + - A failed optional login becomes `Failed(UserError)`; an internal error maps to `UnexpectedFailure`. + - A failed required login returns `CliError::user_with_source(UserError::SetupLoginRequired, login_error)`. + - `SetupCommand::execute` (interactive runs only) re-resolves the policy once through `setup_access_report`, which now returns `(section, policy)`. It renders `SCE access:`, then runs the login step with `auth_command::run_login_in(&repository_root, AuthFormat::Text)` and pushes a login section before the Claude telemetry stage. + - Login section lines: + - `SCE login: skipped; SCE authentication is disabled by config.` + - `SCE login: not requested; run 'sce auth login' to log in or refresh credentials.` + - `SCE login: skipped; run 'sce auth login' to log in.` + - `SCE login: failed: ` followed by `Run 'sce auth login' to retry.` + - `LoginReport.rendered` on success + - `claude_telemetry_report` and `render_claude_telemetry_section` take `telemetry_issued`. `AUTH_PENDING_LINE` is dropped only when this run's login returned `TelemetryProvisioningResult::Issued`. Non-interactive runs pass `false`, so their output is unchanged. + - `UserError::SetupLoginRequired`: key `auth.setup_login_required`, runtime class, fixed message: "Local SCE setup completed, but the SCE login required by `auth.mode: mandatory` did not succeed.\n\nTo finish setup, run `sce auth login`, then rerun `sce setup`." + - Deviations and assumptions: + - The login outcome is its own output section, directly after `SCE access:`, rather than lines inside that section, because a successful login renders the multi-line `sce auth login` text. + - The disabled-skip and not-requested lines are new fixed strings; the Design specified only the declined and failed lines. + - A failed mandatory login returns the error, so the setup sections already rendered are not printed; the error message states that local setup completed. + - Verify outcomes: + - `setup::`: passed (92 tests). New `command::tests`: + - `setup_login_action_covers_every_effective_mode_and_intent` (global optional, mandatory, disabled, and default; repository `mandatory` over global optional; repository `disabled` over global mandatory; all three intents) + - `setup_login_step_never_invokes_login_when_skipped` (closure panics if called) + - `setup_login_step_reports_optional_failure_as_successful_setup` + - `setup_login_step_fails_mandatory_login_with_setup_login_required` + - `setup_login_step_includes_login_text_for_mandatory_and_accepted_optional_login` + - `setup_login_section_renders_exact_skip_lines_without_credentials` (real login text render with secret token values) + - `setup_claude_telemetry_omits_the_pending_line_only_when_setup_login_issued_a_credential` + - `error`: passed (53 tests), including `setup_login_required_has_stable_runtime_catalog_mapping_and_keeps_its_source`. + - Additional check: `clippy --all-targets -- --deny warnings` is clean. + - Context impact: user-visible. Interactive `sce setup` now runs `sce auth login` per the effective mode, prints an `SCE login` outcome section, exits with `auth.setup_login_required` when a mandatory login fails, and drops the Claude "authentication pending" line when this run's login issued a telemetry credential. Affected areas: `context/sce/setup-repo-local-config-bootstrap.md`, `context/cli/cli-command-surface.md`, `context/sce/telemetry-credential.md`, `context/sce/cli-error-code-taxonomy.md`, `context/cli/access-policy.md`. + - Context synchronization: synced + +- [x] T07: `Add sce setup --reconfigure to revise persisted setup answers` (status:done) + - Task ID: T07 + - Scope: In: + - Add a `--reconfigure` flag in `cli/src/cli_schema.rs` `Commands::Setup`. + - Map it in `parse/command_runtime.rs` and add `SetupCliOptions.reconfigure` / `SetupRequest.reconfigure`. + - `resolve_setup_request` rejects it, with fixed messages, when combined with a target flag, `--non-interactive`, `--hooks`, `--repo`, or `--bootstrap-context`. + - With it, `resolve_setup_dispatch` ignores persisted values for suppression and passes them as prompt defaults for auto-sync, attribution, auth mode, and telemetry. Locked and invalid-global gates still apply. + - Add a one-line hint `Run 'sce setup --reconfigure' to change saved setup answers.` to the `SCE access` section when any prompt was suppressed. + - Out: non-interactive consent flags, `sce config set`. + - Dependencies: T04, T05 + - Done when: request-validation tests cover every rejected combination; dispatch tests prove that `--reconfigure` asks all four persisted prompts with the persisted defaults (including a persisted global `disabled` as the auth-mode cursor), and that a repository lock still skips the access prompts; setup help lists the flag. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup`; `nix develop -c ./scripts/run-cli-cargo.sh run --manifest-path cli/Cargo.toml -- setup --help` + - Completed: 2026-10-21 + - Files changed: + - `cli/src/cli_schema.rs` + - `cli/src/services/parse/command_runtime.rs` + - `cli/src/services/command_registry.rs` + - `cli/src/services/setup/mod.rs` + - `cli/src/services/setup/command.rs` + - Result: + - `Commands::Setup` gains `--reconfigure` with help text `Ask every saved setup answer again, using the saved values as defaults (interactive only)`. It is mapped to `SetupCliOptions.reconfigure` and `SetupRequest.reconfigure`. + - `resolve_setup_request` checks `--reconfigure` conflicts first and rejects a target flag, `--non-interactive`, `--hooks`, `--repo`, or `--bootstrap-context` with the fixed message `Option '--reconfigure' cannot be used with ''. Try: run 'sce setup --reconfigure' alone to change saved setup answers interactively.` `--workflow` stays allowed. + - `resolve_setup_dispatch` takes a `reconfigure` flag. Under it, the auto-sync and attribution prompts use the persisted value as the default instead of being suppressed (`persisted_or_prompted`). The auth-mode and telemetry prompts use the persisted global value as their default, falling back to `optional` and `false`. The lock and invalid-global gates are unchanged. + - `SetupDispatch::Proceed` gains `prompts_suppressed`. It is true when, without `--reconfigure`, a persisted repository or global answer skipped a prompt. Lock and invalid-global skips do not count. `SetupAccessSave` carries it, and the `SCE access` section appends `- Run 'sce setup --reconfigure' to change saved setup answers.` + - `SetupAccessGate.effective_mandatory` is renamed `mandatory_locked`. It is set only when a non-global layer decides `mandatory`, which resolves T04's open note: reconfiguring a global `mandatory` to `optional` now offers login. Behavior without `--reconfigure` is unchanged, because a persisted global `mandatory` still makes the prospective mode `mandatory`. + - Deviations and assumptions: + - The hint is rendered as a `- ` list line inside the `SCE access` section, matching the section's other lines. + - `SetupCliOptions` carries `#[allow(clippy::struct_excessive_bools)]` because it mirrors the CLI flags. + - The flag's help text is set through `#[arg(help = …)]` rather than a doc comment. + - Verify outcomes: + - `setup`: passed (107 tests). New tests: + - `reconfigure_asks_every_persisted_prompt_with_the_persisted_defaults` + - `reconfigure_uses_a_persisted_global_disabled_as_the_auth_mode_cursor` + - `reconfigure_keeps_the_lock_and_invalid_global_gates` (repository lock, explicit lock, invalid global) + - `reconfigure_from_a_global_mandatory_offers_login_for_optional` + - `persisted_answers_mark_prompts_suppressed_only_without_reconfigure` + - `reconfigure_request_rejects_every_non_interactive_combination` (all five targets, `--non-interactive`, `--hooks`, `--hooks --repo`, `--repo`, `--bootstrap-context`) + - `setup_access_section_hints_reconfigure_when_saved_answers_suppressed_prompts` (exact output) + - `reconfigure_rewrites_saved_global_answers` + - `setup_reconfigure_parses_to_interactive_reconfigure_request` + - `setup_reconfigure_with_a_target_fails_validation` + - `setup_help_lists_the_reconfigure_flag` + - the existing gate test gains a global-`mandatory` case + - `setup --help`: passed; it lists `--reconfigure` with the help text above. + - Additional check: `clippy --all-targets -- --deny warnings` is clean. + - Context impact: user-visible. The new `sce setup --reconfigure` flag and its validation messages, re-asking saved answers with persisted defaults, and the `SCE access` reconfigure hint. Affected areas: `context/cli/cli-command-surface.md`, `context/sce/setup-repo-local-config-bootstrap.md`, `context/cli/config-precedence-contract.md`, `context/cli/access-policy.md`. + - Context synchronization: synced + +## Open questions + +- **Global versus repository auth mode.** Saving `auth.mode` globally means that choosing `disabled` during setup in one repository turns off login, sync, and telemetry in every repository on the machine. The plan states this in the prompt and report and does not offer a repository-scoped restriction. The alternative is a fourth choice: write `disabled` (or `mandatory`) to the committed `.sce/config.json` as team policy. That alternative changes shared files and breaks older binaries that reject the keys. Is user-level only the right product call? +- **Login offer default.** Default Yes treats pressing Enter as consent to a possible Keychain dialog. Default No is the more conservative choice on privacy, but leaves users who enabled auto-sync unauthenticated. Which one should ship? +- **`--reconfigure` scope.** The plan has it re-ask the two existing repository behavior answers as well, because they are currently impossible to change through setup and a flag named "reconfigure" that skipped them would be confusing. The smaller alternative is to re-ask only the auth-mode and telemetry prompts. +- **Unattended consent.** Without new flags, CI or provisioning scripts can grant consent only by writing the global config file. Is that acceptable, or does a follow-up need a non-interactive `--telemetry`/`--auth-mode` contract? + +## Validation Report + +**Status:** validated +**Date:** 2026-10-21 + +### Commands run + +- `nix flake check` -> exit 0 (all checks passed: `sce-cli-tests`, `sce-cli-clippy`, `sce-cli-fmt`) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup` -> exit 0 (107 passed, 0 failed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml auth_command` -> exit 0 (21 passed, 0 failed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml parse` -> exit 0 (51 passed, 0 failed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml error` -> exit 101 (52 passed, 1 failed: `app::tests::managed_export_marks_failed_output_and_exports_final_error_log`, outside this plan's scope; it passed on 3 reruns in isolation and inside `nix flake check`) +- `nix run .#pkl-check-generated` -> not run (no schema or Pkl inputs changed, as the plan states) + +### Success-criteria verification + +- [x] AC1: First-run prompt order, defaults, and cancellation -> `first_interactive_run_asks_access_prompts_after_existing_prompts_with_defaults`, `cancelling_any_access_prompt_cancels_setup`, `new_prompt_labels_and_defaults_are_fixed`, `auth_mode_default_cursor_points_at_the_default_row` passed +- [x] AC2: Global-only writes, key preservation, idempotence, file modes -> `access_preferences_writer_sets_only_requested_keys`, `access_preferences_writer_is_idempotent_on_rerun`, `access_preferences_writer_preserves_existing_mode_and_creates_private_file`, `access_preferences_writer_without_answers_never_creates_file`, `interactive_setup_saves_access_answers_only_to_the_global_config`, `interactive_setup_rerun_leaves_the_global_config_bytes_unchanged` passed +- [x] AC3: Invalid, unreadable, or raced global config is never overwritten; write failure aborts setup -> `access_preferences_writer_refuses_invalid_files_without_touching_them`, `access_preferences_writer_detects_concurrent_modification_before_rename`, `access_preferences_writer_reports_io_error_for_read_only_directory`, `interactive_setup_skips_access_writes_when_the_global_config_is_invalid`, `interactive_setup_aborts_before_repository_writes_when_the_global_config_is_read_only` passed +- [x] AC4: Repository and explicit locks, opt-out, and mandatory -> `access_gate_locks_only_for_repository_or_explicit_disabled`, `access_mode_and_telemetry_prompts_follow_persisted_values_locks_and_selected_mode`, `setup_access_section_reports_repository_opt_out_after_global_consent`, `setup_claude_telemetry_policy_follows_layered_config` passed +- [x] AC5: Login action per effective mode; mandatory failure maps to `auth.setup_login_required` -> `setup_login_action_covers_every_effective_mode_and_intent`, `setup_login_step_never_invokes_login_when_skipped`, `setup_login_step_reports_optional_failure_as_successful_setup`, `setup_login_step_fails_mandatory_login_with_setup_login_required`, `setup_login_required_has_stable_runtime_catalog_mapping_and_keeps_its_source`, and the `auth_command` provisioning tests passed +- [x] AC6: Rerun suppression and `--reconfigure` validation -> `persisted_answers_mark_prompts_suppressed_only_without_reconfigure`, `reconfigure_asks_every_persisted_prompt_with_the_persisted_defaults`, `reconfigure_keeps_the_lock_and_invalid_global_gates`, `reconfigure_request_rejects_every_non_interactive_combination`, `setup_reconfigure_parses_to_interactive_reconfigure_request`, `setup_reconfigure_with_a_target_fails_validation`, `setup_help_lists_the_reconfigure_flag` passed +- [x] AC7: Non-interactive, hooks, and context-only runs are unchanged -> `non_interactive_targets_prompt_nothing_and_carry_no_access_values` and the existing setup command tests passed (107/107) +- [x] AC8: Report states the effective policy and login outcome without secrets; `sce auth login` output unchanged -> `setup_access_section_renders_exact_lines`, `setup_login_section_renders_exact_skip_lines_without_credentials` (asserts no access or refresh token values), `setup_login_step_includes_login_text_for_mandatory_and_accepted_optional_login`, and the `auth_command` render tests passed +- [x] AC9: The Claude readiness line follows repository authorization (revised by the PR #339 review fix) -> `setup_claude_telemetry_readiness_follows_repository_authorization`, `claude_telemetry_report_marks_unready_repository_without_helper_name`, `repository_readiness_lookup_fails_closed_unless_repository_is_authorized`, `repository_readiness_follows_binding_rather_than_credential_issuance` passed + +### Failed checks and follow-ups + +- PR #339 review fixes (2026-10-21): + - P1: the global config writer now refuses to replace a symlink-managed file (`GlobalAccessPreferencesError::SymlinkManaged`). Tests: `access_preferences_writer_refuses_to_replace_symlinked_global_config`, `access_preferences_writer_leaves_symlinked_global_config_alone_when_unchanged`, `interactive_setup_aborts_before_repository_writes_when_the_global_config_is_a_symlink`. + - P2: Claude readiness now checks the repository-scoped credential binding instead of `TelemetryProvisioningResult::Issued` (AC9 revised). + - P2: non-interactive and target-flag setup no longer calls `repository_telemetry_authorized`; `RepositoryAuthorizationCheck::for_mode` gates the lookup on `SetupMode::Interactive` and the report uses `RepositoryAuthorization::NotChecked`. Tests: `setup_claude_telemetry_readiness_follows_repository_authorization` (panicking lookup for non-interactive, disabled, and conflict cases in both modes), `setup_repository_authorization_is_checked_only_for_interactive_setup`, `setup_claude_telemetry_installs_when_claude_is_selected`, `setup_claude_telemetry_leaves_settings_untouched_when_claude_is_not_installed`. + - Not addressed: the second P2 finding (optional login suppression when `auth.db` exists). + +### Residual risks + +- `app::tests::managed_export_marks_failed_output_and_exports_final_error_log` failed once in a local run and passed on 3 reruns and in `nix flake check`. It looks like a timing-dependent OTLP capture flake outside this plan's scope. +- The plan's open questions (global versus repository auth mode, the login-offer default, `--reconfigure` scope, unattended consent) are product decisions and are still open. diff --git a/context/sce/cli-error-code-taxonomy.md b/context/sce/cli-error-code-taxonomy.md index 68382908b..da97b36fe 100644 --- a/context/sce/cli-error-code-taxonomy.md +++ b/context/sce/cli-error-code-taxonomy.md @@ -33,10 +33,11 @@ It complements the numeric process exit-code classes documented in `context/sce/ ## Ownership - `FailureClass` in `cli/src/services/error.rs` owns class selection and stable code assignment (`FailureClass::code()`). -- `CliError::{User,Internal}` in `cli/src/services/error.rs` is the typed CLI-boundary error type; `CliError::code()`/`CliError::class()` delegate to the failure class. `CliError::User` carries a closed catalog `UserError` (`NotAuthenticated`, `NotGitRepository`, `NotGitRemote`, `AuthStorageUnavailable`, `LoginAuthStorageUnavailable`, or `UnexpectedFailure`) for expected, deliberately-explained failures; `CliError::Internal` carries a live `anyhow::Error` source for every other failure, including non-classifiable setup preflight failures. `CliError::User` may also carry an optional preserved technical `source`, kept for observability only and never rendered to the terminal; the missing-remote source contains the configured remote name but no URL. +- `CliError::{User,Internal}` in `cli/src/services/error.rs` is the typed CLI-boundary error type; `CliError::code()`/`CliError::class()` delegate to the failure class. `CliError::User` carries a closed catalog `UserError` (`NotAuthenticated`, `NotGitRepository`, `NotGitRemote`, `AuthStorageUnavailable`, `LoginAuthStorageUnavailable`, `AuthDisabledByConfig`, `SetupLoginRequired`, or `UnexpectedFailure`) for expected, deliberately-explained failures; `CliError::Internal` carries a live `anyhow::Error` source for every other failure, including non-classifiable setup preflight failures. `CliError::User` may also carry an optional preserved technical `source`, kept for observability only and never rendered to the terminal; the missing-remote source contains the configured remote name but no URL. - `UserError` in `cli/src/services/error.rs` is the closed catalog of deliberately presented terminal failures. It has no arbitrary-message variant (no `Message(String)`/`Custom(...)` escape hatch): every entry returns a fixed reviewed sentence from `UserError::message()`, keyed for structured logging by `UserError::key()`. `NotAuthenticated` (`auth.not_authenticated`) covers Control Plane authentication failures from authenticated `sce auth whoami`; missing credentials from `sce auth logout`/`whoami` are successful state queries and do not enter the error catalog. `AuthStorageUnavailable` and `LoginAuthStorageUnavailable` (both `auth.storage_unavailable`) are used by `sce sync` and the `sce auth login`, `logout`, and `whoami` command boundary for token-storage plus `AuthError::Io`/`Storage` failures; each carries a typed `AuthStorageFailure` cause (`CredentialAccess`, `DatabaseLocked`, `Database`) that selects the guidance text (see `context/sce/auth-db.md`). Both auth-command mappings preserve technical sources for observability. `NotGitRepository` (`setup.not_git_repository`) is used by the setup command only when setup-owned repository-root resolution positively identifies a target as outside a Git repository; `NotGitRemote` (`setup.not_git_remote`) is used only when the configured named remote has no URL. Both preserve technical sources for observability. Other repository-root resolution, Git, and remote-lookup execution failures map to `UnexpectedFailure` (`general.unexpected_failure`). `UnexpectedFailure` is also used by `sce sync`, the config-command boundary for config execution failures, the version and doctor command boundaries for service execution failures, the auth-command boundary, and remaining setup execution failures; it renders one fixed, user-safe log-files guidance sentence and has no automatic `Try:` suffix or dynamic path input. - Command and domain layers construct and return a `CliError`; they do not format terminal text, apply styling, or decide authentication/user-error semantics from string matching. Auth command orchestration classifies expected authentication and credential-storage failures into the existing `UserError` catalog by typed domain variants, never by string matching, and preserves the original technical chain as the optional user-error source. `app_support` is the sole owner of turning a `CliError` into the final stderr sentence. - `UserError` in `cli/src/services/error.rs` is the closed catalog of deliberately presented terminal failures. It has no arbitrary-message variant (no `Message(String)`/`Custom(...)` escape hatch): every entry is a fixed, reviewed sentence returned by `UserError::message()`, keyed for structured logging by `UserError::key()`. `NotAuthenticated` (`auth.not_authenticated`) covers Control Plane authentication failures from authenticated `sce auth whoami`; missing credentials from `sce auth logout`/`whoami` are successful state queries and do not enter the error catalog. `AuthStorageUnavailable` and `LoginAuthStorageUnavailable` (both `auth.storage_unavailable`) are used by `sce sync` and the `sce auth login`, `logout`, and `whoami` command boundary for token-storage plus `AuthError::Io`/`Storage` failures; each carries a typed `AuthStorageFailure` cause (`CredentialAccess`, `DatabaseLocked`, `Database`) that selects the guidance text (see `context/sce/auth-db.md`). Both auth-command mappings preserve technical sources for observability. `NotGitRepository` (`setup.not_git_repository`) is used by the setup command only when setup-owned repository-root resolution positively identifies a target as outside a Git repository; it renders fixed Git-init/rerun guidance and preserves the technical source for observability. Other repository-root resolution failures, including nonexistent, inaccessible, process, and malformed-output failures, map to `UnexpectedFailure` (`general.unexpected_failure`). `UnexpectedFailure` is also used by `sce sync`, the config-command boundary for config execution failures, the version and doctor command boundaries for service execution failures, the auth-command boundary, and remaining setup execution failures; it renders one fixed, user-safe diagnostic sentence and has no automatic `Try:` suffix or dynamic path input. +- `SetupLoginRequired` (`auth.setup_login_required`, runtime class) is returned by interactive `sce setup` only when the effective `auth.mode` is `mandatory` and the setup login step fails. It renders a fixed message saying local setup completed and to run `sce auth login`, then rerun `sce setup`, and preserves the login `CliError` as its source. See [setup login](setup-repo-local-config-bootstrap.md#setup-login). - `Logger::log_cli_error` in `cli/src/services/observability.rs` owns structured error logging with `sce.error.{code}` event IDs. - Config, version, doctor, and remaining setup execution boundaries map their unexpected failures to `UserError::UnexpectedFailure`; auth command mappings preserve their original technical sources for observability while terminal rendering remains user-safe. - `write_error_diagnostic` in `cli/src/services/app_support.rs` owns final stderr rendering: it redacts and writes the catalog variant's message without a wrapper or styling, while `CliError::Internal` retains code-bearing rendering and styles its rendered chain through `services::style::error_text_with_color_policy` under the stderr TTY/`NO_COLOR` policy (`services::style::supports_color_stderr()`), independent of stdout's TTY state. diff --git a/context/sce/setup-repo-local-config-bootstrap.md b/context/sce/setup-repo-local-config-bootstrap.md index 1b2ef4214..b931fa7f2 100644 --- a/context/sce/setup-repo-local-config-bootstrap.md +++ b/context/sce/setup-repo-local-config-bootstrap.md @@ -18,7 +18,24 @@ Task `setup-repo-gate-and-local-config-bootstrap` T02, `turso-local-db-sync` T04 Record SCE involvement in Git commits? (Adds SCE metadata to commits created or assisted by SCE.) ``` - Both default to Yes, and the prompt seam carries each answer separately through setup dispatch so declining one does not change the other. + Both default to Yes, and the prompt seam carries each answer separately through setup dispatch so declining one does not change the other. Each is skipped when the repository config already holds its value (`agent_trace.auto_sync`, `policies.attribution_hooks.enabled`), unless [`--reconfigure`](#reconfigure) is passed. +- Interactive setup then resolves SCE access choices in dispatch, after those two confirmations and before any file write: + - `SCE account mode for this machine` (`Select`; cursor on `optional`). It is skipped when the global user config already holds `auth.mode` (unless `--reconfigure`), or when that config is invalid. + - `Share SCE telemetry?` (`Confirm`; default No). It is skipped when the global user config already holds `telemetry.enabled` (unless `--reconfigure`), when that config is invalid, or when the selected or persisted mode is `disabled`. + - `Log in to SCE now?` (`Confirm`; default Yes). It is offered only when the prospective mode is `optional`, no repository or explicit layer enforces `mandatory`, and either an access prompt was asked in this run or no `auth.db` file exists. + - A repository or explicit (`--config` / `SCE_CONFIG_FILE`) `auth.mode: disabled` skips all three prompts. Cancelling any of them is the standard setup cancellation. + - Inputs are read without credential access: the resolved access policy, the global user config file, and the presence of the `auth.db` file. + - The answers are carried on the dispatch result (`auth_mode`, `telemetry_enabled`, and a `SetupLoginIntent` of `NotOffered | Declined | Requested`). Only answers given in this run are carried; a prompt suppressed by a persisted value carries `None`. The login intent feeds the [setup login step](#setup-login). + - The answers are saved to the global user config before any repository write (see [Global access preferences](#global-access-preferences)). + - Non-interactive, hooks-only, and context-only setup never read these inputs or prompt. + +### Reconfigure + +`sce setup --reconfigure` is interactive setup that asks every persisted answer again: auto-sync, attribution, account mode, and telemetry consent. Each prompt's default is the saved value (falling back to the first-run default), so a persisted global `disabled` puts the account-mode cursor on `disabled`. The repository/explicit `disabled` lock and the invalid-global gate still skip the access prompts. New answers go through the same writers as a first run. + +- It must be used alone (apart from `--workflow`). Combining it with a target flag, `--non-interactive`, `--hooks`, `--repo`, or `--bootstrap-context` fails request validation with `Option '--reconfigure' cannot be used with ''. Try: run 'sce setup --reconfigure' alone to change saved setup answers interactively.` +- A global `mandatory` that `--reconfigure` changes to `optional` gets the login offer, because only a repository or explicit `mandatory` suppresses it. +- A plain interactive run where a saved answer skipped a prompt adds `- Run 'sce setup --reconfigure' to change saved setup answers.` to the `SCE access` section. - The bootstrap writes the canonical JSON payload with the versioned schema declaration and explicit opt-ins for both setup-controlled behaviors: `{"$schema": "https://sce.crocoder.dev/v/config.json", "agent_trace": {"auto_sync": true}, "policies": {"attribution_hooks": {"enabled": true}}}` (where `` is the CLI release version, with a trailing newline). - If `.sce/config.json` already exists, the bootstrap step returns `Ok(())` immediately and leaves the file untouched — no merge, no reformat, no overwrite. A later interactive target-install write may merge the two answered behavior values, while non-interactive setup leaves existing behavior keys and omissions unchanged. - The parent `.sce/` directory is created via `fs::create_dir_all` if missing. @@ -26,6 +43,49 @@ Task `setup-repo-gate-and-local-config-bootstrap` T02, `turso-local-db-sync` T04 - After both repository preflights (`ensure_git_repository` and the effective named-remote URL check), setup consumes the shared resolver's degraded result for an invalid default-discovered repo-local `.sce/config.json`; the file remains untouched and the run continues through prompts, context baseline bootstrap, lifecycle providers, hooks, and target assets. An absent config continues through the normal bootstrap path, while explicit config selections remain fatal. - Config/DB bootstrap runs after those preflights and after context baseline bootstrap, before config/hooks dispatch, so it applies to all normal setup modes: config-only, hooks-only, combined, and interactive. If the repo-local config is invalid, target and optional-workflow persistence is skipped rather than rewriting it. +## Global access preferences + +Setup saves `auth.mode` and `telemetry.enabled` only to the global user config, never to the repository `.sce/config.json` or an explicit config file ([ADR](../decisions/2026-10-21-setup-writes-access-answers-to-user-layer-only.md)). This applies to interactive runs only; non-interactive, hooks-only, and context-only runs never write access keys and print no `SCE access` section. + +- **Order:** the write runs right after dispatch and before `bootstrap_context_baseline`, so it is setup's first write. Cancelling a prompt still writes nothing. +- **Writer:** `persist_global_access_preferences` (`cli/src/services/setup/access_preferences.rs`). It writes explicit answers only, preserves unrelated keys, validates the result with `parse_file_config`, and skips the write when the values are already current. The write is a sibling temp file plus a rename, keeping the existing mode (`0o600` for a new file). It is refused when the file's bytes changed after the first read. When a write is needed and the path is a symlink (valid or dangling, detected with `fs::symlink_metadata`), the writer refuses with `SymlinkManaged` and leaves the link and its target unchanged, because a rename would replace the link. A symlinked file whose values are already current is still a no-op. +- **Invalid global config:** when the file is already invalid at read time, the access prompts are skipped and nothing is written; the file stays byte-identical. +- **Write failure** (unwritable, became invalid, or concurrently modified): setup exits with a runtime error (`SCE-ERR-RUNTIME`) before `context/` or `.sce/` is touched. The error is three fixed lines: `Failed to save SCE access preferences to the global SCE config ''.`, then the writer's error, then `No repository files were changed. Run 'sce config validate' to check the file, then rerun 'sce setup'.` For a symlink-managed file, the writer's error says SCE cannot modify it and to update its source directly (for example, Nix or Home Manager), and the last line is `No repository files were changed. Rerun 'sce setup' after updating the config source.` +- **Report:** after the target install, setup re-resolves the policy for the repository root and prints an `SCE access:` section between the install section and the Claude telemetry stage: + ``` + SCE access: + - auth.mode: (saved to global SCE config ''; applies to all repositories on this machine) + - telemetry.enabled: (saved to global SCE config ''; applies to all repositories on this machine) + - effective auth.mode: (source: [, config_source: ]) + - effective telemetry: enabled | disabled (reason: ) + ``` + - When nothing was written, the two saved lines are replaced by `- saved access preferences: unchanged (global SCE config '')`. + - The source wording matches `sce config show`, and the reason strings are the [access-policy reasons](../cli/access-policy.md#reporting). The effective lines come from re-resolution, so, for example, a repository `telemetry.enabled: false` still reports `disabled (reason: repository_opt_out)` after global consent. + - When a repository or explicit file locks auth to `disabled`, the section adds the first line of the matching `auth.disabled_by_config` message, which names that file. + - When the effective mode is `disabled` and an `auth.db` file exists, it adds `- SCE login: stored SCE credentials remain on this machine; run 'sce auth logout' to remove them.` + - When a saved answer suppressed a prompt in this run, it ends with the [`--reconfigure`](#reconfigure) hint line. + +## Setup login + +Interactive setup runs login after the `SCE access` section and before the Claude telemetry stage. It never runs for non-interactive, hooks-only, or context-only setup. The action is decided by `setup_login_action` (`cli/src/services/setup/command.rs`) from the same re-resolved effective policy the `SCE access` section reports, plus the dispatch's `SetupLoginIntent`, not from the prompt answer alone: + +| Effective `auth.mode` | Login intent | Action | +|---|---|---| +| `disabled` | any | Skipped. No `auth.db` or credential-store access. | +| `mandatory` | any | Login is required. | +| `optional` | `Requested` | Login runs. | +| `optional` | `Declined` / `NotOffered` | Skipped. | + +- **Login path:** the step calls `auth_command::run_login_in(, text)`, the same flow as `sce auth login` from that directory. Stored credentials are renewed when possible, with the device flow as the fallback. Because the global access answers were saved first, telemetry provisioning and repository enrollment inside login see the new consent. +- **Output:** a section after `SCE access:` with one fixed outcome. No token or credential value is printed. + - effective `disabled`: `SCE login: skipped; SCE authentication is disabled by config.` + - declined: `SCE login: skipped; run 'sce auth login' to log in.` + - not offered (an existing `auth.db` and no access prompt asked this run): `SCE login: not requested; run 'sce auth login' to log in or refresh credentials.` + - success: the `sce auth login` text report. + - optional failure: `SCE login: failed: `, then `Run 'sce auth login' to retry.` Setup still succeeds. An uncatalogued login failure renders the `UnexpectedFailure` message. +- **Mandatory failure:** setup exits with `UserError::SetupLoginRequired` (`auth.setup_login_required`, `SCE-ERR-RUNTIME`, exit code 4) and keeps the login error as the source. The fixed message says local setup completed and tells the user to run `sce auth login`, then rerun `sce setup`. Installed assets and saved answers are not rolled back. +- **Claude telemetry stage:** the Claude report is a single `configured` line when the repository is locally authorized to export: `auth.db` already exists, the repository identity resolves from the setup repository root, and a valid, unexpired telemetry credential is bound to this repository for the credential's user and workspace. Otherwise it adds `Claude telemetry: not ready for this repository; ...`, which tells the user to run `sce auth login` in the repository with the SCE account it is enrolled under. The check reuses `load_repository_telemetry_credential` with non-interactive credential access under `CREDENTIAL_LOOKUP_DEADLINE`, never creates `auth.db` or a key, never rebinds a repository, and fails closed. It runs only during interactive `sce setup`, when telemetry is enabled and the install is `configured`. Non-interactive and target-flag runs (`sce setup --claude`, `--all`, with or without `--non-interactive`) never run the check, so they never open `auth.db` or the OS credential store; after a `configured` install they print only `Claude telemetry: configured; repository authorization was not checked during non-interactive setup.` and report neither authorized nor not ready. It does not depend on whether this run issued a credential, and it does not mean telemetry reached the OTLP backend (see [telemetry credential: Claude-native telemetry](telemetry-credential.md)). + ## Context baseline bootstrap - `sce setup --bootstrap-context` is a non-interactive context-only mode and must be used alone (no target, hooks, non-interactive, or `--repo` flags). diff --git a/context/sce/telemetry-credential.md b/context/sce/telemetry-credential.md index 9de9fb4ec..6ee4860a7 100644 --- a/context/sce/telemetry-credential.md +++ b/context/sce/telemetry-credential.md @@ -27,7 +27,7 @@ flowchart LR - `Valid`: anything else. - The runtime and doctor map `Missing` to `not_configured`, `Expired` to `credential_expired`, and `Unusable` to `credential_unavailable`. Repository lookups and enrollment accept only `Valid`. - Ownership: every lookup decodes the stored WorkOS session's access-token claims and returns the credential only when `(sub, workspace_id)` equals the identity stored with it. Switching user or workspace therefore makes an older credential unusable even if it was never deleted. A new device-authorization login also deletes the stored telemetry credential before saving the new WorkOS session (`replace_session_with`), so a failed re-issuance leaves no credential; if that delete fails, the new session is not saved. Renewal of the same session keeps the credential. -- Repository bindings: `telemetry_repository_bindings` maps a repository ID (the canonical `repository_identity` hash, from `agent_trace.repository_id` or the configured remote) to the `(user_id, workspace_id)` it was enrolled under. Enrollment requires a valid, session-owned credential and records that credential's identity. `sce setup` no longer enrolls repositories, because it must not open the encrypted auth DB or touch the OS credential store. The explicit rebinding mode (`Enroll`) currently has no production caller. A successful `sce auth login` enrolls the working-directory repository only if it is unbound (`EnrollIfUnbound`), so a login never silently moves a repository to another workspace. Bindings survive logout and rotation; they authorize nothing without a matching credential. +- Repository bindings: `telemetry_repository_bindings` maps a repository ID (the canonical `repository_identity` hash, from `agent_trace.repository_id` or the configured remote) to the `(user_id, workspace_id)` it was enrolled under. Enrollment requires a valid, session-owned credential and records that credential's identity. `sce setup`'s own install steps never enroll repositories, because they must not open the encrypted auth DB or touch the OS credential store; only its interactive login step, which is `sce auth login`, can enroll. The explicit rebinding mode (`Enroll`) currently has no production caller. A successful `sce auth login` enrolls the working-directory repository only if it is unbound (`EnrollIfUnbound`), so a login never silently moves a repository to another workspace. Bindings survive logout and rotation; they authorize nothing without a matching credential. - Readiness source: `auth.db` is the only source of truth for whether a usable telemetry credential exists. Provisioning reports `issued` exactly when the credential was issued and persisted, then enrolls the working-directory repository; issuance or persistence failure reports `unavailable` and writes nothing. No separate readiness file exists; a legacy readiness file left in the state root by an older binary is never read, written, or removed. - Concurrent saves are single-statement atomic replacements of one fixed row; the last complete writer wins. - `sce auth logout` deletes the WorkOS credential and the telemetry credential, attempting both even when one fails and surfacing the first storage error. `credentials_removed` is true when either record was deleted; output fields are otherwise unchanged. @@ -94,7 +94,7 @@ Claude Code's own OpenTelemetry export is separate from the SCE-CLI managed expo - Written keys: `otelHeadersHelper` set to `sce auth telemetry-headers`, plus an `env` block with `CLAUDE_CODE_ENABLE_TELEMETRY=1`, `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1` (required by Claude Code for span tracing), `OTEL_{TRACES,METRICS,LOGS}_EXPORTER=otlp`, `OTEL_EXPORTER_OTLP_PROTOCOL` / `OTEL_EXPORTER_OTLP_ENDPOINT` from `MANAGED_OTLP_PROTOCOL` / `MANAGED_OTLP_ENDPOINT`, `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS=300000`, and `OTEL_METRICS_INCLUDE_REPOSITORY=true` (unconditional because the Claude Code version cannot be detected during setup; unknown variables are ignored). - Authentication: no token is ever written to settings, generated assets, or setup output, and `OTEL_EXPORTER_OTLP_HEADERS` is never set. Claude runs the hidden helper (see Hidden header helper) and uses its `Authorization` header. - Rotation: Claude re-runs the helper at most every five minutes (debounce 300000 ms), so a credential replaced by a later `sce auth login` is picked up without rewriting settings. `sce auth logout` deletes the stored credential, after which the helper fails and Claude export stops authenticating; local deletion does not revoke the OpenBao token. -- Repository enrollment: setup never enrolls, because it does not open the auth DB. After a successful install it always reports `authentication pending for this repository`. Running `sce auth login` inside the repository enrolls it, if unbound, and starts export. +- Repository enrollment: the Claude install itself never enrolls, because it does not open the auth DB. After a successful install, the Claude report is a single `configured` line when the repository is locally authorized to export: `auth.db` already exists, the repository identity resolves from the setup repository root, and a valid, unexpired telemetry credential is bound to this repository for the credential's user and workspace. Otherwise it adds `Claude telemetry: not ready for this repository; ...`, which tells the user to run `sce auth login` in the repository with the SCE account it is enrolled under. The check reuses `load_repository_telemetry_credential` with non-interactive credential access under `CREDENTIAL_LOOKUP_DEADLINE`, never creates `auth.db` or a key, never rebinds a repository, and fails closed. It runs only during interactive `sce setup`, when telemetry is enabled and the install is `configured`. Non-interactive and target-flag runs (`sce setup --claude`, `--all`, with or without `--non-interactive`) never run the check, so they never open `auth.db` or the OS credential store; after a `configured` install they print only `Claude telemetry: configured; repository authorization was not checked during non-interactive setup.` and report neither authorized nor not ready. It does not depend on whether this run issued a credential, and it does not mean telemetry reached the OTLP backend. The [interactive setup login step](setup-repo-local-config-bootstrap.md#setup-login) is `sce auth login` from the repository root, so it enrolls the repository if unbound; a repository already bound to another identity stays bound (`INSERT OR IGNORE`) and is reported not ready. `TelemetryProvisioningResult::Issued` still means only that a credential was issued. - Failure handling: the helper's failure is nonzero with empty stdout and the fixed diagnostic `Telemetry credential is unavailable.`, and never affects other Claude behavior beyond missing telemetry auth. - Merge safety: repeated setup is byte-idempotent; unrelated settings, env, permissions, and hooks are preserved; writes are atomic via temp-file rename; an existing file's mode is kept and a new file uses `0600`; malformed JSON is never overwritten. - Conflicts and limits: a user-owned `otelHeadersHelper`, an explicit opt-out (`CLAUDE_CODE_ENABLE_TELEMETRY`, `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA`, or `ENABLE_ENHANCED_TELEMETRY_BETA` not `1`, or any `OTEL_*_EXPORTER=none`), `OTEL_METRICS_INCLUDE_REPOSITORY` other than `true`, a different helper refresh interval, or a differing generic/per-signal OTLP endpoint, headers, protocol, or exporter in user settings or in the Linux/macOS managed-settings file (`/etc/claude-code/managed-settings.json`, `/Library/Application Support/ClaudeCode/managed-settings.json`), causes the telemetry install to be skipped and reported with the specific reason while repository setup still succeeds. Environment variables present in a future Claude launch cannot be detected by setup and can override user settings.