diff --git a/.claude/skills/sce-info/hooks/register.ts b/.claude/skills/sce-info/hooks/register.ts index 0928ff873..d5bdc8a24 100644 --- a/.claude/skills/sce-info/hooks/register.ts +++ b/.claude/skills/sce-info/hooks/register.ts @@ -141,6 +141,7 @@ export function parseVersion(versionStdout: string): string | undefined { export const LOGIN_LABELS: Record = { logged_in: `${GREEN} logged in`, not_logged_in: `${RED} not logged in, run \`sce auth login\``, + unavailable: `${YELLOW} login status unavailable, run \`sce doctor\``, not_required: `${WHITE} login not required`, } diff --git a/.opencode/plugins/sce-agent-trace.ts b/.opencode/plugins/sce-agent-trace.ts index c57c3e603..214a09c41 100644 --- a/.opencode/plugins/sce-agent-trace.ts +++ b/.opencode/plugins/sce-agent-trace.ts @@ -89,7 +89,6 @@ function extractDiffTracePayload( event: EventMessageUpdated, ): DiffTracePayload | undefined { const eventInfo = event.properties.info; - // Only capture user messages (filter out assistant, system, etc.) if (eventInfo.role !== "user") { return undefined; } @@ -334,9 +333,6 @@ async function runDiffTraceHook( await new Promise((resolve) => { const child = spawn("sce", ["hooks", "diff-trace"], { cwd: repoRoot, - // Fail-open: stderr is ignored so that sce intake errors - // (connection refused, timeout, etc.) do not leak into the - // OpenCode TUI. Resolve unconditionally on any outcome. stdio: ["pipe", "ignore", "ignore"], }); @@ -359,9 +355,6 @@ async function runConversationTraceHook( await new Promise((resolve) => { const child = spawn("sce", ["hooks", "conversation-trace"], { cwd: repoRoot, - // Fail-open: stderr is ignored so that sce intake errors - // (connection refused, timeout, etc.) do not leak into the - // OpenCode TUI. Resolve unconditionally on any outcome. stdio: ["pipe", "ignore", "ignore"], }); diff --git a/.opencode/plugins/sce-bash-policy.ts b/.opencode/plugins/sce-bash-policy.ts index 0b2b8d9c9..03cf59326 100644 --- a/.opencode/plugins/sce-bash-policy.ts +++ b/.opencode/plugins/sce-bash-policy.ts @@ -13,11 +13,6 @@ interface JsonPolicyResult { const SCE_INSTALL_URL = "https://sce.crocoder.dev/docs/getting-started#install-cli"; -/** - * Evaluate a bash command against SCE bash-tool policy by delegating to the - * Rust `sce policy bash` command. Returns the parsed JSON result, or null if - * the policy check could not be performed (fail-open). - */ function evaluateBashCommandPolicy(command: string): JsonPolicyResult | null { try { const result = spawnSync( @@ -72,7 +67,6 @@ export const SceBashPolicyPlugin: Plugin = async () => { const policyResult = evaluateBashCommandPolicy(command); if (!policyResult) { - // Fail open: if the policy check cannot be performed, allow the command. return; } diff --git a/.pi/extensions/sce/index.ts b/.pi/extensions/sce/index.ts index 54cb2576c..bd4311a62 100644 --- a/.pi/extensions/sce/index.ts +++ b/.pi/extensions/sce/index.ts @@ -94,11 +94,6 @@ type PendingFileMutation = { before: string | undefined; }; -/** - * Evaluate a bash command against SCE bash-tool policy by delegating to the - * Rust `sce policy bash` command. Returns the parsed JSON result, or null if - * the policy check could not be performed (fail-open). - */ function evaluateBashCommandPolicy(command: string): JsonPolicyResult | null { try { const result = spawnSync( @@ -134,11 +129,6 @@ function evaluateBashCommandPolicy(command: string): JsonPolicyResult | null { } } -/** - * Send a conversation-trace payload to `sce hooks conversation-trace`, - * fire-and-forget. Fail-open: stderr is ignored so that sce intake errors do - * not leak into the Pi TUI, and the returned promise never rejects. - */ function runConversationTraceHook( cwd: string, payload: ConversationTracePayload, @@ -228,12 +218,6 @@ function buildMessageEndConversationTracePayload( return { tool_name: TOOL_NAME, payloads }; } -/** - * Resolve the installed Pi package version for diff-trace `tool_version`. - * The package's `exports` map does not expose `package.json`, so resolve the - * package entry point and read `package.json` from the package root instead. - * Returns null when resolution fails (normalized diff traces permit it). - */ async function resolvePiToolVersion(): Promise { try { const entryPath = fileURLToPath( @@ -251,10 +235,6 @@ async function resolvePiToolVersion(): Promise { } } -/** - * Send a diff-trace payload to `sce hooks diff-trace`, fire-and-forget. - * Fail-open: stderr is ignored and the returned promise never rejects. - */ function runDiffTraceHook( cwd: string, payload: DiffTracePayload, @@ -292,11 +272,6 @@ function diffLabelFor(cwd: string, absolutePath: string): string { : absolutePath; } -/** - * Rewrite temp-file path labels in git diff header lines to the repo-relative - * target path. Only header lines before the first `@@` hunk marker are - * touched so that content lines starting with `--- ` / `+++ ` are preserved. - */ function rewriteDiffLabels( diff: string, label: string, @@ -319,12 +294,6 @@ function rewriteDiffLabels( return lines.join("\n"); } -/** - * Produce a unified diff between before/after contents by writing them to - * temp files and spawning `git diff --no-index --no-ext-diff` (exit status 1 - * means "files differ"). Returns undefined for no-op diffs or any failure; - * temp files are always cleaned up. - */ async function buildUnifiedDiff( label: string, before: string | undefined, @@ -775,7 +744,6 @@ export default function sceExtension(pi: ExtensionAPI): void { const policyResult = evaluateBashCommandPolicy(command); if (!policyResult) { - // Fail open: if the policy check cannot be performed, allow the command. return undefined; } diff --git a/cli/assets/hooks/commit-msg b/cli/assets/hooks/commit-msg index c8088cf96..c266231c4 100644 --- a/cli/assets/hooks/commit-msg +++ b/cli/assets/hooks/commit-msg @@ -1,6 +1,7 @@ #!/bin/sh set -eu +# >>> sce managed block (do not edit) >>> if ! command -v sce >/dev/null 2>&1; then if [ -t 2 ]; then RED="$(printf '\033[38;2;220;38;38m')" @@ -27,3 +28,4 @@ fi sce hooks commit-msg "$@" status=$? exit "$status" +# <<< sce managed block <<< diff --git a/cli/assets/hooks/post-commit b/cli/assets/hooks/post-commit index 601f3e003..dc9cfe853 100644 --- a/cli/assets/hooks/post-commit +++ b/cli/assets/hooks/post-commit @@ -1,6 +1,7 @@ #!/bin/sh set -eu +# >>> sce managed block (do not edit) >>> if ! command -v sce >/dev/null 2>&1; then if [ -t 2 ]; then RED="$(printf '\033[38;2;220;38;38m')" @@ -33,3 +34,4 @@ else fi status=$? exit "$status" +# <<< sce managed block <<< diff --git a/cli/assets/hooks/pre-commit b/cli/assets/hooks/pre-commit index 10da16bf8..39629901c 100644 --- a/cli/assets/hooks/pre-commit +++ b/cli/assets/hooks/pre-commit @@ -1,6 +1,7 @@ #!/bin/sh set -eu +# >>> sce managed block (do not edit) >>> if ! command -v sce >/dev/null 2>&1; then if [ -t 2 ]; then RED="$(printf '\033[38;2;220;38;38m')" @@ -27,3 +28,4 @@ fi sce hooks pre-commit "$@" status=$? exit "$status" +# <<< sce managed block <<< diff --git a/cli/src/services/doctor/access.rs b/cli/src/services/doctor/access.rs index 3132cac8c..56f511a70 100644 --- a/cli/src/services/doctor/access.rs +++ b/cli/src/services/doctor/access.rs @@ -1,4 +1,5 @@ use std::future::Future; +use std::time::Duration; use serde_json::{json, Value}; @@ -6,6 +7,8 @@ use crate::services::config::{ AuthMode, ConfigPathSource, ResolvedAccessPolicy, TelemetryDisabledReason, TelemetryPolicyState, ValueSource, }; +use crate::services::managed_telemetry::{run_with_deadline, CREDENTIAL_LOOKUP_DEADLINE}; +use crate::services::token_storage::{self, StoredTokensLookup, TokenStorageError}; use super::types::{ DoctorProblem, ProblemCategory, ProblemFixability, ProblemKind, ProblemSeverity, @@ -22,6 +25,7 @@ pub(super) enum LoginState { NotRequired, LoggedIn, NotLoggedIn, + Unavailable(LoginUnavailableReason), } impl LoginState { @@ -30,6 +34,107 @@ impl LoginState { Self::NotRequired => LOGIN_STATE_NOT_REQUIRED, Self::LoggedIn => LOGIN_STATE_LOGGED_IN, Self::NotLoggedIn => LOGIN_STATE_NOT_LOGGED_IN, + Self::Unavailable(_) => "unavailable", + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum LoginUnavailableReason { + CredentialInaccessible, + DatabaseLocked, + DatabaseError, + PathResolutionError, + SchemaNotCurrent, + LookupTimeout, + ClockError, +} + +impl LoginUnavailableReason { + fn as_str(self) -> &'static str { + match self { + Self::CredentialInaccessible => "credential_inaccessible", + Self::DatabaseLocked => "database_locked", + Self::DatabaseError => "database_error", + Self::PathResolutionError => "path_resolution_error", + Self::SchemaNotCurrent => "schema_not_current", + Self::LookupTimeout => "lookup_timeout", + Self::ClockError => "clock_error", + } + } + + fn guidance(self) -> (&'static str, &'static str) { + match self { + Self::CredentialInaccessible => ( + "SCE cannot read the saved session because credential store access is unavailable.", + "Unlock the system credential store; run 'sce auth login' in an interactive terminal to authorize access, then rerun 'sce doctor'.", + ), + Self::DatabaseLocked => ( + "SCE cannot read the saved session because authentication storage is locked.", + "Wait for other SCE processes to exit, then rerun 'sce doctor'.", + ), + Self::DatabaseError => ( + "SCE cannot read the saved session because authentication storage is unavailable.", + "Check authentication storage access and the SCE logs, then rerun 'sce doctor'.", + ), + Self::PathResolutionError => ( + "SCE cannot locate authentication storage.", + "Check HOME and XDG_STATE_HOME, then rerun 'sce doctor'.", + ), + Self::SchemaNotCurrent => ( + "SCE cannot inspect the saved session until authentication storage is upgraded.", + "Run 'sce auth login' to upgrade authentication storage and reuse the saved session, then rerun 'sce doctor'.", + ), + Self::LookupTimeout => ( + "The saved session lookup did not finish in time.", + "Rerun 'sce doctor'; if this persists, check credential store access and other SCE processes.", + ), + Self::ClockError => ( + "SCE cannot determine the saved session status because the system clock is invalid.", + "Correct the system clock, then rerun 'sce doctor'.", + ), + } + } +} + +pub(super) async fn inspect_login() -> LoginState { + inspect_login_with( + CREDENTIAL_LOOKUP_DEADLINE, + token_storage::load_current_tokens(), + ) + .await +} + +async fn inspect_login_with(deadline: Duration, lookup: Fut) -> LoginState +where + Fut: Future> + Send + 'static, +{ + match run_with_deadline(deadline, lookup).await { + None => LoginState::Unavailable(LoginUnavailableReason::LookupTimeout), + Some(Err(error)) => LoginState::Unavailable(match error { + TokenStorageError::CredentialAccessUnavailable => { + LoginUnavailableReason::CredentialInaccessible + } + TokenStorageError::DatabaseLocked(_) => LoginUnavailableReason::DatabaseLocked, + TokenStorageError::Database(_) => LoginUnavailableReason::DatabaseError, + TokenStorageError::PathResolution(_) => LoginUnavailableReason::PathResolutionError, + }), + Some(Ok(StoredTokensLookup::Missing)) => LoginState::NotLoggedIn, + Some(Ok(StoredTokensLookup::SchemaNotCurrent)) => { + LoginState::Unavailable(LoginUnavailableReason::SchemaNotCurrent) + } + Some(Ok(StoredTokensLookup::Found(tokens))) => { + if !tokens.refresh_token.trim().is_empty() { + return LoginState::LoggedIn; + } + if tokens.access_token.trim().is_empty() { + return LoginState::NotLoggedIn; + } + match crate::services::auth::is_stored_token_expired(&tokens) { + Ok(false) => LoginState::LoggedIn, + Ok(true) => LoginState::NotLoggedIn, + Err(_) => LoginState::Unavailable(LoginUnavailableReason::ClockError), + } } } } @@ -46,11 +151,11 @@ pub(super) struct DoctorAccess { impl DoctorAccess { pub(super) async fn inspect( policy: Option<&ResolvedAccessPolicy>, - authorized: F, + inspect_login: F, ) -> Self where F: FnOnce() -> Fut, - Fut: Future, + Fut: Future, { let Some(policy) = policy else { return Self { @@ -61,12 +166,10 @@ impl DoctorAccess { login: LoginState::NotRequired, }; }; - let login = if policy.auth_mode.value != AuthMode::Mandatory { - LoginState::NotRequired - } else if authorized().await { - LoginState::LoggedIn + let login = if policy.auth_mode.value == AuthMode::Mandatory { + inspect_login().await } else { - LoginState::NotLoggedIn + LoginState::NotRequired }; let telemetry_source = match policy.telemetry { TelemetryPolicyState::Disabled(TelemetryDisabledReason::InvalidConfig) => None, @@ -100,29 +203,53 @@ impl DoctorAccess { } pub(super) fn login_problem(self) -> Option { - (self.login == LoginState::NotLoggedIn).then(|| DoctorProblem { - kind: ProblemKind::SceLoginRequired, + let (kind, severity, summary, remediation, next_action) = match self.login { + LoginState::NotRequired | LoginState::LoggedIn => return None, + LoginState::NotLoggedIn => ( + ProblemKind::SceLoginRequired, + ProblemSeverity::Error, + format!( + "auth.mode: mandatory is set in the {}, but no saved SCE session is available.", + source_label(self.auth_mode_source) + ), + LOGIN_REMEDIATION, + NEXT_ACTION_AUTH_LOGIN, + ), + LoginState::Unavailable(reason) => { + let (summary, remediation) = reason.guidance(); + ( + ProblemKind::SceLoginUnavailable, + ProblemSeverity::Warning, + summary.to_string(), + remediation, + "manual_steps", + ) + } + }; + Some(DoctorProblem { + kind, category: ProblemCategory::GlobalState, - severity: ProblemSeverity::Error, + severity, 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, + summary, + remediation: remediation.to_string(), + next_action, scope: None, mutation_scope_target: None, }) } pub(super) fn login_json(self) -> Value { - json!({ + let mut result = 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), - }) + }); + if let LoginState::Unavailable(reason) = self.login { + result["reason"] = json!(reason.as_str()); + } + result } pub(super) fn telemetry_policy_json(self) -> Value { @@ -153,3 +280,6 @@ fn source_label(source: ValueSource) -> &'static str { ValueSource::Default => "default", } } + +#[cfg(test)] +mod tests; diff --git a/cli/src/services/doctor/access/tests.rs b/cli/src/services/doctor/access/tests.rs new file mode 100644 index 000000000..aa05dd2fd --- /dev/null +++ b/cli/src/services/doctor/access/tests.rs @@ -0,0 +1,92 @@ +use super::*; +use crate::services::token_storage::StoredTokens; + +fn session(access_token: &str, refresh_token: &str, expires_in: u64) -> StoredTokensLookup { + StoredTokensLookup::Found(StoredTokens { + access_token: access_token.to_string(), + refresh_token: refresh_token.to_string(), + token_type: "Bearer".to_string(), + expires_in, + scope: None, + stored_at_unix_seconds: 0, + }) +} + +#[tokio::test] +async fn saved_workos_session_does_not_require_telemetry_or_repository_enrollment() { + let login = inspect_login_with(CREDENTIAL_LOOKUP_DEADLINE, async { + Ok(session("expired-access", "saved-refresh", 0)) + }) + .await; + assert_eq!(login, LoginState::LoggedIn); +} + +#[tokio::test] +async fn current_access_token_without_refresh_token_is_logged_in() { + let login = inspect_login_with(CREDENTIAL_LOOKUP_DEADLINE, async { + Ok(session("current-access", "", u64::MAX)) + }) + .await; + assert_eq!(login, LoginState::LoggedIn); +} + +#[tokio::test] +async fn missing_empty_or_expired_unrenewable_session_requires_login() { + for lookup in [ + StoredTokensLookup::Missing, + session("", " ", u64::MAX), + session("expired-access", "", 0), + ] { + let login = inspect_login_with(CREDENTIAL_LOOKUP_DEADLINE, async { Ok(lookup) }).await; + assert_eq!(login, LoginState::NotLoggedIn); + } +} + +#[tokio::test] +async fn storage_failures_are_unknown_login_status_instead_of_logout() { + for (error, reason) in [ + ( + TokenStorageError::CredentialAccessUnavailable, + LoginUnavailableReason::CredentialInaccessible, + ), + ( + TokenStorageError::DatabaseLocked("private detail".to_string()), + LoginUnavailableReason::DatabaseLocked, + ), + ( + TokenStorageError::Database("private detail".to_string()), + LoginUnavailableReason::DatabaseError, + ), + ( + TokenStorageError::PathResolution("private detail".to_string()), + LoginUnavailableReason::PathResolutionError, + ), + ] { + let login = inspect_login_with(CREDENTIAL_LOOKUP_DEADLINE, async { Err(error) }).await; + assert_eq!(login, LoginState::Unavailable(reason)); + let (summary, remediation) = reason.guidance(); + assert!(!summary.contains("private detail")); + assert!(!remediation.contains("private detail")); + } +} + +#[tokio::test] +async fn outdated_schema_is_unavailable_instead_of_logged_out() { + let login = inspect_login_with(CREDENTIAL_LOOKUP_DEADLINE, async { + Ok(StoredTokensLookup::SchemaNotCurrent) + }) + .await; + assert_eq!( + login, + LoginState::Unavailable(LoginUnavailableReason::SchemaNotCurrent) + ); +} + +#[tokio::test] +async fn lookup_timeout_does_not_claim_the_session_is_missing() { + let login = inspect_login_with(Duration::from_millis(1), std::future::pending()).await; + assert_eq!( + login, + LoginState::Unavailable(LoginUnavailableReason::LookupTimeout) + ); +} diff --git a/cli/src/services/doctor/mod.rs b/cli/src/services/doctor/mod.rs index 09adf42d3..fa72a2ef6 100644 --- a/cli/src/services/doctor/mod.rs +++ b/cli/src/services/doctor/mod.rs @@ -5,7 +5,6 @@ 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}; @@ -122,10 +121,7 @@ async fn execute_doctor_with_context( 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; + let access = DoctorAccess::inspect(policy.as_ref(), access::inspect_login).await; execute_doctor_with_lifecycle_providers( request, repository_root, @@ -519,6 +515,7 @@ fn doctor_problem_kind(kind: HealthProblemKind) -> ProblemKind { HealthProblemKind::MutationScopeHealthInvalid => ProblemKind::MutationScopeHealthInvalid, HealthProblemKind::ManagedTelemetryUnavailable => ProblemKind::ManagedTelemetryUnavailable, HealthProblemKind::SceLoginRequired => ProblemKind::SceLoginRequired, + HealthProblemKind::SceLoginUnavailable => ProblemKind::SceLoginUnavailable, } } @@ -600,6 +597,7 @@ fn health_problem_kind(kind: ProblemKind) -> HealthProblemKind { ProblemKind::MutationScopeHealthInvalid => HealthProblemKind::MutationScopeHealthInvalid, ProblemKind::ManagedTelemetryUnavailable => HealthProblemKind::ManagedTelemetryUnavailable, ProblemKind::SceLoginRequired => HealthProblemKind::SceLoginRequired, + ProblemKind::SceLoginUnavailable => HealthProblemKind::SceLoginUnavailable, } } diff --git a/cli/src/services/doctor/render.rs b/cli/src/services/doctor/render.rs index 3c8372273..ee592ab8a 100644 --- a/cli/src/services/doctor/render.rs +++ b/cli/src/services/doctor/render.rs @@ -315,6 +315,13 @@ fn sce_login_node(report: &HookDoctorReport, access: DoctorAccess) -> DoctorDisp DoctorDisplayStatus::Fail, problem_details(report, |kind| matches!(kind, ProblemKind::SceLoginRequired)), ), + LoginState::Unavailable(_) => top_level_node( + "SCE login status unavailable", + DoctorDisplayStatus::Warn, + problem_details(report, |kind| { + matches!(kind, ProblemKind::SceLoginUnavailable) + }), + ), } } @@ -1335,7 +1342,7 @@ mod access_render_tests { use crate::services::doctor::managed_telemetry; use crate::services::doctor::types::{ DoctorDisplayNode, HookDoctorReport, HookPathSource, PostCommitAutoSyncHealth, - PostCommitAutoSyncState, ProblemSeverity, Readiness, + PostCommitAutoSyncState, ProblemKind, ProblemSeverity, Readiness, }; use crate::services::doctor::DoctorMode; use crate::services::managed_telemetry::ManagedTelemetryHealth; @@ -1374,7 +1381,7 @@ mod access_render_tests { fn inspect(policy: &ResolvedAccessPolicy, authorized: impl FnOnce() -> Fut) -> DoctorAccess where - Fut: Future, + Fut: Future, { tokio::runtime::Builder::new_current_thread() .build() @@ -1421,7 +1428,7 @@ mod access_render_tests { telemetry_default(), not_enabled(), ), - || async { false }, + || async { LoginState::NotLoggedIn }, ); let report = report(access); @@ -1432,7 +1439,7 @@ mod access_render_tests { 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.", + " Problem: auth.mode: mandatory is set in the repository SCE config (`.sce/config.json`), but no saved SCE session is available.", " Remediation: Run 'sce auth login'.", ] ); @@ -1456,7 +1463,7 @@ mod access_render_tests { telemetry_default(), not_enabled(), ), - || async { true }, + || async { LoginState::LoggedIn }, ); let report = report(access); @@ -1468,6 +1475,35 @@ mod access_render_tests { assert_eq!(access.login_json()["state"], "logged_in"); } + #[test] + fn unavailable_login_renders_warning_and_reason_without_logout_guidance() { + use crate::services::doctor::access::LoginUnavailableReason; + + let access = inspect( + &policy( + AuthMode::Mandatory, + REPOSITORY, + telemetry_default(), + not_enabled(), + ), + || async { LoginState::Unavailable(LoginUnavailableReason::DatabaseLocked) }, + ); + let report = report(access); + assert_eq!(report.problems[0].kind, ProblemKind::SceLoginUnavailable); + assert_eq!(report.problems[0].severity, ProblemSeverity::Warning); + assert_eq!(report.problems[0].next_action, "manual_steps"); + assert_eq!( + render(&sce_login_node(&report, access)), + vec![ + " [WARN] SCE login status unavailable", + " Problem: SCE cannot read the saved session because authentication storage is locked.", + " Remediation: Wait for other SCE processes to exit, then rerun 'sce doctor'.", + ] + ); + assert_eq!(access.login_json()["state"], "unavailable"); + assert_eq!(access.login_json()["reason"], "database_locked"); + } + #[test] fn non_mandatory_mode_skips_credential_lookup() { let access = inspect( @@ -1509,7 +1545,7 @@ mod access_render_tests { }, TelemetryPolicyState::Enabled, ), - || async { false }, + || async { LoginState::NotLoggedIn }, ); assert_eq!( @@ -1549,7 +1585,7 @@ mod access_render_tests { telemetry_default(), not_enabled(), ), - || async { false }, + || async { LoginState::NotLoggedIn }, ); let health = ManagedTelemetryHealth::DisabledByConfig { auth_db_present: true, @@ -1593,7 +1629,7 @@ mod access_render_tests { }, TelemetryPolicyState::Disabled(TelemetryDisabledReason::UserOptOut), ), - || async { false }, + || async { LoginState::NotLoggedIn }, ); let health = ManagedTelemetryHealth::DisabledByConfig { auth_db_present: true, diff --git a/cli/src/services/doctor/types.rs b/cli/src/services/doctor/types.rs index 209cee28f..1f1f78a30 100644 --- a/cli/src/services/doctor/types.rs +++ b/cli/src/services/doctor/types.rs @@ -451,6 +451,7 @@ pub(crate) enum ProblemKind { MutationScopeHealthInvalid, ManagedTelemetryUnavailable, SceLoginRequired, + SceLoginUnavailable, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -552,6 +553,7 @@ pub(super) fn problem_kind(kind: ProblemKind) -> &'static str { ProblemKind::MutationScopeHealthInvalid => "mutation_scope_health_invalid", ProblemKind::ManagedTelemetryUnavailable => "managed_telemetry_unavailable", ProblemKind::SceLoginRequired => "sce_login_required", + ProblemKind::SceLoginUnavailable => "sce_login_unavailable", } } diff --git a/cli/src/services/lifecycle.rs b/cli/src/services/lifecycle.rs index dfb1003e0..3e45a2ef9 100644 --- a/cli/src/services/lifecycle.rs +++ b/cli/src/services/lifecycle.rs @@ -78,6 +78,7 @@ pub enum HealthProblemKind { MutationScopeHealthInvalid, ManagedTelemetryUnavailable, SceLoginRequired, + SceLoginUnavailable, } #[derive(Clone, Debug, Eq, PartialEq)] diff --git a/cli/src/services/setup/hook_merge.rs b/cli/src/services/setup/hook_merge.rs index 4f3f1944d..3d292ac16 100644 --- a/cli/src/services/setup/hook_merge.rs +++ b/cli/src/services/setup/hook_merge.rs @@ -315,4 +315,18 @@ mod tests { assert!(merge.unreachable_block_advisory); } + + #[test] + fn embedded_required_hook_templates_contain_one_balanced_managed_block() { + for hook_asset in crate::services::setup::iter_required_hook_assets() { + assert!( + matches!( + locate_block(hook_asset.bytes), + BlockLocation::Balanced(_, _) + ), + "embedded hook template '{}' must contain one balanced SCE managed block", + hook_asset.relative_path + ); + } + } } diff --git a/cli/src/services/token_storage.rs b/cli/src/services/token_storage.rs index ffd771d9f..736a430f9 100644 --- a/cli/src/services/token_storage.rs +++ b/cli/src/services/token_storage.rs @@ -84,6 +84,12 @@ pub struct StoredTokens { pub stored_at_unix_seconds: u64, } +pub(crate) enum StoredTokensLookup { + Missing, + SchemaNotCurrent, + Found(StoredTokens), +} + impl StoredTokens { fn from_token_response(token: &TokenResponse) -> Result { let stored_at_unix_seconds = current_unix_timestamp_seconds()?; @@ -193,6 +199,20 @@ pub async fn load_tokens( return Ok(None); }; + load_tokens_from_db(db).await +} + +pub(crate) async fn load_current_tokens() -> Result { + match open_existing_current_auth_db(CredentialAccess::NonInteractive).await? { + ExistingDbOpen::Missing => Ok(StoredTokensLookup::Missing), + ExistingDbOpen::SchemaNotCurrent => Ok(StoredTokensLookup::SchemaNotCurrent), + ExistingDbOpen::Open(db) => Ok(load_tokens_from_db(db) + .await? + .map_or(StoredTokensLookup::Missing, StoredTokensLookup::Found)), + } +} + +async fn load_tokens_from_db(db: &AuthDb) -> Result, TokenStorageError> { let sql = "SELECT access_token, token_type, expires_in, refresh_token, scope, \ stored_at_unix_seconds FROM auth_credentials WHERE id = ?1"; @@ -254,3 +274,6 @@ fn current_unix_timestamp_seconds() -> Result { })? .as_secs()) } + +#[cfg(test)] +mod tests; diff --git a/cli/src/services/token_storage/tests.rs b/cli/src/services/token_storage/tests.rs new file mode 100644 index 000000000..b004293f0 --- /dev/null +++ b/cli/src/services/token_storage/tests.rs @@ -0,0 +1,121 @@ +use std::process::Command; + +use super::*; +use crate::services::db::encryption_key::AUTH_DB_ENCRYPTION_KEY_ENV; + +const PROBE_CASE: &str = "SCE_TEST_SESSION_PROBE_CASE"; + +#[test] +fn saved_session_inspection_is_independent_of_telemetry_and_does_not_migrate() { + for case in [ + "missing_db", + "missing_session", + "missing_telemetry", + "expired_telemetry", + "unbound_repository", + "outdated_schema", + ] { + let directory = tempfile::tempdir().unwrap(); + let output = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "services::token_storage::tests::session_probe_child", + "--nocapture", + ]) + .env(PROBE_CASE, case) + .env("HOME", directory.path()) + .env("USERPROFILE", directory.path()) + .env("LOCALAPPDATA", directory.path().join("state")) + .env("APPDATA", directory.path().join("config")) + .env("XDG_STATE_HOME", directory.path().join("state")) + .env("XDG_CONFIG_HOME", directory.path().join("config")) + .env("XDG_DATA_HOME", directory.path().join("data")) + .env("XDG_CACHE_HOME", directory.path().join("cache")) + .env( + AUTH_DB_ENCRYPTION_KEY_ENV, + if case == "missing_db" { + "" + } else { + "session-probe-secret" + }, + ) + .output() + .unwrap(); + assert!( + output.status.success(), + "{case}: {}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + } +} + +#[tokio::test] +async fn session_probe_child() { + let Ok(case) = std::env::var(PROBE_CASE) else { + return; + }; + let path = auth_db_path().unwrap(); + if case == "missing_db" { + assert!(matches!( + load_current_tokens().await.unwrap(), + StoredTokensLookup::Missing + )); + assert!(!path.parent().unwrap().exists()); + return; + } + let db = AuthDb::new().await.unwrap(); + if case != "missing_session" { + db.execute( + "INSERT INTO auth_credentials \ + (id, access_token, token_type, expires_in, refresh_token, stored_at_unix_seconds) \ + VALUES (1, 'expired-access', 'Bearer', 0, 'saved-refresh', 0)", + (), + ) + .await + .unwrap(); + } + if matches!(case.as_str(), "expired_telemetry" | "unbound_repository") { + let expires_at = if case == "expired_telemetry" { + 1 + } else { + 4_102_444_800_i64 + }; + db.execute( + "INSERT INTO telemetry_credentials \ + (id, token, accessor, expires_at_unix_seconds, stored_at_unix_seconds, user_id, workspace_id) \ + VALUES (1, 'telemetry-token', 'accessor', ?1, 0, 'user', 'workspace')", + (expires_at,), + ) + .await + .unwrap(); + } + if case == "outdated_schema" { + db.execute( + "DELETE FROM __sce_migrations WHERE id = ?1", + (crate::generated_migrations::AUTH_MIGRATIONS + .last() + .unwrap() + .0,), + ) + .await + .unwrap(); + } + drop(db); + let before = std::fs::read(&path).unwrap(); + let lookup = load_current_tokens().await.unwrap(); + match case.as_str() { + "outdated_schema" => { + assert!(matches!(lookup, StoredTokensLookup::SchemaNotCurrent)); + assert_eq!(std::fs::read(path).unwrap(), before); + } + "missing_session" => assert!(matches!(lookup, StoredTokensLookup::Missing)), + _ => { + let StoredTokensLookup::Found(tokens) = lookup else { + panic!("saved WorkOS session must be found regardless of telemetry readiness"); + }; + assert_eq!(tokens.refresh_token, "saved-refresh"); + assert_eq!(tokens.expires_in, 0); + } + } +} diff --git a/config/lib/sce-info/hooks/register.ts b/config/lib/sce-info/hooks/register.ts index 48f9aed36..04c8301db 100644 --- a/config/lib/sce-info/hooks/register.ts +++ b/config/lib/sce-info/hooks/register.ts @@ -141,6 +141,7 @@ export function parseVersion(versionStdout: string): string | undefined { export const LOGIN_LABELS: Record = { logged_in: `${GREEN} logged in`, not_logged_in: `${RED} not logged in, run \`sce auth login\``, + unavailable: `${YELLOW} login status unavailable, run \`sce doctor\``, not_required: `${WHITE} login not required`, } diff --git a/config/lib/sce-info/tests/login-notice.test.ts b/config/lib/sce-info/tests/login-notice.test.ts index 6c7505ae2..8ebcbec1a 100644 --- a/config/lib/sce-info/tests/login-notice.test.ts +++ b/config/lib/sce-info/tests/login-notice.test.ts @@ -41,6 +41,13 @@ test('session start logs nothing when already logged in', async ($, on) => { expect(lines).toEqual([]) }) +test('unavailable login status does not ask the user to log in again', async ($, on) => { + answerDoctor(on, JSON.stringify({ sce_login: { state: 'unavailable', reason: 'credential_inaccessible', 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) diff --git a/config/lib/sce-info/tests/login-state.test.ts b/config/lib/sce-info/tests/login-state.test.ts new file mode 100644 index 000000000..1164e1eae --- /dev/null +++ b/config/lib/sce-info/tests/login-state.test.ts @@ -0,0 +1,27 @@ +import { expect, test } from 'bun:test' +import { EXPECTED_SCE_VERSION, loginRequired, shortVersion, statusLine } from '../hooks/register' + +const version = `shared-context-engineering ${EXPECTED_SCE_VERSION}\n` +const prefix = `🟢 ${shortVersion(EXPECTED_SCE_VERSION)}` + +test('unavailable login status is yellow and never asks for login', () => { + for (const reason of ['credential_inaccessible', 'database_locked', 'database_error', 'path_resolution_error', 'schema_not_current', 'lookup_timeout', 'clock_error']) { + const doctor = JSON.stringify({ sce_login: { state: 'unavailable', reason } }) + expect(statusLine(version, doctor)).toBe(`${prefix} ┃ 🟡 login status unavailable, run \`sce doctor\``) + expect(loginRequired(doctor)).toBe(false) + } +}) + +test('telemetry readiness cannot override a saved login', () => { + for (const state of ['not_configured', 'disabled', 'disabled_by_config']) { + const doctor = JSON.stringify({ sce_login: { state: 'logged_in' }, managed_telemetry: { state } }) + expect(statusLine(version, doctor)).toBe(`${prefix} ┃ 🟢 logged in`) + expect(loginRequired(doctor)).toBe(false) + } +}) + +test('a genuinely missing login still requests authentication', () => { + const doctor = JSON.stringify({ sce_login: { state: 'not_logged_in' } }) + expect(statusLine(version, doctor)).toBe(`${prefix} ┃ 🔴 not logged in, run \`sce auth login\``) + expect(loginRequired(doctor)).toBe(true) +}) diff --git a/config/lib/sce-info/tests/status-line.test.ts b/config/lib/sce-info/tests/status-line.test.ts index c1a39ae78..7351fbfaf 100644 --- a/config/lib/sce-info/tests/status-line.test.ts +++ b/config/lib/sce-info/tests/status-line.test.ts @@ -72,6 +72,7 @@ test('login and auto sync states each get a colored label', () => { expect(line('not_logged_in', 'disabled')).toBe(`🟢 ${SCE} ┃ 🔴 not logged in, run \`sce auth login\` ┃ 🟡 auto sync off`) expect(line('not_required', 'not_ready')).toBe(`🟢 ${SCE} ┃ ⚪ login not required ┃ 🔴 auto sync not ready`) expect(line('logged_in', 'not_applicable')).toBe(`🟢 ${SCE} ┃ 🟢 logged in ┃ ⚪ auto sync n/a`) + expect(line('unavailable', 'ready')).toBe(`🟢 ${SCE} ┃ 🟡 login status unavailable, run \`sce doctor\` ┃ 🟢 auto sync on`) }) test('git hooks show a setup hint unless every hook is installed and current', () => { diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md index dc151cc1f..674f8562e 100644 --- a/context/cli/access-policy.md +++ b/context/cli/access-policy.md @@ -129,8 +129,8 @@ Setup then enforces the re-resolved mode with a login step: it never logs in und - **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 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 doctor` SCE login row:** under effective `mandatory`, doctor inspects the saved WorkOS session non-interactively with a deadline and without creating or migrating `auth.db`. A renewable session counts as logged in independently of telemetry credentials and repository bindings; unreadable storage, outdated schema, and lookup failures report `unavailable` with a warning and a reason instead of claiming logout. 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 saved usable or renewable WorkOS session), 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/glossary.md b/context/glossary.md index 7e7359f4e..ce106b60e 100644 --- a/context/glossary.md +++ b/context/glossary.md @@ -196,7 +196,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,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. +- `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 saved usable or renewable WorkOS session; telemetry readiness and enrollment are independent, and unreadable storage or an incomplete lookup yield an `unavailable` warning with a reason — 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. diff --git a/context/patterns.md b/context/patterns.md index 6a3cf1cee..fe51efd89 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/`. 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. The module also keeps a persistent `$.ui.status` line, built by `statusLine()`, with segments joined by ` ┃ `. The first segment is the installed version: `🟢 `, or `🟡 (expected )` on a mismatch, or `🔴 not installed` when `sce --version` cannot start. When doctor output parses, it adds the `sce_login.state` label (`logged_in`/`not_logged_in`/`not_required`). It adds ``🔴 git hooks not set up, run `sce setup --hooks` `` unless every doctor hook is `exists`, `executable`, and `content_state: current`. It adds the `post_commit_auto_sync.state` label (`ready`/`disabled`/`not_ready`/`not_applicable`). Last comes ``🟡 issue(s), run `sce doctor` `` when there are Claude doctor notices. On interactive `session.start` it shows the version immediately, then the full line once doctor returns. It refreshes, without overlapping refreshes, after `prompt.submit`, after `turn.complete`, after any Bash tool call whose command matches `\b(sce|git)\b`, and every 10 minutes (`STATUS_REFRESH_INTERVAL_MS`). `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 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. The module also keeps a persistent `$.ui.status` line, built by `statusLine()`, with segments joined by ` ┃ `. The first segment is the installed version: `🟢 `, or `🟡 (expected )` on a mismatch, or `🔴 not installed` when `sce --version` cannot start. When doctor output parses, it adds the `sce_login.state` label (`logged_in`/`not_logged_in`/`not_required`/`unavailable`). An unavailable login status is yellow with `sce doctor` guidance and never emits the login-required notice; it reflects unreadable storage or an incomplete lookup, not logout. Login status comes from the saved WorkOS session independently of telemetry readiness and repository enrollment. It adds ``🔴 git hooks not set up, run `sce setup --hooks` `` unless every doctor hook is `exists`, `executable`, and `content_state: current`. It adds the `post_commit_auto_sync.state` label (`ready`/`disabled`/`not_ready`/`not_applicable`). Last comes ``🟡 issue(s), run `sce doctor` `` when there are Claude doctor notices. On interactive `session.start` it shows the version immediately, then the full line once doctor returns. It refreshes, without overlapping refreshes, after `prompt.submit`, after `turn.complete`, after any Bash tool call whose command matches `\b(sce|git)\b`, and every 10 minutes (`STATUS_REFRESH_INTERVAL_MS`). `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/sce/auth-db.md b/context/sce/auth-db.md index 5ca396b98..cfbc82033 100644 --- a/context/sce/auth-db.md +++ b/context/sce/auth-db.md @@ -48,6 +48,16 @@ Current migration baseline: Storage operations live in `cli/src/services/telemetry_credential_storage.rs`: `save_telemetry_credential` is a single-statement `INSERT OR REPLACE` of the fixed row (last complete writer wins), `load_telemetry_credential` returns the row only when token, accessor, and identity are non-empty, the expiry is non-negative and in the future, and the stored WorkOS session's access-token `(sub, workspace_id)` claims equal the row's identity (it never mints or refreshes), `load_repository_telemetry_credential` additionally requires a matching repository binding, `bind_repository_telemetry` records a binding for the current credential identity, and `delete_telemetry_credential` removes the row. `TelemetryCredential` has a redacted `Debug`, and storage errors use fixed messages without secret values. Saving or deleting never touches `auth_credentials`. Managed OTLP export reads this row at CLI startup through `load_telemetry_credential` and uses only the token as bearer. The shared `AuthDb` singleton comes from `token_storage::get_auth_db`. `sce auth logout` deletes both the `auth_credentials` row and the telemetry row; see [telemetry-credential.md](telemetry-credential.md) for lifecycle and security boundaries. +## Stored session inspection + +`token_storage::load_current_tokens()` reads only the WorkOS session row through +`open_existing_current_auth_db(NonInteractive)`. It distinguishes missing storage +or a missing row from an outdated schema, and preserves storage errors. Doctor +uses this path for login status independently of telemetry credentials and +repository bindings. It creates no database or key and performs no migration or +network refresh. A stored refresh token keeps a session renewable after access +token expiry; remote revocation is not checked by this offline inspection. + ## Concurrency and schema readiness - Many short-lived `sce` processes read `auth.db` at once: every admitted Claude hook resolves the telemetry credential at startup. `EncryptedTursoDb::new()` therefore opens with Turso multiprocess WAL, alongside encryption, so concurrent readers share the file. Multiprocess WAL creates `auth.db-wal` and the `auth.db-tshm` coordination file next to the database. SCE also creates `auth.db-open.lock` once `auth.db` exists, to serialize Turso cold opens (see [Serialized cold opens](#serialized-cold-opens-after-a-legacy-write)). diff --git a/context/sce/doctor-human-text-contract.md b/context/sce/doctor-human-text-contract.md index 767bc5dcd..ed8870880 100644 --- a/context/sce/doctor-human-text-contract.md +++ b/context/sce/doctor-human-text-contract.md @@ -34,22 +34,33 @@ 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` with a saved WorkOS session: `[PASS] SCE login`. A non-empty + refresh token keeps an expired access token renewable; a current access + token also suffices. This is an offline storage check, not remote session + validation, and it never refreshes credentials. - `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 + `Problem: auth.mode: mandatory is set in the , but no saved SCE + session is available.` 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. +- Login reads only the WorkOS `auth_credentials` row, non-interactively under + `CREDENTIAL_LOOKUP_DEADLINE`. Telemetry credential expiry, provisioning, and + repository enrollment do not determine login status. Setup and telemetry + header authorization retain their repository-bound credential checks. +- Unreadable credential storage, database contention, outdated schema, timeout, + or an invalid system clock produce `[WARN] SCE login status unavailable`, + with a `sce_login_unavailable` warning and cause-specific remediation. They + never imply logout. Doctor never creates `auth.db` or a credential-store key, + migrates the schema, or makes a network request to inspect the login. - JSON adds a top-level `sce_login` object: `state` (`not_required`, - `logged_in`, `not_logged_in`), `auth_mode`, `source`, and `config_source`. + `logged_in`, `not_logged_in`, `unavailable`), `auth_mode`, `source`, and + `config_source`. Only `unavailable` adds `reason`: `credential_inaccessible`, + `database_locked`, `database_error`, `path_resolution_error`, + `schema_not_current`, `lookup_timeout`, or `clock_error`. +- The Claude status bar renders `unavailable` as yellow + `login status unavailable, run sce doctor`, without a login-required notice. - Code: `cli/src/services/doctor/access.rs`. ## Header and status vocabulary diff --git a/flake.nix b/flake.nix index c1ebf4d11..59f4d506e 100644 --- a/flake.nix +++ b/flake.nix @@ -1448,6 +1448,19 @@ testCommand = "bun test"; }; + sceInfoLoginStatusTests = mkBunCheck { + name = "sce-info-login-status-tests"; + src = pkgs.lib.fileset.toSource { + root = workspaceRoot; + fileset = pkgs.lib.fileset.unions [ + ./config/lib/sce-info/hooks/register.ts + ./config/lib/sce-info/tests/login-state.test.ts + ]; + }; + workdir = "config/lib/sce-info"; + testCommand = "bun test tests/login-state.test.ts"; + }; + configLibBiomeCheck = mkBiomeCheck { name = "config-lib-biome-check"; src = configLibBashPolicySrc; @@ -1717,6 +1730,7 @@ npm-biome-format = npmBiomeFormat; config-lib-bun-tests = configLibBunTests; + sce-info-login-status-tests = sceInfoLoginStatusTests; config-lib-biome-check = configLibBiomeCheck; config-lib-biome-format = configLibBiomeFormat;