diff --git a/.claude/skills/sce-info/.claude-plugin/plugin.json b/.claude/skills/sce-info/.claude-plugin/plugin.json index de4ac69be..885ccf31b 100644 --- a/.claude/skills/sce-info/.claude-plugin/plugin.json +++ b/.claude/skills/sce-info/.claude-plugin/plugin.json @@ -1,5 +1,5 @@ { - "name": "sce-splash", + "name": "SCE", "version": "0.1.0", "description": "Adds a subtle \"with SCE\" line beneath the Claude Code startup branding" } diff --git a/.claude/skills/sce-info/hooks/hooks.json b/.claude/skills/sce-info/hooks/hooks.json index 0c02ee31f..9f18e1745 100644 --- a/.claude/skills/sce-info/hooks/hooks.json +++ b/.claude/skills/sce-info/hooks/hooks.json @@ -1,4 +1,4 @@ { - "description": "sce-splash hooks module", + "description": "SCE hooks module", "modules": ["./register.ts"] } diff --git a/.claude/skills/sce-info/hooks/register.ts b/.claude/skills/sce-info/hooks/register.ts index 42e4c3fda..ba4ba2dc0 100644 --- a/.claude/skills/sce-info/hooks/register.ts +++ b/.claude/skills/sce-info/hooks/register.ts @@ -1,6 +1,9 @@ -import type { On } from 'claude-code' +import type { EngineInterface, On, Timer } from 'claude-code' let started = false +let missing = false +let pulseFrame = 0 +let pulseTimer: Timer | undefined export const ART = [ '███████╗ ██████╗███████╗', @@ -19,18 +22,135 @@ export function gradientColor(col: number): string { const t = col / Math.max(ART_WIDTH - 1, 1) return ( '#' + - GRADIENT_LEFT.map((a, i) => Math.round(a + (GRADIENT_RIGHT[i] - a) * t).toString(16).padStart(2, '0')).join('') + GRADIENT_LEFT.map((a, i) => Math.round(a + ((GRADIENT_RIGHT[i] ?? a) - a) * t).toString(16).padStart(2, '0')).join('') ) } +export const PULSE = ['#ff2d2d', '#e02424', '#b81c1c', '#8f1414', '#b81c1c', '#e02424'] as const +export const PULSE_INTERVAL_MS = 150 + +export const EXPECTED_SCE_VERSION = '0.4.0-pre-alpha-v11' export const SITE = 'sce.crocoder.dev' +export const INSTALL_URL = `https://${SITE}/docs/getting-started#install-cli` export const FOOTER = `Visit ${SITE} to learn more.` export const LOADED = 'loaded.' +export const NOT_LOADED = 'not loaded.' +export const INSTALL_FOOTER = `Install sce ${EXPECTED_SCE_VERSION}: ` +export const SCE_MISSING = `CLI not found. Install sce ${EXPECTED_SCE_VERSION} from ${INSTALL_URL}` +export const LOGIN_REQUIRED = "Login required for this repository. Run 'sce auth login'." +export const VERSION_ARGV = ['sce', '--version'] as const +export const VERSION_TIMEOUT_MS = 5000 +export const DOCTOR_ARGV = ['sce', 'doctor', '--format', 'json'] as const + +type DoctorProblem = { + kind?: string + target?: string | null + summary?: string + remediation?: { text?: string } +} + +type DoctorHook = { + name?: string + exists?: boolean +} + +type DoctorReport = { + sce_login?: { state?: string } + hooks?: DoctorHook[] + problems?: DoctorProblem[] +} + +export const CLAUDE_ASSETS_STALE = "Claude SCE skills are outdated or modified. Run 'sce setup --claude' to update them." + +const CLAUDE_ASSET_KINDS = new Set([ + 'claude_integration_files_missing', + 'claude_integration_content_mismatch', + 'claude_asset_read_failed', +]) + +export function gitHooksMissing(names: readonly string[]): string { + return `Git hooks missing: ${names.join(', ')}. Run 'sce doctor --fix' to install them.` +} + +function parseDoctor(doctorJson: string): DoctorReport | undefined { + try { + const report = JSON.parse(doctorJson) + return report && typeof report === 'object' ? report : undefined + } catch { + return undefined + } +} + +export function loginRequired(doctorJson: string): boolean { + return parseDoctor(doctorJson)?.sce_login?.state === 'not_logged_in' +} + +function missingGitHookNames(report: DoctorReport): string[] { + if (!Array.isArray(report.hooks)) return [] + return report.hooks + .filter((hook) => hook && hook.exists === false && typeof hook.name === 'string') + .map((hook) => hook.name as string) +} + +export function problemNotices(doctorJson: string): string[] { + const report = parseDoctor(doctorJson) + if (!report) return [] + const missingHooks = missingGitHookNames(report) + const hookNotices = missingHooks.length > 0 ? [gitHooksMissing(missingHooks)] : [] + const claudeProblems = (Array.isArray(report.problems) ? report.problems : []).filter( + (problem) => problem && problem.target === 'claude', + ) + const assetNotices = claudeProblems.some((problem) => CLAUDE_ASSET_KINDS.has(problem.kind ?? '')) + ? [CLAUDE_ASSETS_STALE] + : [] + const otherNotices = claudeProblems + .filter((problem) => !CLAUDE_ASSET_KINDS.has(problem.kind ?? '') && problem.summary) + .map((problem) => [problem.summary, problem.remediation?.text].filter(Boolean).join(' ')) + return [...hookNotices, ...assetNotices, ...new Set(otherNotices)] +} + +function startPulse($: EngineInterface) { + if (pulseTimer || !missing || started) return + pulseTimer = $.clock.every(PULSE_INTERVAL_MS, () => { + pulseFrame = (pulseFrame + 1) % PULSE.length + $.ui.invalidate('ui.render') + }) +} + +function stopPulse() { + pulseTimer?.cancel() + pulseTimer = undefined + pulseFrame = 0 +} export function register(on: On) { + on('session.start', async ($, e, next) => { + const result = await next(e) + if (!e.isInteractive) return result + const probe = await $.process.run(VERSION_ARGV, { cwd: e.cwd, timeoutMs: VERSION_TIMEOUT_MS }).catch(() => undefined) + if (!probe) { + missing = true + startPulse($) + $.ui.invalidate('ui.render') + $.ui.log(SCE_MISSING) + return result + } + if (missing) { + missing = false + stopPulse() + $.ui.invalidate('ui.render') + } + const doctor = await $.process.run(DOCTOR_ARGV, { cwd: e.cwd }).catch(() => undefined) + if (!doctor) return result + if (loginRequired(doctor.stdout)) $.ui.log(LOGIN_REQUIRED) + for (const notice of problemNotices(doctor.stdout)) $.ui.log(notice) + return result + }) + on('prompt.submit', async ($, e, next) => { if (!started) { started = true + stopPulse() $.ui.invalidate('ui.render') } return next(e) @@ -39,6 +159,7 @@ export function register(on: On) { on('session.end', async ($, e, next) => { if (e.reason === 'clear' && started) { started = false + startPulse($) $.ui.invalidate('ui.render') } return next(e) @@ -48,6 +169,23 @@ export function register(on: On) { if (started || e.props.hasSurvey) return next(e) const { Box, Text, Link } = $.ui.resolve(e) const theirs = await next(e) + const status = missing + ? Text({ color: PULSE[pulseFrame], bold: true, children: ` ${NOT_LOADED}` }) + : Text({ color: 'cyan', children: ` ${LOADED}` }) + const footer = missing + ? Text({ + children: [ + INSTALL_FOOTER, + Text({ color: PULSE[pulseFrame], underline: true, children: Link({ href: INSTALL_URL, label: INSTALL_URL }) }), + ], + }) + : Text({ + children: [ + 'Visit ', + Text({ color: 'cyan', underline: true, children: Link({ href: `https://${SITE}`, label: SITE }) }), + ' to learn more.', + ], + }) const label = Box({ paddingLeft: 11, flexDirection: 'column', @@ -55,15 +193,9 @@ export function register(on: On) { ...ART.map((row, i) => { const art = Text({ children: [...row].map((ch, col) => (ch === ' ' ? ch : Text({ color: gradientColor(col), children: ch }))) }) if (i !== ART.length - 2) return art - return Box({ flexDirection: 'row', children: [art, Text({ color: 'cyan', children: ` ${LOADED}` })] }) - }), - Text({ - children: [ - 'Visit ', - Text({ color: 'cyan', underline: true, children: Link({ href: `https://${SITE}`, label: SITE }) }), - ' to learn more.', - ], + return Box({ flexDirection: 'row', children: [art, status] }) }), + footer, ], }) return Box({ flexDirection: 'column', children: [label, theirs] }) diff --git a/.sce/config.json b/.sce/config.json index c70ad5da9..4cf567732 100644 --- a/.sce/config.json +++ b/.sce/config.json @@ -3,6 +3,9 @@ "agent_trace": { "auto_sync": true }, + "auth": { + "mode": "mandatory" + }, "integrations": { "optional_workflows": [], "target": [ @@ -214,5 +217,8 @@ ], "presets": [] } + }, + "telemetry": { + "enabled": true } } diff --git a/cli/src/services/config/render.rs b/cli/src/services/config/render.rs index 4abed0f74..c42973668 100644 --- a/cli/src/services/config/render.rs +++ b/cli/src/services/config/render.rs @@ -13,6 +13,7 @@ use super::types::{ use super::{ConfigPathSource, ReportFormat, ResolvedOptionalValue, ResolvedValue, ValueSource}; const TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE: &str = "Claude Code telemetry settings written by sce setup are removed by the next sce setup run after the global SCE config sets telemetry.enabled to false or auth.mode to disabled; repository-level opt-outs leave them in place."; +const TELEMETRY_NOT_ENABLED_NOTE: &str = "Set telemetry.enabled: true in the repository SCE config to enable SCE telemetry for this repository. Claude Code telemetry settings written by sce setup are removed by the next sce setup run after the global SCE config sets telemetry.enabled to false or auth.mode to disabled; repository-level opt-outs leave them in place."; #[allow(clippy::too_many_lines)] pub(super) fn format_show_output(runtime: &RuntimeConfig, report_format: ReportFormat) -> String { @@ -180,7 +181,10 @@ fn telemetry_policy_note(policy: &ResolvedAccessPolicy) -> Option<&'static str> policy .telemetry .disabled_reason() - .map(|_| TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE) + .map(|reason| match reason { + TelemetryDisabledReason::NotEnabled => TELEMETRY_NOT_ENABLED_NOTE, + _ => TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE, + }) } fn otel_fields(runtime: &RuntimeConfig) -> [(&'static str, &ResolvedValue); 5] { @@ -662,3 +666,55 @@ fn format_database_retry_json(value: &ResolvedOptionalValue "config_source": value.source.and_then(ValueSource::config_source).map(ConfigPathSource::as_str), }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::services::config::types::{AuthMode, TelemetryPolicyState}; + + fn policy_with(telemetry: TelemetryPolicyState) -> ResolvedAccessPolicy { + ResolvedAccessPolicy { + auth_mode: ResolvedValue { + value: AuthMode::Optional, + source: ValueSource::Default, + }, + telemetry_enabled: ResolvedValue { + value: false, + source: ValueSource::Default, + }, + telemetry, + background_cloud_allowed: true, + } + } + + #[test] + fn telemetry_note_points_at_repository_config_when_not_enabled() { + let policy = policy_with(TelemetryPolicyState::Disabled( + TelemetryDisabledReason::NotEnabled, + )); + + assert_eq!( + format_telemetry_policy_json(&policy)["note"], + json!(TELEMETRY_NOT_ENABLED_NOTE) + ); + assert!(TELEMETRY_NOT_ENABLED_NOTE.starts_with( + "Set telemetry.enabled: true in the repository SCE config to enable SCE telemetry for this repository." + )); + } + + #[test] + fn telemetry_note_keeps_claude_settings_note_for_opt_outs_and_is_absent_when_enabled() { + let opted_out = policy_with(TelemetryPolicyState::Disabled( + TelemetryDisabledReason::RepositoryOptOut, + )); + + assert_eq!( + telemetry_policy_note(&opted_out), + Some(TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE) + ); + assert_eq!( + telemetry_policy_note(&policy_with(TelemetryPolicyState::Enabled)), + None + ); + } +} diff --git a/cli/src/services/config/resolver.rs b/cli/src/services/config/resolver.rs index 1786e524f..bcc31e42d 100644 --- a/cli/src/services/config/resolver.rs +++ b/cli/src/services/config/resolver.rs @@ -39,7 +39,6 @@ pub(crate) const WORKOS_CLIENT_ID_KEY: AuthConfigKeySpec = AuthConfigKeySpec { const CONTROL_PLANE_BASE_URL_ENV: &str = "SCE_CONTROL_PLANE_BASE_URL"; const CONTROL_PLANE_BASE_URL_BAKED_DEFAULT: &str = "https://sce.crocoderlab.dev"; -pub(crate) const WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT: &str = "telemetry.enabled is true in the repository config but not in the user config; SCE telemetry stays disabled until the user config sets telemetry.enabled to true."; pub(crate) const WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED: &str = "telemetry.enabled is true but auth.mode resolves to disabled; SCE telemetry is disabled."; pub(crate) const WARNING_AUTO_SYNC_WITH_AUTH_DISABLED: &str = @@ -749,34 +748,18 @@ pub(super) fn resolve_access_policy( let auth_mode = resolve_effective_auth_mode(user, repository, explicit); let auth_disabled = auth_mode.value == AuthMode::Disabled; - let telemetry_enabled = match explicit - .telemetry_enabled - .as_ref() - .or(repository.telemetry_enabled.as_ref()) - .or(user.telemetry_enabled.as_ref()) - { - Some(value) => ResolvedValue { - value: value.value, - source: ValueSource::ConfigFile(value.source), - }, - None => ResolvedValue { - value: false, - source: ValueSource::Default, - }, - }; + let telemetry_enabled = resolve_telemetry_enabled(user, repository, explicit); let telemetry = if degraded { TelemetryPolicyState::Disabled(TelemetryDisabledReason::InvalidConfig) } else if auth_disabled { TelemetryPolicyState::Disabled(TelemetryDisabledReason::AuthDisabled) - } else if user_telemetry_opt_out(user, explicit) { + } else if user.telemetry() == Some(false) || explicit.telemetry() == Some(false) { TelemetryPolicyState::Disabled(TelemetryDisabledReason::UserOptOut) } else if repository.telemetry() == Some(false) { TelemetryPolicyState::Disabled(TelemetryDisabledReason::RepositoryOptOut) - } else if user_telemetry_consent(user, explicit) { + } else if telemetry_enabled.value { TelemetryPolicyState::Enabled - } else if repository.telemetry() == Some(true) { - TelemetryPolicyState::Disabled(TelemetryDisabledReason::NoUserConsent) } else { TelemetryPolicyState::Disabled(TelemetryDisabledReason::NotEnabled) }; @@ -789,12 +772,29 @@ pub(super) fn resolve_access_policy( } } -fn user_telemetry_opt_out(user: &AccessPolicyLayer, explicit: &AccessPolicyLayer) -> bool { - user.telemetry() == Some(false) || explicit.telemetry() == Some(false) -} - -fn user_telemetry_consent(user: &AccessPolicyLayer, explicit: &AccessPolicyLayer) -> bool { - user.telemetry() == Some(true) || explicit.telemetry() == Some(true) +fn resolve_telemetry_enabled( + user: &AccessPolicyLayer, + repository: &AccessPolicyLayer, + explicit: &AccessPolicyLayer, +) -> ResolvedValue { + let opt_out = [explicit, user, repository] + .into_iter() + .filter_map(|layer| layer.telemetry_enabled.as_ref()) + .find(|value| !value.value); + let consent = [explicit, repository, user] + .into_iter() + .filter_map(|layer| layer.telemetry_enabled.as_ref()) + .find(|value| value.value); + match opt_out.or(consent) { + Some(value) => ResolvedValue { + value: value.value, + source: ValueSource::ConfigFile(value.source), + }, + None => ResolvedValue { + value: false, + source: ValueSource::Default, + }, + } } fn build_access_policy_warnings( @@ -808,9 +808,6 @@ fn build_access_policy_warnings( let auth_disabled = policy.auth_mode.value == AuthMode::Disabled; let layers = [user, repository, explicit]; let mut warnings = Vec::new(); - if repository.telemetry() == Some(true) && !user_telemetry_consent(user, explicit) { - warnings.push(WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT.to_string()); - } if auth_disabled && layers.iter().any(|layer| layer.telemetry() == Some(true)) { warnings.push(WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED.to_string()); } @@ -1416,4 +1413,146 @@ mod tests { Some(ValueSource::Env) ); } + + fn access_layer( + auth_mode: Option, + telemetry_enabled: Option, + source: ConfigPathSource, + ) -> AccessPolicyLayer { + AccessPolicyLayer { + auth_mode: auth_mode.map(|value| schema::FileConfigValue { value, source }), + telemetry_enabled: telemetry_enabled + .map(|value| schema::FileConfigValue { value, source }), + } + } + + fn telemetry_layers( + user: Option, + repository: Option, + explicit: Option, + ) -> [AccessPolicyLayer; 3] { + [ + access_layer(None, user, ConfigPathSource::DefaultDiscoveredGlobal), + access_layer(None, repository, ConfigPathSource::DefaultDiscoveredLocal), + access_layer(None, explicit, ConfigPathSource::Flag), + ] + } + + fn repository_config_exists(path: &Path) -> bool { + path == Path::new("/tmp/repo/.git") || path == Path::new("/tmp/repo/.sce/config.json") + } + + #[test] + fn repository_telemetry_true_alone_enables_telemetry() { + let [user, repository, explicit] = telemetry_layers(None, Some(true), None); + + let policy = resolve_access_policy(&user, &repository, &explicit, false); + + assert_eq!(policy.telemetry, TelemetryPolicyState::Enabled); + assert_eq!( + policy.telemetry_enabled, + ResolvedValue { + value: true, + source: ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal), + } + ); + assert!( + build_access_policy_warnings(&user, &repository, &explicit, &policy, false, false) + .is_empty() + ); + } + + #[test] + fn any_telemetry_false_disables_telemetry_with_layer_reason() { + let cases = [ + ( + telemetry_layers(Some(false), Some(true), None), + TelemetryDisabledReason::UserOptOut, + ConfigPathSource::DefaultDiscoveredGlobal, + ), + ( + telemetry_layers(None, Some(true), Some(false)), + TelemetryDisabledReason::UserOptOut, + ConfigPathSource::Flag, + ), + ( + telemetry_layers(Some(true), Some(false), None), + TelemetryDisabledReason::RepositoryOptOut, + ConfigPathSource::DefaultDiscoveredLocal, + ), + ]; + + for ([user, repository, explicit], reason, source) in cases { + let policy = resolve_access_policy(&user, &repository, &explicit, false); + + assert_eq!(policy.telemetry, TelemetryPolicyState::Disabled(reason)); + assert_eq!( + policy.telemetry_enabled, + ResolvedValue { + value: false, + source: ValueSource::ConfigFile(source), + } + ); + } + } + + #[test] + fn telemetry_without_any_value_is_not_enabled() { + let [user, repository, explicit] = telemetry_layers(None, None, None); + + let policy = resolve_access_policy(&user, &repository, &explicit, false); + + assert_eq!( + policy.telemetry, + TelemetryPolicyState::Disabled(TelemetryDisabledReason::NotEnabled) + ); + assert_eq!(policy.telemetry_enabled.source, ValueSource::Default); + } + + #[test] + fn auth_disabled_and_degraded_config_still_disable_repository_consent() { + let user = access_layer( + Some(AuthMode::Disabled), + None, + ConfigPathSource::DefaultDiscoveredGlobal, + ); + let repository = access_layer(None, Some(true), ConfigPathSource::DefaultDiscoveredLocal); + let explicit = AccessPolicyLayer::default(); + + let policy = resolve_access_policy(&user, &repository, &explicit, false); + assert_eq!( + policy.telemetry, + TelemetryPolicyState::Disabled(TelemetryDisabledReason::AuthDisabled) + ); + assert_eq!( + build_access_policy_warnings(&user, &repository, &explicit, &policy, false, false), + vec![WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED.to_string()] + ); + + let policy = + resolve_access_policy(&AccessPolicyLayer::default(), &repository, &explicit, true); + assert_eq!( + policy.telemetry, + TelemetryPolicyState::Disabled(TelemetryDisabledReason::InvalidConfig) + ); + } + + #[test] + fn repository_config_telemetry_true_resolves_enabled_runtime_policy() { + let runtime = resolve_runtime_config_with( + &empty_request(), + Path::new("/tmp/repo"), + |_| None, + |_| Ok(r#"{"telemetry":{"enabled":true}}"#.to_string()), + repository_config_exists, + || Ok(PathBuf::from("/tmp/missing-global-sce-config.json")), + ) + .unwrap(); + + assert_eq!( + runtime.access_policy.telemetry, + TelemetryPolicyState::Enabled + ); + assert!(runtime.validation_warnings.is_empty()); + } } diff --git a/cli/src/services/config/types.rs b/cli/src/services/config/types.rs index 210272acb..46bc5fb52 100644 --- a/cli/src/services/config/types.rs +++ b/cli/src/services/config/types.rs @@ -158,7 +158,6 @@ impl TelemetryPolicyState { pub(crate) enum TelemetryDisabledReason { NotEnabled, UserOptOut, - NoUserConsent, RepositoryOptOut, AuthDisabled, InvalidConfig, @@ -169,7 +168,6 @@ impl TelemetryDisabledReason { match self { Self::NotEnabled => "not_enabled", Self::UserOptOut => "user_opt_out", - Self::NoUserConsent => "no_user_consent", Self::RepositoryOptOut => "repository_opt_out", Self::AuthDisabled => "auth_disabled", Self::InvalidConfig => "invalid_config", diff --git a/cli/src/services/doctor/access.rs b/cli/src/services/doctor/access.rs new file mode 100644 index 000000000..3132cac8c --- /dev/null +++ b/cli/src/services/doctor/access.rs @@ -0,0 +1,155 @@ +use std::future::Future; + +use serde_json::{json, Value}; + +use crate::services::config::{ + AuthMode, ConfigPathSource, ResolvedAccessPolicy, TelemetryDisabledReason, + TelemetryPolicyState, ValueSource, +}; + +use super::types::{ + DoctorProblem, ProblemCategory, ProblemFixability, ProblemKind, ProblemSeverity, +}; + +pub(super) const LOGIN_REMEDIATION: &str = "Run 'sce auth login'."; +const NEXT_ACTION_AUTH_LOGIN: &str = "auth_login"; +const LOGIN_STATE_NOT_REQUIRED: &str = "not_required"; +const LOGIN_STATE_LOGGED_IN: &str = "logged_in"; +const LOGIN_STATE_NOT_LOGGED_IN: &str = "not_logged_in"; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum LoginState { + NotRequired, + LoggedIn, + NotLoggedIn, +} + +impl LoginState { + fn as_str(self) -> &'static str { + match self { + Self::NotRequired => LOGIN_STATE_NOT_REQUIRED, + Self::LoggedIn => LOGIN_STATE_LOGGED_IN, + Self::NotLoggedIn => LOGIN_STATE_NOT_LOGGED_IN, + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) struct DoctorAccess { + pub(super) auth_mode: AuthMode, + pub(super) auth_mode_source: ValueSource, + pub(super) telemetry: TelemetryPolicyState, + pub(super) telemetry_source: Option, + pub(super) login: LoginState, +} + +impl DoctorAccess { + pub(super) async fn inspect( + policy: Option<&ResolvedAccessPolicy>, + authorized: F, + ) -> Self + where + F: FnOnce() -> Fut, + Fut: Future, + { + let Some(policy) = policy else { + return Self { + auth_mode: AuthMode::Optional, + auth_mode_source: ValueSource::Default, + telemetry: TelemetryPolicyState::Disabled(TelemetryDisabledReason::InvalidConfig), + telemetry_source: None, + login: LoginState::NotRequired, + }; + }; + let login = if policy.auth_mode.value != AuthMode::Mandatory { + LoginState::NotRequired + } else if authorized().await { + LoginState::LoggedIn + } else { + LoginState::NotLoggedIn + }; + let telemetry_source = match policy.telemetry { + TelemetryPolicyState::Disabled(TelemetryDisabledReason::InvalidConfig) => None, + TelemetryPolicyState::Disabled(TelemetryDisabledReason::AuthDisabled) => { + Some(policy.auth_mode.source) + } + _ => Some(policy.telemetry_enabled.source), + }; + Self { + auth_mode: policy.auth_mode.value, + auth_mode_source: policy.auth_mode.source, + telemetry: policy.telemetry, + telemetry_source, + login, + } + } + + pub(super) fn telemetry_label(self) -> String { + match self.telemetry { + TelemetryPolicyState::Enabled => { + "Managed telemetry: enabled for this repository".to_string() + } + TelemetryPolicyState::Disabled(reason) => { + format!("Managed telemetry: disabled (reason: {})", reason.as_str()) + } + } + } + + pub(super) fn telemetry_source_label(self) -> Option<&'static str> { + self.telemetry_source.map(source_label) + } + + pub(super) fn login_problem(self) -> Option { + (self.login == LoginState::NotLoggedIn).then(|| DoctorProblem { + kind: ProblemKind::SceLoginRequired, + category: ProblemCategory::GlobalState, + severity: ProblemSeverity::Error, + fixability: ProblemFixability::ManualOnly, + summary: format!( + "auth.mode: mandatory is set in the {}, but no valid SCE login was found.", + source_label(self.auth_mode_source) + ), + remediation: LOGIN_REMEDIATION.to_string(), + next_action: NEXT_ACTION_AUTH_LOGIN, + scope: None, + mutation_scope_target: None, + }) + } + + pub(super) fn login_json(self) -> Value { + json!({ + "state": self.login.as_str(), + "auth_mode": self.auth_mode.as_str(), + "source": self.auth_mode_source.as_str(), + "config_source": self.auth_mode_source.config_source().map(ConfigPathSource::as_str), + }) + } + + pub(super) fn telemetry_policy_json(self) -> Value { + json!({ + "state": self.telemetry.as_str(), + "reason": self.telemetry.disabled_reason().map(TelemetryDisabledReason::as_str), + "source": self.telemetry_source.map(ValueSource::as_str), + "config_source": self + .telemetry_source + .and_then(ValueSource::config_source) + .map(ConfigPathSource::as_str), + }) + } +} + +fn source_label(source: ValueSource) -> &'static str { + match source { + ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal) => { + "repository SCE config (`.sce/config.json`)" + } + ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal) => "global SCE config", + ValueSource::ConfigFile(ConfigPathSource::Flag) => "SCE config file passed with `--config`", + ValueSource::ConfigFile(ConfigPathSource::Env) => { + "SCE config file named by `SCE_CONFIG_FILE`" + } + ValueSource::Flag => "command-line flag", + ValueSource::Env => "environment", + ValueSource::Default => "default", + } +} diff --git a/cli/src/services/doctor/managed_telemetry.rs b/cli/src/services/doctor/managed_telemetry.rs index 49a6a3c12..0b653eb85 100644 --- a/cli/src/services/doctor/managed_telemetry.rs +++ b/cli/src/services/doctor/managed_telemetry.rs @@ -5,6 +5,7 @@ use crate::services::managed_telemetry::{ ManagedTelemetryHealth, TelemetryFallbackReason, CREDENTIAL_LOOKUP_DEADLINE, }; +use super::access::DoctorAccess; use super::types::{ DoctorProblem, ProblemCategory, ProblemFixability, ProblemKind, ProblemSeverity, }; @@ -16,7 +17,7 @@ const STATE_DISABLED_BY_CONFIG: &str = "disabled_by_config"; const SEVERITY_WARNING: &str = "warning"; const NEXT_ACTION_AUTH_LOGIN: &str = "auth_login"; const NEXT_ACTION_MANUAL_STEPS: &str = "manual_steps"; -pub(super) const OPT_IN_NOTE: &str = "Managed telemetry export is off because telemetry.enabled is not true; set telemetry.enabled: true in the global SCE config to resume it."; +pub(super) const OPT_IN_NOTE: &str = "Managed telemetry export is off because telemetry.enabled is not true; set telemetry.enabled: true in the repository SCE config to enable it for this repository."; pub(super) const HOOK_IMPACT: &str = "Claude Code hooks continue working, but telemetry export is disabled."; const MACOS_INACCESSIBLE_SUMMARY: &str = @@ -161,7 +162,13 @@ pub(super) fn problem(health: ManagedTelemetryHealth) -> Option { }) } -pub(super) fn json(health: ManagedTelemetryHealth) -> Value { +pub(super) fn json(health: ManagedTelemetryHealth, access: DoctorAccess) -> Value { + let mut payload = health_json(health); + payload["policy"] = access.telemetry_policy_json(); + payload +} + +fn health_json(health: ManagedTelemetryHealth) -> Value { match (health, diagnostic(health)) { (_, Some(diagnostic)) => json!({ "state": STATE_DISABLED, diff --git a/cli/src/services/doctor/mod.rs b/cli/src/services/doctor/mod.rs index 5a56a7ccc..09adf42d3 100644 --- a/cli/src/services/doctor/mod.rs +++ b/cli/src/services/doctor/mod.rs @@ -5,7 +5,9 @@ use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use crate::app::{ContextWithRepoRoot, HasRepoRoot}; +use crate::services::auth_command; use crate::services::codex_hook_policy; +use crate::services::config::{ResolvedAccessPolicy, TelemetryPolicyState}; use crate::services::default_paths::{resolve_sce_default_locations, resolve_state_data_root}; use crate::services::lifecycle::{ lifecycle_providers, FixOutcome, HealthCategory, HealthFixability, HealthProblem, @@ -19,6 +21,7 @@ use crate::services::mutation_trace::runtime::{ use crate::services::output_format::OutputFormat; use crate::services::setup; +mod access; mod fixes; mod inspect; mod managed_telemetry; @@ -27,6 +30,7 @@ pub(crate) mod types; pub mod command; +use access::DoctorAccess; use fixes::build_manual_fix_results; use inspect::{ build_report_with_lifecycle_problems, finalize_mutation_scope_repair_results, @@ -63,11 +67,13 @@ struct DoctorDependencies<'a, G, S, C, P> { resolve_global_config_path: &'a C, probe_codex_hook_policy: &'a P, managed_telemetry: ManagedTelemetryHealth, + access: DoctorAccess, } struct DoctorExecution { report: HookDoctorReport, managed_telemetry: ManagedTelemetryHealth, + access: DoctorAccess, fix_results: Vec, ref_reconciliation: Option, ref_reconciliation_fix: Option, @@ -115,6 +121,11 @@ async fn execute_doctor_with_context( reconcile_seam: &impl std::ops::AsyncFn(&Path) -> ReconciliationFix, recommendation_seam: &impl Fn(&Path) -> Option, ) -> DoctorExecution { + let policy = access_policy_for(repository_root); + let access = DoctorAccess::inspect(policy.as_ref(), || { + auth_command::repository_telemetry_authorized(repository_root) + }) + .await; execute_doctor_with_lifecycle_providers( request, repository_root, @@ -127,9 +138,10 @@ async fn execute_doctor_with_context( }, probe_codex_hook_policy: &codex_hook_policy::probe_default, managed_telemetry: crate::services::managed_telemetry::inspect_health( - telemetry_enabled_for(repository_root), + access.telemetry == TelemetryPolicyState::Enabled, ) .await, + access, }, mutation_scope_seam, reconcile_seam, @@ -138,9 +150,10 @@ async fn execute_doctor_with_context( .await } -fn telemetry_enabled_for(repository_root: &Path) -> bool { +fn access_policy_for(repository_root: &Path) -> Option { crate::services::config::resolve_observability_runtime_config(repository_root) - .is_ok_and(|config| config.access_policy.telemetry_enabled()) + .ok() + .map(|config| config.access_policy) } async fn execute_doctor_with_lifecycle_providers( @@ -164,12 +177,14 @@ async fn execute_doctor_with_lifecycle_providers( ) -> DoctorExecution { let policy_readiness = (dependencies.probe_codex_hook_policy)(); let managed_telemetry = dependencies.managed_telemetry; + let access = dependencies.access; let providers = lifecycle_providers(true); let initial_problems = diagnose_lifecycle_providers(context, &providers).await; let initial_doctor_problems = initial_problems .iter() .map(|problem| problem.problem.clone()) + .chain(access.login_problem()) .chain(managed_telemetry::problem(managed_telemetry)) .collect::>(); let initial_report = build_report_with_lifecycle_problems( @@ -185,6 +200,7 @@ async fn execute_doctor_with_lifecycle_providers( return DoctorExecution { report: initial_report, managed_telemetry, + access, fix_results: Vec::new(), ref_reconciliation: recommendation_seam(repository_root), ref_reconciliation_fix: None, @@ -202,6 +218,7 @@ async fn execute_doctor_with_lifecycle_providers( let final_doctor_problems = final_problems .into_iter() .map(|problem| problem.problem) + .chain(access.login_problem()) .chain(managed_telemetry::problem(managed_telemetry)) .collect::>(); let final_report = build_report_with_lifecycle_problems( @@ -227,6 +244,7 @@ async fn execute_doctor_with_lifecycle_providers( DoctorExecution { report: final_report, managed_telemetry, + access, fix_results, ref_reconciliation: None, ref_reconciliation_fix: Some(reconciliation_fix), @@ -500,6 +518,7 @@ fn doctor_problem_kind(kind: HealthProblemKind) -> ProblemKind { HealthProblemKind::MutationScopeHealthBlocked => ProblemKind::MutationScopeHealthBlocked, HealthProblemKind::MutationScopeHealthInvalid => ProblemKind::MutationScopeHealthInvalid, HealthProblemKind::ManagedTelemetryUnavailable => ProblemKind::ManagedTelemetryUnavailable, + HealthProblemKind::SceLoginRequired => ProblemKind::SceLoginRequired, } } @@ -580,6 +599,7 @@ fn health_problem_kind(kind: ProblemKind) -> HealthProblemKind { ProblemKind::MutationScopeHealthBlocked => HealthProblemKind::MutationScopeHealthBlocked, ProblemKind::MutationScopeHealthInvalid => HealthProblemKind::MutationScopeHealthInvalid, ProblemKind::ManagedTelemetryUnavailable => HealthProblemKind::ManagedTelemetryUnavailable, + ProblemKind::SceLoginRequired => HealthProblemKind::SceLoginRequired, } } diff --git a/cli/src/services/doctor/render.rs b/cli/src/services/doctor/render.rs index 16146a9b6..d9bd16fc9 100644 --- a/cli/src/services/doctor/render.rs +++ b/cli/src/services/doctor/render.rs @@ -4,15 +4,17 @@ use serde_json::json; use crate::services::hooks::mutation_scope_health::MutationScopeHealthStatus; use crate::services::style::{heading, label, supports_color, value, OwoColorize}; +use super::access::{DoctorAccess, LoginState}; use super::types::{ fix_result_outcome, mutation_scope_health_status, mutation_scope_target_id, problem_category, - problem_fixability, problem_severity, DoctorDisplayDetail, DoctorDisplayNode, - DoctorDisplayNodeKind, DoctorDisplayStatus, HookContentState, HookDoctorReport, HookFileHealth, - HookPathSource, IntegrationArea, IntegrationChildHealth, IntegrationContentState, - IntegrationGroupHealth, IntegrationGroupKey, IntegrationTarget, MutationScopeHealthRow, - PostCommitAutoSyncState, ProblemKind, ProblemSeverity, Readiness, + problem_fixability, problem_kind, problem_severity, problem_target, DoctorDisplayDetail, + DoctorDisplayNode, DoctorDisplayNodeKind, DoctorDisplayStatus, HookContentState, + HookDoctorReport, HookFileHealth, HookPathSource, IntegrationArea, IntegrationChildHealth, + IntegrationContentState, IntegrationGroupHealth, IntegrationGroupKey, IntegrationTarget, + MutationScopeHealthRow, PostCommitAutoSyncState, ProblemKind, ProblemSeverity, Readiness, }; use super::{managed_telemetry, DoctorExecution, DoctorFormat, DoctorMode, DoctorRequest, NAME}; +use crate::services::config::{TelemetryDisabledReason, TelemetryPolicyState}; use crate::services::managed_telemetry::ManagedTelemetryHealth; use crate::services::mutation_trace::runtime::{ ReconciliationCounts, ReconciliationFix, ReconciliationRecommendation, StateWarning, @@ -31,7 +33,7 @@ pub(super) fn render_report(request: DoctorRequest, execution: &DoctorExecution) fn format_execution(execution: &DoctorExecution) -> String { let report = &execution.report; - let base_report = format_report(report, execution.managed_telemetry); + let base_report = format_report(report, execution.managed_telemetry, execution.access); let mut lines = base_report .lines() .map(ToOwned::to_owned) @@ -104,13 +106,18 @@ fn format_age(age_ms: i64) -> String { } } -fn format_report(report: &HookDoctorReport, managed_telemetry: ManagedTelemetryHealth) -> String { - format_report_with_color_policy(report, managed_telemetry, supports_color()) +fn format_report( + report: &HookDoctorReport, + managed_telemetry: ManagedTelemetryHealth, + access: DoctorAccess, +) -> String { + format_report_with_color_policy(report, managed_telemetry, access, supports_color()) } fn format_report_with_color_policy( report: &HookDoctorReport, managed_telemetry: ManagedTelemetryHealth, + access: DoctorAccess, color_enabled: bool, ) -> String { let blocking_problem_count = report @@ -130,7 +137,7 @@ fn format_report_with_color_policy( }); lines.push(format!("\n{}", heading("Environment"))); - for node in environment_nodes(report, managed_telemetry) { + for node in environment_nodes(report, managed_telemetry, access) { render_display_node(&mut lines, &node, color_enabled, 2, true); } @@ -256,6 +263,7 @@ fn format_human_text_row( fn environment_nodes( report: &HookDoctorReport, managed_telemetry: ManagedTelemetryHealth, + access: DoctorAccess, ) -> Vec { vec![ top_level_node( @@ -291,39 +299,62 @@ fn environment_nodes( ) }), ), - managed_telemetry_node(managed_telemetry), + sce_login_node(report, access), + managed_telemetry_node(managed_telemetry, access), ] } -fn managed_telemetry_node(health: ManagedTelemetryHealth) -> DoctorDisplayNode { - match (health, managed_telemetry::diagnostic(health)) { - (_, Some(diagnostic)) => top_level_node( - "Managed telemetry", - DoctorDisplayStatus::Warn, - vec![DoctorDisplayDetail::ManagedTelemetry { +fn sce_login_node(report: &HookDoctorReport, access: DoctorAccess) -> DoctorDisplayNode { + match access.login { + LoginState::NotRequired => top_level_node( + "SCE login (not required)", + DoctorDisplayStatus::Pass, + Vec::new(), + ), + LoginState::LoggedIn => top_level_node("SCE login", DoctorDisplayStatus::Pass, Vec::new()), + LoginState::NotLoggedIn => top_level_node( + "SCE login", + DoctorDisplayStatus::Fail, + problem_details(report, |kind| matches!(kind, ProblemKind::SceLoginRequired)), + ), + } +} + +fn managed_telemetry_node( + health: ManagedTelemetryHealth, + access: DoctorAccess, +) -> DoctorDisplayNode { + let label = access.telemetry_label(); + let mut details = access + .telemetry_source_label() + .map(DoctorDisplayDetail::Source) + .into_iter() + .collect::>(); + let (label, status) = match (health, managed_telemetry::diagnostic(health)) { + (_, Some(diagnostic)) => { + details.push(DoctorDisplayDetail::ManagedTelemetry { reason: diagnostic.reason, summary: diagnostic.summary, remediation: diagnostic.remediation, - }], - ), - (ManagedTelemetryHealth::Healthy, None) => { - top_level_node("Managed telemetry", DoctorDisplayStatus::Pass, Vec::new()) + }); + (label, DoctorDisplayStatus::Warn) } - (ManagedTelemetryHealth::Disabled(_), None) => top_level_node( - "Managed telemetry (not configured)", + (ManagedTelemetryHealth::Disabled(_), None) => ( + format!("{label} (not configured)"), DoctorDisplayStatus::Pass, - Vec::new(), ), - (ManagedTelemetryHealth::DisabledByConfig { auth_db_present }, None) => top_level_node( - "Managed telemetry (disabled by config)", - DoctorDisplayStatus::Pass, - if auth_db_present { - vec![DoctorDisplayDetail::Note(managed_telemetry::OPT_IN_NOTE)] - } else { - Vec::new() - }, - ), - } + (ManagedTelemetryHealth::DisabledByConfig { auth_db_present }, None) => { + if auth_db_present + && access.telemetry + == TelemetryPolicyState::Disabled(TelemetryDisabledReason::NotEnabled) + { + details.push(DoctorDisplayDetail::Note(managed_telemetry::OPT_IN_NOTE)); + } + (label, DoctorDisplayStatus::Pass) + } + (ManagedTelemetryHealth::Healthy, None) => (label, DoctorDisplayStatus::Pass), + }; + top_level_node(&label, status, details) } fn top_level_node( @@ -666,7 +697,10 @@ fn render_display_node( )); if !expand_unhealthy || node.status == DoctorDisplayStatus::Pass { for detail in &node.details { - if matches!(detail, DoctorDisplayDetail::Note(_)) { + if matches!( + detail, + DoctorDisplayDetail::Note(_) | DoctorDisplayDetail::Source(_) + ) { render_display_detail(lines, detail, indent + 2); } } @@ -752,6 +786,7 @@ fn render_display_detail(lines: &mut Vec, detail: &DoctorDisplayDetail, lines.extend(remediation.lines().map(|line| format!("{prefix}{line}"))); } DoctorDisplayDetail::Note(note) => lines.push(format!("{prefix}{note}")), + DoctorDisplayDetail::Source(source) => lines.push(format!("{prefix}Source: {source}")), } } @@ -963,17 +998,15 @@ fn render_report_json(execution: &DoctorExecution) -> Result { .hooks_directory .as_ref() .map(|path| path.display().to_string()), - "post_commit_auto_sync": { - "state": post_commit_auto_sync_state(report.post_commit_auto_sync.state), - "enabled": report.post_commit_auto_sync.enabled, - "source": report.post_commit_auto_sync.source, - "config_source": report.post_commit_auto_sync.config_source, - }, + "post_commit_auto_sync": post_commit_auto_sync_json(report), "config_paths": config_paths, "hooks": hooks, "mutation_scope_health": mutation_scope_health_json(&report.mutation_scope_health), - "managed_telemetry": managed_telemetry::json(execution.managed_telemetry), + "sce_login": execution.access.login_json(), + "managed_telemetry": managed_telemetry::json(execution.managed_telemetry, execution.access), "problems": report.problems.iter().map(|problem| json!({ + "kind": problem_kind(problem.kind), + "target": problem_target(problem), "category": problem_category(problem.category), "severity": problem_severity(problem.severity), "fixability": problem_fixability(problem.fixability), @@ -1001,6 +1034,15 @@ fn render_report_json(execution: &DoctorExecution) -> Result { serde_json::to_string_pretty(&payload).context("failed to serialize doctor report to JSON") } +fn post_commit_auto_sync_json(report: &HookDoctorReport) -> serde_json::Value { + json!({ + "state": post_commit_auto_sync_state(report.post_commit_auto_sync.state), + "enabled": report.post_commit_auto_sync.enabled, + "source": report.post_commit_auto_sync.source, + "config_source": report.post_commit_auto_sync.config_source, + }) +} + fn post_commit_auto_sync_state(state: PostCommitAutoSyncState) -> &'static str { match state { PostCommitAutoSyncState::Ready => "ready", @@ -1283,3 +1325,374 @@ mod reconciliation_render_tests { } } } + +#[cfg(test)] +mod access_render_tests { + use std::future::Future; + + use serde_json::json; + + use super::{managed_telemetry_node, render_display_node, sce_login_node}; + use crate::services::config::{ + AuthMode, ConfigPathSource, ResolvedAccessPolicy, ResolvedValue, TelemetryDisabledReason, + TelemetryPolicyState, ValueSource, + }; + use crate::services::doctor::access::{DoctorAccess, LoginState}; + use crate::services::doctor::managed_telemetry; + use crate::services::doctor::types::{ + DoctorDisplayNode, HookDoctorReport, HookPathSource, PostCommitAutoSyncHealth, + PostCommitAutoSyncState, ProblemSeverity, Readiness, + }; + use crate::services::doctor::DoctorMode; + use crate::services::managed_telemetry::ManagedTelemetryHealth; + + const REPOSITORY: ValueSource = + ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal); + const GLOBAL: ValueSource = ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal); + + fn policy( + auth_mode: AuthMode, + auth_source: ValueSource, + telemetry_enabled: ResolvedValue, + telemetry: TelemetryPolicyState, + ) -> ResolvedAccessPolicy { + ResolvedAccessPolicy { + auth_mode: ResolvedValue { + value: auth_mode, + source: auth_source, + }, + telemetry_enabled, + telemetry, + background_cloud_allowed: auth_mode != AuthMode::Disabled, + } + } + + fn telemetry_default() -> ResolvedValue { + ResolvedValue { + value: false, + source: ValueSource::Default, + } + } + + fn not_enabled() -> TelemetryPolicyState { + TelemetryPolicyState::Disabled(TelemetryDisabledReason::NotEnabled) + } + + fn inspect(policy: &ResolvedAccessPolicy, authorized: impl FnOnce() -> Fut) -> DoctorAccess + where + Fut: Future, + { + tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(DoctorAccess::inspect(Some(policy), authorized)) + } + + fn report(access: DoctorAccess) -> HookDoctorReport { + HookDoctorReport { + mode: DoctorMode::Diagnose, + readiness: Readiness::Ready, + state_root: None, + agent_trace_db: None, + repository_root: None, + hook_path_source: HookPathSource::Default, + hooks_directory: None, + post_commit_auto_sync: PostCommitAutoSyncHealth { + state: PostCommitAutoSyncState::NotApplicable, + enabled: false, + source: "default", + config_source: None, + }, + config_locations: Vec::new(), + hooks: Vec::new(), + integration_groups: Vec::new(), + integration_targets_absent: false, + mutation_scope_health: Vec::new(), + problems: access.login_problem().into_iter().collect(), + } + } + + fn render(node: &DoctorDisplayNode) -> Vec { + let mut lines = Vec::new(); + render_display_node(&mut lines, node, false, 2, true); + lines + } + + #[test] + fn mandatory_without_login_reports_blocking_sce_login_failure() { + let access = inspect( + &policy( + AuthMode::Mandatory, + REPOSITORY, + telemetry_default(), + not_enabled(), + ), + || async { false }, + ); + let report = report(access); + + assert_eq!(access.login, LoginState::NotLoggedIn); + assert_eq!(report.problems.len(), 1); + assert_eq!(report.problems[0].severity, ProblemSeverity::Error); + assert_eq!( + render(&sce_login_node(&report, access)), + vec![ + " [FAIL] SCE login", + " Problem: auth.mode: mandatory is set in the repository SCE config (`.sce/config.json`), but no valid SCE login was found.", + " Remediation: Run 'sce auth login'.", + ] + ); + assert_eq!( + access.login_json(), + json!({ + "state": "not_logged_in", + "auth_mode": "mandatory", + "source": "config_file", + "config_source": "default_discovered_local", + }) + ); + } + + #[test] + fn mandatory_with_login_passes_without_problem() { + let access = inspect( + &policy( + AuthMode::Mandatory, + GLOBAL, + telemetry_default(), + not_enabled(), + ), + || async { true }, + ); + let report = report(access); + + assert!(report.problems.is_empty()); + assert_eq!( + render(&sce_login_node(&report, access)), + vec![" [PASS] SCE login"] + ); + assert_eq!(access.login_json()["state"], "logged_in"); + } + + #[test] + fn non_mandatory_mode_skips_credential_lookup() { + let access = inspect( + &policy( + AuthMode::Optional, + ValueSource::Default, + telemetry_default(), + not_enabled(), + ), + || async { panic!("credential lookup must not run outside mandatory mode") }, + ); + let report = report(access); + + assert!(report.problems.is_empty()); + assert_eq!( + render(&sce_login_node(&report, access)), + vec![" [PASS] SCE login (not required)"] + ); + assert_eq!( + access.login_json(), + json!({ + "state": "not_required", + "auth_mode": "optional", + "source": "default", + "config_source": null, + }) + ); + } + + #[test] + fn repository_telemetry_consent_reports_enabled_state_and_source() { + let access = inspect( + &policy( + AuthMode::Optional, + ValueSource::Default, + ResolvedValue { + value: true, + source: REPOSITORY, + }, + TelemetryPolicyState::Enabled, + ), + || async { false }, + ); + + assert_eq!( + render(&managed_telemetry_node( + ManagedTelemetryHealth::Healthy, + access + )), + vec![ + " [PASS] Managed telemetry: enabled for this repository", + " Source: repository SCE config (`.sce/config.json`)", + ] + ); + assert_eq!( + managed_telemetry::json(ManagedTelemetryHealth::Healthy, access), + json!({ + "state": "healthy", + "reason": null, + "kind": null, + "severity": null, + "next_action": null, + "policy": { + "state": "enabled", + "reason": null, + "source": "config_file", + "config_source": "default_discovered_local", + }, + }) + ); + } + + #[test] + fn unconfigured_telemetry_reports_reason_and_repository_opt_in_note() { + let access = inspect( + &policy( + AuthMode::Optional, + ValueSource::Default, + telemetry_default(), + not_enabled(), + ), + || async { false }, + ); + let health = ManagedTelemetryHealth::DisabledByConfig { + auth_db_present: true, + }; + + assert_eq!( + render(&managed_telemetry_node(health, access)), + vec![ + " [PASS] Managed telemetry: disabled (reason: not_enabled)", + " Source: default", + " Managed telemetry export is off because telemetry.enabled is not true; set telemetry.enabled: true in the repository SCE config to enable it for this repository.", + ] + ); + assert_eq!( + managed_telemetry::json(health, access), + json!({ + "state": "disabled_by_config", + "reason": "disabled_by_config", + "kind": null, + "severity": null, + "next_action": null, + "policy": { + "state": "disabled", + "reason": "not_enabled", + "source": "default", + "config_source": null, + }, + }) + ); + } + + #[test] + fn user_opt_out_reports_deciding_layer_without_opt_in_note() { + let access = inspect( + &policy( + AuthMode::Optional, + ValueSource::Default, + ResolvedValue { + value: false, + source: GLOBAL, + }, + TelemetryPolicyState::Disabled(TelemetryDisabledReason::UserOptOut), + ), + || async { false }, + ); + let health = ManagedTelemetryHealth::DisabledByConfig { + auth_db_present: true, + }; + + assert_eq!( + render(&managed_telemetry_node(health, access)), + vec![ + " [PASS] Managed telemetry: disabled (reason: user_opt_out)", + " Source: global SCE config", + ] + ); + assert_eq!( + managed_telemetry::json(health, access)["policy"], + json!({ + "state": "disabled", + "reason": "user_opt_out", + "source": "config_file", + "config_source": "default_discovered_global", + }) + ); + } +} + +#[cfg(test)] +mod problem_json_tests { + use super::{problem_kind, problem_target}; + use crate::services::doctor::types::{ + DoctorProblem, IntegrationArea, IntegrationGroupKey, IntegrationTarget, ProblemCategory, + ProblemFixability, ProblemKind, ProblemSeverity, + }; + + fn problem( + kind: ProblemKind, + category: ProblemCategory, + scope: Option, + mutation_scope_target: Option, + ) -> DoctorProblem { + DoctorProblem { + kind, + category, + severity: ProblemSeverity::Error, + fixability: ProblemFixability::ManualOnly, + summary: String::new(), + remediation: String::new(), + next_action: "manual_steps", + scope, + mutation_scope_target, + } + } + + #[test] + fn problem_json_identifies_kind_and_claude_target_for_integration_scoped_problems() { + let missing = problem( + ProblemKind::ClaudeIntegrationFilesMissing, + ProblemCategory::RepoAssets, + Some(IntegrationGroupKey::new( + IntegrationTarget::ClaudeCode, + IntegrationArea::Skills, + )), + None, + ); + + assert_eq!( + problem_kind(missing.kind), + "claude_integration_files_missing" + ); + assert_eq!(problem_target(&missing), Some("claude")); + } + + #[test] + fn problem_json_uses_mutation_scope_target_when_no_integration_scope_exists() { + let blocked = problem( + ProblemKind::MutationScopeHealthBlocked, + ProblemCategory::MutationScopeHealth, + None, + Some(IntegrationTarget::ClaudeCode), + ); + + assert_eq!(problem_kind(blocked.kind), "mutation_scope_health_blocked"); + assert_eq!(problem_target(&blocked), Some("claude")); + } + + #[test] + fn problem_json_leaves_target_null_for_repository_wide_problems() { + let hook = problem( + ProblemKind::RequiredHookMissing, + ProblemCategory::HookRollout, + None, + None, + ); + + assert_eq!(problem_kind(hook.kind), "required_hook_missing"); + assert_eq!(problem_target(&hook), None); + } +} diff --git a/cli/src/services/doctor/types.rs b/cli/src/services/doctor/types.rs index 8ac9499cd..b10bc7067 100644 --- a/cli/src/services/doctor/types.rs +++ b/cli/src/services/doctor/types.rs @@ -284,6 +284,7 @@ pub(super) enum DoctorDisplayDetail { remediation: String, }, Note(&'static str), + Source(&'static str), } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -471,6 +472,7 @@ pub(crate) enum ProblemKind { MutationScopeHealthBlocked, MutationScopeHealthInvalid, ManagedTelemetryUnavailable, + SceLoginRequired, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -530,6 +532,59 @@ pub(super) fn mutation_scope_target_id(target: IntegrationTarget) -> &'static st } } +pub(super) fn problem_kind(kind: ProblemKind) -> &'static str { + match kind { + ProblemKind::GitUnavailable => "git_unavailable", + ProblemKind::BareRepository => "bare_repository", + ProblemKind::NotInsideGitRepository => "not_inside_git_repository", + ProblemKind::UnableToResolveGitHooksDirectory => "unable_to_resolve_git_hooks_directory", + ProblemKind::UnableToResolveStateRoot => "unable_to_resolve_state_root", + ProblemKind::GlobalConfigValidationFailed => "global_config_validation_failed", + ProblemKind::UnableToResolveGlobalConfigPath => "unable_to_resolve_global_config_path", + ProblemKind::LocalConfigValidationFailed => "local_config_validation_failed", + ProblemKind::HooksDirectoryMissing => "hooks_directory_missing", + ProblemKind::HooksPathNotDirectory => "hooks_path_not_directory", + ProblemKind::RequiredHookMissing => "required_hook_missing", + ProblemKind::HookNotExecutable => "hook_not_executable", + ProblemKind::HookContentStale => "hook_content_stale", + ProblemKind::NoIntegrationsInstalled => "no_integrations_installed", + ProblemKind::OpenCodeIntegrationFilesMissing => "opencode_integration_files_missing", + ProblemKind::OpenCodeIntegrationContentMismatch => "opencode_integration_content_mismatch", + ProblemKind::ClaudeIntegrationFilesMissing => "claude_integration_files_missing", + ProblemKind::ClaudeIntegrationContentMismatch => "claude_integration_content_mismatch", + ProblemKind::PiIntegrationFilesMissing => "pi_integration_files_missing", + ProblemKind::PiIntegrationContentMismatch => "pi_integration_content_mismatch", + ProblemKind::CodexIntegrationFilesMissing => "codex_integration_files_missing", + ProblemKind::CodexIntegrationContentMismatch => "codex_integration_content_mismatch", + ProblemKind::OpenCodePluginRegistryInvalid => "opencode_plugin_registry_invalid", + ProblemKind::OpenCodeAssetMissingOrInvalid => "opencode_asset_missing_or_invalid", + ProblemKind::HookReadFailed => "hook_read_failed", + ProblemKind::OpenCodeAssetReadFailed => "opencode_asset_read_failed", + ProblemKind::ClaudeAssetReadFailed => "claude_asset_read_failed", + ProblemKind::PiAssetReadFailed => "pi_asset_read_failed", + ProblemKind::CodexAssetReadFailed => "codex_asset_read_failed", + ProblemKind::CodexHookRegistrationMalformed => "codex_hook_registration_malformed", + ProblemKind::CodexHookRegistrationNotTrusted => "codex_hook_registration_not_trusted", + ProblemKind::CodexHookRegistrationPolicyBlocked => "codex_hook_registration_policy_blocked", + ProblemKind::CodexHookRegistrationPolicyUnknown => "codex_hook_registration_policy_unknown", + ProblemKind::AgentTraceDbConnectionFailed => "agent_trace_db_connection_failed", + ProblemKind::AgentTraceDbSchemaNotReady => "agent_trace_db_schema_not_ready", + ProblemKind::MutationScopeHealthRecovering => "mutation_scope_health_recovering", + ProblemKind::MutationScopeHealthBlocked => "mutation_scope_health_blocked", + ProblemKind::MutationScopeHealthInvalid => "mutation_scope_health_invalid", + ProblemKind::ManagedTelemetryUnavailable => "managed_telemetry_unavailable", + ProblemKind::SceLoginRequired => "sce_login_required", + } +} + +pub(super) fn problem_target(problem: &DoctorProblem) -> Option<&'static str> { + problem + .scope + .map(|scope| scope.target) + .or(problem.mutation_scope_target) + .map(mutation_scope_target_id) +} + pub(super) fn compute_readiness(problems: &[DoctorProblem]) -> Readiness { if problems .iter() diff --git a/cli/src/services/lifecycle.rs b/cli/src/services/lifecycle.rs index 20490aca9..a683f7d92 100644 --- a/cli/src/services/lifecycle.rs +++ b/cli/src/services/lifecycle.rs @@ -77,6 +77,7 @@ pub enum HealthProblemKind { MutationScopeHealthBlocked, MutationScopeHealthInvalid, ManagedTelemetryUnavailable, + SceLoginRequired, } #[derive(Clone, Debug, Eq, PartialEq)] diff --git a/cli/src/services/setup/access_preferences.rs b/cli/src/services/setup/access_preferences.rs index 690d9f02a..4f35b1a5d 100644 --- a/cli/src/services/setup/access_preferences.rs +++ b/cli/src/services/setup/access_preferences.rs @@ -18,7 +18,7 @@ const TELEMETRY_KEY: &str = "telemetry"; const TELEMETRY_ENABLED_KEY: &str = "enabled"; #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub(crate) enum GlobalAccessPreferences { +pub(crate) enum AccessPreferences { Missing, Valid { auth_mode: Option, @@ -28,35 +28,35 @@ pub(crate) enum GlobalAccessPreferences { } #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub(crate) enum GlobalWriteOutcome { +pub(crate) enum AccessWriteOutcome { Unchanged, Written, } #[derive(Debug)] -pub(crate) enum GlobalAccessPreferencesError { - InvalidGlobalConfig { path: PathBuf, reason: String }, +pub(crate) enum RepositoryAccessPreferencesError { + InvalidRepositoryConfig { path: PathBuf, reason: String }, ConcurrentModification { path: PathBuf }, SymlinkManaged { path: PathBuf }, Io(anyhow::Error), } -impl fmt::Display for GlobalAccessPreferencesError { +impl fmt::Display for RepositoryAccessPreferencesError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::InvalidGlobalConfig { path, reason } => write!( + Self::InvalidRepositoryConfig { path, reason } => write!( f, - "Global SCE config '{}' is invalid and was left unchanged: {reason}", + "Repository 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.", + "Repository 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).", + "Repository SCE config '{}' is a symlink and was left unchanged; SCE cannot modify a symlink-managed repository config. Update the file's source directly.", path.display() ), Self::Io(error) => write!(f, "{error:#}"), @@ -64,62 +64,143 @@ impl fmt::Display for GlobalAccessPreferencesError { } } -impl std::error::Error for GlobalAccessPreferencesError {} +impl std::error::Error for RepositoryAccessPreferencesError {} -pub(crate) fn read_global_access_preferences( - path: &Path, -) -> anyhow::Result { - let Some(bytes) = read_optional(path)? else { - return Ok(GlobalAccessPreferences::Missing); +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ConfigLayer { + Global, + Repository, +} + +impl ConfigLayer { + fn path_source(self) -> ConfigPathSource { + match self { + Self::Global => ConfigPathSource::DefaultDiscoveredGlobal, + Self::Repository => ConfigPathSource::DefaultDiscoveredLocal, + } + } + + fn label(self) -> &'static str { + match self { + Self::Global => "global SCE config", + Self::Repository => "repository SCE config", + } + } + + fn bootstrap_value(self) -> Value { + match self { + Self::Global => Value::Object(Map::from_iter([( + CONFIG_SCHEMA_DECLARATION_KEY.to_string(), + Value::String(sce_config_schema_url()), + )])), + Self::Repository => serde_json::from_str(&super::repo_local_config_bootstrap_payload()) + .expect("repo-local config bootstrap payload must be valid JSON"), + } + } +} + +#[derive(Debug)] +enum WriteFailure { + Invalid(String), + ConcurrentModification, + SymlinkManaged, + Io(anyhow::Error), +} + +pub(crate) fn read_global_access_preferences(path: &Path) -> anyhow::Result { + read_access_preferences(path, ConfigLayer::Global) +} + +pub(crate) fn read_repository_access_preferences(path: &Path) -> anyhow::Result { + read_access_preferences(path, ConfigLayer::Repository) +} + +fn read_access_preferences(path: &Path, layer: ConfigLayer) -> anyhow::Result { + let Some(bytes) = read_optional(path, layer)? else { + return Ok(AccessPreferences::Missing); }; let Ok(raw) = String::from_utf8(bytes) else { - return Ok(GlobalAccessPreferences::Invalid); + return Ok(AccessPreferences::Invalid); }; - let Ok(config) = parse_file_config(&raw, path, ConfigPathSource::DefaultDiscoveredGlobal) - else { - return Ok(GlobalAccessPreferences::Invalid); + let Ok(config) = parse_file_config(&raw, path, layer.path_source()) else { + return Ok(AccessPreferences::Invalid); }; - Ok(GlobalAccessPreferences::Valid { + Ok(AccessPreferences::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( +pub(crate) fn persist_repository_access_preferences( path: &Path, auth_mode: Option, telemetry_enabled: Option, -) -> Result { - persist_global_access_preferences_with(path, auth_mode, telemetry_enabled, read_optional) +) -> Result { + persist_repository_access_preferences_with(path, auth_mode, telemetry_enabled, |path| { + read_optional(path, ConfigLayer::Repository) + }) } -fn persist_global_access_preferences_with( +fn persist_repository_access_preferences_with( path: &Path, auth_mode: Option, telemetry_enabled: Option, reread: R, -) -> Result +) -> Result +where + R: FnOnce(&Path) -> anyhow::Result>>, +{ + persist_access_preferences_with( + path, + ConfigLayer::Repository, + auth_mode, + telemetry_enabled, + reread, + ) + .map_err(|failure| match failure { + WriteFailure::Invalid(reason) => { + RepositoryAccessPreferencesError::InvalidRepositoryConfig { + path: path.to_path_buf(), + reason, + } + } + WriteFailure::ConcurrentModification => { + RepositoryAccessPreferencesError::ConcurrentModification { + path: path.to_path_buf(), + } + } + WriteFailure::SymlinkManaged => RepositoryAccessPreferencesError::SymlinkManaged { + path: path.to_path_buf(), + }, + WriteFailure::Io(error) => RepositoryAccessPreferencesError::Io(error), + }) +} + +fn persist_access_preferences_with( + path: &Path, + layer: ConfigLayer, + 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); + return Ok(AccessWriteOutcome::Unchanged); } - let original = read_optional(path).map_err(GlobalAccessPreferencesError::Io)?; + let original = read_optional(path, layer).map_err(WriteFailure::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()), - )])), + Some(bytes) => parse_config(path, layer, bytes)?, + None => layer.bootstrap_value(), }; 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"))?; + .ok_or_else(|| WriteFailure::Invalid("expected a top-level JSON object".to_string()))?; if let Some(mode) = auth_mode { set_nested_value( object, @@ -138,38 +219,34 @@ where } if original.is_some() && updated_value == original_value { - return Ok(GlobalWriteOutcome::Unchanged); + return Ok(AccessWriteOutcome::Unchanged); } let mut serialized = serde_json::to_string_pretty(&updated_value) - .context("Failed to serialize global SCE config") - .map_err(GlobalAccessPreferencesError::Io)?; + .with_context(|| format!("Failed to serialize {}", layer.label())) + .map_err(WriteFailure::Io)?; serialized.push('\n'); - parse_file_config(&serialized, path, ConfigPathSource::DefaultDiscoveredGlobal) - .map_err(|error| invalid_global_config(path, &format!("{error:#}")))?; + parse_file_config(&serialized, path, layer.path_source()) + .map_err(|error| WriteFailure::Invalid(format!("{error:#}")))?; - let current = reread(path).map_err(GlobalAccessPreferencesError::Io)?; + let current = reread(path).map_err(WriteFailure::Io)?; if current != original { - return Err(GlobalAccessPreferencesError::ConcurrentModification { - path: path.to_path_buf(), - }); + return Err(WriteFailure::ConcurrentModification); } - if is_symlink(path).map_err(GlobalAccessPreferencesError::Io)? { - return Err(GlobalAccessPreferencesError::SymlinkManaged { - path: path.to_path_buf(), - }); + if is_symlink(path, layer).map_err(WriteFailure::Io)? { + return Err(WriteFailure::SymlinkManaged); } - write_atomically(path, serialized.as_bytes()).map_err(GlobalAccessPreferencesError::Io)?; - Ok(GlobalWriteOutcome::Written) + write_atomically(path, serialized.as_bytes()).map_err(WriteFailure::Io)?; + Ok(AccessWriteOutcome::Written) } -fn parse_global_config(path: &Path, bytes: &[u8]) -> Result { +fn parse_config(path: &Path, layer: ConfigLayer, 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())) + .map_err(|_| WriteFailure::Invalid("file is not valid UTF-8".to_string()))?; + parse_file_config(raw, path, layer.path_source()) + .map_err(|error| WriteFailure::Invalid(format!("{error:#}")))?; + serde_json::from_str(raw).map_err(|error| WriteFailure::Invalid(error.to_string())) } fn set_nested_value(object: &mut Map, section: &str, key: &str, value: Value) { @@ -184,27 +261,236 @@ fn set_nested_value(object: &mut Map, section: &str, key: &str, v } } -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 { +fn is_symlink(path: &Path, layer: ConfigLayer) -> 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())), + .with_context(|| format!("Failed to inspect {} '{}'", layer.label(), path.display())), } } -fn read_optional(path: &Path) -> anyhow::Result>> { +fn read_optional(path: &Path, layer: ConfigLayer) -> 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())), + .with_context(|| format!("Failed to read {} '{}'", layer.label(), path.display())), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn repository_config_path(dir: &Path) -> PathBuf { + dir.join(".sce").join("config.json") + } + + fn write_repository_config(path: &Path, value: &Value) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, serde_json::to_string_pretty(value).unwrap() + "\n").unwrap(); + } + + fn read_json(path: &Path) -> Value { + serde_json::from_slice(&fs::read(path).unwrap()).unwrap() + } + + #[test] + fn repository_writer_bootstraps_missing_file_with_only_explicit_answers() { + let dir = tempfile::tempdir().unwrap(); + let path = repository_config_path(dir.path()); + + let outcome = + persist_repository_access_preferences(&path, Some(AuthMode::Mandatory), None).unwrap(); + + assert_eq!(outcome, AccessWriteOutcome::Written); + let written = read_json(&path); + assert_eq!(written["auth"], json!({ "mode": "mandatory" })); + assert!(written.get("telemetry").is_none()); + assert_eq!(written["agent_trace"], json!({ "auto_sync": true })); + assert_eq!( + written["policies"], + json!({ "attribution_hooks": { "enabled": true } }) + ); + assert_eq!( + written[CONFIG_SCHEMA_DECLARATION_KEY], + json!(sce_config_schema_url()) + ); + assert_eq!( + read_repository_access_preferences(&path).unwrap(), + AccessPreferences::Valid { + auth_mode: Some(AuthMode::Mandatory), + telemetry_enabled: None, + } + ); + } + + #[test] + fn repository_writer_preserves_unrelated_keys_and_skips_no_op_writes() { + let dir = tempfile::tempdir().unwrap(); + let path = repository_config_path(dir.path()); + write_repository_config( + &path, + &json!({ + "$schema": sce_config_schema_url(), + "agent_trace": { "auto_sync": false }, + "auth": { "mode": "optional" }, + }), + ); + + let outcome = + persist_repository_access_preferences(&path, Some(AuthMode::Disabled), Some(true)) + .unwrap(); + + assert_eq!(outcome, AccessWriteOutcome::Written); + let written = read_json(&path); + assert_eq!(written["agent_trace"], json!({ "auto_sync": false })); + assert_eq!(written["auth"], json!({ "mode": "disabled" })); + assert_eq!(written["telemetry"], json!({ "enabled": true })); + + let before = fs::read(&path).unwrap(); + for (auth_mode, telemetry_enabled) in [ + (Some(AuthMode::Disabled), Some(true)), + (Some(AuthMode::Disabled), None), + (None, Some(true)), + (None, None), + ] { + assert_eq!( + persist_repository_access_preferences(&path, auth_mode, telemetry_enabled).unwrap(), + AccessWriteOutcome::Unchanged + ); + assert_eq!(fs::read(&path).unwrap(), before); + } + } + + #[test] + fn repository_writer_skips_missing_file_without_answers() { + let dir = tempfile::tempdir().unwrap(); + let path = repository_config_path(dir.path()); + + assert_eq!( + persist_repository_access_preferences(&path, None, None).unwrap(), + AccessWriteOutcome::Unchanged + ); + assert!(!path.exists()); + assert_eq!( + read_repository_access_preferences(&path).unwrap(), + AccessPreferences::Missing + ); + } + + #[test] + fn repository_writer_refuses_invalid_file_and_leaves_it_unchanged() { + let dir = tempfile::tempdir().unwrap(); + let path = repository_config_path(dir.path()); + for invalid in [ + b"{ not json".to_vec(), + b"{\"unknown_key\": true}\n".to_vec(), + vec![0xff, 0xfe], + ] { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, &invalid).unwrap(); + + let error = + persist_repository_access_preferences(&path, Some(AuthMode::Mandatory), Some(true)) + .unwrap_err(); + + assert!(matches!( + error, + RepositoryAccessPreferencesError::InvalidRepositoryConfig { .. } + )); + assert!(error.to_string().starts_with(&format!( + "Repository SCE config '{}' is invalid and was left unchanged: ", + path.display() + ))); + assert_eq!(fs::read(&path).unwrap(), invalid); + assert_eq!( + read_repository_access_preferences(&path).unwrap(), + AccessPreferences::Invalid + ); + } + } + + #[test] + fn repository_writer_refuses_concurrently_modified_file_and_leaves_it_unchanged() { + let dir = tempfile::tempdir().unwrap(); + let path = repository_config_path(dir.path()); + write_repository_config(&path, &json!({ "agent_trace": { "auto_sync": true } })); + let concurrent = b"{\"agent_trace\": {\"auto_sync\": false}}\n".to_vec(); + + let error = persist_repository_access_preferences_with( + &path, + Some(AuthMode::Mandatory), + None, + |path| { + fs::write(path, &concurrent).unwrap(); + Ok(Some(fs::read(path).unwrap())) + }, + ) + .unwrap_err(); + + assert_eq!( + error.to_string(), + format!( + "Repository SCE config '{}' changed while setup was updating it and was left unchanged.", + path.display() + ) + ); + assert_eq!(fs::read(&path).unwrap(), concurrent); + } + + #[cfg(unix)] + #[test] + fn repository_writer_refuses_symlinked_file_and_leaves_it_unchanged() { + use std::os::unix::fs::symlink; + + let dir = tempfile::tempdir().unwrap(); + let path = repository_config_path(dir.path()); + let target = dir.path().join("shared-config.json"); + write_repository_config(&target, &json!({ "agent_trace": { "auto_sync": true } })); + let target_before = fs::read(&target).unwrap(); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + symlink(&target, &path).unwrap(); + + let error = + persist_repository_access_preferences(&path, Some(AuthMode::Mandatory), Some(false)) + .unwrap_err(); + + assert!(matches!( + error, + RepositoryAccessPreferencesError::SymlinkManaged { .. } + )); + assert!(fs::symlink_metadata(&path) + .unwrap() + .file_type() + .is_symlink()); + assert_eq!(fs::read_link(&path).unwrap(), target); + assert_eq!(fs::read(&target).unwrap(), target_before); + } + + #[cfg(unix)] + #[test] + fn repository_writer_replaces_file_atomically_and_keeps_its_mode() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let path = repository_config_path(dir.path()); + write_repository_config(&path, &json!({ "agent_trace": { "auto_sync": true } })); + fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap(); + + persist_repository_access_preferences(&path, None, Some(true)).unwrap(); + + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o7777, + 0o640 + ); + let entries: Vec<_> = fs::read_dir(path.parent().unwrap()) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(entries, vec![std::ffi::OsString::from("config.json")]); + assert_eq!(read_json(&path)["telemetry"], json!({ "enabled": true })); } } diff --git a/cli/src/services/setup/command.rs b/cli/src/services/setup/command.rs index de70722dd..1d4d3b456 100644 --- a/cli/src/services/setup/command.rs +++ b/cli/src/services/setup/command.rs @@ -6,23 +6,25 @@ use anyhow::Context; use crate::app::ContextWithRepoRoot; use crate::services::auth_command::{self, AuthFormat, LoginReport}; use crate::services::config::{AuthMode, ResolvedAccessPolicy, ValueSource}; +use crate::services::default_paths::RepoPaths; use crate::services::error::{AuthPolicyConfigFile, CliError, UserError}; use crate::services::lifecycle::{ lifecycle_providers, RequiredHookInstallStatus, RequiredHooksInstallOutcome, }; use crate::services::setup::access_preferences::{ - persist_global_access_preferences, read_global_access_preferences, GlobalAccessPreferences, - GlobalAccessPreferencesError, GlobalWriteOutcome, + persist_repository_access_preferences, read_global_access_preferences, + read_repository_access_preferences, AccessPreferences, AccessWriteOutcome, + RepositoryAccessPreferencesError, }; use crate::services::setup::claude_telemetry::CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE; use crate::services::{config, managed_telemetry, setup}; const SCE_ACCESS_HEADING: &str = "SCE access:"; -const SAVED_ACCESS_SCOPE: &str = "applies to all repositories on this machine"; +const SAVED_ACCESS_SCOPE: &str = "applies only to this repository"; 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 = +const REPOSITORY_ACCESS_WRITE_REMEDIATION: &str = "No repository files were changed. Run 'sce config validate' to check the file, then rerun 'sce setup'."; +const REPOSITORY_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."; @@ -31,6 +33,7 @@ const SETUP_LOGIN_NOT_REQUESTED_LINE: &str = 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 SETUP_LOGIN_REMINDER_LINE: &str = "SCE login: required by auth.mode: mandatory for this repository; run 'sce auth login' if you are not logged in."; const RECONFIGURE_HINT_LINE: &str = "- Run 'sce setup --reconfigure' to change saved setup answers."; @@ -134,7 +137,7 @@ impl SetupCommand { let (removal_action, deferred_action) = split_pre_login_removal(claude_telemetry_action( - read_global_preferences(&access_save.global_config_path), + default_global_preferences(), policy.telemetry_enabled(), claude_telemetry_selected, true, @@ -149,7 +152,7 @@ impl SetupCommand { sections.push(render_setup_login_section(&login_status)); deferred_action } else { - non_interactive_claude_telemetry_action(&repository_root, claude_telemetry_selected) + non_interactive_followup(&repository_root, claude_telemetry_selected, &mut sections) }; sections.extend(render_claude_telemetry(deferred_telemetry_action).await); @@ -198,8 +201,6 @@ impl SetupCommand { }); } - 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( @@ -207,7 +208,6 @@ impl SetupCommand { repository_root, &setup::InquireSetupTargetPrompter, &optional_workflow_defaults, - &global_config_path, resolve_access_policy, auth_db_present, self.request.reconfigure, @@ -235,10 +235,10 @@ enum PreparedSetup { #[derive(Clone, Debug, Eq, PartialEq)] struct SetupAccessSave { - global_config_path: PathBuf, + repository_config_path: PathBuf, auth_mode: Option, telemetry_enabled: Option, - outcome: GlobalWriteOutcome, + outcome: AccessWriteOutcome, prompts_suppressed: bool, } @@ -259,7 +259,6 @@ 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, @@ -269,10 +268,11 @@ where 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 repository_config_path = RepoPaths::new(repository_root).sce_config_file(); + let repository_preferences = + read_repository_access_preferences(&repository_config_path).map_err(unexpected_failure)?; let persisted_confirmations = setup::persisted_setup_confirmations(repository_root) - .with_global_access_preferences(global_preferences); + .with_repository_access_preferences(repository_preferences); let dispatch = setup::resolve_setup_dispatch( setup::SetupMode::Interactive, @@ -297,7 +297,7 @@ where let access_save = SetupAccessSave { prompts_suppressed, - ..persist_setup_access_preferences(global_config_path, auth_mode, telemetry_enabled)? + ..persist_setup_access_preferences(&repository_config_path, auth_mode, telemetry_enabled)? }; Ok(InteractiveSetup::Ready { @@ -307,16 +307,16 @@ where } fn persist_setup_access_preferences( - global_config_path: &Path, + repository_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))?; + persist_repository_access_preferences(repository_config_path, auth_mode, telemetry_enabled) + .map_err(|source| repository_access_write_failure(repository_config_path, &source))?; Ok(SetupAccessSave { - global_config_path: global_config_path.to_path_buf(), + repository_config_path: repository_config_path.to_path_buf(), auth_mode, telemetry_enabled, outcome, @@ -324,17 +324,19 @@ fn persist_setup_access_preferences( }) } -fn global_access_write_failure( - global_config_path: &Path, - source: &GlobalAccessPreferencesError, +fn repository_access_write_failure( + repository_config_path: &Path, + source: &RepositoryAccessPreferencesError, ) -> CliError { let remediation = match source { - GlobalAccessPreferencesError::SymlinkManaged { .. } => GLOBAL_ACCESS_SYMLINK_REMEDIATION, - _ => GLOBAL_ACCESS_WRITE_REMEDIATION, + RepositoryAccessPreferencesError::SymlinkManaged { .. } => { + REPOSITORY_ACCESS_SYMLINK_REMEDIATION + } + _ => REPOSITORY_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() + "Failed to save SCE access preferences to the repository SCE config '{}'.\n{source}\n{remediation}", + repository_config_path.display() )) } @@ -390,6 +392,19 @@ fn setup_login_action( } } +fn non_interactive_login_reminder( + repository_root: &Path, + resolve_policy: R, +) -> Option<&'static str> +where + R: Fn(&Path) -> anyhow::Result, +{ + resolve_policy(repository_root) + .ok() + .filter(|policy| policy.auth_mode.value == AuthMode::Mandatory) + .map(|_| SETUP_LOGIN_REMINDER_LINE) +} + async fn run_setup_login_step( action: SetupLoginAction, login: L, @@ -440,7 +455,7 @@ fn render_setup_access_section( policy: &ResolvedAccessPolicy, auth_db_present: bool, ) -> String { - let global_config_path = access_save.global_config_path.display(); + let repository_config_path = access_save.repository_config_path.display(); let mut lines = vec![SCE_ACCESS_HEADING.to_string()]; let saved_values = [ @@ -451,15 +466,15 @@ fn render_setup_access_section( .telemetry_enabled .map(|enabled| ("telemetry.enabled", enabled.to_string())), ]; - if access_save.outcome == GlobalWriteOutcome::Written { + if access_save.outcome == AccessWriteOutcome::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})" + "- {key}: {saved} (saved to repository SCE config '{repository_config_path}'; {SAVED_ACCESS_SCOPE})" ) })); } else { lines.push(format!( - "- saved access preferences: unchanged (global SCE config '{global_config_path}')" + "- saved access preferences: unchanged (repository SCE config '{repository_config_path}')" )); } @@ -536,13 +551,13 @@ enum ClaudeTelemetryAction { SkipDisabled, } -fn global_consent_withdrawn(global: GlobalAccessPreferences) -> bool { +fn global_consent_withdrawn(global: AccessPreferences) -> bool { matches!( global, - GlobalAccessPreferences::Valid { + AccessPreferences::Valid { telemetry_enabled: Some(false), .. - } | GlobalAccessPreferences::Valid { + } | AccessPreferences::Valid { auth_mode: Some(AuthMode::Disabled), .. } @@ -550,7 +565,7 @@ fn global_consent_withdrawn(global: GlobalAccessPreferences) -> bool { } fn claude_telemetry_action( - global: GlobalAccessPreferences, + global: AccessPreferences, effective_enabled: bool, claude_selected: bool, interactive: bool, @@ -577,6 +592,17 @@ fn split_pre_login_removal( } } +fn non_interactive_followup( + repository_root: &Path, + claude_selected: bool, + sections: &mut Vec, +) -> Option { + sections.extend( + non_interactive_login_reminder(repository_root, resolve_access_policy).map(str::to_string), + ); + non_interactive_claude_telemetry_action(repository_root, claude_selected) +} + fn non_interactive_claude_telemetry_action( repository_root: &Path, claude_selected: bool, @@ -584,20 +610,23 @@ fn non_interactive_claude_telemetry_action( if !claude_selected { return None; } - let global = config::resolver::resolve_default_global_config_path() - .map_or(GlobalAccessPreferences::Invalid, |path| { - read_global_preferences(&path) - }); claude_telemetry_action( - global, + default_global_preferences(), effective_telemetry_enabled(repository_root), claude_selected, false, ) } -fn read_global_preferences(global_config_path: &Path) -> GlobalAccessPreferences { - read_global_access_preferences(global_config_path).unwrap_or(GlobalAccessPreferences::Invalid) +fn default_global_preferences() -> AccessPreferences { + config::resolver::resolve_default_global_config_path() + .map_or(AccessPreferences::Invalid, |path| { + read_global_preferences(&path) + }) +} + +fn read_global_preferences(global_config_path: &Path) -> AccessPreferences { + read_global_access_preferences(global_config_path).unwrap_or(AccessPreferences::Invalid) } fn effective_telemetry_enabled(repository_root: &Path) -> bool { @@ -777,6 +806,7 @@ mod tests { targets: Option>, auth_mode: Option, telemetry_consent: bool, + asked: std::cell::RefCell>, } impl FakePrompter { @@ -785,8 +815,21 @@ mod tests { targets, auth_mode: None, telemetry_consent: false, + asked: std::cell::RefCell::default(), } } + + fn answering(auth_mode: Option, telemetry_consent: bool) -> Self { + Self { + auth_mode, + telemetry_consent, + ..Self::with_targets(Some(Vec::new())) + } + } + + fn asked(&self) -> Vec { + self.asked.borrow().clone() + } } impl SetupTargetPrompter for FakePrompter { @@ -810,14 +853,21 @@ mod tests { } fn prompt_auth_mode(&self, default: AuthMode) -> Result> { + self.asked + .borrow_mut() + .push(format!("auth.mode={}", default.as_str())); Ok(Some(self.auth_mode.unwrap_or(default))) } - fn prompt_telemetry_consent(&self, _default: bool) -> Result> { + fn prompt_telemetry_consent(&self, default: bool) -> Result> { + self.asked + .borrow_mut() + .push(format!("telemetry.enabled={default}")); Ok(Some(self.telemetry_consent)) } fn prompt_login(&self) -> Result> { + self.asked.borrow_mut().push("login".to_string()); Ok(Some(false)) } } @@ -1045,7 +1095,7 @@ mod tests { fn claude_telemetry_action_follows_global_withdrawal_only() { use ClaudeTelemetryAction::{Install, Remove, SkipDisabled}; - let valid = |auth_mode, telemetry_enabled| GlobalAccessPreferences::Valid { + let valid = |auth_mode, telemetry_enabled| AccessPreferences::Valid { auth_mode, telemetry_enabled, }; @@ -1060,8 +1110,8 @@ mod tests { valid(Some(AuthMode::Optional), Some(true)), valid(Some(AuthMode::Mandatory), None), valid(None, None), - GlobalAccessPreferences::Missing, - GlobalAccessPreferences::Invalid, + AccessPreferences::Missing, + AccessPreferences::Invalid, ]; let modes = [(true, true), (true, false), (false, true), (false, false)]; @@ -1251,7 +1301,7 @@ mod tests { install_sce_claude_settings(&settings); let action = claude_telemetry_action( - GlobalAccessPreferences::Valid { + AccessPreferences::Valid { auth_mode: None, telemetry_enabled: Some(false), }, @@ -1317,5 +1367,331 @@ mod tests { fn policy(&self) -> ResolvedAccessPolicy { self.resolve_policy()(&self.repo).unwrap() } + + fn repo_config_path(&self) -> std::path::PathBuf { + self.repo.join(".sce").join("config.json") + } + + fn prepare( + &self, + prompter: &FakePrompter, + reconfigure: bool, + ) -> Result { + prepare_interactive_setup( + &self.repo, + prompter, + &[], + self.resolve_policy(), + false, + reconfigure, + ) + } + } + + fn ready_access_save(setup: InteractiveSetup) -> SetupAccessSave { + match setup { + InteractiveSetup::Ready { access_save, .. } => access_save, + InteractiveSetup::Cancelled => panic!("setup should not be cancelled"), + } + } + + #[test] + fn interactive_setup_saves_access_answers_to_repository_config_only() { + let fixture = AccessFixture::new(); + fixture.write_repo_config(r#"{"agent_trace":{"auto_sync":false}}"#); + let prompter = FakePrompter::answering(Some(AuthMode::Mandatory), true); + + let access_save = ready_access_save(fixture.prepare(&prompter, false).unwrap()); + + let written: Value = + serde_json::from_slice(&fs::read(fixture.repo_config_path()).unwrap()).unwrap(); + assert_eq!( + written["agent_trace"], + serde_json::json!({ "auto_sync": false }) + ); + assert_eq!(written["auth"], serde_json::json!({ "mode": "mandatory" })); + assert_eq!(written["telemetry"], serde_json::json!({ "enabled": true })); + assert!(!fixture.global.exists()); + + let (section, _) = + setup_access_report(&fixture.repo, &access_save, fixture.resolve_policy(), false) + .unwrap(); + let path = fixture.repo_config_path(); + let path = path.display(); + assert_eq!( + section, + format!( + "SCE access:\n\ + - auth.mode: mandatory (saved to repository SCE config '{path}'; applies only to this repository)\n\ + - telemetry.enabled: true (saved to repository SCE config '{path}'; applies only to this repository)\n\ + - effective auth.mode: mandatory (source: config_file, config_source: default_discovered_local)\n\ + - effective telemetry: enabled\n\ + {RECONFIGURE_HINT_LINE}" + ) + ); + + let rerun = FakePrompter::answering(Some(AuthMode::Optional), false); + let unchanged = ready_access_save(fixture.prepare(&rerun, false).unwrap()); + let (section, _) = + setup_access_report(&fixture.repo, &unchanged, fixture.resolve_policy(), false) + .unwrap(); + assert!(section.contains(&format!( + "- saved access preferences: unchanged (repository SCE config '{path}')" + ))); + assert!(section.ends_with(RECONFIGURE_HINT_LINE)); + } + + type PromptCase = ( + &'static str, + Option<&'static str>, + Option<&'static str>, + bool, + &'static [&'static str], + ); + + #[test] + fn interactive_setup_access_prompts_follow_repository_saved_answers() { + let cases: [PromptCase; 6] = [ + ( + "repository answers suppress prompts", + None, + Some(r#"{"auth":{"mode":"optional"},"telemetry":{"enabled":false}}"#), + false, + &["login"], + ), + ( + "global answers no longer suppress prompts", + Some(r#"{"auth":{"mode":"optional"},"telemetry":{"enabled":true}}"#), + None, + false, + &["auth.mode=optional", "telemetry.enabled=false", "login"], + ), + ( + "reconfigure defaults to repository answers", + Some(r#"{"auth":{"mode":"optional"},"telemetry":{"enabled":false}}"#), + Some(r#"{"auth":{"mode":"mandatory"},"telemetry":{"enabled":true}}"#), + true, + &["auth.mode=mandatory", "telemetry.enabled=true"], + ), + ( + "repository disabled is only a prompt default", + None, + Some(r#"{"auth":{"mode":"disabled"}}"#), + true, + &["auth.mode=disabled"], + ), + ( + "global disabled locks the access prompts", + Some(r#"{"auth":{"mode":"disabled"}}"#), + None, + true, + &[], + ), + ( + "global mandatory suppresses the login offer", + Some(r#"{"auth":{"mode":"mandatory"}}"#), + None, + false, + &["auth.mode=optional", "telemetry.enabled=false"], + ), + ]; + for (name, global_json, repo_json, reconfigure, expected) in cases { + let fixture = AccessFixture::new(); + if let Some(json) = global_json { + fs::write(&fixture.global, json).unwrap(); + } + if let Some(json) = repo_json { + fixture.write_repo_config(json); + } + let global_before = fs::read(&fixture.global).ok(); + let prompter = FakePrompter::answering(None, false); + + fixture.prepare(&prompter, reconfigure).unwrap(); + + assert_eq!(prompter.asked(), expected, "{name}"); + assert_eq!(fs::read(&fixture.global).ok(), global_before, "{name}"); + } + + let fixture = AccessFixture::new(); + let invalid = br#"{"unknown_key":true}"#; + fixture.write_repo_config(std::str::from_utf8(invalid).unwrap()); + let prompter = FakePrompter::answering(None, false); + let access_save = ready_access_save(fixture.prepare(&prompter, false).unwrap()); + assert_eq!(prompter.asked(), ["login"]); + assert_eq!(access_save.outcome, AccessWriteOutcome::Unchanged); + assert_eq!(fs::read(fixture.repo_config_path()).unwrap(), invalid); + } + + #[test] + fn setup_access_gate_locks_on_global_and_explicit_layers_only() { + for (name, layer, mode, auth_locked_by, mandatory_locked) in [ + ("repository disabled", "repository", "disabled", None, false), + ( + "repository mandatory", + "repository", + "mandatory", + None, + false, + ), + ( + "global disabled", + "global", + "disabled", + Some(AuthPolicyConfigFile::Global), + false, + ), + ("global mandatory", "global", "mandatory", None, true), + ( + "explicit disabled", + "explicit", + "disabled", + Some(AuthPolicyConfigFile::ConfigEnv), + false, + ), + ("explicit mandatory", "explicit", "mandatory", None, true), + ] { + let fixture = AccessFixture::new(); + let json = format!(r#"{{"auth":{{"mode":"{mode}"}}}}"#); + let explicit = fixture.global.with_file_name("explicit.json"); + match layer { + "repository" => fixture.write_repo_config(&json), + "global" => fs::write(&fixture.global, &json).unwrap(), + _ => fs::write(&explicit, &json).unwrap(), + } + let policy = config::resolver::resolve_auth_runtime_config_with( + &fixture.repo, + |key| { + (layer == "explicit" && key == "SCE_CONFIG_FILE") + .then(|| explicit.display().to_string()) + }, + |path| fs::read_to_string(path).map_err(anyhow::Error::from), + Path::exists, + || Ok(fixture.global.clone()), + ) + .unwrap() + .access_policy; + + let gate = SetupAccessGate::from_policy(&policy, false); + + assert_eq!(gate.auth_locked_by, auth_locked_by, "{name}"); + assert_eq!(gate.mandatory_locked, mandatory_locked, "{name}"); + } + } + + #[cfg(unix)] + #[test] + fn interactive_setup_aborts_before_install_when_repository_config_is_symlinked() { + let fixture = AccessFixture::new(); + let target = fixture.global.with_file_name("shared.json"); + fs::write(&target, r#"{"agent_trace":{"auto_sync":true}}"#).unwrap(); + let target_before = fs::read(&target).unwrap(); + fs::create_dir_all(fixture.repo.join(".sce")).unwrap(); + std::os::unix::fs::symlink(&target, fixture.repo_config_path()).unwrap(); + let prompter = FakePrompter::answering(Some(AuthMode::Mandatory), true); + + let error = fixture.prepare(&prompter, false).unwrap_err(); + + let path = fixture.repo_config_path(); + assert_eq!( + error.to_string(), + format!( + "Failed to save SCE access preferences to the repository SCE config '{0}'.\n\ + Repository SCE config '{0}' is a symlink and was left unchanged; SCE cannot modify a symlink-managed repository config. Update the file's source directly.\n\ + {REPOSITORY_ACCESS_SYMLINK_REMEDIATION}", + path.display() + ) + ); + assert_eq!(fs::read(&target).unwrap(), target_before); + assert!(!fixture.global.exists()); + let entries: Vec<_> = fs::read_dir(&fixture.repo) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(entries.len(), 2); + } + #[test] + fn non_interactive_setup_reminds_login_only_under_mandatory() { + let mandatory = r#"{"auth":{"mode":"mandatory"}}"#; + let cases = [ + ("repository mandatory", "repository", Some(mandatory), true), + ("global mandatory", "global", Some(mandatory), true), + ("explicit mandatory", "explicit", Some(mandatory), true), + ( + "repository optional", + "repository", + Some(r#"{"auth":{"mode":"optional"}}"#), + false, + ), + ( + "repository disabled", + "repository", + Some(r#"{"auth":{"mode":"disabled"}}"#), + false, + ), + ("default", "repository", None, false), + ]; + for (name, layer, json, reminded) in cases { + let fixture = AccessFixture::new(); + let explicit = fixture.global.with_file_name("explicit.json"); + if let Some(json) = json { + match layer { + "repository" => fixture.write_repo_config(json), + "global" => fs::write(&fixture.global, json).unwrap(), + _ => fs::write(&explicit, json).unwrap(), + } + } + let resolve_policy = |root: &Path| { + config::resolver::resolve_auth_runtime_config_with( + root, + |key| { + (layer == "explicit" && key == "SCE_CONFIG_FILE") + .then(|| explicit.display().to_string()) + }, + |path| fs::read_to_string(path).map_err(anyhow::Error::from), + Path::exists, + || Ok(fixture.global.clone()), + ) + .map(|config| config.access_policy) + }; + + assert_eq!( + non_interactive_login_reminder(&fixture.repo, resolve_policy), + reminded.then_some( + "SCE login: required by auth.mode: mandatory for this repository; run 'sce auth login' if you are not logged in." + ), + "{name}" + ); + let auth_files: Vec<_> = walk_files(fixture.repo.parent().unwrap()) + .into_iter() + .filter(|path| { + path.file_name() + .is_some_and(|name| name.to_string_lossy().starts_with("auth")) + }) + .collect(); + assert!(auth_files.is_empty(), "{name}: {auth_files:?}"); + } + } + + #[test] + fn non_interactive_setup_skips_login_reminder_when_policy_resolution_fails() { + assert_eq!( + non_interactive_login_reminder(Path::new("/nonexistent"), |_| { + Err(anyhow::anyhow!("resolution failed")) + }), + None + ); + } + + fn walk_files(root: &Path) -> Vec { + let mut files = Vec::new(); + for entry in fs::read_dir(root).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + files.extend(walk_files(&path)); + } else { + files.push(path); + } + } + files } } diff --git a/cli/src/services/setup/mod.rs b/cli/src/services/setup/mod.rs index 3f488443d..29b0de097 100644 --- a/cli/src/services/setup/mod.rs +++ b/cli/src/services/setup/mod.rs @@ -475,19 +475,19 @@ pub struct PersistedSetupConfirmations { pub attribution_hooks_enabled: Option, pub auth_mode: Option, pub telemetry_enabled: Option, - pub global_config_invalid: bool, + pub repository_config_invalid: bool, } impl PersistedSetupConfirmations { - pub(crate) fn with_global_access_preferences( + pub(crate) fn with_repository_access_preferences( self, - preferences: access_preferences::GlobalAccessPreferences, + preferences: access_preferences::AccessPreferences, ) -> Self { - use access_preferences::GlobalAccessPreferences; + use access_preferences::AccessPreferences; match preferences { - GlobalAccessPreferences::Missing => self, - GlobalAccessPreferences::Valid { + AccessPreferences::Missing => self, + AccessPreferences::Valid { auth_mode, telemetry_enabled, } => Self { @@ -495,8 +495,8 @@ impl PersistedSetupConfirmations { telemetry_enabled, ..self }, - GlobalAccessPreferences::Invalid => Self { - global_config_invalid: true, + AccessPreferences::Invalid => Self { + repository_config_invalid: true, ..self }, } @@ -528,13 +528,16 @@ 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); + .filter(|file| *file != AuthPolicyConfigFile::Repository); Self { auth_locked_by, mandatory_locked: policy.auth_mode.value == AuthMode::Mandatory - && policy.auth_mode.source - != ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal), + && !matches!( + policy.auth_mode.source, + ValueSource::Default + | ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal) + ), auth_db_present, } } @@ -1202,15 +1205,15 @@ where return Ok(Some(choices)); } - let global_writable = !persisted.global_config_invalid; + let repository_writable = !persisted.repository_config_invalid; - if global_writable && (reconfigure || persisted.auth_mode.is_none()) { + if repository_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 { + } else if repository_writable { choices.prompts_suppressed = true; } @@ -1228,7 +1231,7 @@ where return Ok(Some(choices)); } - if global_writable && (reconfigure || persisted.telemetry_enabled.is_none()) { + if repository_writable && (reconfigure || persisted.telemetry_enabled.is_none()) { let default = persisted .telemetry_enabled .unwrap_or(FIRST_RUN_TELEMETRY_CONSENT_DEFAULT); @@ -1236,7 +1239,7 @@ where return Ok(None); }; choices.telemetry_enabled = Some(consent); - } else if global_writable { + } else if repository_writable { choices.prompts_suppressed = true; } diff --git a/cli/src/services/setup/prompt.rs b/cli/src/services/setup/prompt.rs index a95f978ee..25ef51d2b 100644 --- a/cli/src/services/setup/prompt.rs +++ b/cli/src/services/setup/prompt.rs @@ -92,7 +92,7 @@ pub(super) fn prompt_attribution_hooks_enabled(default: bool) -> Result Math.round(a + (GRADIENT_RIGHT[i] - a) * t).toString(16).padStart(2, '0')).join('') + GRADIENT_LEFT.map((a, i) => Math.round(a + ((GRADIENT_RIGHT[i] ?? a) - a) * t).toString(16).padStart(2, '0')).join('') ) } +export const PULSE = ['#ff2d2d', '#e02424', '#b81c1c', '#8f1414', '#b81c1c', '#e02424'] as const +export const PULSE_INTERVAL_MS = 150 + +export const EXPECTED_SCE_VERSION = '__SCE_VERSION__' export const SITE = 'sce.crocoder.dev' +export const INSTALL_URL = `https://${SITE}/docs/getting-started#install-cli` export const FOOTER = `Visit ${SITE} to learn more.` export const LOADED = 'loaded.' +export const NOT_LOADED = 'not loaded.' +export const INSTALL_FOOTER = `Install sce ${EXPECTED_SCE_VERSION}: ` +export const SCE_MISSING = `CLI not found. Install sce ${EXPECTED_SCE_VERSION} from ${INSTALL_URL}` +export const LOGIN_REQUIRED = "Login required for this repository. Run 'sce auth login'." +export const VERSION_ARGV = ['sce', '--version'] as const +export const VERSION_TIMEOUT_MS = 5000 +export const DOCTOR_ARGV = ['sce', 'doctor', '--format', 'json'] as const + +type DoctorProblem = { + kind?: string + target?: string | null + summary?: string + remediation?: { text?: string } +} + +type DoctorHook = { + name?: string + exists?: boolean +} + +type DoctorReport = { + sce_login?: { state?: string } + hooks?: DoctorHook[] + problems?: DoctorProblem[] +} + +export const CLAUDE_ASSETS_STALE = "Claude SCE skills are outdated or modified. Run 'sce setup --claude' to update them." + +const CLAUDE_ASSET_KINDS = new Set([ + 'claude_integration_files_missing', + 'claude_integration_content_mismatch', + 'claude_asset_read_failed', +]) + +export function gitHooksMissing(names: readonly string[]): string { + return `Git hooks missing: ${names.join(', ')}. Run 'sce doctor --fix' to install them.` +} + +function parseDoctor(doctorJson: string): DoctorReport | undefined { + try { + const report = JSON.parse(doctorJson) + return report && typeof report === 'object' ? report : undefined + } catch { + return undefined + } +} + +export function loginRequired(doctorJson: string): boolean { + return parseDoctor(doctorJson)?.sce_login?.state === 'not_logged_in' +} + +function missingGitHookNames(report: DoctorReport): string[] { + if (!Array.isArray(report.hooks)) return [] + return report.hooks + .filter((hook) => hook && hook.exists === false && typeof hook.name === 'string') + .map((hook) => hook.name as string) +} + +export function problemNotices(doctorJson: string): string[] { + const report = parseDoctor(doctorJson) + if (!report) return [] + const missingHooks = missingGitHookNames(report) + const hookNotices = missingHooks.length > 0 ? [gitHooksMissing(missingHooks)] : [] + const claudeProblems = (Array.isArray(report.problems) ? report.problems : []).filter( + (problem) => problem && problem.target === 'claude', + ) + const assetNotices = claudeProblems.some((problem) => CLAUDE_ASSET_KINDS.has(problem.kind ?? '')) + ? [CLAUDE_ASSETS_STALE] + : [] + const otherNotices = claudeProblems + .filter((problem) => !CLAUDE_ASSET_KINDS.has(problem.kind ?? '') && problem.summary) + .map((problem) => [problem.summary, problem.remediation?.text].filter(Boolean).join(' ')) + return [...hookNotices, ...assetNotices, ...new Set(otherNotices)] +} + +function startPulse($: EngineInterface) { + if (pulseTimer || !missing || started) return + pulseTimer = $.clock.every(PULSE_INTERVAL_MS, () => { + pulseFrame = (pulseFrame + 1) % PULSE.length + $.ui.invalidate('ui.render') + }) +} + +function stopPulse() { + pulseTimer?.cancel() + pulseTimer = undefined + pulseFrame = 0 +} export function register(on: On) { + on('session.start', async ($, e, next) => { + const result = await next(e) + if (!e.isInteractive) return result + const probe = await $.process.run(VERSION_ARGV, { cwd: e.cwd, timeoutMs: VERSION_TIMEOUT_MS }).catch(() => undefined) + if (!probe) { + missing = true + startPulse($) + $.ui.invalidate('ui.render') + $.ui.log(SCE_MISSING) + return result + } + if (missing) { + missing = false + stopPulse() + $.ui.invalidate('ui.render') + } + const doctor = await $.process.run(DOCTOR_ARGV, { cwd: e.cwd }).catch(() => undefined) + if (!doctor) return result + if (loginRequired(doctor.stdout)) $.ui.log(LOGIN_REQUIRED) + for (const notice of problemNotices(doctor.stdout)) $.ui.log(notice) + return result + }) + on('prompt.submit', async ($, e, next) => { if (!started) { started = true + stopPulse() $.ui.invalidate('ui.render') } return next(e) @@ -39,6 +159,7 @@ export function register(on: On) { on('session.end', async ($, e, next) => { if (e.reason === 'clear' && started) { started = false + startPulse($) $.ui.invalidate('ui.render') } return next(e) @@ -48,6 +169,23 @@ export function register(on: On) { if (started || e.props.hasSurvey) return next(e) const { Box, Text, Link } = $.ui.resolve(e) const theirs = await next(e) + const status = missing + ? Text({ color: PULSE[pulseFrame], bold: true, children: ` ${NOT_LOADED}` }) + : Text({ color: 'cyan', children: ` ${LOADED}` }) + const footer = missing + ? Text({ + children: [ + INSTALL_FOOTER, + Text({ color: PULSE[pulseFrame], underline: true, children: Link({ href: INSTALL_URL, label: INSTALL_URL }) }), + ], + }) + : Text({ + children: [ + 'Visit ', + Text({ color: 'cyan', underline: true, children: Link({ href: `https://${SITE}`, label: SITE }) }), + ' to learn more.', + ], + }) const label = Box({ paddingLeft: 11, flexDirection: 'column', @@ -55,15 +193,9 @@ export function register(on: On) { ...ART.map((row, i) => { const art = Text({ children: [...row].map((ch, col) => (ch === ' ' ? ch : Text({ color: gradientColor(col), children: ch }))) }) if (i !== ART.length - 2) return art - return Box({ flexDirection: 'row', children: [art, Text({ color: 'cyan', children: ` ${LOADED}` })] }) - }), - Text({ - children: [ - 'Visit ', - Text({ color: 'cyan', underline: true, children: Link({ href: `https://${SITE}`, label: SITE }) }), - ' to learn more.', - ], + return Box({ flexDirection: 'row', children: [art, status] }) }), + footer, ], }) return Box({ flexDirection: 'column', children: [label, theirs] }) diff --git a/config/lib/sce-info/tests/login-notice.test.ts b/config/lib/sce-info/tests/login-notice.test.ts new file mode 100644 index 000000000..6c7505ae2 --- /dev/null +++ b/config/lib/sce-info/tests/login-notice.test.ts @@ -0,0 +1,77 @@ +import type { On } from 'claude-code' +import { expect, test } from 'claude-code/testing' +import { DOCTOR_ARGV, LOGIN_REQUIRED, VERSION_ARGV, VERSION_TIMEOUT_MS } from '../hooks/register' + +const START = { cwd: '/repo', surface: 'terminal', isInteractive: true } as const + +function answerDoctor(on: On, stdout: string, calls: unknown[] = []) { + on('process.run', ($, e) => { + calls.push(e) + const output = e.argv[1] === '--version' ? 'shared-context-engineering 0.0.0\n' : stdout + return { value: { exitCode: 0, stdout: output, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } } + }) +} + +function collectLog(on: On): string[] { + const lines: string[] = [] + on('ui.log', ($, e) => { + lines.push(e.text) + return { value: undefined } + }) + on('session.start', ($, e) => ({ cwd: e.cwd })) + return lines +} + +test('session start logs the login notice once when doctor reports not_logged_in', async ($, on) => { + const calls: unknown[] = [] + answerDoctor(on, JSON.stringify({ sce_login: { state: 'not_logged_in', auth_mode: 'mandatory' } }), calls) + const lines = collectLog(on) + await $.session.start(START) + expect(lines).toEqual([LOGIN_REQUIRED]) + expect(calls).toEqual([ + { argv: VERSION_ARGV, init: { cwd: '/repo', timeoutMs: VERSION_TIMEOUT_MS } }, + { argv: DOCTOR_ARGV, init: { cwd: '/repo' } }, + ]) +}) + +test('session start logs nothing when already logged in', async ($, on) => { + answerDoctor(on, JSON.stringify({ sce_login: { state: 'logged_in', auth_mode: 'mandatory' } })) + const lines = collectLog(on) + await $.session.start(START) + expect(lines).toEqual([]) +}) + +test('session start logs nothing when login is not mandatory', async ($, on) => { + answerDoctor(on, JSON.stringify({ sce_login: { state: 'not_required', auth_mode: 'optional' } })) + const lines = collectLog(on) + await $.session.start(START) + expect(lines).toEqual([]) +}) + +test('session start logs nothing when the doctor command cannot run', async ($, on) => { + on('process.run', ($, e) => { + if (e.argv[1] === '--version') { + return { value: { exitCode: 0, stdout: 'sce\n', stderr: '', isStdoutTruncated: false, isStderrTruncated: false } } + } + return { deny: 'doctor timed out' } + }) + const lines = collectLog(on) + await $.session.start(START) + expect(lines).toEqual([]) +}) + +test('session start logs nothing when doctor output is unusable', async ($, on) => { + answerDoctor(on, 'not json') + const lines = collectLog(on) + await $.session.start(START) + expect(lines).toEqual([]) +}) + +test('non-interactive sessions skip the notice', async ($, on) => { + const calls: unknown[] = [] + answerDoctor(on, JSON.stringify({ sce_login: { state: 'not_logged_in' } }), calls) + const lines = collectLog(on) + await $.session.start({ ...START, surface: null, isInteractive: false }) + expect(lines).toEqual([]) + expect(calls).toEqual([]) +}) diff --git a/config/lib/sce-info/tests/sce-splash.test.ts b/config/lib/sce-info/tests/sce-splash.test.ts index 98aa33855..7f8451518 100644 --- a/config/lib/sce-info/tests/sce-splash.test.ts +++ b/config/lib/sce-info/tests/sce-splash.test.ts @@ -3,7 +3,7 @@ import { expect, test } from 'claude-code/testing' import { ART, FOOTER, LOADED, SITE } from '../hooks/register' const BAND = { - plugin: 'sce-splash', + plugin: 'SCE', surface: 'terminal', component: 'AbovePrompt', props: { diff --git a/config/lib/sce-info/tests/sce-status.test.ts b/config/lib/sce-info/tests/sce-status.test.ts new file mode 100644 index 000000000..088a12de8 --- /dev/null +++ b/config/lib/sce-info/tests/sce-status.test.ts @@ -0,0 +1,215 @@ +import type { On } from 'claude-code' +import { expect, mock, test } from 'claude-code/testing' +import { + ART, + CLAUDE_ASSETS_STALE, + gitHooksMissing, + INSTALL_URL, + LOADED, + NOT_LOADED, + PULSE, + PULSE_INTERVAL_MS, + SCE_MISSING, + SITE, +} from '../hooks/register' + + +const START = { cwd: '/repo', surface: 'terminal', isInteractive: true } as const + +const BAND = { + plugin: 'SCE', + surface: 'terminal', + component: 'AbovePrompt', + props: { + hasSurvey: false, + isWorking: false, + maxRows: 20, + bodyColumns: 100, + scroll: { offset: 0, bodyRows: 20 }, + view: {}, + }, +} as const + +function sceMissing(on: On, calls: string[][] = []) { + on('process.run', ($, e) => { + calls.push([...e.argv]) + return { deny: 'spawn sce ENOENT' } + }) +} + +function doctorReports(on: On, report: unknown) { + on('process.run', ($, e) => { + const stdout = e.argv[1] === '--version' ? 'sce\n' : JSON.stringify(report) + return { value: { exitCode: 0, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } } + }) +} + +function collectLog(on: On): string[] { + const lines: string[] = [] + on('ui.log', ($, e) => { + lines.push(e.text) + return { value: undefined } + }) + on('session.start', ($, e) => ({ cwd: e.cwd })) + on('ui.render', { component: 'AbovePrompt' }, ($, e) => { + const { Text } = $.ui.resolve(e) + return Text({ children: 'beneath' }) + }) + return lines +} + +test('a missing sce CLI logs the install guidance and skips doctor', async ($, on) => { + const clock = mock.clock(on) + const calls: string[][] = [] + sceMissing(on, calls) + const lines = collectLog(on) + await $.session.start(START) + expect(lines).toEqual([SCE_MISSING]) + expect(SCE_MISSING).toContain('https://sce.crocoder.dev/docs/getting-started#install-cli') + expect(calls).toEqual([['sce', '--version']]) + await clock.advance(0) +}) + +test('a missing sce CLI turns the splash into a pulsing red "not loaded."', async ($, on) => { + const clock = mock.clock(on) + sceMissing(on) + collectLog(on) + await $.session.start(START) + const ui = await $.ui.mount(BAND) + + expect(await ui.find({ type: 'Text', text: ART[0] })).toBeDefined() + const loaded = await ui.findAll({ type: 'Text', text: ` ${LOADED}` }) + expect(loaded.map((node) => node.text)).toEqual([` ${NOT_LOADED}`]) + const links = await ui.findAll({ type: 'Link', text: SITE }) + expect(links.map((node) => node.props.href)).toEqual([INSTALL_URL]) + + const status = await ui.find({ type: 'Text', text: ` ${NOT_LOADED}` }) + expect(status?.props.color).toBe(PULSE[0]) + + await clock.advance(PULSE_INTERVAL_MS) + await ui.redraw() + expect((await ui.find({ type: 'Text', text: ` ${NOT_LOADED}` }))?.props.color).toBe(PULSE[1]) + + await clock.advance(PULSE_INTERVAL_MS * (PULSE.length - 1)) + await ui.redraw() + expect((await ui.find({ type: 'Text', text: ` ${NOT_LOADED}` }))?.props.color).toBe(PULSE[0]) +}) + +test('the pulse stops once the first prompt is sent', async ($, on) => { + const clock = mock.clock(on) + sceMissing(on) + collectLog(on) + on('prompt.submit', ($, e) => ({ text: e.text })) + await $.session.start(START) + const ui = await $.ui.mount(BAND) + await $.prompt.submit({ text: 'hello', wait: false, origin: { kind: 'composer' } }) + await clock.advance(PULSE_INTERVAL_MS * 3) + expect(await ui.find({ type: 'Text', text: ` ${NOT_LOADED}` })).toBeUndefined() + expect(await ui.find({ type: 'Text', text: 'beneath' })).toBeDefined() +}) + +const HOOK_PROBLEMS = ['pre-commit', 'commit-msg', 'post-commit'].map((name) => ({ + kind: 'required_hook_missing', + target: null, + category: 'hook_rollout', + summary: `Missing required hook '${name}'.`, + remediation: { next_action: 'doctor_fix', text: "Run 'sce doctor --fix'." }, +})) + +test('missing git hooks collapse into one notice listing every missing hook', async ($, on) => { + doctorReports(on, { + sce_login: { state: 'logged_in' }, + hooks: [ + { name: 'pre-commit', exists: false, state: 'missing' }, + { name: 'commit-msg', exists: true, state: 'ok' }, + { name: 'post-commit', exists: false, state: 'missing' }, + ], + problems: [HOOK_PROBLEMS[0], HOOK_PROBLEMS[2]], + }) + const lines = collectLog(on) + await $.session.start(START) + expect(lines).toEqual([gitHooksMissing(['pre-commit', 'post-commit'])]) + expect(lines[0]).toBe("Git hooks missing: pre-commit, post-commit. Run 'sce doctor --fix' to install them.") +}) + +test('git hooks that all exist produce no git hook notice', async ($, on) => { + doctorReports(on, { + sce_login: { state: 'logged_in' }, + hooks: [ + { name: 'pre-commit', exists: true, state: 'ok' }, + { name: 'commit-msg', exists: true, state: 'ok' }, + { name: 'post-commit', exists: true, state: 'ok' }, + ], + problems: [], + }) + const lines = collectLog(on) + await $.session.start(START) + expect(lines).toEqual([]) +}) + +test('doctor problems for Claude are shown; other targets are not', async ($, on) => { + doctorReports(on, { + sce_login: { state: 'logged_in' }, + hooks: [ + { name: 'pre-commit', exists: false, state: 'missing' }, + { name: 'commit-msg', exists: false, state: 'missing' }, + { name: 'post-commit', exists: false, state: 'missing' }, + ], + problems: [ + ...HOOK_PROBLEMS, + { + kind: 'claude_integration_files_missing', + target: 'claude', + category: 'repo_assets', + summary: 'ClaudeCode skills required file(s) are missing.', + remediation: { next_action: 'manual_steps', text: 'Reinstall repo-root Claude assets.' }, + }, + { + kind: 'claude_integration_content_mismatch', + target: 'claude', + category: 'repo_assets', + summary: 'ClaudeCode commands file(s) differ from the canonical embedded content.', + remediation: { next_action: 'manual_steps', text: 'Reinstall repo-root Claude assets.' }, + }, + { + kind: 'mutation_scope_health_blocked', + target: 'claude', + category: 'mutation_scope_health', + summary: 'Claude mutation scope is blocked.', + remediation: { next_action: 'doctor_fix', text: "Run 'sce doctor --fix'." }, + }, + { + kind: 'codex_hook_registration_not_trusted', + target: 'codex', + category: 'repo_assets', + summary: 'Codex has not trusted the hooks.', + remediation: { next_action: 'manual_steps', text: 'Trust them in Codex.' }, + }, + { + kind: 'sce_login_required', + target: null, + category: 'global_state', + summary: 'No valid SCE login was found.', + remediation: { next_action: 'auth_login', text: "Run 'sce auth login'." }, + }, + ], + }) + const lines = collectLog(on) + await $.session.start(START) + expect(lines).toEqual([ + gitHooksMissing(['pre-commit', 'commit-msg', 'post-commit']), + CLAUDE_ASSETS_STALE, + "Claude mutation scope is blocked. Run 'sce doctor --fix'.", + ]) + expect(CLAUDE_ASSETS_STALE).toBe("Claude SCE skills are outdated or modified. Run 'sce setup --claude' to update them.") +}) + +test('a healthy doctor report keeps the splash "loaded." and logs nothing', async ($, on) => { + doctorReports(on, { sce_login: { state: 'logged_in' }, problems: [] }) + const lines = collectLog(on) + await $.session.start(START) + const ui = await $.ui.mount(BAND) + expect(lines).toEqual([]) + expect(await ui.findAll({ type: 'Text', text: ` ${LOADED}` })).toHaveLength(1) + expect(await ui.find({ type: 'Text', text: ` ${NOT_LOADED}` })).toBeUndefined() +}) diff --git a/config/pkl/renderers/claude-content.pkl b/config/pkl/renderers/claude-content.pkl index 9b9408756..a987d9d1f 100644 --- a/config/pkl/renderers/claude-content.pkl +++ b/config/pkl/renderers/claude-content.pkl @@ -3,10 +3,12 @@ import "common.pkl" as common import "claude-metadata.pkl" as metadata import "workflow-composite.pkl" as workflowResults +local sceVersion = read("../../../.version").text.trim() + sceInfoRuntimeFiles = new Mapping { ["sce-info/.claude-plugin/plugin.json"] = read("../../lib/sce-info/.claude-plugin/plugin.json").text ["sce-info/hooks/hooks.json"] = read("../../lib/sce-info/hooks/hooks.json").text - ["sce-info/hooks/register.ts"] = read("../../lib/sce-info/hooks/register.ts").text + ["sce-info/hooks/register.ts"] = read("../../lib/sce-info/hooks/register.ts").text.replaceAll("__SCE_VERSION__", sceVersion) } local missingSceInstallMessage = "sce CLI not found. Install it from https://sce.crocoder.dev/docs/getting-started#install-cli" diff --git a/config/pkl/renderers/generation-contract-check.pkl b/config/pkl/renderers/generation-contract-check.pkl index 1e8edebf9..ecb7f58c5 100644 --- a/config/pkl/renderers/generation-contract-check.pkl +++ b/config/pkl/renderers/generation-contract-check.pkl @@ -61,20 +61,27 @@ hidden generatedArtifacts = new Mapping { } } +local sceInfoVersion = read("../../../.version").text.trim() + +local sceInfoRegisterSource = read("../../lib/sce-info/hooks/register.ts").text + local sceInfoExpectedSources = new Mapping { ["config/.claude/skills/sce-info/.claude-plugin/plugin.json"] = read("../../lib/sce-info/.claude-plugin/plugin.json").text ["config/.claude/skills/sce-info/hooks/hooks.json"] = read("../../lib/sce-info/hooks/hooks.json").text - ["config/.claude/skills/sce-info/hooks/register.ts"] = read("../../lib/sce-info/hooks/register.ts").text + ["config/.claude/skills/sce-info/hooks/register.ts"] = sceInfoRegisterSource.replaceAll("__SCE_VERSION__", sceInfoVersion) } local assertSceInfoRuntimeContract = (artifacts: Mapping) -> if ( sceInfoExpectedSources.every((path, source) -> artifacts.containsKey(path) && artifacts[path] == source) && artifacts.every((path, _) -> !path.contains("/sce-info/") || sceInfoExpectedSources.containsKey(path)) - && artifacts["config/.claude/skills/sce-info/.claude-plugin/plugin.json"].contains("\"name\": \"sce-splash\"") + && artifacts["config/.claude/skills/sce-info/.claude-plugin/plugin.json"].contains("\"name\": \"SCE\"") && artifacts["config/.claude/skills/sce-info/hooks/hooks.json"].contains("\"./register.ts\"") - ) "sce-info: exactly three unchanged Claude-only runtime assets; development files excluded" - else throw("sce-info runtime allowlist, source contents, or target isolation violated") + && sceInfoRegisterSource.contains("export const EXPECTED_SCE_VERSION = '__SCE_VERSION__'") + && artifacts["config/.claude/skills/sce-info/hooks/register.ts"].contains("export const EXPECTED_SCE_VERSION = '\(sceInfoVersion)'") + && !artifacts["config/.claude/skills/sce-info/hooks/register.ts"].contains("__SCE_VERSION__") + ) "sce-info: exactly three Claude-only runtime assets with the expected SCE version stamped; development files excluded" + else throw("sce-info runtime allowlist, source contents, version stamp, or target isolation violated") local assertCodexHookInvocationContract = (artifacts: Mapping) -> let (text = artifacts["config/.codex/hooks.json"]) diff --git a/context/architecture.md b/context/architecture.md index 1cac1bd2b..1a7d00c93 100644 --- a/context/architecture.md +++ b/context/architecture.md @@ -71,12 +71,12 @@ The repository includes a new placeholder Rust binary crate at `cli/`. - `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_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/setup/access_preferences.rs` owns setup's access preferences (`auth.mode`, `telemetry.enabled`): the repository-layer reader and atomic writer for `.sce/config.json` (`read_repository_access_preferences` / `persist_repository_access_preferences`, a guarded write over the shared temp-file-plus-rename helper in `setup/atomic_write.rs`), plus a read-only global reader used for the Claude telemetry removal check. `setup/command.rs` calls the writer after dispatch and before the target install, 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. - `cli/src/services/completion/mod.rs` defines completion parser/rendering contract (`parse_completion_request`, `render_completion`) with deterministic Bash/Zsh/Fish script output aligned to current parser-valid command/flag surfaces; `cli/src/services/completion/command.rs` owns the `CompletionCommand` payload used by the static `RuntimeCommand` enum. -- `cli/src/services/hooks/mod.rs` defines the current local hook runtime parsing/dispatch (`HookSubcommand`, `run_hooks_subcommand`), including the silent `claude-model-state` lifecycle intake delegated to `cli/src/services/hooks/claude_model_state.rs`, the hidden non-fail-open `mutation-scope` runtime ingress delegated to `cli/src/services/hooks/mutation_scope.rs` (STDIN normalized JSON → one `mutation_trace::runtime` `coordinate()` / `abandon_scope()` call with a lazy DB provider; see `context/cli/mutation-scope-hook-ingress.md`), the hidden non-fail-open `claude-mutation-scope` adapter delegated to `cli/src/services/hooks/claude_mutation_scope/` (STDIN raw Claude hook JSON → tool classification + identity/`ScopeId` derivation → the same `mutation_scope.rs` `pub(crate)` in-process seam, one mutation `ScopeId` per mutation-capable tool execution; registered by `sce setup`; see `context/cli/claude-mutation-scope-integration.md`), plus a commit-msg co-author policy seam (`apply_commit_msg_coauthor_policy`) that injects one canonical SCE trailer only when the enabled-by-default attribution-hooks config/env control is not opted out, `SCE_DISABLED` is false, and the staged-diff AI-overlap preflight confirms AI/editor evidence (`StagedDiffAiOverlapResult::Overlap`); the preflight is wired into `run_commit_msg_subcommand_in_repo` and logs `sce.hooks.commit_msg.ai_overlap_error` on error paths; `cli/src/services/hooks/command.rs` owns the `HooksCommand` payload used by the static `RuntimeCommand` enum. In the current attribution-only baseline, `pre-commit` and `post-rewrite` are deterministic no-op surfaces; `post-commit` requires validated `--remote-url`, threads that URL through the Agent Trace flow, prints it to stderr, and remains an active intersection + Agent Trace persistence entrypoint (captures current commit patch, queries recent repository-level `diff_traces` from the bounded past-7-days window, combines valid patches via `patch::combine_patches`, intersects with post-commit patch via `patch::intersect_patches`, persists the direct-only intersection metadata to `post_commit_patch_intersections`, then — for committed touched lines that direct intersection did not cover — resolves bounded, read-only mutation-history AI coverage scoped to the invoking worktree's existing identity (newest 128 events replayed oldest-to-newest as one causal tree-transition provenance lineage bounded by a worktree-lock-captured commit attribution cut — `revision <= latest_mutation_event_revision` read under the worktree lock — with a committed line attributed AI only if an AI event's line survives every later transition into the committed tree; no provenance, no `diff_traces` or mutation-cursor write) and passes direct and mutation-AI evidence separately into the Agent Trace builder, and persists the built Agent Trace payloads with range-level `content_hash` values to `agent_traces` in the repository-scoped Agent Trace DB without post-commit file artifacts); after successful validation and persistence, the setup-enabled config-file-only `agent_trace.auto_sync` gate launches one detached sync-owned `sync --format json` child when its resolved value is true (a newly created setup config supplies the explicit `true`; omitted configuration resolves to `false`), with launcher failures ignored and no high-frequency hook trigger; `diff-trace` performs STDIN JSON intake, validates required non-empty `sessionID`/`diff`/`tool_name`, optional `model_id` (absent/`null` → `None`), required nullable/non-empty `tool_version` plus required `u64` `time` (Unix epoch milliseconds), rejects values that cannot fit signed `time_ms` storage, prefixes the stored `diff_traces.session_id` before insert construction (`oc_` for OpenCode, `cc_` for Claude, `pi_` for Pi, same-tool idempotent), and inserts the parsed payload fields into `RepositoryAgentTraceDb` without creating a parsed-payload `context/tmp` artifact; Claude structured `PostToolUse` diff-trace intake resolves model attribution with `direct > exact transcript > exact session/agent state > bridge-derived chain state > NULL`: direct top-level or nested metadata wins, otherwise the event's `transcript_path` is scanned for the assistant envelope whose `tool_use.id` matches `tool_use_id`, then persistence performs one exact local `claude_model_state` lookup using canonical session and ephemeral agent scope. Only for a raw structured payload in the exact main-session scope, a state miss then resolves the newest `claude_model_state` observation across the transcript's bridge-linked chain members (bounded leading-record reads, one exact-scope read per member, winner by `observed_at_ms`) and, on a hit, writes a `claude_model_state` row for the current session (`source="bridge_inherited"`) before using that model — the only diff-trace resolution path that writes state. Model values normalize once through `claude/`, subagents do not inherit main-session state, and unresolved values remain nullable. `session-model` is no longer a supported hook route. +- `cli/src/services/hooks/mod.rs` defines the current local hook runtime parsing/dispatch (`HookSubcommand`, `run_hooks_subcommand`), including the `claude-model-state` lifecycle intake (silent) delegated to `cli/src/services/hooks/claude_model_state.rs`, the hidden non-fail-open `mutation-scope` runtime ingress delegated to `cli/src/services/hooks/mutation_scope.rs` (STDIN normalized JSON → one `mutation_trace::runtime` `coordinate()` / `abandon_scope()` call with a lazy DB provider; see `context/cli/mutation-scope-hook-ingress.md`), the hidden non-fail-open `claude-mutation-scope` adapter delegated to `cli/src/services/hooks/claude_mutation_scope/` (STDIN raw Claude hook JSON → tool classification + identity/`ScopeId` derivation → the same `mutation_scope.rs` `pub(crate)` in-process seam, one mutation `ScopeId` per mutation-capable tool execution; registered by `sce setup`; see `context/cli/claude-mutation-scope-integration.md`), plus a commit-msg co-author policy seam (`apply_commit_msg_coauthor_policy`) that injects one canonical SCE trailer only when the enabled-by-default attribution-hooks config/env control is not opted out, `SCE_DISABLED` is false, and the staged-diff AI-overlap preflight confirms AI/editor evidence (`StagedDiffAiOverlapResult::Overlap`); the preflight is wired into `run_commit_msg_subcommand_in_repo` and logs `sce.hooks.commit_msg.ai_overlap_error` on error paths; `cli/src/services/hooks/command.rs` owns the `HooksCommand` payload used by the static `RuntimeCommand` enum. In the current attribution-only baseline, `pre-commit` and `post-rewrite` are deterministic no-op surfaces; `post-commit` requires validated `--remote-url`, threads that URL through the Agent Trace flow, prints it to stderr, and remains an active intersection + Agent Trace persistence entrypoint (captures current commit patch, queries recent repository-level `diff_traces` from the bounded past-7-days window, combines valid patches via `patch::combine_patches`, intersects with post-commit patch via `patch::intersect_patches`, persists the direct-only intersection metadata to `post_commit_patch_intersections`, then — for committed touched lines that direct intersection did not cover — resolves bounded, read-only mutation-history AI coverage scoped to the invoking worktree's existing identity (newest 128 events replayed oldest-to-newest as one causal tree-transition provenance lineage bounded by a worktree-lock-captured commit attribution cut — `revision <= latest_mutation_event_revision` read under the worktree lock — with a committed line attributed AI only if an AI event's line survives every later transition into the committed tree; no provenance, no `diff_traces` or mutation-cursor write) and passes direct and mutation-AI evidence separately into the Agent Trace builder, and persists the built Agent Trace payloads with range-level `content_hash` values to `agent_traces` in the repository-scoped Agent Trace DB without post-commit file artifacts); after successful validation and persistence, the setup-enabled config-file-only `agent_trace.auto_sync` gate launches one detached sync-owned `sync --format json` child when its resolved value is true (a newly created setup config supplies the explicit `true`; omitted configuration resolves to `false`), with launcher failures ignored and no high-frequency hook trigger; `diff-trace` performs STDIN JSON intake, validates required non-empty `sessionID`/`diff`/`tool_name`, optional `model_id` (absent/`null` → `None`), required nullable/non-empty `tool_version` plus required `u64` `time` (Unix epoch milliseconds), rejects values that cannot fit signed `time_ms` storage, prefixes the stored `diff_traces.session_id` before insert construction (`oc_` for OpenCode, `cc_` for Claude, `pi_` for Pi, same-tool idempotent), and inserts the parsed payload fields into `RepositoryAgentTraceDb` without creating a parsed-payload `context/tmp` artifact; Claude structured `PostToolUse` diff-trace intake resolves model attribution with `direct > exact transcript > exact session/agent state > bridge-derived chain state > NULL`: direct top-level or nested metadata wins, otherwise the event's `transcript_path` is scanned for the assistant envelope whose `tool_use.id` matches `tool_use_id`, then persistence performs one exact local `claude_model_state` lookup using canonical session and ephemeral agent scope. Only for a raw structured payload in the exact main-session scope, a state miss then resolves the newest `claude_model_state` observation across the transcript's bridge-linked chain members (bounded leading-record reads, one exact-scope read per member, winner by `observed_at_ms`) and, on a hit, writes a `claude_model_state` row for the current session (`source="bridge_inherited"`) before using that model — the only diff-trace resolution path that writes state. Model values normalize once through `claude/`, subagents do not inherit main-session state, and unresolved values remain nullable. `session-model` is no longer a supported hook route. - Generated Claude settings register `SessionStart` and `PostModelSwitch` only for the local model-state hook; `sce hooks session-model` is no longer a supported hook command. Claude Code 2.1.250 and 2.1.251 compatibility smoke passed with the unknown `PostModelSwitch` registration, so SCE installs it unconditionally without a raised minimum or capability gate. The `session_models` table/API and generic session-level fallback lookup were removed in T02 of the `remove-session-models-direct-claude-model-id` plan; the separate `sce hooks claude-model-state` command writes Claude lifecycle observations into the non-exported exact-scope register through the no-migration hook-runtime DB path, without restoring that generic abstraction. `diff-trace` uses direct-first/event-transcript-second Claude `model_id` resolution and consults the exact local lifecycle state only as its final fallback, with direct `tool_version` values. - `cli/src/services/resilience.rs` defines bounded retry/timeout/backoff execution policy (`RetryPolicy`, `run_with_retry`) for transient operation hardening with deterministic failure messaging and retry observability. - `context/cli/agent-trace-auto-sync.md` documents the sync-owned, one-shot post-commit launcher boundary: it reuses `sce sync`, has no daemon or local retry machinery, and fails open when child startup cannot be completed; doctor reports this capability without invoking the launcher. diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md index 4c7584084..dc151cc1f 100644 --- a/context/cli/access-policy.md +++ b/context/cli/access-policy.md @@ -2,9 +2,9 @@ ## Scope -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). +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); its user-side-only consent rule is superseded by [ADR: repository telemetry.enabled grants consent](../decisions/2026-10-22-repository-telemetry-enabled-grants-consent.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)). Interactive `sce setup` is the writer for the user layer's access keys (see [Setup](#setup)). +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`, post-commit auto-sync, and the Claude `SessionStart` login notice enforce the policy (see [Enforcement](#enforcement)). Interactive `sce setup` is the writer for the repository layer's access keys (see [Setup](#setup)). ## Terms @@ -13,15 +13,15 @@ Status: the resolver computes and exposes the policy, and `sce config show` / `v - **User layer:** the `DefaultDiscoveredGlobal` file. - **Repository layer:** the `DefaultDiscoveredLocal` file, `.sce/config.json` at the enclosing Git worktree root (see [Repository discovery](#repository-discovery)). - **Explicit layer:** the single file selected with `--config` (`Flag`) or `SCE_CONFIG_FILE` (`Env`). It is loaded in addition to the discovered files, never instead of them. - - **User side:** the user layer and the explicit layer together. Only the user side can grant telemetry consent. + - **User side:** the user layer and the explicit layer together. A user-side `false` is a `user_opt_out`. Any layer, including the repository layer, can grant telemetry consent. - Neither key has an environment-variable or CLI-flag layer of its own. - **Effective access policy** (`ResolvedAccessPolicy`), with these fields: - `auth_mode`: the effective mode, with the deciding layer as its source. - - `telemetry_enabled`: the configured merged value with its provenance. + - `telemetry_enabled`: the configured value of the layer that decided the effective state, with its provenance. - `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). +- **Setup repository access preferences** (`AccessPreferences`, read by `read_repository_access_preferences`): the `auth.mode` / `telemetry.enabled` values in the repository `.sce/config.json` that interactive setup reads to suppress its access prompts and writes from new answers. Setup also reads the global file's values (`read_global_access_preferences`) only for the Claude telemetry removal check. Read as `Missing`, `Valid { auth_mode, telemetry_enabled }` (an absent key means not asked yet), or `Invalid`. See [Setup](#setup). ## Repository discovery @@ -34,7 +34,7 @@ Every consumer goes through this one resolver, so running from the repository ro `--config` / `SCE_CONFIG_FILE` select one explicit file. The loaded paths are, in order: the global file (if present), the repository file (if present), then the explicit file. - **Ordinary keys** (logging, Agent Trace, `otel`, `policies`, `integrations`, `workos_client_id`, `control_plane_base_url`) come only from the explicit file, as before. The discovered files contribute nothing to them. -- **Access-policy keys** (`auth.mode`, `telemetry.enabled`) are read from every loaded layer. The explicit layer can add a restriction or grant user-side consent, but cannot lift a global or repository restriction. +- **Access-policy keys** (`auth.mode`, `telemetry.enabled`) are read from every loaded layer. The explicit layer can add a restriction or grant consent, but cannot lift a global or repository restriction. - An invalid explicit file stays fatal. An invalid discovered file is skipped and degrades the policy exactly as without an explicit file, so an unreadable global opt-out can never be bypassed by `--config`. ## Resolution @@ -50,17 +50,15 @@ flowchart TD U0 -- yes --> UO[Disabled UserOptOut] U0 -- no --> R0{repository false?} R0 -- yes --> RO[Disabled RepositoryOptOut] - R0 -- no --> U1{user or explicit true?} - U1 -- yes --> E[Enabled] - U1 -- no --> R1{repository true?} - R1 -- yes --> NC[Disabled NoUserConsent] - R1 -- no --> NE[Disabled NotEnabled] + R0 -- no --> T1{any layer true?} + T1 -- yes --> E[Enabled] + T1 -- no --> NE[Disabled NotEnabled] ``` - **Auth mode:** the most restrictive layer wins (`disabled > mandatory > optional`). - The source is the deciding layer. Layers are compared in the order user, repository, explicit; on a tie the later layer is the source. - When no layer sets it, the result is `optional` with `source: default`. -- **`telemetry_enabled` value:** the explicit value if set, otherwise the repository value, otherwise the user value, otherwise `false` with `source: default`. This is the configured value (ordinary override order), not the effective state. +- **`telemetry_enabled` value** (`resolve_telemetry_enabled`): the first `false` in the order explicit, user, repository; otherwise the first `true` in the order explicit, repository, user; otherwise `false` with `source: default`. Its source is therefore the layer that decided the opt-out or consent. - **`background_cloud_allowed`:** `!auth_disabled && !degraded`. - **Helpers:** - `telemetry_enabled()` is true only for `Enabled`. @@ -79,25 +77,24 @@ flowchart TD | `auth.mode: optional` | `auth.mode: disabled` | `auth.mode: mandatory` | auth `disabled` (source repository) | | `telemetry.enabled: false` | `telemetry.enabled: true` | `telemetry.enabled: true` | telemetry disabled (`user_opt_out`) | | absent | absent | `auth.mode: mandatory`, `telemetry.enabled: true` | auth `mandatory` (source explicit), telemetry enabled | +| absent | `telemetry.enabled: true` | absent | telemetry enabled (source repository) | | invalid | absent | `telemetry.enabled: true` | telemetry disabled (`invalid_config`), no background cloud | ## Contradiction warnings The resolver appends these fixed strings to `validation_warnings`, after the bash-policy redundancy warnings, in this order: -1. Repository `telemetry.enabled: true` without a user-side `true`: - `telemetry.enabled is true in the repository config but not in the user config; SCE telemetry stays disabled until the user config sets telemetry.enabled to true.` -2. Any layer has `telemetry.enabled: true` while the effective auth is `disabled`: +1. Any layer has `telemetry.enabled: true` while the effective auth is `disabled`: `telemetry.enabled is true but auth.mode resolves to disabled; SCE telemetry is disabled.` -3. `agent_trace.auto_sync` resolves `true` while the effective auth is `disabled`: +2. `agent_trace.auto_sync` resolves `true` while the effective auth is `disabled`: `agent_trace.auto_sync is true but auth.mode resolves to disabled; post-commit auto-sync is skipped.` -4. Repository `mandatory` while the user or explicit layer is `disabled`: +3. Repository `mandatory` while the user or explicit layer is `disabled`: `auth.mode is mandatory in the repository config but disabled in the user config; auth.mode resolves to disabled.` -5. Explicit `auth.mode` less restrictive than the effective mode: +4. Explicit `auth.mode` less restrictive than the effective mode: `auth.mode in the explicitly selected config is less restrictive than the global or repository config; the most restrictive auth.mode applies.` -6. Explicit `telemetry.enabled: true` while the global or repository layer is `false`: +5. Explicit `telemetry.enabled: true` while the global or repository layer is `false`: `telemetry.enabled is true in the explicitly selected config but false in the global or repository config; SCE telemetry is disabled.` -7. Degraded: +6. Degraded: `A discovered config file was skipped as invalid; SCE telemetry and background cloud operations are disabled.` Each string is a `WARNING_*` constant in `resolver.rs`. The skipped file's own error still appears in `validation_errors`. @@ -108,20 +105,21 @@ Each string is a `WARNING_*` constant in `resolver.rs`. The skipped file's own e - **Text:** four lines directly after `agent_trace.auto_sync` and before `otel.*`: - `- auth.mode: (source: …[, config_source: …])` (the effective mode and its deciding layer) - - `- telemetry.enabled: (source: …[, config_source: …])` (the configured merged value) + - `- telemetry.enabled: (source: …[, config_source: …])` (the deciding layer's configured value) - `- telemetry.effective: enabled`, or `- telemetry.effective: disabled (reason: )` - - only when disabled: `- telemetry.note: Claude Code telemetry settings written by sce setup are removed by the next sce setup run after the global SCE config sets telemetry.enabled to false or auth.mode to disabled; repository-level opt-outs leave them in place.` -- **JSON:** `result.resolved.auth.mode` and `result.resolved.telemetry.enabled` use the usual `{value, source, config_source}` shape. `result.resolved.telemetry.effective` is `{state, reason}`, where `reason` is `null` when the state is enabled. `result.resolved.telemetry.note` is the fixed note string, or `null` when enabled. -- **Reason strings** (`TelemetryDisabledReason::as_str`): `not_enabled`, `user_opt_out`, `no_user_consent`, `repository_opt_out`, `auth_disabled`, `invalid_config`. + - only when disabled with reason `not_enabled`: `- telemetry.note: Set telemetry.enabled: true in the repository SCE config to enable SCE telemetry for this repository. Claude Code telemetry settings written by sce setup are removed by the next sce setup run after the global SCE config sets telemetry.enabled to false or auth.mode to disabled; repository-level opt-outs leave them in place.` + - only when disabled with any other reason: `- telemetry.note: Claude Code telemetry settings written by sce setup are removed by the next sce setup run after the global SCE config sets telemetry.enabled to false or auth.mode to disabled; repository-level opt-outs leave them in place.` +- **JSON:** `result.resolved.auth.mode` and `result.resolved.telemetry.enabled` use the usual `{value, source, config_source}` shape. `result.resolved.telemetry.effective` is `{state, reason}`, where `reason` is `null` when the state is enabled. `result.resolved.telemetry.note` is the same fixed note string as the text line, or `null` when enabled. +- **Reason strings** (`TelemetryDisabledReason::as_str`): `not_enabled`, `user_opt_out`, `repository_opt_out`, `auth_disabled`, `invalid_config`. - **Warnings:** the contradiction warnings appear in `show` warnings after any `Skipped invalid config: …` entries. In `validate` they appear in `warnings` / `Validation warnings`. `validate` adds no policy fields. The note documents a coverage limit: a repository or explicit-layer opt-out does not remove Claude-native telemetry settings already written to user-level Claude settings. Only a global withdrawal does, on the next `sce setup` run (see Enforcement). ## 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). +Interactive `sce setup` saves its auth-mode and telemetry-consent answers only to the repository `.sce/config.json` (the repository layer), before the target install, so each answer applies only to that repository. It never writes them to the user or explicit layers ([ADR](../decisions/2026-10-22-setup-writes-access-answers-to-repository-config.md)). Setup does not change this resolver's precedence: after the install it re-resolves the policy and reports the effective state, so a leftover global `mandatory` or `telemetry.enabled: false` still applies. Repository values are setup's saved answers, not locks: a saved repository value suppresses its prompt on reruns and changes through `sce setup --reconfigure`, which shows it as the default. Only a global or explicit `auth.mode: disabled` skips the access prompts, and only a global or explicit `mandatory` suppresses the login offer. The write, its failure handling, and the `SCE access` report are described in [setup local bootstrap: repository access preferences](../sce/setup-repo-local-config-bootstrap.md#repository-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). +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). Non-interactive and target-flag setup never log in. Under effective `mandatory` they print a fixed `SCE login: required by auth.mode: mandatory ...` reminder without touching `auth.db` or the credential store, and still exit 0. See [non-interactive login reminder](../sce/setup-repo-local-config-bootstrap.md#non-interactive-login-reminder). ## Exposure @@ -130,7 +128,9 @@ Setup then enforces the re-resolved mode with a login step: it never logs in und ## Enforcement - **Managed telemetry startup** (commands and admitted Claude hooks): `cli/src/app.rs` takes `telemetry_enabled()` from the startup `ResolvedObservabilityRuntimeConfig`. When telemetry is not `Enabled`, `RuntimeTelemetry::resolve` returns Noop with fallback reason `disabled_by_config` (logged at `debug`). This happens before `auth.db` is opened or the credential store is touched. See [telemetry credential](../sce/telemetry-credential.md). -- **`sce doctor` managed-telemetry health:** doctor resolves the policy for the inspected repository root. A resolution failure counts as not enabled. When telemetry is not `Enabled`, it reports `[PASS] Managed telemetry (disabled by config)` (JSON `state` / `reason` `disabled_by_config`). It may check whether `auth.db` exists (for the opt-in note), but never opens it or touches the credential store. See [telemetry credential: doctor health check](../sce/telemetry-credential.md#doctor-health-check). +- **`sce doctor` managed-telemetry health:** doctor resolves the policy for the inspected repository root once. A resolution failure counts as `invalid_config`. The row reports the effective state (`Managed telemetry: enabled for this repository` or `Managed telemetry: disabled (reason: )`) and the deciding layer, and JSON adds `managed_telemetry.policy`. When telemetry is not `Enabled`, the health is `disabled_by_config`. Doctor may then check whether `auth.db` exists (for the opt-in note), but never opens it or touches the credential store. See [telemetry credential: doctor health check](../sce/telemetry-credential.md#doctor-health-check). +- **`sce doctor` SCE login row:** under effective `mandatory`, doctor runs the setup login check (non-interactive, deadline-bounded, fail-closed, only when `auth.db` exists). A missing login is a blocking `[FAIL] SCE login` that names the deciding config file, with the fix `Run 'sce auth login'.`. Other modes skip the lookup. Local SCE features are never blocked. See [doctor human text: SCE login row](../sce/doctor-human-text-contract.md#sce-login-row). +- **Claude session login notice:** the Claude-only `sce-info` hooks module (`config/lib/sce-info/hooks/register.ts`) owns it. On an interactive `session.start`, after Claude's own start step, it first probes `sce --version` (5 s timeout); when that cannot start, it logs the install guidance described in [patterns](../patterns.md) and skips doctor. Otherwise it runs `sce doctor --format json` in the session's working directory. When `sce_login.state` is `not_logged_in` (effective `mandatory` without a valid stored credential), it writes the single transcript line `Login required for this repository. Run 'sce auth login'.` through `$.ui.log`. A doctor command that cannot run, unparseable output, any other login state, or a non-interactive session shows nothing. The notice never fails or blocks the session. `sce hooks claude-model-state` emits no notice. OpenCode, Pi, and Codex sessions get no notice. - **`sce auth telemetry-headers`** (Claude's `otelHeadersHelper`): the helper resolves the policy from its working directory through `resolve_auth_runtime_config`. A missing working directory or a resolution failure counts as not enabled. When telemetry is not `Enabled`, it fails closed with the existing fixed `Telemetry credential is unavailable.` diagnostic and empty stdout. This happens before the destination tripwire, the `auth.db` existence check, repository resolution, and the `auth.db` lookup. See [telemetry credential: hidden header helper](../sce/telemetry-credential.md#hidden-header-helper). - **`sce setup` Claude telemetry install:** with the Claude target selected, setup resolves the policy for the setup repository root through `resolve_auth_runtime_config`. A resolution failure counts as not enabled. When telemetry is not `Enabled`, it skips the Claude-native install with the fixed line `Claude telemetry: skipped; SCE telemetry is disabled by config.` and leaves user Claude settings unchanged. The exception is a withdrawal in the global user config itself (`telemetry.enabled: false` or `auth.mode: disabled`, read with `read_global_access_preferences`, never the effective reason): setup then removes the SCE-owned Claude settings, in every interactive run and in non-interactive runs with Claude selected. See [telemetry credential: Claude-native telemetry](../sce/telemetry-credential.md#claude-native-telemetry). - **`sce auth login` / `sce auth whoami`:** both resolve the policy from the working directory through `resolve_auth_runtime_config` and check `auth_allowed()` before any `token_storage` call. A resolution failure is a command error. diff --git a/context/cli/cli-command-surface.md b/context/cli/cli-command-surface.md index 3eecf9f74..9a1de8db8 100644 --- a/context/cli/cli-command-surface.md +++ b/context/cli/cli-command-surface.md @@ -62,7 +62,7 @@ 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). +After those confirmations, interactive setup asks the SCE access prompts (account mode, telemetry consent, login offer), saves the answers to the repository `.sce/config.json`, 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). diff --git a/context/cli/config-precedence-contract.md b/context/cli/config-precedence-contract.md index 93a2c0a44..74dd0231b 100644 --- a/context/cli/config-precedence-contract.md +++ b/context/cli/config-precedence-contract.md @@ -100,7 +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). +- Interactive `sce setup` writes `auth.mode` and `telemetry.enabled` to the repository `.sce/config.json` only, and only for answers given in that run. It never adds `auth` or `telemetry` to the global or explicit files. See [setup local bootstrap: repository access preferences](../sce/setup-repo-local-config-bootstrap.md#repository-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. diff --git a/context/context-map.md b/context/context-map.md index 8052f4c37..920c2a033 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -79,7 +79,7 @@ Feature/domain context: - `context/sce/agent-trace-commit-msg-coauthor-policy.md` (current commit-msg canonical co-author trailer policy with enabled-by-default attribution hooks, explicit opt-out controls, `SCE_DISABLED` kill switch, caller-provided `ai_contribution_present` transformer seam wired from staged-diff AI-overlap preflight, idempotent dedupe, the `agent_trace::patches_have_overlap` pure overlap seam, the `StagedDiffAiOverlapResult` three-valued evidence gate, and `sce.hooks.commit_msg.ai_overlap_error` error logging) - `context/sce/agent-trace-post-commit-dual-write.md` (historical post-commit no-op/dual-write reference; current post-commit behavior is documented in `agent-trace-hooks-command-routing.md`) - `context/sce/agent-trace-hook-doctor.md` (approved operator-environment contract for broadening `sce doctor` into the canonical health-and-repair entrypoint, including stable problem taxonomy — now including `mutation_scope_health` — `--fix` semantics, repository-scoped Agent Trace DB reporting, post-commit Agent Trace auto-sync readiness proof and opt-out behavior, setup-to-doctor alignment rules, canonical Git-hook payload restoration, and the approved downstream human text-mode layout/status/integration contract) -- `context/sce/doctor-human-text-contract.md` (implemented compact `sce doctor` human text contract: Environment/Repository/Integrations hierarchy, post-commit Agent Trace auto-sync readiness labels, `[PASS]`/`[WARN]`/`[FAIL]`/`[MISS]` status vocabulary, healthy-row metadata suppression, typed Claude Code/OpenCode/Pi/Codex target and area ordering, configured/detected/empty target resolution, selection-scoped optional-workflow inventory, the Codex hook trust/review reminder, the per-target `Mutation-scope health` row, no-installed-integrations guidance, and JSON as the full-detail route) +- `context/sce/doctor-human-text-contract.md` (implemented compact `sce doctor` human text contract: Environment/Repository/Integrations hierarchy, post-commit Agent Trace auto-sync readiness labels, `[PASS]`/`[WARN]`/`[FAIL]`/`[MISS]` status vocabulary, healthy-row metadata suppression, typed Claude Code/OpenCode/Pi/Codex target and area ordering, configured/detected/empty target resolution, selection-scoped optional-workflow inventory, the Codex hook trust/review reminder, the per-target `Mutation-scope health` row, the `SCE login` row under `auth.mode: mandatory`, no-installed-integrations guidance, and JSON as the full-detail route) - `context/sce/mutation-scope-health-status.md` (the `doctor-mutation-scope-health` plan's T06, extended by the `doctor-mutation-scope-fix` plan's T05 and T06: the shared `healthy | recovering | blocked | invalid` vocabulary `sce doctor` consumes from each adapter's own classifier, the `mutation_scope_health` `DoctorProblem` category and severity/fixability/readiness mapping — `invalid` is always `manual_only`; `blocked` now carries a second, adapter-owned `Repairability` fact (`AutoFixable`/`ManualOnly`, `cli/src/services/hooks/mutation_scope_health.rs`) that `sce doctor --fix` (`repair_blocked_mutation_scope_targets`) uses to call Claude's or OpenCode's own `assess_repairability`/`repair_blocked` and, only once a freshly recomputed `classify_health` confirms `healthy`/`recovering`, report the row `fixed`, never trusting the repair call's `Ok(())` alone; a `manual_only` `blocked` row still gets the never-delete-the-state-file manual remediation, and `recovering` is still the distinct `no_action_required` fixability with adapter-neutral remediation; the `DoctorProblem`'s own rendered `fixability`/remediation text (both JSON `problems[].remediation` and the human "Agent tracing" tree row's `Remediation:` line, plus `sce doctor --fix`'s `[manual]` fix-result line) now varies by this same repairability fact instead of a static `manual_only` string, per T06 — and the JSON/text output shape — links out to each adapter's own detailed reachability/reasoning doc) - `context/cli/doctor-recovery-safety-model.md` (the `doctor-mutation-scope-fix` plan's T01/T07: the standalone, verified `spec/doctor_recovery.qnt` model of the safety pattern behind `sce doctor --fix`'s repair of a `Blocked` Agent-tracing state — its abstract phase/recovery/owner-oracle concepts and their real Claude/OpenCode mappings, its eight `Safety` invariants each connected to at least one Rust regression test rather than a Quint-Connect trace-replay harness, and why that harness was not built for this model) - `context/sce/setup-githooks-install-contract.md` (canonical `sce setup --hooks` install contract for target-path resolution, all-hook non-blocking missing-CLI bootstrap behavior, foreign-hook preservation and managed-block merge/idempotent outcomes, atomic-swap replacement behavior, and doctor-readiness alignment) @@ -148,7 +148,10 @@ 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-22-repository-telemetry-enabled-grants-consent.md` (a `telemetry.enabled: true` in any layer, including the repository `.sce/config.json`, grants telemetry consent unless some layer opts out; removes `no_user_consent` and its warning; supersedes only the user-side-only consent rule of `2026-10-20-consent-gated-access-policy-precedence.md`) +- `context/decisions/2026-10-22-setup-writes-access-answers-to-repository-config.md` (interactive setup writes `auth.mode` / `telemetry.enabled` only to the repository `.sce/config.json`, atomically and before the target install; repository values are saved answers, not locks, while global/explicit `disabled` and `mandatory` lock the prompts and login offer; supersedes `2026-10-21-setup-writes-access-answers-to-user-layer-only.md`) +- `context/decisions/2026-10-21-setup-writes-access-answers-to-user-layer-only.md` (superseded by `2026-10-22-setup-writes-access-answers-to-repository-config.md`; retained as history: interactive setup wrote `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-20-consent-gated-access-policy-precedence.md` (partially superseded by `2026-10-22-repository-telemetry-enabled-grants-consent.md` for the user-side-only consent rule; still current for access-policy layer discovery, `auth.mode` most-restrictive-wins precedence, degraded handling, and explicit-layer semantics) - `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-20-consent-gated-access-policy-precedence.md b/context/decisions/2026-10-20-consent-gated-access-policy-precedence.md index b29d45b45..fcbd45c02 100644 --- a/context/decisions/2026-10-20-consent-gated-access-policy-precedence.md +++ b/context/decisions/2026-10-20-consent-gated-access-policy-precedence.md @@ -1,10 +1,13 @@ # Decision: Consent-gated precedence for the effective access policy Date: 2026-10-20 -Status: Accepted +Status: Accepted (partially superseded) +Partially superseded by: `context/decisions/2026-10-22-repository-telemetry-enabled-grants-consent.md` (the user-side-only consent rule only) Plan: `context/plans/auth-telemetry-policy-config.md` Task: `T02` +> Partially superseded on 2026-10-22 by [A repository telemetry.enabled true grants telemetry consent](2026-10-22-repository-telemetry-enabled-grants-consent.md). A `telemetry.enabled: true` in any layer, including the repository layer, now grants consent unless some layer opts out, and the `no_user_consent` reason and its contradiction warning are removed. Layer discovery, `auth.mode` precedence, degraded handling, and explicit-layer semantics below still apply. + ## Context Before this decision, credential state alone decided whether SCE exported telemetry or used cloud access. Once a user logged in, a telemetry credential was provisioned and Claude hooks exported spans. No setting let a user opt out of telemetry while staying logged in, forbid authentication on a machine, or stop a repository from turning these features on. The new `auth.mode` and `telemetry.enabled` config keys can appear in both the global and the repo-local `sce/config.json`. The ordinary per-key merge (last layer wins) would let a repository enable telemetry without the user's consent, or override a user's prohibition. 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 index adbb99f4e..c884d9eac 100644 --- 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 @@ -1,10 +1,13 @@ # Decision: Setup writes access-policy answers to the user layer only Date: 2026-10-21 -Status: Accepted +Status: Superseded +Superseded by: `context/decisions/2026-10-22-setup-writes-access-answers-to-repository-config.md` Plan: `context/plans/setup-auth-telemetry-consent.md` Task: `T01, T05` +> Superseded on 2026-10-22 by [Setup writes access-policy answers to the repository config](2026-10-22-setup-writes-access-answers-to-repository-config.md). Interactive `sce setup` now saves `auth.mode` and `telemetry.enabled` to the repository `.sce/config.json`, and only global or explicit values lock the setup prompts. This record is kept as history. + ## 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. diff --git a/context/decisions/2026-10-22-repository-telemetry-enabled-grants-consent.md b/context/decisions/2026-10-22-repository-telemetry-enabled-grants-consent.md new file mode 100644 index 000000000..664a829cd --- /dev/null +++ b/context/decisions/2026-10-22-repository-telemetry-enabled-grants-consent.md @@ -0,0 +1,63 @@ +# Decision: A repository telemetry.enabled true grants telemetry consent + +Date: 2026-10-22 +Status: Accepted +Plan: `context/plans/setup-auth-mode-repo-local.md` +Task: `T02` +Supersedes: `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md` (the user-side-only consent rule only) + +## Context + +The [2026-10-20 decision](2026-10-20-consent-gated-access-policy-precedence.md) let only the user side (the global or explicit config) grant telemetry consent. A repository-layer `telemetry.enabled: true` alone resolved to `Disabled(NoUserConsent)` and produced a contradiction warning. The plan moves setup's access answers into the repository's `.sce/config.json`, so each answer applies only to that repository. A consent saved there has to take effect. Under the old rule it could not. + +## Decision + +A `telemetry.enabled: true` in any layer, including the repository layer, grants telemetry consent unless some layer opts out. The first matching rule decides the effective state: + +1. Any skipped invalid discovered layer → `Disabled(InvalidConfig)`. +2. Effective auth is `disabled` → `Disabled(AuthDisabled)`. +3. User or explicit layer is `false` → `Disabled(UserOptOut)`. +4. Repository layer is `false` → `Disabled(RepositoryOptOut)`. +5. Any layer is `true` → `Enabled`. +6. Otherwise → `Disabled(NotEnabled)`. + +The `no_user_consent` reason and its repository-true-without-user-consent warning no longer exist. The reported `telemetry.enabled` value and source come from the layer that decided the outcome. Explicit, user, and repository layers are checked in that order for a `false`. If none is `false`, explicit, repository, and user layers are checked in that order for a `true`. The rest of the 2026-10-20 decision is unchanged: `auth.mode` precedence (most restrictive wins), degraded handling, layer discovery, and explicit-layer semantics. + +## Rationale + +The user asked for per-repository access answers stored in the repository's own config. A consent that only counted from the global file would have made the per-repository answer pointless. Opt-outs still win over any consent, so a global or explicit `false` stays a standing personal prohibition, and a repository `false` still opts the repository out. + +## Alternatives considered + +- **Keep user-side-only consent:** rejected. A repository-saved setup answer could never enable telemetry. +- **A gitignored per-user repository file (for example `.sce/config.local.json`):** not selected. It would keep per-repository scope and per-person consent, but the user chose the committed `.sce/config.json`. + +## Compatibility and risks + +- A committed `.sce/config.json` with `telemetry.enabled: true` opts in everyone who clones or pulls the repository, without asking them. A user can still withdraw with `telemetry.enabled: false` in the global config. +- Repositories that already commit `telemetry.enabled: true` switch from `no_user_consent` to `Enabled` for users without a user-side value. +- Consumers that matched on the `no_user_consent` reason string no longer receive it. + +## Guardrails + +- Any `false` in any layer still disables telemetry. A `true` never overrides an opt-out. +- `auth.mode: disabled` and a degraded config still disable telemetry before consent is considered. +- There is still no env-var or CLI-flag override for `telemetry.enabled`. + +## Consequences + +- One repository-local answer controls SCE telemetry for that repository. +- The `sce config show` `not_enabled` note tells the user to set `telemetry.enabled: true` in the repository SCE config. + +## Follow-up + +- Plan task T07 records the setup write-location change that supersedes [`2026-10-21-setup-writes-access-answers-to-user-layer-only`](2026-10-21-setup-writes-access-answers-to-user-layer-only.md). + +## References + +- Plan: [`setup-auth-mode-repo-local`](../plans/setup-auth-mode-repo-local.md) +- Task: `T02` +- Current-state context: [`access-policy`](../cli/access-policy.md) +- Evidence: [`resolver.rs`](../../cli/src/services/config/resolver.rs) +- Evidence: [`render.rs`](../../cli/src/services/config/render.rs) +- Related decision: [`Consent-gated precedence for the effective access policy`](2026-10-20-consent-gated-access-policy-precedence.md) diff --git a/context/decisions/2026-10-22-setup-writes-access-answers-to-repository-config.md b/context/decisions/2026-10-22-setup-writes-access-answers-to-repository-config.md new file mode 100644 index 000000000..458211560 --- /dev/null +++ b/context/decisions/2026-10-22-setup-writes-access-answers-to-repository-config.md @@ -0,0 +1,72 @@ +# Decision: Setup writes access-policy answers to the repository config + +Date: 2026-10-22 +Status: Accepted +Plan: `context/plans/setup-auth-mode-repo-local.md` +Task: `T03` +Supersedes: `context/decisions/2026-10-21-setup-writes-access-answers-to-user-layer-only.md` + +## Context + +Under the [2026-10-21 decision](2026-10-21-setup-writes-access-answers-to-user-layer-only.md), interactive `sce setup` saved `auth.mode` and `telemetry.enabled` to the global user config. As a result, a `mandatory` mode or a telemetry consent chosen in one repository silently applied to every repository on the machine. The user asked for each answer to apply only to the repository being set up. The [repository-consent decision](2026-10-22-repository-telemetry-enabled-grants-consent.md) made a repository `telemetry.enabled: true` able to grant consent, so a repository-saved answer now takes effect. + +## Decision + +Interactive `sce setup` saves the `auth.mode` and `telemetry.enabled` answers to the repository's committed `/.sce/config.json`, not to the global user config. + +- Saved answers, prompt suppression, and the `--reconfigure` defaults come from the repository file. When the repository file is invalid, setup skips the access prompts and writes nothing. +- Repository values are setup's saved answers, not locks. Only a global or explicit (`--config` / `SCE_CONFIG_FILE`) `auth.mode: disabled` skips the access prompts. Only a global or explicit `mandatory` suppresses the login offer. +- The repository writer (`persist_repository_access_preferences`) keeps the guardrails of the previous global writer: + - It writes explicit answers only and preserves unrelated keys. + - It validates the result with `parse_file_config` and skips no-op writes. + - It writes atomically (temp file plus rename, keeping the file mode). + - It refuses a concurrently modified, symlinked, or invalid file. + - It bootstraps a missing file from the repo-local payload. +- The write runs before the target install, so a failed write aborts setup before any other repository file changes. +- Setup no longer writes access keys to the global config, and the global access writer is removed. Existing global values are not migrated. +- The Claude-native telemetry removal step still acts only on a withdrawal in the global config. + +## Rationale + +Saving the answers in the repository config keeps each one scoped to the repository it was given for. Treating repository values as saved answers rather than locks follows from setup itself writing them: setup cannot tell a team-authored value from one it wrote earlier. Global and explicit values stay user-side restrictions that setup does not override. + +## Alternatives considered + +- **Keep writing to the global user config** — rejected: answers would keep leaking across repositories on the same machine. +- **A gitignored per-user repository file (for example `.sce/config.local.json`)** — not selected: the user chose the committed `.sce/config.json`, although this alternative would have kept per-person consent. + +## Compatibility and risks + +- A committed `telemetry.enabled: true` opts in everyone who clones or pulls the repository, without asking them. A global `telemetry.enabled: false` still opts a user out. +- Releases `v0.4.0-pre-alpha-v11` and earlier reject the `auth` and `telemetry` keys. They skip the whole repository config as invalid, including bash policies and integration targets. +- A team-committed `auth.mode: disabled` no longer locks the setup prompts, so `sce setup --reconfigure` can change it. +- Values left in the global config by earlier setup runs stay in effect: a global `mandatory` still wins, and a global `false` still opts out. +- A repository `telemetry.enabled: false` answer does not trigger the Claude-native telemetry removal. Removal still follows only a global withdrawal. + +## Guardrails + +- The resolver's `auth.mode` precedence, where the most restrictive value wins, is unchanged. +- Setup never writes an invalid, concurrently modified, or symlinked repository config. +- Non-interactive, hooks-only, and context-only setup never write access keys. + +## Consequences + +- One repository's access answers no longer affect other repositories. +- Saved access answers become shared team configuration once the file is committed. + +## Follow-up + +- Durable context for setup and the access policy must describe repository-scoped answers. + +## References + +- Plan: [`setup-auth-mode-repo-local`](../plans/setup-auth-mode-repo-local.md) +- Task: `T03` +- Current-state context: [`setup-repo-local-config-bootstrap`](../sce/setup-repo-local-config-bootstrap.md) +- Current-state context: [`access-policy`](../cli/access-policy.md) +- Evidence: [`access_preferences.rs`](../../cli/src/services/setup/access_preferences.rs) +- Evidence: [`command.rs`](../../cli/src/services/setup/command.rs) +- Evidence: [`mod.rs`](../../cli/src/services/setup/mod.rs) +- Evidence: [`prompt.rs`](../../cli/src/services/setup/prompt.rs) +- Related decision: [`Setup writes access-policy answers to the user layer only`](2026-10-21-setup-writes-access-answers-to-user-layer-only.md) +- Related decision: [`A repository telemetry.enabled true grants telemetry consent`](2026-10-22-repository-telemetry-enabled-grants-consent.md) diff --git a/context/glossary.md b/context/glossary.md index 68daf0505..73c071e5d 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, 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). +- CLI execution terminology: [command dispatch, runtime dependencies and telemetry](cli/execution-glossary.md). Auth mode, policy layer (user/repository), effective access policy, setup repository 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, 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 service orchestration`: Setup execution logic in `cli/src/services/setup/command.rs` that resolves the repository root, saves interactive access answers to the repository `.sce/config.json`, 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. @@ -191,7 +191,7 @@ - `agent trace commit-msg co-author policy`: Current contract in `cli/src/services/hooks/mod.rs` (`apply_commit_msg_coauthor_policy`) that applies exactly one canonical trailer (`Co-authored-by: SCE `) only when attribution hooks are enabled, SCE is not disabled, and the staged-diff AI-overlap preflight confirms AI/editor evidence (`StagedDiffAiOverlapResult::Overlap`); `NoOverlap` and `Error` both suppress the trailer, with `Error` logged via `sce.hooks.commit_msg.ai_overlap_error`; duplicate canonical trailers are deduped idempotently. - `local DB migration contract`: `cli/src/services/local_db/mod.rs` delegates migration execution to `TursoDb` through the `DbSpec::migrations()` contract. The current `LocalDbSpec` migration list is empty, so `LocalDb::new()` opens/creates the canonical local DB without creating local tables. - `hook no-op baseline`: Current `cli/src/services/hooks/mod.rs` runtime posture where `pre-commit` and `post-rewrite` return deterministic no-op status text, `commit-msg` is a gated mutating path, `post-commit` persists intersections and built Agent Trace payloads without post-commit file artifacts, `diff-trace` validates STDIN payloads, resolves Claude `model_id` with `direct > exact transcript > exact session/agent state > bridge-derived chain state > NULL` precedence, persists direct `tool_version`, applies stored `session_id` prefixes (`oc_`/`cc_`/`pi_`), and inserts DB-only AgentTraceDb rows, `conversation-trace` is the active message/part intake path, and `codex` (`cli/src/services/hooks/codex/`) classifies its own raw hook JSON into four supported dispatch arms — `UserPromptSubmit` and `Stop` capture real conversation evidence, `PreToolUse(Bash)` delegates to the existing Bash policy engine, `PostToolUse(apply_patch)` parses/normalizes/persists a `diff_traces` row using event-scoped synthetic line identities — with every other event/tool combination (including `PreToolUse(apply_patch)`) and malformed STDIN failing open as a no-op. `session-model` is no longer a supported hook route. -- `sce doctor` operator-health contract: `cli/src/services/doctor/mod.rs` is the stable doctor entrypoint, with focused `doctor/{inspect,render,fixes,types}.rs` submodules implementing the current approved operator-health surface in `context/sce/agent-trace-hook-doctor.md`: `sce doctor --fix` selects repair intent, Agent Trace DB discovery is repository-scoped only (the checkout-scoped `sce trace --legacy` surface was removed by the `retire-legacy-agent-trace-db` plan), and output exposes deterministic doctor mode, readiness, stable problem taxonomy/fixability fields, checkout/database records, and fix-result records. The runtime validates state-root resolution, global and repo-local `sce/config.json` readability/schema health, local DB and repository-scoped Agent Trace DB path/health, DB-parent readiness barriers, git availability, non-repo vs bare-repo targeting failures, effective hook-path source resolution, required hook presence/executable/content drift against canonical embedded hook assets, and repo-root installed OpenCode, Claude, Pi, plus Codex integration content health. Human text mode uses the approved sectioned layout (`Environment`, `Configuration` with repository-scoped Agent Trace DB rows when available, `Repository`, `Git Hooks`, `Integrations`), `SCE doctor diagnose` / `SCE doctor fix` headers, bracketed `[PASS]`/`[FAIL]`/`[MISS]` status tokens with shared-style green/red colorization when enabled, simplified `label (path)` row formatting, top-level-only hook rows, and integration parent/child rows where missing files surface as `[MISS]`, mismatches/read failures as `[FAIL]`, and affected parent groups as `[FAIL]`. Agent Trace DB rows include repository ID, identity source, safe canonical identity, configured remote name, and never raw remote URLs. Current integration groups include `OpenCode plugins`, `OpenCode agents`, `OpenCode commands`, `OpenCode skills`, `ClaudeCode plugins`, `ClaudeCode commands`, `ClaudeCode skills`, `Pi prompts`, `Pi skills`, `Pi extensions`, `Codex skills`, and `Codex hooks`; Claude `settings.json` plus `hooks/**` belong to `ClaudeCode plugins`, including `.claude/hooks/run-sce-or-show-install-guidance.sh`, Pi `prompts/**` and `skills/**` map to the Pi groups, and Codex's `.agents/skills/**` plus `.codex/hooks.json`/`.codex/hooks/**` map to the Codex groups (the latter also carrying a Codex hook trust/review reminder when unhealthy). Fix mode reuses canonical setup hook installation for missing/stale/non-executable required hooks and missing hooks directories and can bootstrap canonical missing SCE-owned DB parent directories. +- `sce doctor` operator-health contract: `cli/src/services/doctor/mod.rs` is the stable doctor entrypoint, with focused `doctor/{inspect,render,fixes,types,managed_telemetry,access}.rs` submodules (`access.rs` owns the `SCE login` row — a blocking failure under effective `auth.mode: mandatory` without a valid stored credential — and the managed-telemetry policy state and source, see [doctor human text](sce/doctor-human-text-contract.md#sce-login-row)) implementing the current approved operator-health surface in `context/sce/agent-trace-hook-doctor.md`: `sce doctor --fix` selects repair intent, Agent Trace DB discovery is repository-scoped only (the checkout-scoped `sce trace --legacy` surface was removed by the `retire-legacy-agent-trace-db` plan), and output exposes deterministic doctor mode, readiness, stable problem taxonomy/fixability fields, checkout/database records, and fix-result records. The runtime validates state-root resolution, global and repo-local `sce/config.json` readability/schema health, local DB and repository-scoped Agent Trace DB path/health, DB-parent readiness barriers, git availability, non-repo vs bare-repo targeting failures, effective hook-path source resolution, required hook presence/executable/content drift against canonical embedded hook assets, and repo-root installed OpenCode, Claude, Pi, plus Codex integration content health. Human text mode uses the approved sectioned layout (`Environment`, `Configuration` with repository-scoped Agent Trace DB rows when available, `Repository`, `Git Hooks`, `Integrations`), `SCE doctor diagnose` / `SCE doctor fix` headers, bracketed `[PASS]`/`[FAIL]`/`[MISS]` status tokens with shared-style green/red colorization when enabled, simplified `label (path)` row formatting, top-level-only hook rows, and integration parent/child rows where missing files surface as `[MISS]`, mismatches/read failures as `[FAIL]`, and affected parent groups as `[FAIL]`. Agent Trace DB rows include repository ID, identity source, safe canonical identity, configured remote name, and never raw remote URLs. Current integration groups include `OpenCode plugins`, `OpenCode agents`, `OpenCode commands`, `OpenCode skills`, `ClaudeCode plugins`, `ClaudeCode commands`, `ClaudeCode skills`, `Pi prompts`, `Pi skills`, `Pi extensions`, `Codex skills`, and `Codex hooks`; Claude `settings.json` plus `hooks/**` belong to `ClaudeCode plugins`, including `.claude/hooks/run-sce-or-show-install-guidance.sh`, Pi `prompts/**` and `skills/**` map to the Pi groups, and Codex's `.agents/skills/**` plus `.codex/hooks.json`/`.codex/hooks/**` map to the Codex groups (the latter also carrying a Codex hook trust/review reminder when unhealthy). Fix mode reuses canonical setup hook installation for missing/stale/non-executable required hooks and missing hooks directories and can bootstrap canonical missing SCE-owned DB parent directories. - `compact doctor text report`: Current human-readable `sce doctor` rendering collapses healthy state, repository, and typed integration-area checks into the `Environment`/`Repository`/`Integrations` hierarchy, suppresses healthy paths and identity metadata, and uses `--format json` as the full-detail route. The canonical current contract is [doctor human text](sce/doctor-human-text-contract.md). - `cli warnings-denied lint policy`: `cli/Cargo.toml` sets `warnings = "deny"`, so plain `cargo clippy --manifest-path cli/Cargo.toml` already fails on warnings without needing an extra `-- -D warnings` tail. - `agent trace local DB schema migration contract`: Retired `apply_core_schema_migrations` behavior removed from the current runtime during `agent-trace-removal-and-hook-noop-reset` T01; the local DB baseline is now file open/create only. @@ -242,7 +242,7 @@ - `conversation-trace mixed batch`: Rust `sce hooks conversation-trace` STDIN contract accepting `{ payloads: [{ type: "message" | "message.part", ... }] }` with top-level `type` ignored and malformed-item skipping. See `context/sce/agent-trace-hooks-command-routing.md` and `context/sce/agent-trace-db.md`. - `conversation-trace raw Claude event path`: Claude hook event classification via `hook_event_name` routing (`UserPromptSubmit`/`Stop`/`PostToolUse`) that produces normalized `message` + `message.part` items. See `context/sce/agent-trace-hooks-command-routing.md`. - `agent-trace plugin conversation-trace handoff seam`: OpenCode plugin (`config/lib/agent-trace-plugin/`) mixed-batch envelope construction for `sce hooks conversation-trace`. See `context/sce/opencode-agent-trace-plugin-runtime.md`. -- `sce hooks claude-model-state`: Silent Claude lifecycle hook command that accepts raw `SessionStart` and `PostModelSwitch` JSON, records normalized model observations in the local exact-scope `claude_model_state` register through the no-migration repository hook path, and best-effort seeds a model-less `SessionStart` from its bridge-linked chain using the same shared newest-chain-observation selection rule as the `diff-trace` state-miss path (bounded leading-record reads, one exact-scope state read per chain member, winner by greatest `observed_at_ms`) and `source="bridge_inherited"`. In practice this `SessionStart` attempt cannot read its own lazily created transcript, so `bridge session correlation` for a cleared session is carried by the `diff-trace` state-miss path (see `Claude diff-trace attribution`); the `SessionStart` attempt is kept for the case Claude ever creates transcripts eagerly. Missing discovery/state and all other intake, clock, DB-open, DB-read, or DB-write failures remain fail-open with empty stdout while logging failures. `SessionStart` is synchronous relative to Claude execution; `PostModelSwitch` is asynchronous, so local write completion—not Claude causal event order—determines state visibility. See [Agent Trace hook routing](sce/agent-trace-hooks-command-routing.md). +- `sce hooks claude-model-state`: Claude lifecycle hook command that accepts raw `SessionStart` and `PostModelSwitch` JSON, records normalized model observations in the local exact-scope `claude_model_state` register through the no-migration repository hook path, and best-effort seeds a model-less `SessionStart` from its bridge-linked chain using the same shared newest-chain-observation selection rule as the `diff-trace` state-miss path (bounded leading-record reads, one exact-scope state read per chain member, winner by greatest `observed_at_ms`) and `source="bridge_inherited"`. In practice this `SessionStart` attempt cannot read its own lazily created transcript, so `bridge session correlation` for a cleared session is carried by the `diff-trace` state-miss path (see `Claude diff-trace attribution`); the `SessionStart` attempt is kept for the case Claude ever creates transcripts eagerly. Missing discovery/state and all other intake, clock, DB-open, DB-read, or DB-write failures remain fail-open with empty stdout while logging failures. `SessionStart` is synchronous relative to Claude execution; `PostModelSwitch` is asynchronous, so local write completion—not Claude causal event order—determines state visibility. It writes no stdout; the Claude session login notice is owned by the `sce-info` hooks module (see [access policy: enforcement](cli/access-policy.md#enforcement)). See [Agent Trace hook routing](sce/agent-trace-hooks-command-routing.md). - `agent-trace plugin secondary diff persistence ownership`: Current runtime contract where `buildTrace` no longer writes diff-trace artifacts or database rows directly; extracted diff payloads are forwarded to CLI `diff-trace` intake and the Rust hook runtime owns AgentTraceDb insertion without any `context/tmp` artifact fallback. - `messages table (Agent Trace DB)`: Agent Trace DB table created by migration `008_create_messages.sql`; stores session-scoped parent messages with columns `session_id`, `message_id`, `role` (`user`/`assistant` via CHECK constraint), `generated_at_unix_ms`, `created_at`, and `updated_at`. Message body text belongs to `parts.text`, not the parent `messages` row. Has a unique index on `(session_id, message_id)` for duplicate-ignore parent message inserts and a compound index on `(session_id, generated_at_unix_ms, id)` for chronological session message retrieval. No foreign keys to any other table. - `musl static Linux release`: The Linux binary release targets (`x86_64-unknown-linux-musl` and `aarch64-unknown-linux-musl`) compile against musl libc and link fully statically. The resulting binary has no runtime libc dependency and zero `/nix/store/` references in ELF metadata, strings, or dynamic-linker fields, satisfying the native portability audit. The musl targets replace the previous glibc-linked `*-unknown-linux-gnu` targets; macOS (`aarch64-apple-darwin`) is unchanged. Introduced in the `musl-static-linux-release` plan. diff --git a/context/overview.md b/context/overview.md index b0364eb47..3f4c0f691 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. 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`). +- **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 repository `.sce/config.json` before the target install, so they apply only to that repository, 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, 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 setup service also provides repository-root install orchestration: it resolves the repository root, saves interactive access answers to the repository `.sce/config.json`, 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/patterns.md b/context/patterns.md index 9f76ac40d..454d9c362 100644 --- a/context/patterns.md +++ b/context/patterns.md @@ -65,7 +65,7 @@ ## Pkl renderer layering -- Keep the Claude-only `sce-info` package in canonical `config/lib/sce-info` sources. `claude-content.pkl` reads an explicit three-file runtime allowlist: `.claude-plugin/plugin.json`, `hooks/hooks.json`, and `hooks/register.ts`, emitted beneath `config/.claude/skills/sce-info/`. Preserve the supplied `sce-splash` manifest identity and runtime contents. Retain development tests and `tsconfig.json` only in authoring sources; no generated target receives them. Keep this plugin-shaped package outside shared workflow catalogs, composition, and skill-document inventories; OpenCode, Pi, and Codex receive no `sce-info` assets. Declare each shipped source consistently in `config/pkl/generator-inputs.txt`, `cli/build.rs`, and the filtered Nix generation/build source sets; generation never reads the local `.claude` runtime tree. See [config generation architecture](sce/config-generation.md) and [setup installation policy](sce/setup-no-backup-policy-seam.md). +- Keep the Claude-only `sce-info` package in canonical `config/lib/sce-info` sources. `claude-content.pkl` reads an explicit three-file runtime allowlist: `.claude-plugin/plugin.json`, `hooks/hooks.json`, and `hooks/register.ts`, emitted beneath `config/.claude/skills/sce-info/`. Keep the `SCE` manifest identity (shown as the transcript-line prefix) and splash behavior; the module also owns the Claude session login notice (interactive `session.start` → `sce doctor --format json` → one `$.ui.log` line when `sce_login.state` is `not_logged_in`). It probes `sce --version` first: when the CLI cannot start, the splash status turns into a pulsing red `not loaded.` with an install link, and one `$.ui.log` line names the expected CLI version and `https://sce.crocoder.dev/docs/getting-started#install-cli`. When the CLI runs, any doctor `hooks[]` entry with `exists: false` produces one combined line `Git hooks missing: . Run 'sce doctor --fix' to install them.`; any Claude asset problem (`claude_integration_files_missing`, `claude_integration_content_mismatch`, `claude_asset_read_failed`) produces one line `Claude SCE skills are outdated or modified. Run 'sce setup --claude' to update them.`; any other doctor problem with `target` `claude` is logged once as ` ` (the engine prefixes the `SCE` plugin name). These notices are user-facing only and never enter model context. `register.ts` holds the `__SCE_VERSION__` placeholder; `claude-content.pkl` replaces it with the trimmed repository `.version`, and the generation contract asserts the stamped value. Retain development tests and `tsconfig.json` only in authoring sources; no generated target receives them. Keep this plugin-shaped package outside shared workflow catalogs, composition, and skill-document inventories; OpenCode, Pi, and Codex receive no `sce-info` assets. Declare each shipped source consistently in `config/pkl/generator-inputs.txt`, `cli/build.rs`, and the filtered Nix generation/build source sets; generation never reads the local `.claude` runtime tree. See [config generation architecture](sce/config-generation.md) and [setup installation policy](sce/setup-no-backup-policy-seam.md). - Keep the six target-agnostic workflow packages in `config/pkl/base/workflow-{change-to-plan,next-task,validate,commit,handover,brownfield}.pkl`, with shared package/composite frontmatter, body, semantic-reference, document, and composite-source primitives in `workflow-content.pkl`, workflow-specific behavior and migrated package-local documents in their canonical workflow modules, and shared task synchronization policy in `workflow-context-sync.pkl`. Persist task synchronization lifecycle state in the plan template and let `/next-task` own the pending/terminal lifecycle writes around task synchronization; `/validate` owns validation and Validation Report writing only. Render context-sync `SKILL.md` content from explicit role data in named frontmatter, purpose, input, workflow, boundaries, and completion order, and render its report introduction, synced, no-context-change, blocked, and rules sections from a typed report role. Do not use numbered fragments or positional role/common interleaving for either document. Canonical workflow modules must consume the shared constructors rather than defining local equivalents. Do not reintroduce the removed grouped shared-content catalog or automated-profile variants. - Keep final validation observational: `/validate` measures the completed implementation without deleting or repairing application, test, configuration, context, debug, temporary, or local-scaffolding artifacts; leftover debug/temp artifacts are failure evidence for a later implementation session. - Keep standalone internal skills that have no user-facing entrypoint outside `workflow-catalog.pkl`. The current `sce-decision` package is authored in `config/pkl/base/decision-skill.pkl`, rendered directly by each target with only supported frontmatter, and covered by explicit exact-path and required-content assertions. Do not manufacture a command or prompt merely to make an internal package fit the command workflow matrix. diff --git a/context/plans/setup-auth-mode-repo-local.md b/context/plans/setup-auth-mode-repo-local.md new file mode 100644 index 000000000..6adeb3bc7 --- /dev/null +++ b/context/plans/setup-auth-mode-repo-local.md @@ -0,0 +1,230 @@ +# Plan: setup-auth-mode-repo-local + +## Change summary + +Interactive `sce setup` saves both access answers, `auth.mode` and `telemetry.enabled`, to the repository-local `.sce/config.json` of the repository being set up, so each applies only to that repository. Today `persist_global_access_preferences` (`cli/src/services/setup/access_preferences.rs`) writes both to the global user config (`~/.config/sce/config.json`), so a `mandatory` or a telemetry consent chosen in one repository silently applies to every repository on the machine. To make a repository-local consent take effect, the access-policy resolver also changes: a repository `telemetry.enabled: true` now grants consent instead of resolving to `no_user_consent`. + +The plan also makes a missing login under `auth.mode: mandatory` visible without blocking local work. `sce doctor` reports a blocking `SCE login` problem and shows this repository's effective telemetry state. Non-interactive setup prints a login reminder. A Claude Code session prints one message per session telling the user to run `sce auth login`. + +This replaces the 2026-10-21 decision "Setup writes access-policy answers to the user layer only" and the user-side-only consent rule of the 2026-10-20 decision "Consent-gated precedence for the effective access policy". The prompt seam, the setup login step, and the most-restrictive-wins `auth.mode` precedence are otherwise unchanged. Existing global `auth.mode` / `telemetry.enabled` values are not migrated; the user removes them by hand. + +## Design + +### Current implementation findings + +- `prepare_interactive_setup` (`cli/src/services/setup/command.rs`) reads `read_global_access_preferences(global_config_path)` and folds both keys into `PersistedSetupConfirmations` through `with_global_access_preferences`. `persisted_setup_confirmations(repository_root)` reads only `agent_trace.auto_sync` and `policies.attribution_hooks.enabled` from the repository file. +- The prompt step in `resolve_setup_dispatch` (`cli/src/services/setup/mod.rs`) asks for each access answer when it isn't saved yet (or `--reconfigure` is passed) and the global config is valid. The labels are `SCE account mode for this machine` and a telemetry label ending `Applies to all repositories on this machine.` (`prompt.rs`). +- `SetupAccessGate::from_policy` treats a repository or explicit `auth.mode: disabled` as a lock (`auth_locked_by` filters out only `Global`), and treats a non-global `mandatory` as `mandatory_locked`. +- `persist_setup_access_preferences` writes both answers to the global file before any repository write. The `SCE access:` report renders `saved to global SCE config ''; applies to all repositories on this machine` (`SAVED_ACCESS_SCOPE`). +- `persist_integration_targets` writes the repository file after the target install, skips an invalid file, and uses non-atomic `fs::write`. A shared `atomic_write::write_atomically` exists. +- `resolve_access_policy` (`cli/src/services/config/resolver.rs`) enables telemetry only on a user or explicit `true`. A repository `true` alone gives `Disabled(NoUserConsent)` plus the contradiction warning `telemetry.enabled is true in the repository config but not in the user config; ...`. +- `sce doctor` reports `[PASS] Managed telemetry (disabled by config)` or `(not configured)`, and its opt-in note (`OPT_IN_NOTE`, `cli/src/services/doctor/managed_telemetry.rs`) tells the user to set `telemetry.enabled: true` in the global SCE config. Doctor has no login check. +- Claude-native telemetry settings are written to the user-level `~/.claude/settings.json` (`resolve_claude_settings_path`). The `otelHeadersHelper` (`sce auth telemetry-headers`) resolves the policy from its working directory and fails closed when telemetry is not `Enabled` there. +- The generated Claude `settings.json` (`config/pkl/renderers/claude-content.pkl`) has a `SessionStart` hook running `sce hooks claude-model-state`. The mutation-scope lifecycle returns empty output for `SessionStart`. +- The `auth` / `telemetry` schema sections were added in `d46c03cd` (2026-10-20), after the latest release tag `v0.4.0-pre-alpha-v11`. The schema uses `additionalProperties = false`. + +### Target behavior + +- **Writer:** setup writes the `auth.mode` and `telemetry.enabled` answers to `/.sce/config.json`. The repository writer has the same guardrails as the global writer: write explicit answers only, preserve unrelated keys, validate with `parse_file_config`, skip no-op writes, write atomically (temp file plus rename, keeping the mode), refuse when the bytes changed since the first read, refuse to replace a symlink, and never rewrite an invalid file. A missing file is bootstrapped first. It runs before the target install, so a failed write aborts setup before any other repository file changes. Setup no longer writes access keys to the global config. +- **Saved answers:** prompt suppression and the `--reconfigure` defaults come from the repository file. An invalid repository file skips the access prompts. +- **Locks:** a repository value is setup's saved answer, not a lock. Global and explicit values are the locks: `disabled` there skips the access prompts, and `mandatory` there suppresses the login offer. +- **Telemetry precedence:** any `false` in any layer disables telemetry (`user_opt_out` for user or explicit, `repository_opt_out` for repository). Otherwise any `true` in any layer enables it. `auth.mode: disabled` and a degraded config still disable it first. The `no_user_consent` reason and its contradiction warning are removed. +- **Wording:** the prompt labels and the `SCE access:` saved lines say `saved to repository SCE config ''; applies only to this repository`. Doctor's opt-in note and the `sce config show` telemetry note point at the repository config. +- **Doctor:** a new `SCE login` row. When the effective mode is `mandatory` and no valid stored credential is found, it is a blocking `[FAIL]` that names the config file setting `mandatory`, with the fix `Run 'sce auth login'`. The managed-telemetry row reports the effective state for the inspected repository (`enabled for this repository`, or `disabled (reason: )`) and its source layer. +- **Non-interactive setup:** when the effective mode is `mandatory`, setup completes and adds the fixed line `SCE login: required by auth.mode: mandatory for this repository; run 'sce auth login' if you are not logged in.`. It doesn't open `auth.db` or the credential store, and it exits 0. +- **Claude session notice:** at `SessionStart`, when the effective mode for the session's working directory is `mandatory` and no valid stored credential is found, the hook emits one Claude `systemMessage`: `SCE login required for this repository. Run 'sce auth login'.`. It never fails the hook, emits nothing otherwise, and runs once per session start. + +## Acceptance criteria + +- [x] AC1: Interactive setup writes the answered `auth.mode` and `telemetry.enabled` to the repository `.sce/config.json`, writes no access keys to the global config, and keeps unrelated repository keys. + - Validate: setup command tests in `cli/src/services/setup/command.rs`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup`. +- [x] AC2: A rerun suppresses each access prompt when the repository file holds its value, `--reconfigure` asks again with that value as the default, and a global value no longer suppresses a prompt. + - Validate: `resolve_setup_dispatch` / `prepare_interactive_setup` tests with `FakePrompter` for the repo-saved, global-only, and `--reconfigure` cases. +- [x] AC3: The repository writer refuses an invalid, concurrently modified, or symlinked file and leaves it byte-identical, and setup then aborts before the target install. + - Validate: repository writer unit tests plus one setup command abort test. +- [x] AC4: Global or explicit `disabled` skips the access prompts and global or explicit `mandatory` suppresses the login offer, while repository values are only prompt defaults. + - Validate: `SetupAccessGate::from_policy` and dispatch tests per layer. +- [x] AC5: A repository `telemetry.enabled: true` with no `false` in any layer gives effective telemetry `enabled`. Any `false` still disables it, and `no_user_consent` no longer exists. + - Validate: `resolve_access_policy` tests in `cli/src/services/config/resolver.rs`; `sce config show --format json` shows `result.resolved.telemetry.effective.state` `enabled` in a repository with only a repository `true`. +- [x] AC6: Under `mandatory` with no valid stored credential, `sce doctor` reports a blocking `SCE login` failure with the `sce auth login` fix. It also shows the repository's effective telemetry state and its source. + - Validate: doctor render tests with exact text and JSON assertions; `nix run .#sce -- doctor` in a repository with `auth.mode: mandatory` and no login. +- [x] AC7: Non-interactive setup under effective `mandatory` prints the fixed login reminder line, exits 0, and never touches `auth.db` or the credential store. + - Validate: setup command test for `SetupMode::NonInteractive` under `mandatory` asserting the exact line and no credential-store access. +- [x] AC8: A Claude `SessionStart` under `mandatory` without a valid stored credential emits exactly one `systemMessage` with `SCE login required for this repository. Run 'sce auth login'.`, and emits nothing when logged in or not `mandatory`. The hook always succeeds. + - Validate: hook tests for each case; `nix run .#pkl-check-generated` if the generated Claude settings change. +- [x] AC9: A new ADR supersedes the 2026-10-21 decision and the user-side-only consent rule of the 2026-10-20 decision, and durable context no longer says setup writes access keys globally or that only the user side grants consent. + - Validate: inspect `context/decisions/` and the files listed under Context sync; `nix shell nixpkgs#ripgrep -c rg -n "applies to all repositories on this machine|for this machine|no_user_consent" context cli/src` returns no matches outside superseded ADRs and completed plans. + +### Full validation + +- `nix flake check` +- `nix run .#pkl-check-generated` + +### Context sync + +- `context/cli/access-policy.md` (resolution, contradiction warnings, reasons, Setup, Enforcement). +- `context/sce/setup-repo-local-config-bootstrap.md` (access prompts, Reconfigure, access preferences, report lines, setup login, non-interactive reminder). +- `context/sce/telemetry-credential.md` (doctor health check and its opt-in note, Claude-native telemetry scope). +- `context/glossary.md` (setup access preferences, auth login, doctor entries). +- `context/decisions/` new ADR, with supersession notes on `2026-10-21-setup-writes-access-answers-to-user-layer-only.md` and `2026-10-20-consent-gated-access-policy-precedence.md`. + +## Task context synchronization lifecycle + +- **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/services/setup/` (access preferences, command, mod, prompt), `cli/src/services/config/resolver.rs` and its config types/render, `cli/src/services/doctor/`, the Claude `SessionStart` hook handler under `cli/src/services/hooks/` and its Pkl hook wiring if needed, inline tests, the new ADR, and the context files listed under Context sync. +- **Out of scope:** migrating or deleting existing global access values, `auth.mode` precedence (most restrictive still wins), moving Claude-native telemetry settings out of user-level `~/.claude/settings.json`, changing Claude telemetry removal rules, OpenCode/Pi/Codex session notices, and blocking local SCE features when not logged in. +- **Constraints:** hooks never fail or block a tool call or commit because of a missing login; non-interactive setup keeps its no-credential-store-access contract; keep stdout/stderr contracts and fixed strings apart from the wording changes listed; no new dependencies. +- **Non-goal:** a gitignored per-user repository override file. Values go to the committed `.sce/config.json`. + +## Assumptions + +- "Local" means the repository's committed `.sce/config.json`, so saved answers, including telemetry consent, apply to everyone who uses the repository. The user chose to store telemetry consent there knowing it replaces the consent-gated rule. +- Repository access values are treated as setup's saved answers, not team locks, because setup can't tell which values it wrote. +- Leftover global values from earlier setup runs stay in effect: a global `mandatory` still wins, and a global `telemetry.enabled: false` still opts out. +- "Valid stored credential" for doctor and the session notice uses the non-interactive credential lookup under `CREDENTIAL_LOOKUP_DEADLINE`, as the setup authorization check does, and fails closed: an unavailable store counts as not logged in. Non-interactive setup doesn't do this lookup, so it prints its reminder whenever the mode is `mandatory`. +- The Claude session notice uses the `SessionStart` hook's JSON `systemMessage` output. Whether it extends `sce hooks claude-model-state` or adds a new hook entry is decided in T06. + +## Task stack + +- [x] T01: `Add repository-local access preferences writer` (status:done) + - Task ID: T01 + - Scope: In — a repository `auth.mode` / `telemetry.enabled` reader and writer in `cli/src/services/setup/access_preferences.rs` (or a sibling module) reusing `write_atomically`, plus unit tests. Out — setup wiring, resolver, report wording, docs. + - Dependencies: none + - Done when: the writer writes only explicit answers, bootstraps a missing file, preserves unrelated keys, skips no-op writes, writes atomically, and refuses invalid, concurrently modified, and symlinked files without changing them; targeted tests pass. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml access_preferences`. + - Completed: 2026-10-22 + - Files changed: `cli/src/services/setup/access_preferences.rs`, `cli/src/services/setup/command.rs`, `cli/src/services/setup/mod.rs` + - Result: The writer core now depends on the config layer (`ConfigLayer::Global` / `Repository`). The layer picks the validation source, the labels in errors and I/O context, and the bootstrap value. A missing repository file starts from the existing repo-local bootstrap payload. Added `read_repository_access_preferences` and `persist_repository_access_preferences`, which return `RepositoryAccessPreferencesError` with repository-specific text. The global API and its error strings are unchanged. The shared types were renamed `GlobalAccessPreferences` → `AccessPreferences` and `GlobalWriteOutcome` → `AccessWriteOutcome`; `command.rs` and `mod.rs` only follow the rename. The two new entry points carry `#[cfg_attr(not(test), expect(dead_code))]` until T03 wires them in, and T03 must remove it. Added 7 inline unit tests covering bootstrap, explicit-only answers, preserved keys, no-op skip, invalid/concurrent/symlink refusal with unchanged bytes, and atomic replace keeping the mode. + - Verify outcome: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml access_preferences` passed (7 passed). Extra checks: the `setup` filter passed (69 passed), and `clippy --all-targets --all-features -- -D warnings` was clean. + - Context impact: none — internal helper with no behavior change until T03 wires it; durable context updates belong to T07. + - Context synchronization: synced + +- [x] T02: `Let repository telemetry.enabled grant consent` (status:done) + - Task ID: T02 + - Scope: In — `resolve_access_policy` telemetry state (any `false` disables, otherwise any `true` enables), removal of `TelemetryDisabledReason::NoUserConsent` and its contradiction warning, the `sce config show` telemetry note text, resolver and render tests. Out — `auth.mode` precedence, setup, doctor. + - Dependencies: none + - Done when: AC5 holds; the remaining contradiction warnings and reason strings are unchanged. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml resolver`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml config`. + - Completed: 2026-10-22 + - Files changed: `cli/src/services/config/resolver.rs`, `cli/src/services/config/types.rs`, `cli/src/services/config/render.rs` + - Result: `resolve_access_policy` now checks in this order: `invalid_config`, then `auth_disabled`, then user/explicit `false` → `user_opt_out`, then repository `false` → `repository_opt_out`, then any `true` → `Enabled`, otherwise `not_enabled`. A new helper, `resolve_telemetry_enabled`, sets the reported `telemetry.enabled` value and source from the layer that decides the outcome: the first `false` across explicit, user, repository, otherwise the first `true` across explicit, repository, user. Before, it was the first layer with any value. Removed `TelemetryDisabledReason::NoUserConsent`, `WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT`, and the `user_telemetry_*` helpers. The other warnings and reason strings are unchanged. For `not_enabled`, `sce config show` now uses the new `TELEMETRY_NOT_ENABLED_NOTE`, which begins `Set telemetry.enabled: true in the repository SCE config to enable SCE telemetry for this repository.` and then repeats the unchanged Claude-settings removal text. Every other disabled reason keeps the existing note. Added 5 resolver tests and 2 render tests. + - Verify outcome: `resolver` filter passed (25 passed); `config` filter passed (91 passed). Extra checks: `setup` filter passed (69 passed); `clippy --all-targets --all-features -- -D warnings` was clean; the built `sce config show --format json` in a temp repository with only a repository `telemetry.enabled: true` (isolated `XDG_CONFIG_HOME`) gave `effective.state` `enabled`, `enabled.config_source` `default_discovered_local`, `note` null, and no warnings. + - Context impact: behavior change to the effective access policy — `no_user_consent` and its warning are gone, a repository `true` grants consent, the reported `telemetry.enabled` source is the deciding layer, and there is a new `not_enabled` note. Affects `context/cli/access-policy.md` (resolution flow, contradiction warnings, reason strings, `telemetry.note`); the ADR supersession belongs to T07. + - Context synchronization: synced + +- [x] T03: `Save and read setup access answers in the repository layer` (status:done) + - Task ID: T03 + - Scope: In — `prepare_interactive_setup` reads saved answers from the repository file and writes new ones through the T01 writer before the target install; remove setup's global access write; `SetupAccessGate::from_policy` locks on global/explicit instead of repository; the invalid repository file gates the access prompts; prompt labels, `SCE access:` saved lines, and write-failure text naming the repository file; setup tests. Out — login step behavior, non-interactive setup, doctor, hooks. + - Dependencies: T01, T02 + - Done when: AC1–AC4 hold in setup command and dispatch tests, and the report shows repository scope for both answers. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup`. + - Completed: 2026-10-22 + - Files changed: `cli/src/services/setup/access_preferences.rs`, `cli/src/services/setup/command.rs`, `cli/src/services/setup/mod.rs`, `cli/src/services/setup/prompt.rs` + - Result: `prepare_interactive_setup` gets the global config path no more. It reads saved answers from `/.sce/config.json` through `read_repository_access_preferences`, and `PersistedSetupConfirmations::with_repository_access_preferences` folds them in. It writes the answers through `persist_repository_access_preferences` inside `prepare_dispatch`, so this runs before the target install. `SetupAccessSave` now holds `repository_config_path`. A failed write maps to `Failed to save SCE access preferences to the repository SCE config ''.` plus the writer error and `REPOSITORY_ACCESS_*_REMEDIATION`, which keeps the existing remediation text. Removed `persist_global_access_preferences`, `GlobalAccessPreferencesError`, and the T01 `dead_code` expects. `global_config_invalid` became `repository_config_invalid`: an invalid repository file skips the access prompts, and an invalid global file no longer does. `SetupAccessGate::from_policy`: `auth_locked_by` drops `Repository` instead of `Global`, and `mandatory_locked` holds for every source except `Default` and the repository file. Wording: `SAVED_ACCESS_SCOPE` is now `applies only to this repository`. Saved and unchanged lines name `repository SCE config ''`. The prompt title is now `SCE account mode for this repository`, and the telemetry label ends `Applies only to this repository.`. Deviation (approved assumption): the Claude-native telemetry removal step still reads only the global preferences (`default_global_preferences()`), because the removal rules are out of scope. So a repository `telemetry.enabled: false` answer gives `SkipDisabled`, not `Remove`. T07 should record this in the ADR. Added 4 setup command tests: repository-only write with preserved keys and the exact report; saved-answer prompt suppression, global-only prompting, `--reconfigure` defaults, the repository/global `disabled` and global `mandatory` gates, and invalid-file skip; per-layer gate locks; the symlink abort with the exact error and an untouched target. The recording `FakePrompter` now logs each prompt with its default. + - Verify outcome: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup` passed (73 passed). Extra checks: `clippy --all-targets --all-features -- -D warnings` was clean, `cargo fmt` was applied, and `rg "applies to all repositories on this machine|for this machine|Applies to all repositories|global_config_invalid" cli/src` returned no matches. + - Context impact: user-visible behavior change. Interactive setup now saves `auth.mode` / `telemetry.enabled` to the repository `.sce/config.json`. Saved answers and prompt suppression come from the repository file. Global or explicit values are the locks. Prompt labels and the `SCE access:` lines say repository scope. Affects `context/sce/setup-repo-local-config-bootstrap.md` (access prompts, Reconfigure, access preferences, report lines), the Setup section of `context/cli/access-policy.md`, and the glossary entry for setup access preferences. The ADR belongs to T07. + - Context synchronization: synced + +- [x] T04: `Report mandatory login and repository telemetry state in sce doctor` (status:done) + - Task ID: T04 + - Scope: In — a doctor `SCE login` check (blocking `[FAIL]` under effective `mandatory` without a valid stored credential, naming the deciding config file, fix `Run 'sce auth login'`); the managed-telemetry row and JSON show the repository's effective telemetry state and source; `OPT_IN_NOTE` points at the repository config; doctor render tests. Out — `sce doctor --fix` behavior, credential creation, other doctor rows. + - Dependencies: T02 + - Done when: AC6 holds with exact text and JSON assertions; doctor still never creates `auth.db` or a credential-store key. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml doctor`. + - Completed: 2026-10-22 + - Files changed: `cli/src/services/doctor/access.rs` (new), `cli/src/services/doctor/managed_telemetry.rs`, `cli/src/services/doctor/mod.rs`, `cli/src/services/doctor/render.rs`, `cli/src/services/doctor/types.rs`, `cli/src/services/lifecycle.rs` + - Result: A new `doctor/access.rs` holds `DoctorAccess`. It is built once per run from `resolve_observability_runtime_config(repository_root).access_policy`; a failed resolution becomes `invalid_config` with no login check. Under effective `mandatory` it calls `auth_command::repository_telemetry_authorized`, the same non-interactive, deadline-bounded, fail-closed lookup setup uses. That lookup checks `auth.db` exists before opening it, so doctor never creates it. Other modes skip the lookup. A missing login adds a `SceLoginRequired` problem (`Error`, `ManualOnly`, `global_state`, next action `auth_login`). Its summary is `auth.mode: mandatory is set in the , but no valid SCE login was found.` and its remediation is `Run 'sce auth login'.`. The config file labels are `repository SCE config (`.sce/config.json`)`, `global SCE config`, `SCE config file passed with `--config``, and `SCE config file named by `SCE_CONFIG_FILE``. The new Environment row reads `SCE login` (`[FAIL]` with details, or `[PASS]`), or `SCE login (not required)`. The managed-telemetry row label is now `Managed telemetry: enabled for this repository` or `Managed telemetry: disabled (reason: )`, with ` (not configured)` added when telemetry is enabled but no credential is stored. A `Source: ` detail shows on every row, including pass rows. The source is the deciding `telemetry.enabled` layer, the `auth.mode` source for `auth_disabled`, and none for `invalid_config`. The existing credential warnings are unchanged. `OPT_IN_NOTE` now says `... set telemetry.enabled: true in the repository SCE config to enable it for this repository.` and shows only for `not_enabled` when an auth DB exists. JSON adds a top-level `sce_login` {`state`: `not_required`|`logged_in`|`not_logged_in`, `auth_mode`, `source`, `config_source`} and `managed_telemetry.policy` {`state`, `reason`, `source`, `config_source`}. Existing keys are unchanged. `HealthProblemKind::SceLoginRequired` was added so the doctor/lifecycle kind mappings stay exhaustive. To keep `render_report_json` under clippy's line limit, the `post_commit_auto_sync` JSON moved into a helper with no output change. Approved assumptions: I chose the row labels, source wording, and JSON field names; the plan did not fix them. Added 6 render tests with exact text and JSON assertions: mandatory without login, mandatory with login, non-mandatory skipping the lookup (the lookup closure panics if called), repository consent enabled, `not_enabled` with the opt-in note, and user opt-out without the note. + - Verify outcome: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml doctor` passed (27 passed). Extra checks: `clippy --all-targets --all-features -- -D warnings` was clean, and `cargo fmt` was applied. I ran the built `sce doctor` in a temp git repository with `.sce/config.json` `{"auth":{"mode":"mandatory"}}` and isolated `HOME` / `XDG_CONFIG_HOME` / `XDG_STATE_HOME`. It printed `[FAIL] SCE login` with the exact problem and remediation. It printed `[PASS] Managed telemetry: disabled (reason: not_enabled)` / `Source: default`. JSON had `sce_login.state` `not_logged_in` with `config_source` `default_discovered_local`. No `auth*` file was created under the isolated directories. + - Context impact: user-visible behavior change to `sce doctor` text and JSON: a new `SCE login` row and blocking problem, new managed-telemetry row labels and the `Source:` detail, new `OPT_IN_NOTE` text, and new `sce_login` / `managed_telemetry.policy` JSON objects. Affects `context/sce/telemetry-credential.md` (doctor health check and opt-in note), the doctor entries in `context/glossary.md`, and any doctor output description in `context/cli/cli-command-surface.md`. + - Context synchronization: synced + +- [x] T05: `Print a login reminder in non-interactive setup under mandatory` (status:done) + - Task ID: T05 + - Scope: In — non-interactive and target-flag setup add the fixed `SCE login: required by auth.mode: mandatory for this repository; run 'sce auth login' if you are not logged in.` line when the effective mode is `mandatory`; setup tests. Out — running login, credential lookup, exit-code changes, hooks-only and context-only modes. + - Dependencies: T03 + - Done when: AC7 holds; non-`mandatory` runs and interactive runs print no new line. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup`. + - Completed: 2026-10-22 + - Files changed: `cli/src/services/setup/command.rs` + - Result: Added `SETUP_LOGIN_REMINDER_LINE` (`SCE login: required by auth.mode: mandatory for this repository; run 'sce auth login' if you are not logged in.`) and `non_interactive_login_reminder`. That function resolves the access policy for the repository root and returns the line only when the effective `auth.mode` is `mandatory`. A failed policy resolution returns no line, so setup never fails or changes its exit code because of the reminder. A new `non_interactive_followup` helper replaces the inline non-interactive `else` branch of `SetupCommand::execute`. It pushes the reminder as its own section after the target install output and before the Claude telemetry section, then returns the existing non-interactive Claude telemetry action. The helper exists only to keep `execute` under clippy's line limit. Only non-interactive and target-flag setup reach that branch. Interactive runs keep their login step, and hooks-only and context-only runs never reach it. The reminder only resolves config: no `auth.db` open, no credential lookup. Approved assumptions: the reminder's placement, and no reminder when resolution fails. Added 2 tests. One covers repository, global, and explicit `mandatory`, which print the exact line, and repository `optional`, `disabled`, and the default, which print nothing; it also asserts no `auth*` file is created under the fixture directory. The other covers resolution failure, which prints nothing. + - Verify outcome: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup` passed (75 passed). Extra checks: `clippy --all-targets --all-features -- -D warnings` was clean, and `cargo fmt` was applied. The built `sce setup --opencode` was run in a temp git repository with a remote and isolated `HOME` / `XDG_CONFIG_HOME` / `XDG_STATE_HOME`. With `.sce/config.json` `{"auth":{"mode":"mandatory"}}` it exited 0 and printed the exact reminder line. With `optional` it exited 0 and printed no `SCE login` line. No `auth*` file was created under the isolated directories. + - Context impact: user-visible output addition to non-interactive setup: a fixed reminder line under effective `mandatory`. Affects the non-interactive reminder part of `context/sce/setup-repo-local-config-bootstrap.md` and the Setup / Enforcement part of `context/cli/access-policy.md`. + - Context synchronization: synced + +- [x] T06: `Notify Claude sessions when an SCE login is required` (status:done) + - Task ID: T06 + - Scope: In — at Claude `SessionStart`, resolve the policy for the session working directory and, under `mandatory` without a valid stored credential, emit one `systemMessage` `SCE login required for this repository. Run 'sce auth login'.`; Pkl hook wiring if a new hook entry is needed; hook tests. Out — OpenCode/Pi/Codex notices, blocking the session, repeated notices within a session. + - Dependencies: T04 + - Done when: AC8 holds; the hook exits successfully in every case, including policy-resolution and credential-lookup failures. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude`; `nix run .#pkl-check-generated` when Pkl changes. + - Completed: 2026-10-22 + - Files changed: `cli/src/services/hooks/claude_model_state.rs` + - Result: The notice is added to the existing `sce hooks claude-model-state` handler, which the generated Claude settings already run at `SessionStart`. No new hook entry or Pkl change was needed. A new `session_login_notice` helper takes injected policy and credential seams. It returns nothing unless the payload's `hook_event_name` is `SessionStart`. It then resolves the access policy for the hook working directory through `resolve_auth_runtime_config` and, only under effective `mandatory`, runs `auth_command::repository_telemetry_authorized`. That is the same non-interactive, deadline-bounded, fail-closed lookup doctor uses, and it never creates `auth.db`. With no valid credential it returns `{"systemMessage":"SCE login required for this repository. Run 'sce auth login'."}` (constant `SESSION_LOGIN_REQUIRED_MESSAGE`). `run_claude_model_state_subcommand` computes the notice right after reading stdin and before the clock and model-state persistence. It returns the notice as the hook output, so a model-state failure never suppresses it. A failed policy resolution returns nothing, and model-state behavior is unchanged. The hook still always returns successfully. It fires once per `SessionStart` event. Approved assumption: extend `claude-model-state` rather than add a new hook entry. Added 5 inline tests: mandatory without login emits exactly the one-key `systemMessage`; mandatory with login emits nothing; `optional` / `disabled` emit nothing and never run the lookup; non-`SessionStart`, eventless, and non-JSON payloads never resolve the policy; a resolution failure emits nothing. + - Verify outcome: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude` passed (43 passed; the 5 new tests ran under the `claude_model_state` filter, 7 passed). `nix run .#pkl-check-generated` was not needed because no Pkl changed. Extra checks: `clippy --all-targets --all-features -- -D warnings` was clean, and `cargo fmt` was applied. I ran the built `sce hooks claude-model-state` in a temp git repository with isolated `HOME` / `XDG_CONFIG_HOME` / `XDG_STATE_HOME`. A `SessionStart` under repository `mandatory` printed exactly the `systemMessage` JSON and exited 0. `PostModelSwitch` under `mandatory`, `SessionStart` under `optional`, and `SessionStart` with an invalid `.sce/config.json` printed nothing to stdout and exited 0. The existing invalid-config startup diagnostic still goes to stderr. No `auth*` file was created. + - Context impact: user-visible addition. At Claude `SessionStart`, `sce hooks claude-model-state` may now emit a `systemMessage` login notice under effective `mandatory` without a valid stored credential. Affects the Enforcement part of `context/cli/access-policy.md` and any description of `claude-model-state` hook output (for example the Claude hook entries in `context/glossary.md` or `context/sce/` hook docs). + - Context synchronization: synced + +- [x] T07: `Record repository-scoped access answers and sync context` (status:done) + - Task ID: T07 + - Scope: In — new ADR under `context/decisions/` superseding `2026-10-21-setup-writes-access-answers-to-user-layer-only.md` and the user-side-only consent rule of `2026-10-20-consent-gated-access-policy-precedence.md` (supersession notes added to both), covering the lock change, the committed-file consent risk, and the older-binary risk; update the context files listed under Context sync. Out — code changes. + - Dependencies: T03, T04, T05, T06 + - Done when: AC9 holds. + - Verify: `nix shell nixpkgs#ripgrep -c rg -n "applies to all repositories on this machine|for this machine|no_user_consent" context cli/src`. + - Completed: 2026-10-22 + - Files changed: `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`, `context/decisions/2026-10-21-setup-writes-access-answers-to-user-layer-only.md` + - Result: The replacing ADRs were already recorded during the T02 and T03 context syncs. `2026-10-22-setup-writes-access-answers-to-repository-config.md` covers the lock change, the committed-file consent risk, the older-binary risk, and the T03 Claude-removal deviation. `2026-10-22-repository-telemetry-enabled-grants-consent.md` covers the consent rule. Approved assumption: those two ADRs together serve as the plan's new ADR, so no third ADR was written. T07 added the supersession notes. The 2026-10-21 ADR is now `Status: Superseded`, with a `Superseded by:` line and a note pointing to the repository-config ADR. The 2026-10-20 ADR is now `Status: Accepted (partially superseded)`, with a `Partially superseded by:` line limited to the user-side-only consent rule, and a note saying which parts still apply. The Context sync files (`access-policy.md`, `setup-repo-local-config-bootstrap.md`, `telemetry-credential.md`, `glossary.md`, `context-map.md`) already describe repository-scoped answers, any-layer consent, the doctor `SCE login` row, the non-interactive reminder, and the Claude session notice, so none of them changed. Follow-up outside this task's no-code scope: the login provisioning message `TELEMETRY_PROVISIONING_DISABLED` (`cli/src/services/auth_command/mod.rs`) still says `Set telemetry.enabled: true in the global SCE config to enable it.`. `context/cli/access-policy.md` quotes it exactly. + - Verify outcome: the planned `rg` check ran. Matches remain only in: completed plans (`auth-telemetry-policy-config`, `setup-auth-telemetry-consent`, `claude-telemetry-consent-reconciliation`); this active plan's own description of the change; the superseded 2026-10-21 ADR; the partially superseded 2026-10-20 ADR; the 2026-10-22 consent ADR and its `context-map.md` index entry, both of which record the removal of `no_user_consent`. There are no matches in `cli/src` or in any current-state context file. AC9 holds. + - Context impact: decision records only. The two older ADRs now carry supersession status and notes. No current-state context or code behavior changed. + - Context synchronization: synced + +## Open questions + +- Storing `telemetry.enabled: true` in the committed `.sce/config.json` means anyone who clones or pulls the repository is opted in without being asked. The 2026-10-20 decision existed to prevent exactly that. The plan does what you asked. A smaller alternative keeps the per-repository scope and per-person consent: save the answer to a gitignored per-user file such as `.sce/config.local.json`. +- Claude-native telemetry settings stay in the user-level `~/.claude/settings.json`, so Claude Code is set up to export in every repository. In repositories without consent the headers helper fails closed, so export there has no SCE credential. Claude may still try to send to the OTLP endpoint. Moving those settings into the repository's Claude settings is out of scope here. +- Older released binaries (`v0.4.0-pre-alpha-v11` and earlier) reject the `auth` and `telemetry` keys. A teammate on one of them has the whole repository config skipped as invalid, including bash policies and integration targets. The plan records this as a release-coupling risk in the ADR. The safer alternative is to hold the repository write until a release that accepts the keys has shipped. +- Should a team-committed repository value (especially `auth.mode: disabled`) still lock the setup prompts? The plan lets `sce setup --reconfigure` change any repository value. + +## Validation Report + +**Status:** validated +**Date:** 2026-10-22 + +### Commands run + +- `nix flake check` -> exit 0 (all 3 checks passed: `cli-tests`, `cli-clippy`, `cli-fmt`) +- `nix run .#pkl-check-generated` -> exit 0 (ephemeral Pkl generation passed: 145 files) +- `nix shell nixpkgs#ripgrep -c rg -n "applies to all repositories on this machine|for this machine|no_user_consent" context cli/src` -> exit 0 (matches only in completed plans, this plan, the superseded/partially superseded ADRs, and the 2026-10-22 consent ADR plus its `context-map.md` index entry recording the removal; none in `cli/src`) +- `nix build .#default` then built `sce config show --format json` in a temp repo with only repository `telemetry.enabled: true` (isolated `HOME`/`XDG_*`) -> exit 0 (`effective.state` `enabled`, `enabled.config_source` `default_discovered_local`, `note` null) +- Built `sce doctor` (text and `--format json`) in a temp repo with repository `auth.mode: mandatory` and no login -> exit 0 (`[FAIL] SCE login` with `auth.mode: mandatory is set in the repository SCE config (`.sce/config.json`), but no valid SCE login was found.` / `Run 'sce auth login'.`; JSON `sce_login.state` `not_logged_in`; no `auth*` file created) +- Built `sce doctor` in the repository-consent temp repo -> exit 0 (`[PASS] Managed telemetry: enabled for this repository (not configured)`, `Source: repository SCE config (`.sce/config.json`)`) + +### Success-criteria verification + +- [x] AC1: Interactive setup writes access answers to the repository `.sce/config.json` only, keeping unrelated keys -> setup command tests pass inside `nix flake check` `cli-tests` +- [x] AC2: Repository-saved answers suppress prompts, `--reconfigure` defaults to them, global values no longer suppress -> `FakePrompter` dispatch tests pass in `cli-tests` +- [x] AC3: Repository writer refuses invalid, concurrently modified, or symlinked files byte-identically; setup aborts before target install -> writer unit tests and symlink abort test pass in `cli-tests` +- [x] AC4: Global/explicit `disabled` skips prompts, global/explicit `mandatory` suppresses login offer; repository values are defaults only -> `SetupAccessGate::from_policy` per-layer tests pass in `cli-tests` +- [x] AC5: Repository `true` alone enables telemetry, any `false` disables, `no_user_consent` gone -> resolver tests pass; built `sce config show --format json` shows `enabled`; no `no_user_consent` in `cli/src` +- [x] AC6: `sce doctor` reports blocking `SCE login` failure with fix and shows repository telemetry state and source -> doctor render tests pass; built `sce doctor` text/JSON confirmed in both temp repos +- [x] AC7: Non-interactive setup under `mandatory` prints the fixed reminder, exits 0, no credential-store access -> non-interactive setup tests pass in `cli-tests` +- [x] AC8: Claude `SessionStart` under `mandatory` without login emits exactly one `systemMessage`, nothing otherwise, always succeeds -> `claude_model_state` hook tests pass in `cli-tests`; no Pkl change, `pkl-check-generated` passed +- [x] AC9: New ADRs supersede the 2026-10-21 decision and the user-side-only consent rule; durable context updated -> inspected `context/decisions/` (2026-10-21 `Superseded`, 2026-10-20 `partially superseded`, two 2026-10-22 ADRs); remaining `rg` matches are historical records of the change only + +### Failed checks and follow-ups + +- None. + +### Residual risks + +- `TELEMETRY_PROVISIONING_DISABLED` in `cli/src/services/auth_command/mod.rs` still says `Set telemetry.enabled: true in the global SCE config to enable it.` (recorded T07 follow-up, outside this plan's wording changes). +- Committed repository `telemetry.enabled: true` opts in every cloner without asking, and older binaries (`v0.4.0-pre-alpha-v11` and earlier) reject the `auth`/`telemetry` keys; both are recorded open questions/ADR risks. +- Claude-native telemetry removal still reads only global preferences, so a repository `telemetry.enabled: false` answer gives `SkipDisabled` rather than `Remove` (recorded T03 deviation). +- In a bare temp repo, `sce doctor` repeats the same state/repository-identity problems under several Environment rows; this is outside the plan's scope and was not investigated here. diff --git a/context/sce/agent-trace-hook-doctor.md b/context/sce/agent-trace-hook-doctor.md index ad2be4b91..15c9931e7 100644 --- a/context/sce/agent-trace-hook-doctor.md +++ b/context/sce/agent-trace-hook-doctor.md @@ -97,6 +97,8 @@ Every detected issue must map to exactly one stable problem category: Each problem record must also include stable severity and fixability classes. +JSON problem records also carry `kind` (a stable snake_case problem identifier such as `claude_integration_files_missing` or `required_hook_missing`) and `target` (`claude`, `opencode`, `pi`, or `codex` when the problem is scoped to one integration or adapter mutation-scope runtime; `null` for repository-wide problems such as git hooks or login). Consumers filter on these fields rather than parsing `summary` text. + ### Severity classes - `error`: blocks readiness and requires repair or explicit manual action diff --git a/context/sce/agent-trace-hooks-command-routing.md b/context/sce/agent-trace-hooks-command-routing.md index ab1e9ed97..73bfae75d 100644 --- a/context/sce/agent-trace-hooks-command-routing.md +++ b/context/sce/agent-trace-hooks-command-routing.md @@ -129,7 +129,7 @@ Interactive `sce setup` persists the independent confirmations at `agent_trace.a - Current valid-payload success output reports deterministic mixed-batch accounting: `conversation-trace hook persisted mixed payload batch to AgentTraceDb: attempted=, persisted_messages=, persisted_parts=, skipped=.` The hook does not persist `context/tmp` artifacts. - Fail-open output for conversation-trace intake failures is `conversation-trace hook intake failed open; error logged.` so hook callers do not receive app-level classified errors or non-zero exits for intake failures. - The generated OpenCode agent-trace plugin emits this mixed-batch shape for conversation-trace handoff with `tool_name: "opencode"`: ordinary message/part events produce one-item mixed envelopes, completed question-tool parts produce `message.part` items with `part_type: "question"`, and diff-backed message events produce one envelope containing the synthetic parent `message` item plus patch `message.part` items. The Pi extension uses the same shape with `tool_name: "pi"`. -- `sce hooks claude-model-state` is a silent, local-only lifecycle intake for raw Claude `SessionStart` and `PostModelSwitch` events. A model-bearing `SessionStart` writes normalized `claude/` state, while a `PostModelSwitch` validates `from_model` and `to_model` but writes normalized `to_model`; both use canonical `cc_` plus exact optional `agent_id` scope (`""` for the main conversation). Missing or null `agent_id` means the main scope; a present string is trimmed and must remain non-empty, so malformed empty or non-string values fail open without a state write. Current Claude sources include `command`, `picker`, `sdk`, `auto`, and `resume`; SCE accepts any non-empty source string and stores it opaquely. A model-less `SessionStart` first attempts bounded, local-only bridge-session correlation through the event's `transcript_path`: it reads only leading records for the `bridgeSessionId`, then resolves the model through the same single newest-chain-observation selection rule the `diff-trace` state-miss path uses — bounded leading-record reads of sibling `.jsonl` transcripts sharing that `bridgeSessionId`, one exact-scope `(cc_, "")` read per member, winner by greatest `observed_at_ms` with a deterministic session-ID tie-break — and seeds the current session with that model as `source="bridge_inherited"` when a chain observation exists. There is no separate SessionStart selection rule and no most-recently-modified-sibling pick. Missing or malformed discovery inputs, no chain observation, filesystem races, and DB reads fail open to the existing no-op. In practice this `SessionStart` attempt fires before Claude has created the session's transcript file, so it reads nothing and always no-ops; bridge inheritance for a cleared session is actually carried by the `diff-trace` state-miss path above, and this attempt is kept only for the case Claude ever creates transcripts eagerly. The command uses the existing guarded latest-locally-observed register and local SCE observation time. The command reads and writes directly through the no-migration hook-runtime repository DB path before returning, does not migrate, sync, or access the network, and returns zero stdout bytes with logger-only fail-open diagnostics for input, clock, DB-open, DB-read, and DB-write failures. Claude's SessionStart invocation is synchronous relative to Claude execution, while PostModelSwitch is asynchronous; overlapping hooks and bridge/model-switch races are accepted and local observation time does not prove Claude causal ordering. Generated Claude settings register both lifecycle events for this command, while the existing five SCE registrations remain unchanged. Claude Code 2.1.250 and 2.1.251 compatibility smoke passed with an unknown PostModelSwitch registration, so installation remains unconditional with no raised minimum or capability gate. +- `sce hooks claude-model-state` is a local-only lifecycle intake for raw Claude `SessionStart` and `PostModelSwitch` events. It is silent; the Claude session login notice is owned by the `sce-info` hooks module ([access policy: enforcement](../cli/access-policy.md#enforcement)). A model-bearing `SessionStart` writes normalized `claude/` state, while a `PostModelSwitch` validates `from_model` and `to_model` but writes normalized `to_model`; both use canonical `cc_` plus exact optional `agent_id` scope (`""` for the main conversation). Missing or null `agent_id` means the main scope; a present string is trimmed and must remain non-empty, so malformed empty or non-string values fail open without a state write. Current Claude sources include `command`, `picker`, `sdk`, `auto`, and `resume`; SCE accepts any non-empty source string and stores it opaquely. A model-less `SessionStart` first attempts bounded, local-only bridge-session correlation through the event's `transcript_path`: it reads only leading records for the `bridgeSessionId`, then resolves the model through the same single newest-chain-observation selection rule the `diff-trace` state-miss path uses — bounded leading-record reads of sibling `.jsonl` transcripts sharing that `bridgeSessionId`, one exact-scope `(cc_, "")` read per member, winner by greatest `observed_at_ms` with a deterministic session-ID tie-break — and seeds the current session with that model as `source="bridge_inherited"` when a chain observation exists. There is no separate SessionStart selection rule and no most-recently-modified-sibling pick. Missing or malformed discovery inputs, no chain observation, filesystem races, and DB reads fail open to the existing no-op. In practice this `SessionStart` attempt fires before Claude has created the session's transcript file, so it reads nothing and always no-ops; bridge inheritance for a cleared session is actually carried by the `diff-trace` state-miss path above, and this attempt is kept only for the case Claude ever creates transcripts eagerly. The command uses the existing guarded latest-locally-observed register and local SCE observation time. The command reads and writes directly through the no-migration hook-runtime repository DB path before returning, does not migrate, sync, or access the network, and returns zero stdout bytes with logger-only fail-open diagnostics for input, clock, DB-open, DB-read, and DB-write failures. Claude's SessionStart invocation is synchronous relative to Claude execution, while PostModelSwitch is asynchronous; overlapping hooks and bridge/model-switch races are accepted and local observation time does not prove Claude causal ordering. Generated Claude settings register both lifecycle events for this command, while the existing five SCE registrations remain unchanged. Claude Code 2.1.250 and 2.1.251 compatibility smoke passed with an unknown PostModelSwitch registration, so installation remains unconditional with no raised minimum or capability gate. - `session-model` is no longer a supported `sce hooks` subcommand and generated Claude settings no longer produce the retired generic session-model route. The `session_models` DB API/table and generic fallback are removed from active code; upgraded databases may still contain the retired table, but runtime paths no longer read or write it. The separate `sce hooks claude-model-state` command is a Claude-specific local register, and `diff-trace` consults its exact `(cc_, agent_id)` state after direct and transcript attribution fail, then — for a main-session-scope raw structured payload only — the newest observation across the transcript's bridge-linked chain, seeding a `source="bridge_inherited"` row for the current session; this remains Claude-specific and does not restore the generic abstraction. - `sce hooks codex` is a separate single dispatcher subcommand (not routed through `diff-trace`/`conversation-trace`), classifying raw Codex hook JSON internally instead. Its `UserPromptSubmit` and `Stop` arms are each a second writer into the same `messages`/`parts` tables, calling the shared `insert_conversation_text_event` atomic primitive rather than the plain `insert_messages`/`insert_parts` calls described above. Its `PostToolUse(apply_patch)` arm is a second, independent writer into `diff_traces` via the existing `insert_diff_trace`, carrying `tool_name = "codex"` and the same `cx_`-prefixed `session_id`; it is independent of the concrete Codex mutation-scope adapter. Apply_patch persistence requires a trimmed non-empty session, preserves reported model IDs without fabricating a provider prefix, and returns empty stdout on every non-policy success or fail-open path. Before persistence it resolves source and move-destination paths independently from the event `cwd` against the canonical Git root: valid `..` components and absolute-inside paths are accepted, missing Add File targets are allowed through their nearest existing prefix, and outside or symlink-escaping mappings are rejected. The existing Codex command resolves that Git root at invocation time and invokes the installed helper with quoted paths, so root and nested cwd (including spaced repository paths) share one entrypoint; its root-resolution failure remains silent and fail-open where designed. The Codex setup/doctor boundary is separate from evidence intake: `.codex/hooks.json` is merged through the shared structural `codex_hook_config` service, which preserves valid user handlers and recognizes the generated helper path plus either the `sce hooks codex` or `sce hooks codex-mutation-scope` command contract, attributing each handler to whichever it matches and merging the two contracts' registrations independently. The mutation-scope `PreToolUse`/`PostToolUse` registrations use matcher `^(Bash|apply_patch)$`; `Stop`/`Interrupt`/`SubagentStop`/`SessionEnd` are unmatched and feed the generic mutation-scope ingress ([../cli/mutation-scope-hook-ingress.md](../cli/mutation-scope-hook-ingress.md)). - `sce hooks mutation-scope` (hidden) is a separate single ingress (not routed through `diff-trace`/`conversation-trace`) that drives the mutation-scope runtime rather than writing conversation/diff evidence. It reads one normalized JSON lifecycle object from STDIN via the shared `read_hook_stdin`, strictly parses it into exactly `start`/`advance`/`close`/`flush`/`abandon`, and translates it into one `RuntimeBoundary` (`start`/`advance`/`close` → `Start`/`Advance`/`Close`; `flush` → `Flush`) passed to `mutation_trace::runtime::coordinate(...)`, or a direct `mutation_trace::runtime::abandon_scope(...)` call for `abandon`. `scope_id`/`event_id`/`actor_kind` (`claude_code`/`codex`/`opencode`/`pi`) are forwarded verbatim — no trim, prefix, hash, UUID, or timestamp — because `EventId` equality is the runtime's replay/idempotency key; `start` alone additionally accepts an optional `provenance` object (non-blank `session_id`, optional `model_id`) forwarded the same way as `RuntimeBoundary::Start`'s `StartProvenance` and, when the runtime's admission-bounded rule allows it, durably registered before the protocol commits — a row may only be created while the durable scope is still `NeverSeen`, so a `start` replayed against an already-admitted scope that has no provenance still succeeds and still persists none, while an existing row is validated on every provenance-carrying `start` and a differing `session_id` remains a hard conflict — while `advance`/`close`/`flush`/`abandon` reject the key; any `worktree_id` key is a hard rejection (worktree identity is derived by the runtime from the invoking checkout). DB acquisition is lazy: a `FnOnce` provider closure reusing `open_agent_trace_db_for_hook_runtime` is passed into `coordinate()`/`abandon_scope()` so it runs inside the runtime's protected-worktree ordering, never before. **Non-fail-open intake contract, distinct from `diff-trace`/`conversation-trace`:** a lost lifecycle boundary can change which scope stays live and therefore alter attribution, so the dispatch arm is unwrapped like `pre-commit` (no `Ok(...)` fail-open shim) and there is no dropped-boundary / `exit 0` branch. Results are classified by durable completion — a malformed payload or any pre-completion `CoordinateError`/`AbandonScopeError` returns `CliError`/non-zero; `CoordinateError::MarkerClearAfterCommit` and `AbandonScopeError::MarkerClearAfterCompletion` are the two carried-outcome success variants (the durable transition already succeeded and only the trailing external-taint marker cleanup failed), reported as empty-stdout `Ok` with the failure logged via `sce.hooks.mutation_scope.marker_clear_after_durable_completion` and the transition **not** retried. Every successful execution emits empty stdout with no serialized outcome/revision/worktree/scope state. It writes `mutation_trace_*` rows only — never `diff_traces`, `post_commit_patch_intersections`, or `agent_traces`. A first Claude Code adapter driver now consumes it in-process (see below); the Codex adapter also consumes it in-process, while OpenCode and Pi still have no lifecycle adapter. See [mutation-scope-hook-ingress.md](../cli/mutation-scope-hook-ingress.md) for the full contract. diff --git a/context/sce/doctor-human-text-contract.md b/context/sce/doctor-human-text-contract.md index c3c84ea44..767bc5dcd 100644 --- a/context/sce/doctor-human-text-contract.md +++ b/context/sce/doctor-human-text-contract.md @@ -13,8 +13,10 @@ Human text output renders these sections in this exact order: 3. `Integrations` The `Environment` domain contains `State`, `Configuration`, `Repository -identity`, and `Managed telemetry` (read-only credential health; rows, JSON, and -remediation in [telemetry-credential.md](telemetry-credential.md#doctor-health-check)). +identity`, `SCE login` (see [SCE login row](#sce-login-row)), and `Managed +telemetry` (read-only credential health plus the repository's effective +telemetry state; rows, JSON, and remediation in +[telemetry-credential.md](telemetry-credential.md#doctor-health-check)). A warning row expands into `Reason: `, the summary, the hook-impact line, and a `To fix:` step list. The `Repository` domain contains `Git repository`, `Post-commit Agent Trace auto-sync`, and `Git hooks`. @@ -25,6 +27,31 @@ reconciliation` section; it is omitted otherwise. `sce doctor --fix` appends one `mutation_scope_health` fix-result row for its reconciliation pass. Details in [../cli/doctor-ref-reconciliation.md](../cli/doctor-ref-reconciliation.md). +## SCE login row + +The row makes a missing login under `auth.mode: mandatory` visible without +blocking local SCE features. + +- Effective mode not `mandatory`: `[PASS] SCE login (not required)`. No + credential lookup runs. +- `mandatory` with a valid stored credential: `[PASS] SCE login`. +- `mandatory` without one: `[FAIL] SCE login`, expanded into + `Problem: auth.mode: mandatory is set in the , but no valid SCE + login was found.` and `Remediation: Run 'sce auth login'.`. The config file is + the layer that decided the mode (repository `.sce/config.json`, global SCE + config, `--config` file, or `SCE_CONFIG_FILE` file). The problem is + `global_state`, severity `error` (blocking), `manual_only`, next action + `auth_login`, so `--fix` reports it as a `manual` fix result and never logs in. +- "Valid stored credential" uses the setup login check + (`auth_command::repository_telemetry_authorized`): a repository-bound + credential that the current session owns. It is looked up only when `auth.db` + exists, non-interactively, under `CREDENTIAL_LOOKUP_DEADLINE`, and it fails + closed: an unavailable store counts as not logged in. Doctor never creates + `auth.db` or a credential-store key. +- JSON adds a top-level `sce_login` object: `state` (`not_required`, + `logged_in`, `not_logged_in`), `auth_mode`, `source`, and `config_source`. +- Code: `cli/src/services/doctor/access.rs`. + ## Header and status vocabulary - Diagnose mode renders `SCE doctor`. diff --git a/context/sce/setup-no-backup-policy-seam.md b/context/sce/setup-no-backup-policy-seam.md index e2d71edde..a40f9fcf2 100644 --- a/context/sce/setup-no-backup-policy-seam.md +++ b/context/sce/setup-no-backup-policy-seam.md @@ -25,8 +25,8 @@ `sce setup --claude` and `sce setup --all` install the three runtime files in `.claude/skills/sce-info`: `.claude-plugin/plugin.json`, `hooks/hooks.json`, and -`hooks/register.ts`. The package retains its `sce-splash` manifest identity -and supplied startup-rendering behavior. Packaging does not add a workflow +`hooks/register.ts`. The package uses the `SCE` manifest identity +and supplied startup-rendering behavior, plus the Claude session login notice, missing-CLI install guidance stamped with the expected CLI version, a single missing-git-hooks notice, a single outdated-Claude-skills notice, and other Claude doctor problem notices. Packaging does not add a workflow entrypoint or change plugin activation. Individual OpenCode, Pi, and Codex setup targets install no `sce-info` assets. diff --git a/context/sce/setup-repo-local-config-bootstrap.md b/context/sce/setup-repo-local-config-bootstrap.md index 5baab6eb3..ab725439f 100644 --- a/context/sce/setup-repo-local-config-bootstrap.md +++ b/context/sce/setup-repo-local-config-bootstrap.md @@ -20,21 +20,21 @@ Task `setup-repo-gate-and-local-config-bootstrap` T02, `turso-local-db-sync` T04 ``` 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. + - `SCE account mode for this repository` (`Select`; cursor on `optional`). It is skipped when the repository `.sce/config.json` already holds `auth.mode` (unless `--reconfigure`), or when that file is invalid. + - `Share SCE telemetry?` (`Confirm`; default No; its label ends `Applies only to this repository.`). It is skipped when the repository file already holds `telemetry.enabled` (unless `--reconfigure`), when that file 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 global or explicit layer enforces `mandatory`, and either an access prompt was asked in this run or no `auth.db` file exists. + - A global or explicit (`--config` / `SCE_CONFIG_FILE`) `auth.mode: disabled` skips all three prompts. Repository values are setup's saved answers, not locks: a repository `disabled` or `mandatory` only suppresses or defaults its own prompt. A global value no longer suppresses a prompt. Cancelling any prompt is the standard setup cancellation. + - Inputs are read without credential access: the resolved access policy, the repository `.sce/config.json`, 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)). + - The answers are saved to the repository `.sce/config.json` before any other setup write (see [Repository access preferences](#repository-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. +`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 repository file's saved value (falling back to the first-run default), so a saved repository `disabled` puts the account-mode cursor on `disabled`. The global/explicit `disabled` lock and the invalid-repository-file 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 repository `mandatory` that `--reconfigure` changes to `optional` gets the login offer, because only a global 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. @@ -43,31 +43,31 @@ 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 +## Repository 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. +Setup saves `auth.mode` and `telemetry.enabled` only to the repository's committed `/.sce/config.json`, so each answer applies only to that repository ([ADR](../decisions/2026-10-22-setup-writes-access-answers-to-repository-config.md)). It never writes them to the global user config or an explicit config file, and it does not migrate access values that earlier setup runs left in the global config; those stay in effect. 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.` +- **Writer:** `persist_repository_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. A missing file starts from the repo-local bootstrap payload. The write is a sibling temp file plus a rename, keeping the existing mode. 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. The global config is only read, for the [Claude telemetry removal](#setup-login) check. +- **Invalid repository 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 the target install, with no other repository file changed. The error is three fixed lines: `Failed to save SCE access preferences to the repository SCE config ''.`, then the writer's `Repository SCE config '' ...` 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, 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) + - auth.mode: (saved to repository SCE config ''; applies only to this repository) + - telemetry.enabled: (saved to repository SCE config ''; applies only to this repository) - 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 nothing was written, the two saved lines are replaced by `- saved access preferences: unchanged (repository 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 leftover global `telemetry.enabled: false` still reports `disabled (reason: user_opt_out)` after a repository consent. + - When a global 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 install stage. When the global user config records a telemetry withdrawal, the [Claude telemetry removal](telemetry-credential.md#claude-native-telemetry) runs and reports between the `SCE access` section and login, whatever the target, so a failed mandatory login cannot skip it. Login never runs for non-interactive, hooks-only, or context-only setup. The login 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: +Interactive setup runs login after the `SCE access` section and before the Claude telemetry install stage. When the global user config records a telemetry withdrawal (a repository `false` answer does not), the [Claude telemetry removal](telemetry-credential.md#claude-native-telemetry) runs and reports between the `SCE access` section and login, whatever the target, so a failed mandatory login cannot skip it. Login never runs for non-interactive, hooks-only, or context-only setup; non-interactive and target-flag runs print a [login reminder](#non-interactive-login-reminder) instead. The login 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 | |---|---|---| @@ -76,7 +76,7 @@ Interactive setup runs login after the `SCE access` section and before the Claud | `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. +- **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 repository 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.` @@ -86,6 +86,10 @@ Interactive setup runs login after the `SCE access` section and before the Claud - **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)). +### Non-interactive login reminder + +Non-interactive and target-flag setup (`sce setup --opencode|--claude|--pi|--codex|--all`, with or without `--non-interactive`) resolves the effective access policy for the setup repository root after the target install. When the effective `auth.mode` is `mandatory`, from any layer, it adds the fixed section `SCE login: required by auth.mode: mandatory for this repository; run 'sce auth login' if you are not logged in.` before the Claude telemetry stage. The reminder only reads config. It never opens `auth.db` or the OS credential store and never checks for a stored login, so it prints whenever the mode is `mandatory`. It never changes the exit code, and a failed policy resolution prints nothing. Other modes, interactive runs (which use the login step above), and hooks-only and context-only runs print no reminder. + ## 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 b0b039896..a58468894 100644 --- a/context/sce/telemetry-credential.md +++ b/context/sce/telemetry-credential.md @@ -39,7 +39,7 @@ flowchart LR ## Doctor health check -`sce doctor` reports managed telemetry as the last `Environment` row and as a top-level JSON `managed_telemetry` object. `managed_telemetry::inspect_health` computes it once per invocation, and it is read-only: +`sce doctor` reports managed telemetry as the last `Environment` row and as a top-level JSON `managed_telemetry` object. `managed_telemetry::inspect_health` computes it once per invocation, and it is read-only. The row and the JSON also report the effective policy for the inspected repository (see [Policy state](#policy-state)): - It never issues a credential, contacts the Control Plane, or starts an OTLP exporter. - It checks the effective access policy for the inspected repository root first; an unresolvable config counts as not enabled. When telemetry is not `Enabled`, it returns `DisabledByConfig { auth_db_present }` without opening `auth.db` or touching the credential store. It only checks whether `auth.db` exists (a stat), to decide on the opt-in line. @@ -48,9 +48,9 @@ flowchart LR | Health | Text row | JSON `state` / `reason` | Problem `kind` | `next_action` | | --- | --- | --- | --- | --- | -| Telemetry not `Enabled` by policy | `[PASS] Managed telemetry (disabled by config)` | `disabled_by_config` / `disabled_by_config` | none | none | -| No `auth.db`, or no telemetry row | `[PASS] Managed telemetry (not configured)` | `not_configured` / `not_configured` | none | none | -| Credential valid | `[PASS] Managed telemetry` | `healthy` / `null` | none | none | +| Telemetry not `Enabled` by policy | `[PASS] Managed telemetry: disabled (reason: )` | `disabled_by_config` / `disabled_by_config` | none | none | +| No `auth.db`, or no telemetry row | `[PASS] Managed telemetry: enabled for this repository (not configured)` | `not_configured` / `not_configured` | none | none | +| Credential valid | `[PASS] Managed telemetry: enabled for this repository` | `healthy` / `null` | none | none | | Store refuses silent access | `[WARN]` | `disabled` / `credential_inaccessible` | `managed_telemetry_credential_inaccessible` | `auth_login` | | Unusable row (no WorkOS session, identity mismatch, legacy or malformed) or schema not current | `[WARN]` | `disabled` / `credential_unavailable` | `managed_telemetry_credential_unavailable` | `auth_login` | | Credential expired | `[WARN]` | `disabled` / `credential_expired` | `managed_telemetry_credential_expired` | `auth_login` | @@ -60,10 +60,16 @@ flowchart LR - The JSON object has `state`, `reason`, `kind`, `severity` (`warning` or `null`), and `next_action`. A warning also appears in `problems` (category `global_state`, severity `warning`, fixability `manual_only`) with the same `next_action`. It never makes doctor `not_ready`. - Every warning says that Claude Code hooks continue working and only telemetry export is disabled. -- When telemetry is disabled by config and `auth.db` exists (an earlier login stored credentials), the `disabled by config` row adds one fixed line: `Managed telemetry export is off because telemetry.enabled is not true; set telemetry.enabled: true in the global SCE config to resume it.` +- When the disabled reason is `not_enabled` and `auth.db` exists (an earlier login stored credentials), the row adds one fixed line: `Managed telemetry export is off because telemetry.enabled is not true; set telemetry.enabled: true in the repository SCE config to enable it for this repository.` Other disabled reasons (an opt-out, `auth_disabled`, `invalid_config`) never show it. - Only macOS `credential_inaccessible` recommends choosing "Always Allow" in the Keychain dialog shown by `sce auth login`. Other platforms name their store (Secret Service, Windows Credential Manager) instead. Expiry, missing credentials, timeouts, and DB or path errors never mention it. - Output uses fixed text only. It never includes `TokenStorageError` details, Keychain error codes, keys, WorkOS tokens, or OpenBao tokens. The detailed reason stays in the local `sce.telemetry.fallback` log event that the same doctor invocation's startup lookup writes. -- Code: `cli/src/services/doctor/managed_telemetry.rs` (classification text and JSON) and `cli/src/services/managed_telemetry.rs` (`inspect_health`, `inspect_health_with`). +- Code: `cli/src/services/doctor/managed_telemetry.rs` (classification text and JSON), `cli/src/services/doctor/access.rs` (policy state and source), and `cli/src/services/managed_telemetry.rs` (`inspect_health`, `inspect_health_with`). + +### Policy state + +- The row label carries the effective telemetry state for the inspected repository: `Managed telemetry: enabled for this repository` or `Managed telemetry: disabled (reason: )`, with the reasons from [access-policy.md](../cli/access-policy.md). A warning row keeps the enabled label. +- Every row, healthy rows included, adds `Source: ` naming the deciding layer: `repository SCE config (`.sce/config.json`)`, `global SCE config`, the `--config` or `SCE_CONFIG_FILE` file, or `default`. The deciding layer is the `telemetry.enabled` layer for an opt-out, consent, or `not_enabled`, and the `auth.mode` layer for `auth_disabled`. `invalid_config` has no source line. +- JSON adds `managed_telemetry.policy` with `state` (`enabled` / `disabled`), `reason` (or `null`), `source` (`config_file` / `default`), and `config_source` (the config layer, or `null`). The health keys above keep their meaning. ## Hidden header helper