From d46c03cd984fabd3fd4bbf2ae3a2e0e496b6d9a1 Mon Sep 17 00:00:00 2001 From: David Abram Date: Tue, 20 Oct 2026 13:52:40 +0200 Subject: [PATCH 1/9] config: Add auth and telemetry config sections Define the new auth.mode and telemetry.enabled sections in the generated Pkl schema and parse them into per-layer file configuration with provenance. Add schema-pointer validation coverage and document the accepted keys while leaving runtime policy resolution for the follow-up work. Plan: auth-telemetry-policy-config Task: T01 Co-authored-by: SCE --- cli/src/services/config/resolver.rs | 2 + cli/src/services/config/schema.rs | 221 ++++++++++- cli/src/services/config/types.rs | 29 ++ config/pkl/base/sce-config-schema.pkl | 25 ++ context/cli/config-precedence-contract.md | 6 +- context/context-map.md | 2 +- context/plans/auth-telemetry-policy-config.md | 347 ++++++++++++++++++ 7 files changed, 626 insertions(+), 6 deletions(-) create mode 100644 context/plans/auth-telemetry-policy-config.md diff --git a/cli/src/services/config/resolver.rs b/cli/src/services/config/resolver.rs index 00b2d32c8..bfc5e4a7b 100644 --- a/cli/src/services/config/resolver.rs +++ b/cli/src/services/config/resolver.rs @@ -401,6 +401,8 @@ where agent_trace_repository_id: None, agent_trace_repository_remote: None, agent_trace_auto_sync: None, + auth_mode: None, + telemetry_enabled: None, otel: schema::OtelFileConfig::default(), bash_policy_presets: None, bash_policy_custom: None, diff --git a/cli/src/services/config/schema.rs b/cli/src/services/config/schema.rs index 00f13a6e2..d756b57e1 100644 --- a/cli/src/services/config/schema.rs +++ b/cli/src/services/config/schema.rs @@ -18,9 +18,10 @@ use serde_json::Value; use super::policy::{parse_bash_policy_presets, parse_custom_bash_policies, CustomBashPolicyEntry}; use super::types::{ - parse_optional_workflow_id, AgentTraceDbRetryConfig, ConfigPathSource, DatabaseRetryConfig, - IntegrationTargetId, IntegrationsConfig, LogFormat, LogLevel, PerDbRetryConfig, - AGENT_TRACE_DB_BUSY_TIMEOUT_MAX_MS, AGENT_TRACE_DB_CONTENTION_DEADLINE_MAX_MS, + parse_optional_workflow_id, AgentTraceDbRetryConfig, AuthMode, ConfigPathSource, + DatabaseRetryConfig, IntegrationTargetId, IntegrationsConfig, LogFormat, LogLevel, + PerDbRetryConfig, AGENT_TRACE_DB_BUSY_TIMEOUT_MAX_MS, + AGENT_TRACE_DB_CONTENTION_DEADLINE_MAX_MS, }; use crate::services::resilience::{RetryPolicy, RetryPolicyError}; @@ -41,13 +42,15 @@ pub(crate) const TOP_LEVEL_CONFIG_KEYS: &[&str] = &[ super::resolver::WORKOS_CLIENT_ID_KEY.config_key, super::resolver::CONTROL_PLANE_BASE_URL_KEY.config_key, "agent_trace", + "auth", + "telemetry", "otel", "policies", "integrations", ]; pub(crate) const TOP_LEVEL_CONFIG_KEYS_DESCRIPTION: &str = - "$schema, log_level, log_format, log_to_file, workos_client_id, control_plane_base_url, agent_trace, otel, policies, integrations, log_dir, log_file_retention_limit"; + "$schema, log_level, log_format, log_to_file, workos_client_id, control_plane_base_url, agent_trace, auth, telemetry, otel, policies, integrations, log_dir, log_file_retention_limit"; const PER_DB_RETRY_KEYS: &[&str] = &["connection_open", "query"]; const PER_DB_RETRY_KEYS_DESCRIPTION: &str = "connection_open, query"; @@ -90,6 +93,8 @@ pub(crate) struct ParsedFileConfigDocument { pub(crate) workos_client_id: Option, pub(crate) control_plane_base_url: Option, pub(crate) agent_trace: Option, + pub(crate) auth: Option, + pub(crate) telemetry: Option, pub(crate) otel: Option, pub(crate) policies: Option, pub(crate) integrations: Option, @@ -102,6 +107,16 @@ pub(crate) struct ParsedAgentTraceConfigDocument { pub(crate) auto_sync: Option, } +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +pub(crate) struct ParsedAuthConfigDocument { + pub(crate) mode: Option, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +pub(crate) struct ParsedTelemetryConfigDocument { + pub(crate) enabled: Option, +} + #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] pub(crate) struct ParsedOtelConfigDocument { pub(crate) endpoint: Option, @@ -207,6 +222,10 @@ pub(crate) struct FileConfig { pub(crate) agent_trace_repository_id: Option>, pub(crate) agent_trace_repository_remote: Option>, pub(crate) agent_trace_auto_sync: Option>, + #[allow(dead_code)] + pub(crate) auth_mode: Option>, + #[allow(dead_code)] + pub(crate) telemetry_enabled: Option>, pub(crate) otel: OtelFileConfig, pub(crate) bash_policy_presets: Option>>, pub(crate) bash_policy_custom: Option>>, @@ -358,6 +377,8 @@ pub(crate) fn parse_file_config( .map(|value| FileConfigValue { value, source }); let (agent_trace_repository_id, agent_trace_repository_remote, agent_trace_auto_sync) = map_agent_trace_config(typed.agent_trace.as_ref(), object, path, source)?; + let auth_mode = map_auth_config(typed.auth.as_ref(), object, path, source)?; + let telemetry_enabled = map_telemetry_config(typed.telemetry.as_ref(), object, path, source)?; let otel = map_otel_config(typed.otel.as_ref(), object, path, source)?; let (attribution_hooks_enabled, bash_policy_presets, bash_policy_custom, database_retry) = map_policies_config(typed.policies.as_ref(), object, path, source)?; @@ -375,6 +396,8 @@ pub(crate) fn parse_file_config( agent_trace_repository_id, agent_trace_repository_remote, agent_trace_auto_sync, + auth_mode, + telemetry_enabled, otel, bash_policy_presets, bash_policy_custom, @@ -775,6 +798,66 @@ fn map_agent_trace_config( Ok((repository_id, repository_remote, auto_sync)) } +fn map_auth_config( + typed: Option<&ParsedAuthConfigDocument>, + object: &serde_json::Map, + path: &Path, + source: ConfigPathSource, +) -> Result>> { + let Some(auth_value) = object.get("auth") else { + return Ok(None); + }; + + let auth_object = auth_value.as_object().with_context(|| { + format!( + "Config key 'auth' in '{}' must be an object.", + path.display() + ) + })?; + + validate_object_keys(auth_object, path, Some("auth"), &["mode"], "mode")?; + + typed + .and_then(|config| config.mode.as_deref()) + .map(|raw| -> Result> { + Ok(FileConfigValue { + value: AuthMode::parse(raw, &format!("config file '{}'", path.display()))?, + source, + }) + }) + .transpose() +} + +fn map_telemetry_config( + typed: Option<&ParsedTelemetryConfigDocument>, + object: &serde_json::Map, + path: &Path, + source: ConfigPathSource, +) -> Result>> { + let Some(telemetry_value) = object.get("telemetry") else { + return Ok(None); + }; + + let telemetry_object = telemetry_value.as_object().with_context(|| { + format!( + "Config key 'telemetry' in '{}' must be an object.", + path.display() + ) + })?; + + validate_object_keys( + telemetry_object, + path, + Some("telemetry"), + &["enabled"], + "enabled", + )?; + + Ok(typed + .and_then(|config| config.enabled) + .map(|value| FileConfigValue { value, source })) +} + fn map_otel_config( typed: Option<&ParsedOtelConfigDocument>, object: &serde_json::Map, @@ -1043,6 +1126,136 @@ mod agent_trace_config_tests { } } +#[cfg(test)] +mod access_policy_config_tests { + use std::path::Path; + + use super::{parse_file_config, AuthMode, ConfigPathSource, FileConfig}; + + const CONFIG_PATH: &str = "/tmp/sce-config.json"; + + fn parse_from(raw: &str, source: ConfigPathSource) -> anyhow::Result { + parse_file_config(raw, Path::new(CONFIG_PATH), source) + } + + #[test] + fn auth_and_telemetry_sections_parse_with_layer_source() { + let sources = [ + ConfigPathSource::Flag, + ConfigPathSource::Env, + ConfigPathSource::DefaultDiscoveredGlobal, + ConfigPathSource::DefaultDiscoveredLocal, + ]; + let cases = [ + ("disabled", AuthMode::Disabled, false), + ("optional", AuthMode::Optional, true), + ("mandatory", AuthMode::Mandatory, false), + ]; + + for source in sources { + for (raw_mode, mode, enabled) in cases { + let config = parse_from( + &format!( + r#"{{"auth":{{"mode":"{raw_mode}"}},"telemetry":{{"enabled":{enabled}}}}}"# + ), + source, + ) + .unwrap(); + + let auth_mode = config.auth_mode.unwrap(); + assert_eq!(auth_mode.value, mode); + assert_eq!(auth_mode.source, source); + assert_eq!(mode.as_str(), raw_mode); + let telemetry_enabled = config.telemetry_enabled.unwrap(); + assert_eq!(telemetry_enabled.value, enabled); + assert_eq!(telemetry_enabled.source, source); + } + } + } + + #[test] + fn omitted_or_empty_auth_and_telemetry_sections_parse_as_unset() { + for raw in [ + "{}", + r#"{"log_level":"warn"}"#, + r#"{"auth":{},"telemetry":{}}"#, + ] { + let config = parse_from(raw, ConfigPathSource::Flag).unwrap(); + assert_eq!(config.auth_mode, None, "{raw}"); + assert_eq!(config.telemetry_enabled, None, "{raw}"); + } + } + + #[test] + fn invalid_auth_and_telemetry_sections_fail_with_schema_pointer() { + let cases = [ + (r#"{"auth":{"mode":"required"}}"#, "/auth/mode"), + (r#"{"auth":{"mode":true}}"#, "/auth/mode"), + (r#"{"auth":{"level":"optional"}}"#, "/auth"), + (r#"{"auth":"optional"}"#, "/auth"), + (r#"{"telemetry":{"enabled":"true"}}"#, "/telemetry/enabled"), + (r#"{"telemetry":{"enabled":1}}"#, "/telemetry/enabled"), + (r#"{"telemetry":{"export":true}}"#, "/telemetry"), + (r#"{"telemetry":true}"#, "/telemetry"), + ]; + + for (raw, pointer) in cases { + let error = parse_from(raw, ConfigPathSource::DefaultDiscoveredLocal) + .unwrap_err() + .to_string(); + assert!( + error.starts_with(&format!( + "Config file '{CONFIG_PATH}' failed schema validation against generated schema" + )), + "{raw}: {error}" + ); + assert!(error.contains(&format!(": {pointer}: ")), "{raw}: {error}"); + } + } + + #[test] + fn auth_and_telemetry_key_checks_reject_unknown_keys_as_backstop() { + let object = serde_json::json!({"auth": {"level": "optional"}}); + let error = super::map_auth_config( + None, + object.as_object().unwrap(), + Path::new(CONFIG_PATH), + ConfigPathSource::Flag, + ) + .unwrap_err() + .to_string(); + assert_eq!( + error, + "Config key 'auth' in '/tmp/sce-config.json' contains unknown key 'level'. Allowed keys: mode." + ); + + let object = serde_json::json!({"telemetry": {"export": true}}); + let error = super::map_telemetry_config( + None, + object.as_object().unwrap(), + Path::new(CONFIG_PATH), + ConfigPathSource::Flag, + ) + .unwrap_err() + .to_string(); + assert_eq!( + error, + "Config key 'telemetry' in '/tmp/sce-config.json' contains unknown key 'export'. Allowed keys: enabled." + ); + } + + #[test] + fn auth_mode_parse_rejects_unknown_value() { + let error = AuthMode::parse("required", "test source") + .unwrap_err() + .to_string(); + assert_eq!( + error, + "Invalid auth mode 'required' from test source. Valid values: disabled, optional, mandatory." + ); + } +} + #[cfg(test)] mod database_retry_config_tests { use std::path::Path; diff --git a/cli/src/services/config/types.rs b/cli/src/services/config/types.rs index bed656c23..dd5b76e28 100644 --- a/cli/src/services/config/types.rs +++ b/cli/src/services/config/types.rs @@ -86,6 +86,35 @@ impl LogFormat { } } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum AuthMode { + Disabled, + Optional, + Mandatory, +} + +impl AuthMode { + pub(crate) fn parse(raw: &str, source: &str) -> anyhow::Result { + match raw { + "disabled" => Ok(Self::Disabled), + "optional" => Ok(Self::Optional), + "mandatory" => Ok(Self::Mandatory), + _ => anyhow::bail!( + "Invalid auth mode '{raw}' from {source}. Valid values: disabled, optional, mandatory." + ), + } + } + + #[allow(dead_code)] + pub(crate) fn as_str(self) -> &'static str { + match self { + Self::Disabled => "disabled", + Self::Optional => "optional", + Self::Mandatory => "mandatory", + } + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum ValueSource { Flag, diff --git a/config/pkl/base/sce-config-schema.pkl b/config/pkl/base/sce-config-schema.pkl index d21f1323a..5af7ba8f1 100644 --- a/config/pkl/base/sce-config-schema.pkl +++ b/config/pkl/base/sce-config-schema.pkl @@ -161,6 +161,31 @@ local sceConfigSchema = new JsonSchema { } } } + ["auth"] = new JsonSchema { + type = "object" + description = "Authentication policy for SCE cloud access. The most restrictive mode across the user and repository layers wins." + additionalProperties = false + properties { + ["mode"] = new JsonSchema { + type = "string" + description = "Authentication mode: `disabled` forbids login and cloud access, `optional` allows them, and `mandatory` requires authentication for explicit auth commands." + enum = new { "disabled"; "optional"; "mandatory" } + default = "optional" + } + } + } + ["telemetry"] = new JsonSchema { + type = "object" + description = "Consent for SCE-managed telemetry. A repository layer can opt out but cannot enable telemetry without user-layer consent." + additionalProperties = false + properties { + ["enabled"] = new JsonSchema { + type = "boolean" + description = "Enable SCE-managed OTLP export and the Claude telemetry headers helper. Does not select the destination; the `otel` block declares endpoints." + default = false + } + } + } ["otel"] = new JsonSchema { type = "object" description = "Optional managed OpenTelemetry declaration. Omitting the block or any field keeps the code-owned managed defaults; managed export never lets this block redirect authenticated requests." diff --git a/context/cli/config-precedence-contract.md b/context/cli/config-precedence-contract.md index d3505ad72..f4d68ec83 100644 --- a/context/cli/config-precedence-contract.md +++ b/context/cli/config-precedence-contract.md @@ -82,7 +82,7 @@ When a default-discovered global or repo-local config file exists but fails JSON - Startup/runtime config resolution degrades gracefully for default-discovered files across ordinary startup, setup, and Agent Trace storage: invalid discovered files are skipped and reported via collected `validation_errors`, while explicit `--config` / `SCE_CONFIG_FILE` targets still fail immediately on the same parse or validation errors. - Config file content must be valid JSON with a top-level object. -- Allowed keys: `$schema`, `log_level`, `log_format`, `log_to_file`, `log_dir`, `log_file_retention_limit`, `workos_client_id`, `control_plane_base_url`, `agent_trace`, `otel`, `policies`, `integrations`. +- Allowed keys: `$schema`, `log_level`, `log_format`, `log_to_file`, `log_dir`, `log_file_retention_limit`, `workos_client_id`, `control_plane_base_url`, `agent_trace`, `auth`, `telemetry`, `otel`, `policies`, `integrations`. - Unknown keys fail validation. - `log_to_file` must be a boolean when present and defaults to `true`; it is independent of `log_dir`. - `log_level` must be one of `error|warn|info|debug`. @@ -97,6 +97,10 @@ When a default-discovered global or repo-local config file exists but fails JSON - `agent_trace.repository_remote` must be a non-empty string when present; omitted values resolve to `origin`. - `agent_trace.auto_sync` must be a boolean when present; omitted values resolve to `false`. A newly created repo-local config from `sce setup` contains an explicit `true` value. +- `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. +- 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 does not yet merge or consume either value, so they have no runtime effect and do not appear in `sce config show`. + - `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. - `integrations` must be an object when present and currently allows `target` and `optional_workflows`; either key alone yields a parsed `IntegrationsConfig` with the other defaulting to empty. - `integrations.target` must be an array of unique canonical target IDs when present. diff --git a/context/context-map.md b/context/context-map.md index 4544c0f36..48bd7ff95 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -24,7 +24,7 @@ Feature/domain context: - `context/cli/sync-command.md` (the top-level `sce sync` command: repository-scoped Agent Trace storage resolution, WorkOS-authenticated three-stream control-plane synchronization (`messages`, `parts`, `agent_traces`; `diff_traces` stays local and is absent from the report) through the sync-owned consumer-typed `services::sync::progress` reporter contract with sync-owned events, its generic/no-op contract and `indicatif` presentation adapter for aligned stderr progress with independent stream completion, explicit successful finalization, JSON stdout silence, and rejection of the removed `sce trace` command group) - `context/cli/async-persistence-guarantees.md` (verified guarantees and named limits of the directly awaited Turso persistence migration — exclusive `&mut` transactions, deferred rollback, credential-rotation and terminal-sync behavior, lease/descriptor protection — plus PR1–PR4 staging and the PR3 cleanup ledger) - `context/cli/agent-trace-sync-command.md` (composed local-to-control-plane `sce sync` architecture: the `hooks/plugins → repository Agent Trace DB → AgentTraceExportReader → sce sync → HTTPS + WorkOS Bearer → control plane` data flow, the `sce auth login` / `cd ` / `sce sync` user flow, the no-local-cursor/no-`agent-trace-sync.db`/no-Turso-Sync/no-`BridgeLock`/no-local-DWH invariants, the four-local-capture-streams versus three-remote-streams boundary with its `diff_traces` release gate, the optional `commitPatchId` field on the existing `agent_traces` stream with its Control Plane release dependency and no-backfill limit, and `401`/`409`/ambiguous-batch-failure recovery semantics) -- `context/cli/config-precedence-contract.md` (implemented `sce config` show/validate command contract, deterministic `flags > env > config file > defaults` resolution order, focused `config/resolver.rs` ownership for config discovery/merge/runtime precedence plus default-discovered invalid-file degradation, focused `config/render.rs` ownership for `show`/`validate` text+JSON output construction, canonical `$schema` acceptance for startup-loaded `sce/config.json` files, shared auth-key env/config/optional baked-default support starting with `workos_client_id`, shared runtime resolution for flat logging observability keys including config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` with `/sce/logs` defaulting plus config-file/default-only positive `log_file_retention_limit`, config-file-only `agent_trace.repository_id`/`agent_trace.repository_remote` repository-identity keys with default remote `origin`, `agent_trace.auto_sync` resolution with omitted-value fallback `false`, explicit-false opt-out, and setup-written explicit `true` bootstrap behavior for the post-commit trigger boundary, the catalog-derived `integrations.optional_workflows` optional-workflow selection key, JSON-pointer-prefixed schema-validation errors, canonical Pkl-generated `sce/config.json` schema ownership plus CLI embedding/reuse contract including `policies.attribution_hooks.enabled` default-true/explicit-false opt-out metadata, config-file selection order, `show` provenance output, and trimmed `validate` output contract) +- `context/cli/config-precedence-contract.md` (implemented `sce config` show/validate command contract, deterministic `flags > env > config file > defaults` resolution order, focused `config/resolver.rs` ownership for config discovery/merge/runtime precedence plus default-discovered invalid-file degradation, focused `config/render.rs` ownership for `show`/`validate` text+JSON output construction, canonical `$schema` acceptance for startup-loaded `sce/config.json` files, shared auth-key env/config/optional baked-default support starting with `workos_client_id`, shared runtime resolution for flat logging observability keys including config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` with `/sce/logs` defaulting plus config-file/default-only positive `log_file_retention_limit`, config-file-only `agent_trace.repository_id`/`agent_trace.repository_remote` repository-identity keys with default remote `origin`, `agent_trace.auto_sync` resolution with omitted-value fallback `false`, explicit-false opt-out, and setup-written explicit `true` bootstrap behavior for the post-commit trigger boundary, the catalog-derived `integrations.optional_workflows` optional-workflow selection key, schema-validated per-layer `auth.mode` / `telemetry.enabled` sections, JSON-pointer-prefixed schema-validation errors, canonical Pkl-generated `sce/config.json` schema ownership plus CLI embedding/reuse contract including `policies.attribution_hooks.enabled` default-true/explicit-false opt-out metadata, config-file selection order, `show` provenance output, and trimmed `validate` output contract) - `context/cli/capability-traits.md` (current broad CLI capability seam in `cli/src/services/capabilities.rs`, including `FsOps`/`StdFsOps` (method-less marker), `GitOps`/`ProcessGitOps` (command execution and availability), compile-time-typed borrowed AppContext wiring with scoped borrowing across directly awaited commands with associated-type narrow capability accessors plus `ContextWithRepoRoot` repo-root-scoped context derivation, generic command execution bounds, and test-only unimplemented stubs; current service internals do not consume fs/git traits until later lifecycle migration tasks) - `context/cli/service-lifecycle.md` (current async lifecycle seam in `cli/src/services/lifecycle.rs`, including default no-op `ServiceLifecycle` diagnose/fix/setup methods against narrow `HasRepoRoot`, lifecycle-owned health/fix/setup result types with generic setup messages, doctor/setup adapter boundaries, the static `LifecycleProvider` enum catalog/dispatcher, hook/config/local_db/auth_db/agent_trace_db lifecycle providers including setup-time repository-scoped Agent Trace DB initialization plus checkout identity diagnostics, implemented doctor aggregation over diagnose/fix providers, and implemented setup aggregation over `setup` providers in order config → local_db → auth_db → agent_trace_db → hooks when requested) - `context/cli/mutation-trace-protocol.md` (pure, dependency-free `cli/src/services/mutation_trace/` refinement of the verified `spec/mutation_cursor.qnt` mutation-cursor protocol: the full pure action set — `prepare`/`commit` transition logic, attribution/mutation-event materialization, snapshot-failure/database-failure taint actions, scope abandonment, and recovery with an explicit observed-tree input — plus cross-action sequence/invariant tests and a module-level Quint refinement matrix are all complete (`types.rs`, `protocol.rs`, `mod.rs`, `tests.rs`, registered with `#[allow(dead_code)]`); opaque-newtype identity refinement decisions vs. the Quint model's bounded enums, and the `coordinator.rs` target end-state seam this layout leaves room for but does not create — `store.rs`, `runtime/git_snapshot.rs`, and `runtime/coordinator.rs` (including its public `coordinate()` entrypoint) now exist, built out by the `mutation-cursor-store-persistence` and `mutation-cursor-runtime-coordinator` plans respectively; `protocol.rs` is invoked only through the runtime, and the runtime is now driven by the generic `sce hooks mutation-scope` CLI ingress and a first Claude Code adapter driver, registered by `sce setup` and reachable by a real Claude Code session, now proven against real Git repositories and a real Agent Trace DB by the `claude-mutation-scope-integration` plan's T08 regressions) diff --git a/context/plans/auth-telemetry-policy-config.md b/context/plans/auth-telemetry-policy-config.md new file mode 100644 index 000000000..4d453b33d --- /dev/null +++ b/context/plans/auth-telemetry-policy-config.md @@ -0,0 +1,347 @@ +# Plan: auth-telemetry-policy-config + +## Change summary + +Add two config sections to `sce/config.json` (global and repo-local): `auth.mode` (`disabled | optional | mandatory`, default `optional`) and `telemetry.enabled` (`true | false`, default `false`). The CLI resolves both into one effective access policy, computed in one place, and enforces it where SCE uses authentication or exports data: `sce auth login`, `whoami`, `sync`, post-commit auto-sync, managed telemetry startup, telemetry-credential provisioning, `sce auth telemetry-headers`, the Claude telemetry install step in setup, and doctor's read-only telemetry health check. + +This extends the existing config resolver (`cli/src/services/config/`) and the existing consumer seams (`ResolvedAuthRuntimeConfig`, `ResolvedHookRuntimeConfig`, `ResolvedObservabilityRuntimeConfig`). It adds no new config file, resolver, or policy service. Local-only behavior (Agent Trace persistence, mutation-scope hooks, attribution, bash policy) does not change. The existing `otel` endpoint block stays separate from `telemetry.enabled`. Telemetry export becomes opt-in, which changes current behavior: after upgrading, an installation without an explicit global `telemetry.enabled: true` stops managed SCE export (see Migration). + +## Design + +### Problem + +Today, telemetry export and cloud access depend only on credential state. After `sce auth login`, a telemetry credential is provisioned automatically. Claude hooks then export spans while the `telemetry-ready.json` hint exists, and post-commit auto-sync uploads data whenever `agent_trace.auto_sync` is true. No setting lets a user: + +- opt out of telemetry while staying logged in, +- forbid authentication or cloud access on a machine, or +- keep a repository from turning these features on. + +When the user is logged in, hook processes read the encrypted `auth.db` and its OS-credential-store key (non-interactively). With an explicit policy, users who have not consented never reach that path. + +### Current implementation findings + +- **Config file model:** `cli/src/services/config/schema.rs`. + - `parse_file_config` validates each file against the generated schema (`SCE_CONFIG_SCHEMA_JSON`) and against `TOP_LEVEL_CONFIG_KEYS`. Unknown keys fail. + - It maps sections through `map_agent_trace_config` and `map_otel_config` into `FileConfig`, wrapping each value as `FileConfigValue { value, source: ConfigPathSource }`. +- **Merge and resolution:** `cli/src/services/config/resolver.rs::resolve_runtime_config_with`. + - Merges layers key by key, with the last layer winning (`global -> local`). + - Because of that merge, the per-layer values are gone by the time `RuntimeConfig` is built. Consent rules need them, so the policy must be captured during the merge loop. + - An invalid default-discovered layer is skipped and recorded in `validation_errors`. + - An explicit `--config` or `SCE_CONFIG_FILE` file replaces discovery entirely (no global layer). An invalid explicit file is fatal. + - `resolve_config_paths` discovers the local file as `/.sce/config.json`, not relative to the Git root. +- **Resolver wrappers:** `resolve_auth_runtime_config` (used by login, whoami, and sync), `resolve_hook_runtime_config` (used by post-commit auto-sync), `resolve_observability_runtime_config` (used by app startup), and `resolve_agent_trace_storage_runtime_config`. Each re-runs the full resolution and projects one slice of it. These are the extension points. +- **Types:** `cli/src/services/config/types.rs` has `ValueSource`, `ConfigPathSource`, `ResolvedValue`, and the projected `Resolved*RuntimeConfig` structs. +- **Rendering:** `cli/src/services/config/render.rs::format_show_output` and `format_validate_output`. Warnings come from `RuntimeConfig.validation_warnings` plus the skipped-file `validation_errors`. +- **Schema source:** `config/pkl/base/sce-config-schema.pkl`. `otel` describes endpoints only. Managed export always uses the code-owned `MANAGED_OTLP_DEFAULTS`. +- **App startup:** `cli/src/app.rs::run_with_dependency_check_and_streams`. + - Computes `managed_span_kind` (Claude hooks → `ClaudeHook`; other hooks, `setup`, and `auth telemetry-headers` → none; everything else → `Command`). + - Then calls `RuntimeTelemetry::resolve(span_kind, logger)`. + - `build_startup_context` already resolves the full config through `resolve_observability_runtime_config(&cwd)`. +- **Managed telemetry:** `cli/src/services/managed_telemetry.rs`. + - `RuntimeTelemetry::resolve` → `resolve_when_ready(telemetry_readiness::is_ready(..), load_telemetry_credential(), ..)`. + - Lookups use `CredentialAccess::NonInteractive` under `CREDENTIAL_LOOKUP_DEADLINE`. + - `TelemetryFallbackReason` classifies Noop outcomes. + - `inspect_health` / `inspect_health_with` back `sce doctor` (`cli/src/services/doctor/mod.rs`, `doctor/managed_telemetry.rs`). +- **Telemetry credential storage:** `cli/src/services/telemetry_credential_storage.rs`. + - Functions: `load_telemetry_credential`, `load_repository_telemetry_credential`, `bind_repository_telemetry`, `delete_telemetry_credential`. + - Reads go through the existing-DB path in `cli/src/services/token_storage.rs` (`open_existing_auth_db(access)`). It never creates `auth.db` or a key. +- **Auth commands:** `cli/src/services/auth_command/mod.rs`. + - `run_login`: interactive `load_tokens`, renewal or device flow, then `provision_telemetry_credential`. Provisioning calls `issue_and_save_telemetry_credential`, `telemetry_readiness::mark_ready`, and `enroll_current_repository_if_unbound`. + - `TelemetryProvisioningResult` has two values, `Issued | Unavailable`. + - `run_logout`: clears the hint, then deletes both credential rows through interactive access. A missing DB returns `false`. + - `run_whoami`: interactive `load_tokens`. Without tokens it renders an unauthenticated success. + - `run_telemetry_headers` / `telemetry_headers_with`: gated on the readiness hint and the destination tripwire, then repository resolution and `load_repository_telemetry_credential`. +- **Sync:** `cli/src/services/sync/sync.rs::run_current_sync_without_progress` builds `AuthenticatedControlPlaneClient` with `CredentialAccess::NonInteractive`. `sync/command.rs::classify_sync_error` maps auth failures to `UserError::NotAuthenticated`. +- **Auto-sync:** `cli/src/services/hooks/commit_hooks.rs::run_post_commit_subcommand` reads `resolve_hook_runtime_config(root).agent_trace_auto_sync` and then calls `sync::auto_sync::launch(root)`, a detached `sce sync --format json`. +- **Claude-native telemetry:** `cli/src/services/setup/claude_telemetry.rs::install_claude_telemetry` and `setup/config_merge.rs::merge_claude_telemetry_settings`. + - Setup writes them into *user-level* Claude settings whenever the Claude target is selected (`setup/command.rs::render_claude_telemetry_section`). + - Written keys: `CLAUDE_CODE_ENABLE_TELEMETRY=1`, `OTEL_*_EXPORTER=otlp`, the managed endpoint, and `otelHeadersHelper = sce auth telemetry-headers`. + - `setup/config_merge.rs` holds only the Claude and OpenCode settings merges. Repo-local `.sce/config.json` persistence is `setup/mod.rs::persist_integration_targets`, which writes only `integrations`, `agent_trace.auto_sync`, and `policies.attribution_hooks.enabled`. +- **Errors:** `cli/src/services/error.rs::UserError` (`NotAuthenticated`, `AuthStorageUnavailable`, …) owns stable keys and messages. + +### Configuration schema and Rust types + +```json +{ + "auth": { "mode": "disabled" | "optional" | "mandatory" }, + "telemetry": { "enabled": true | false } +} +``` + +- Pkl (`config/pkl/base/sce-config-schema.pkl`): + - `auth` is an object with `additionalProperties = false`. `mode` is a string enum, default `"optional"`. + - `telemetry` is an object with `additionalProperties = false`. `enabled` is a boolean, default `false`. Its description must say that it controls SCE-managed export and the Claude headers helper, not the `otel` destination. +- Rust (`config/types.rs`). `AuthMode` follows the `LogLevel` parse / `as_str` pattern: + + ```rust + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub(crate) enum AuthMode { Disabled, Optional, Mandatory } + + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub(crate) enum PolicyLayer { User, Repository } + + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub(crate) enum TelemetryPolicyState { + Enabled, + Disabled(TelemetryDisabledReason), + } + + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub(crate) enum TelemetryDisabledReason { + NotEnabled, // no layer enabled it (default) + UserOptOut, // user layer enabled=false + NoUserConsent, // repository enabled=true without user-layer true + RepositoryOptOut, // repository enabled=false + AuthDisabled, // effective auth mode is disabled + InvalidConfig, // a discovered layer was skipped as invalid + } + + #[derive(Clone, Debug, Eq, PartialEq)] + pub(crate) struct ResolvedAccessPolicy { + pub(crate) auth_mode: ResolvedValue, // effective mode, source = deciding layer + pub(crate) telemetry_enabled: ResolvedValue, // configured (merged) value with provenance + pub(crate) telemetry: TelemetryPolicyState, // effective state + pub(crate) background_cloud_allowed: bool, // false when auth disabled or any discovered layer invalid + } + ``` + + Small methods on `ResolvedAccessPolicy` (`telemetry_enabled()`, `auth_allowed()`, `auto_sync_allowed(configured: bool)`) let call sites stay one-line checks. +- `schema.rs`: `FileConfig` gains `auth_mode: Option>` and `telemetry_enabled: Option>`. They are mapped by `map_auth_config` / `map_telemetry_config`, mirroring `map_agent_trace_config`. `TOP_LEVEL_CONFIG_KEYS` and its description add `auth` and `telemetry`. + +### Policy precedence and effective resolution + +Layer classification comes from the existing `ConfigPathSource`: + +- **User layer:** `DefaultDiscoveredGlobal`, or the single explicit file (`Flag` or `Env`). An explicit `--config` or `SCE_CONFIG_FILE` is the user's own choice, and it already replaces global discovery. +- **Repository layer:** `DefaultDiscoveredLocal`. +- There is no environment-variable or flag layer for either key. + +`resolve_access_policy(user, repo, degraded)` is a pure function. `user` and `repo` are the per-layer `(Option, Option)`, captured inside the existing merge loop. `degraded` is `!validation_errors.is_empty()`. Rules, applied in order: + +1. **Auth mode (most-restrictive wins, ordered `disabled > mandatory > optional`).** + - If either layer is `disabled`, the effective mode is `disabled`. A repository therefore cannot override a global prohibition. A repository can also opt itself out of cloud access. + - Otherwise, if either layer is `mandatory`, the effective mode is `mandatory`. + - Otherwise the mode is `optional` (the default when both layers omit it). + - The source is the deciding layer. When both layers agree, the source is the repository layer, matching the existing merge. +2. **Telemetry (consent-gated).** The first matching rule wins: + - `degraded` → `Disabled(InvalidConfig)`. + - Effective auth is `disabled` → `Disabled(AuthDisabled)`. + - User layer `false` → `Disabled(UserOptOut)`. The global opt-out always wins. + - Repository layer `false` → `Disabled(RepositoryOptOut)`. + - User layer `true` → `Enabled`. + - Repository layer `true` without user `true` → `Disabled(NoUserConsent)`. + - Otherwise → `Disabled(NotEnabled)`. +3. **Background cloud operations** (post-commit auto-sync, hook-time credential reads) are allowed only when the effective auth mode is not `disabled` and the policy is not `degraded`. If an invalid file is skipped, nothing it might have prohibited can happen in the background through fallback defaults. Commands the user runs explicitly (`login`, `whoami`, `sync`) use the auth mode resolved from the remaining valid layers. An invalid explicit file stays fatal, as today. +4. **Contradictions** are deterministic `validation_warnings`, never errors, because each file can be valid on its own. Exact strings are fixed in T02: + - Repository `telemetry.enabled: true` without user consent. + - Any layer with `telemetry.enabled: true` while the effective auth is `disabled`. + - `agent_trace.auto_sync: true` while the effective auth is `disabled` (auto-sync is skipped). + - Repository `auth.mode: mandatory` overridden by a user-layer `disabled`. + - A skipped invalid layer forcing telemetry and background cloud operations off. + +### Authentication and telemetry behavior matrix + +"Rejected" means a new `UserError::AuthDisabledByConfig` (key `auth.disabled_by_config`, runtime class). Its fixed message names `auth.mode` and the config file that set it. A rejection happens before any `auth.db` or credential-store access. + +| Operation | `disabled` | `optional` | `mandatory` | +| --- | --- | --- | --- | +| `sce auth login` | Rejected | Allowed (current flow) | Allowed (current flow) | +| Telemetry provisioning inside login | n/a | Only when telemetry is `Enabled`. Otherwise skipped with result `disabled`: no issuance, no hint write, no repository enrollment | Same as `optional` | +| `sce auth logout` | Allowed (interactive deletion, explicit user action; no policy check) | Allowed | Allowed | +| `sce auth whoami` | Rejected | Unauthenticated → current success output | Unauthenticated → `UserError::NotAuthenticated` (nonzero) | +| `sce sync` | Rejected | Current behavior (missing or expired credentials → `NotAuthenticated`) | Same as `optional` | +| Post-commit auto-sync | Silently skipped (no spawn, `debug` log) | Spawned when `auto_sync` is true and background cloud is allowed | Same as `optional` | +| Managed telemetry init (commands and Claude hooks) | Noop `disabled_by_config` | Telemetry `Enabled` → current hint plus non-interactive lookup. Otherwise Noop `disabled_by_config` before the hint or `auth.db` is read | Same as `optional` | +| `sce auth telemetry-headers` | Fails closed with the existing fixed diagnostic | Telemetry `Enabled` → current behavior. Otherwise fails closed before repository resolution or `auth.db` | Same as `optional` | +| Claude hook execution (local work) | Unchanged | Unchanged | Unchanged (never prompts, never blocks on auth) | +| `sce doctor` managed telemetry row | `[PASS] Managed telemetry (disabled by config)`, no `auth.db` read | Telemetry not `Enabled` → same PASS row; otherwise current check | Same as `optional` | +| Setup Claude telemetry install | Skipped with a fixed "disabled by SCE config" line | Telemetry not `Enabled` → skipped with the same line; otherwise current install | Same as `optional` | + +Repository binding, credential identity (`sub`, `workspace_id`), expiry checks, and the readiness hint keep their current behavior whenever an operation is allowed. The policy check is an extra precondition and replaces nothing. + +`mandatory` enforcement boundary: it changes only explicit interactive results (`whoami` fails when unauthenticated). Cloud commands already require credentials. Hooks and background work never initiate login and never fail because of missing auth in any mode. + +### Telemetry coverage limits (not claimed as full opt-out) + +- `telemetry.enabled: false` stops SCE-managed OTLP export from the CLI, telemetry credential issuance, loading, and headers-helper output, and new Claude telemetry installs by setup. +- It does **not** remove Claude-native telemetry settings that an earlier `sce setup` already wrote to user-level Claude settings. With those settings, Claude Code keeps exporting to the managed collector without the `Authorization` header, and the collector is expected to reject the data. Claude telemetry from other repositories also shares the one user-level settings file. A real opt-out of Claude-native export needs settings reconciliation, which is out of scope. `sce config show` and the plan's context sync must state this. +- A user `OTEL_*` environment or Claude managed settings remain outside SCE control. + +### Backward compatibility and migration + +- **Existing configs:** files without `auth` or `telemetry` stay valid and resolve to `optional` / telemetry `Disabled(NotEnabled)`. +- **Behavior change for existing logged-in installs:** managed SCE export stops until the user sets `telemetry.enabled: true` in the global config. There is no inference from `telemetry-ready.json` or `auth.db` state, so no hidden state decides consent. + - Discoverability: doctor's managed-telemetry row reports `disabled_by_config`. + - When a valid readiness hint exists while telemetry is disabled, doctor's text adds one fixed line naming the opt-in key. + - `sce auth login` reports `telemetry_provisioning: disabled` with a fixed message naming the key. +- **Stored state** (`auth.db`, telemetry credential, bindings, hint) is left untouched when telemetry is disabled. It is not read, and re-enabling resumes use without a new login while the credential is unexpired. +- **Older SCE binaries reject the new keys** (`additionalProperties: false`, `TOP_LEVEL_CONFIG_KEYS`). An older binary skips the whole discovered file as invalid, which also drops that file's other settings (for example `policies.bash`). Setup therefore does not write either key in this plan. Release notes must call this out. +- **`agent_trace.auto_sync`** keeps its semantics. It is additionally gated by background-cloud permission. + +### Risks + +- **Privacy:** the Claude-native export described under coverage limits. + - Mitigation: setup no longer installs it without consent. Documented residual for existing installs. +- **macOS Keychain:** + - The policy check must run before every `telemetry_readiness` / `auth.db` touch on hook and startup paths. Tests inject lookups that fail if called. + - `logout` keeps interactive access in every mode, so one Keychain dialog per explicit logout remains possible. This is intended. + - Non-interactive Keychain semantics stay unchanged. +- **Startup cost on hook paths:** the policy comes from the config resolution `build_startup_context` already performs. No additional file reads. +- **cwd-based local discovery:** Claude hooks and the headers helper resolve `/.sce/config.json`. A launch from a subdirectory misses the repository layer, which can only *restrict*, so the failure mode is fail-open toward the user's global consent. This matches the existing config contract and is listed as an open question. +- **Mixed versions:** older binaries reject configs that carry the new keys (see Migration). + +### Out of scope, with future interfaces + +- Interactive `sce setup` consent questions and auto-login. + - Interface: a future setup step writes `telemetry.enabled` / `auth.mode` into the **global** config file (the user layer). `resolve_access_policy` needs no change. + - Keep `AuthMode::parse` / `as_str` and the key names stable for that writer. +- Keychain "Always Allow" verification commands. + - Interface: they can call `ResolvedAccessPolicy::telemetry_enabled()` / `auth_allowed()` to decide applicability. +- Removing `telemetry-ready.json`. The policy gate sits before the hint, so the hint can later be removed without touching policy code. +- `auth.db` storage or migrations, macOS Keychain or code-signing changes, and Claude settings reconciliation. + - Interface: reconciliation can consume `TelemetryPolicyState` to decide whether to remove SCE-owned Claude telemetry keys. + +## Acceptance criteria + +- [ ] AC1: `auth.mode` (`disabled|optional|mandatory`) and `telemetry.enabled` (boolean) are accepted in global and repo-local config, unknown sub-keys and wrong types fail validation with JSON-pointer-prefixed errors, and configs without the sections remain valid. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml config::schema`; `nix run .#pkl-check-generated`. +- [ ] AC2: Effective policy follows the precedence rules exactly: user telemetry opt-out always wins, repository `true` alone never enables telemetry, repository `false` disables it, user `disabled` auth cannot be overridden by the repository, `auth.mode: disabled` forces telemetry and auto-sync off, and any skipped invalid discovered layer forces telemetry and background cloud operations off. + - Validate: table-driven `resolve_access_policy` test in `cli/src/services/config/resolver.rs` covering every user × repository × degraded combination; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml access_policy`. +- [ ] AC3: `sce config show` reports `auth.mode`, `telemetry.enabled` (value, `source`, `config_source`), and the effective telemetry state with its reason in text and JSON; `sce config validate` and `show` report the defined contradiction warnings verbatim. + - Validate: exact-output render tests in `cli/src/services/config/render.rs`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml config::render`. +- [ ] AC4: With telemetry not `Enabled`, no SCE process (command, Claude hook, doctor, headers helper) reads the readiness hint, opens `auth.db`, resolves the encryption key, issues a telemetry credential, or exports managed spans — even when a valid `auth.db`, telemetry credential, and readiness hint exist. + - Validate: unit tests with lookups that fail the test if invoked; multiprocess test in `cli/src/services/auth_db/multiprocess_tests.rs` running a Claude hook through `app::run` with an existing credential and `telemetry.enabled: false`, asserting zero exported spans at the loopback collector and an empty-key environment that would fail any key resolution. +- [ ] AC5: With `auth.mode: disabled`, `sce auth login`, `whoami`, and `sync` fail with `auth.disabled_by_config` before any credential-store access, post-commit does not spawn auto-sync, and `sce auth logout` still deletes stored credentials. + - Validate: auth-command, sync-command, and `run_post_commit_subcommand_with` tests with injected storage/spawn closures; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml auth_command sync commit_hooks`. +- [ ] AC6: With `auth.mode: mandatory`, unauthenticated `sce auth whoami` exits nonzero with `auth.not_authenticated`, while hooks and auto-sync behave as in `optional`; with `optional`, current outputs are byte-identical. + - Validate: auth-command tests for both modes with missing and expired stored credentials. +- [ ] AC7: Login with telemetry not `Enabled` reports `telemetry_provisioning` `disabled` (text and JSON), makes no issuance request, writes no readiness hint, and enrolls no repository; with telemetry `Enabled` the existing issued/unavailable behavior is unchanged. + - Validate: `run_login_with_stored_credentials` / provisioning tests with a provisioning closure that fails if called. +- [ ] AC8: `sce setup` with the Claude target skips the Claude-native telemetry install with a fixed "disabled by SCE config" line when telemetry is not `Enabled`, leaving user Claude settings byte-unchanged, and installs as today when it is. + - Validate: `cli/src/services/setup/command.rs` tests around `render_claude_telemetry_section`. +- [ ] AC9: `sce doctor` reports `[PASS] Managed telemetry (disabled by config)` / JSON `state: disabled_by_config` without reading `auth.db` when telemetry is not `Enabled`, and post-commit auto-sync readiness reports disabled when auth is disabled. + - Validate: `inspect_health_with` and doctor rendering tests; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml doctor`. + +### Full validation + +- `nix flake check` +- `nix run .#pkl-check-generated` +- Manual macOS check (not covered by CI): with an existing logged-in `auth.db` and readiness hint, a locked login Keychain, and global `telemetry.enabled: false`, run a Claude Code session in an SCE repository and `sce doctor`; confirm no Keychain dialog appears, no `sce.hook` spans arrive, and `sce auth logout` shows at most one interactive Keychain prompt. + +### Context sync + +- `context/cli/config-precedence-contract.md` (new keys, layer classification, precedence rules, warnings, show output) +- `context/sce/telemetry-credential.md` (policy gate before readiness hint, headers helper, setup install gate, coverage limits) +- `context/cli/agent-trace-auto-sync.md` (auth-policy gate on the trigger boundary) +- `context/cli/cli-command-surface.md` (auth command policy outcomes) +- `context/sce/cli-observability-contract.md` (`disabled_by_config` fallback reason) +- `context/sce/auth-db.md` (which paths may reach `auth.db` under each policy) +- `context/glossary.md` (auth mode, effective access policy, user/repository layer) +- `context/context-map.md` +- A decision record for the consent-gated precedence model (`context/decisions/`) + +## Task context synchronization lifecycle + +Persist this field in every plan; this is durable plan state, not chat state: + +- **Task context synchronization:** every task carries `pending | synced | blocked`. + A completed task must be `synced` before another task can start or the plan can + finish. +- For `blocked`, record **Blocker**, **Required action**, and **Retry condition** + beside the status. Never infer `synced` from conversation history; write every + lifecycle transition to the plan file. + +## Constraints and non-goals + +- **In scope:** `config/pkl/base/sce-config-schema.pkl`; `cli/src/services/config/{types,schema,resolver,render,mod}.rs`; `cli/src/app.rs` (telemetry startup); `cli/src/services/managed_telemetry.rs`; `cli/src/services/doctor/{mod,managed_telemetry,inspect}.rs`; `cli/src/services/auth_command/mod.rs`; `cli/src/services/sync/{sync,command}.rs`; `cli/src/services/hooks/commit_hooks.rs`; `cli/src/services/setup/command.rs`; `cli/src/services/error.rs`; `cli/src/services/auth_db/multiprocess_tests.rs`; the context files listed under Context sync. +- **Out of scope:** new interactive setup questions; automatic login during setup; Keychain Always Allow verification commands; removing `telemetry-ready.json`; `auth.db` storage or migration changes; macOS Keychain implementation or code signing; reconciling or removing existing Claude Code telemetry settings; setup writing `auth`/`telemetry` keys; env-var or CLI-flag overrides for either key. +- **Constraints:** policy resolved once per config resolution through the existing resolver (no second resolver, no global mutable policy state); policy checks precede every readiness-hint, `auth.db`, and credential-store access on startup and hook paths; stable fixed user-facing strings; no secrets in output; deterministic warnings; `optional` mode output for existing commands stays byte-identical; Rust 2021, `anyhow` with context, rustfmt. +- **Non-goal:** a general feature-flag or permissions framework; per-command policy overrides; changing what `mandatory` means for hooks. + +## Assumptions + +- An explicit `--config` / `SCE_CONFIG_FILE` file is the user layer, consistent with it already replacing global discovery. +- Missing `telemetry.enabled` means disabled for every installation, existing ones included. Consent is never inferred from `telemetry-ready.json` or `auth.db`. +- Contradictions across layers are warnings, not validation errors, because each file can be individually valid. +- `sce auth logout` performs no policy check in any mode. +- `mandatory` adds no new hook or background behavior; its only enforced difference today is a nonzero unauthenticated `whoami`. +- Repository-layer discovery keeps the existing `/.sce/config.json` rule. + +## Task stack + +- [x] T01: `Add auth and telemetry sections to the config schema and file model` (status:done) + - Task ID: T01 + - Scope: In — Pkl `auth` and `telemetry` schema blocks with descriptions and defaults; `AuthMode` in `config/types.rs` (`parse`, `as_str`); `FileConfig.auth_mode` / `FileConfig.telemetry_enabled`; `map_auth_config` / `map_telemetry_config` and `TOP_LEVEL_CONFIG_KEYS` (+ description) in `config/schema.rs`; initializing the new fields in `resolve_runtime_config_with`. Out — merge semantics, effective policy, rendering, and runtime enforcement. + - Dependencies: none + - Done when: both sections parse from any layer with correct `ConfigPathSource`; invalid enum values, non-boolean `enabled`, unknown sub-keys, and non-object sections fail with schema-pointer errors; files without the sections parse unchanged. + - Verify: table-driven parse tests in `config/schema.rs` (valid modes, invalid mode, `"true"` string, unknown sub-key, non-object, omitted); `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml config::schema`; `nix run .#pkl-check-generated`. + - Completed: 2026-10-20 + - Files changed: `config/pkl/base/sce-config-schema.pkl`, `cli/src/services/config/types.rs`, `cli/src/services/config/schema.rs`, `cli/src/services/config/resolver.rs`, `context/plans/auth-telemetry-policy-config.md` + - Result: Added Pkl `auth` (`mode` enum `disabled|optional|mandatory`, default `optional`) and `telemetry` (`enabled` boolean, default `false`) objects with `additionalProperties = false`; added `AuthMode` with `parse`/`as_str`; added `ParsedAuthConfigDocument`/`ParsedTelemetryConfigDocument`, `FileConfig.auth_mode`/`telemetry_enabled`, `map_auth_config`/`map_telemetry_config`, and `auth`/`telemetry` in `TOP_LEVEL_CONFIG_KEYS` and its description; `resolve_runtime_config_with` initializes both fields to `None` without merging them. New `access_policy_config_tests` module covers all four `ConfigPathSource` layers × three modes, omitted/empty sections, schema-pointer failures (invalid mode, non-string mode, `"true"`, `1`, unknown sub-keys, non-object sections), the key-allowlist backstop, and the `AuthMode::parse` error. + - Verify outcome: `config::schema` tests passed (28 passed, 0 failed); `nix run .#pkl-check-generated` passed (142 files); `cargo clippy --all-targets -- -D warnings` via `run-cli-cargo.sh` passed. + - Deviation: `FileConfig.auth_mode`, `FileConfig.telemetry_enabled`, and `AuthMode::as_str` carry `#[allow(dead_code)]` until T02 consumes them in the merge loop; T02 should remove these attributes. + - Context impact: localized — config schema and file model only; no runtime behavior change until T02 merges the fields. Durable docs (`context/cli/config-precedence-contract.md`) gain the new keys and layer rules with T02/T03. + - Context synchronization: synced + +- [ ] T02: `Resolve the effective access policy from user and repository layers` (status:todo) + - Task ID: T02 + - Scope: In — `PolicyLayer`, `TelemetryPolicyState`, `TelemetryDisabledReason`, `ResolvedAccessPolicy` in `config/types.rs`; per-layer capture inside the `resolve_runtime_config_with` merge loop; pure `resolve_access_policy(user, repo, degraded)` in `config/resolver.rs`; `RuntimeConfig.access_policy`; contradiction strings appended to `validation_warnings`; exposing the policy on `ResolvedAuthRuntimeConfig`, `ResolvedHookRuntimeConfig`, and `ResolvedObservabilityRuntimeConfig`. Out — rendering and consumer enforcement. + - Dependencies: T01 + - Done when: the resolver implements the precedence rules in Design exactly, with source/provenance of the deciding layer; explicit config files act as the user layer; a skipped invalid discovered layer yields `Disabled(InvalidConfig)` and `background_cloud_allowed = false`; contradiction warnings are deterministic and ordered. + - Verify: one table-driven test over user {absent, disabled, optional, mandatory} × repository {same} for auth and user {absent, true, false} × repository {absent, true, false} × degraded {false, true} × auth-disabled for telemetry; integration tests through `resolve_runtime_config_with` for explicit-file-as-user-layer, invalid-global-skipped, and invalid-local-skipped; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml access_policy`. + - Context synchronization: pending + +- [ ] T03: `Report auth and telemetry policy in config show and validate` (status:todo) + - Task ID: T03 + - Scope: In — `config/render.rs` text lines and JSON objects for `auth.mode` and `telemetry.enabled` (value, `source`, `config_source`) plus effective telemetry state and reason (`result.resolved.auth`, `result.resolved.telemetry`); contradiction warnings in `show` warnings and `validate` warnings; a fixed note when telemetry is disabled that Claude settings written by earlier setups are not changed. Out — enforcement. + - Dependencies: T02 + - Done when: `show` text and JSON include the new fields in a deterministic position for defaults, global-only, local-only, and contradictory layers; `validate` stays limited to its existing fields and lists the new warnings. + - Verify: exact-output tests in `config/render.rs` for default, user-enabled, repo-only-enabled, and auth-disabled-with-telemetry cases in both formats; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml config::render`. + - Context synchronization: pending + +- [ ] T04: `Gate managed telemetry startup and doctor health on telemetry policy` (status:todo) + - Task ID: T04 + - Scope: In — `TelemetryFallbackReason::DisabledByConfig` (`disabled_by_config`, non-failure, `debug` log); `RuntimeTelemetry::resolve` / `resolve_when_ready` taking the policy state and returning Noop before the readiness hint or lookup when not `Enabled`; `app.rs` passing the policy from `StartupContext` (the existing `resolve_observability_runtime_config` result); `inspect_health` / `inspect_health_with` and `doctor/managed_telemetry.rs` rendering `[PASS] Managed telemetry (disabled by config)` / JSON `disabled_by_config` plus the fixed opt-in line when a ready hint exists; multiprocess hook regression. Out — headers helper, login, sync. + - Dependencies: T02 + - Done when: with telemetry not `Enabled`, command and Claude-hook startup and doctor never call `telemetry_readiness` or the credential lookup; with telemetry `Enabled`, behavior and fallback reasons are unchanged. + - Verify: unit tests with a lookup future that panics if polled and a readiness probe that fails if called; doctor JSON/text tests; multiprocess test in `auth_db/multiprocess_tests.rs` running a Claude hook via `app::run` with a seeded credential, ready hint, empty `SCE_AUTH_DB_ENCRYPTION_KEY`, and `telemetry.enabled: false`, asserting no exported spans; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_telemetry doctor multiprocess`. + - Context synchronization: pending + +- [ ] T05: `Fail closed in the telemetry headers helper when telemetry is disabled` (status:todo) + - Task ID: T05 + - Scope: In — `auth_command::run_telemetry_headers` resolving the policy from the working directory and `telemetry_headers_with` taking a `telemetry_enabled` input checked before readiness, repository resolution, and lookup. Out — Claude settings changes. + - Dependencies: T02 + - Done when: telemetry not `Enabled` (including `auth.mode: disabled` and invalid discovered config) yields the existing fixed `Telemetry credential is unavailable.` with empty stdout, without calling the repository resolver or lookup; enabled behavior is unchanged. + - Verify: extend `telemetry_headers_fail_closed_before_lookup_without_repository_or_on_conflict` into a table including the policy-disabled row with resolver/lookup closures that fail if called; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml telemetry_headers`. + - Context synchronization: pending + +- [ ] T06: `Enforce auth mode and telemetry consent in auth login and whoami` (status:todo) + - Task ID: T06 + - Scope: In — `UserError::AuthDisabledByConfig` (`auth.disabled_by_config`) in `error.rs`; `run_login` and `run_whoami` checking the policy from `resolve_auth_runtime_config` before any `token_storage` call; `TelemetryProvisioningResult::Disabled` (status `disabled`, fixed message naming `telemetry.enabled`) and skipping `provision_telemetry_credential` when telemetry is not `Enabled`; `mandatory` unauthenticated `whoami` → `NotAuthenticated`; logout unchanged. Out — sync, setup. + - Dependencies: T02 + - Done when: the auth rows of the behavior matrix hold for all three modes; `optional` outputs are byte-identical to today; logout under `disabled` still deletes both credential rows. + - Verify: table-driven tests over mode × stored credentials {none, valid, expired} using injected storage/provision closures that fail if called where access is forbidden; login text/JSON rendering tests for `disabled` provisioning; `run_logout_with` test under `disabled`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml auth_command error`. + - Context synchronization: pending + +- [ ] T07: `Gate sce sync and post-commit auto-sync on auth policy` (status:todo) + - Task ID: T07 + - Scope: In — `sync::sync::run_current_sync_without_progress` returning a policy rejection before storage/credential access when auth is `disabled`, mapped by `sync/command.rs::classify_sync_error` to `AuthDisabledByConfig`; `commit_hooks::run_post_commit_subcommand` deciding launch from `ResolvedHookRuntimeConfig` (`auto_sync && background_cloud_allowed`); doctor `post_commit_auto_sync` reporting disabled when auth policy prevents it. Out — changing the auto-sync launcher or sync protocol. + - Dependencies: T02, T06 + - Done when: `sce sync` under `disabled` fails with `auth.disabled_by_config` and no credential-store access; post-commit with `auto_sync: true` under `disabled` or degraded config never calls the launcher and still succeeds; `optional`/`mandatory` behavior is unchanged. + - Verify: `run_post_commit_subcommand_with` table test with a launch closure that records calls across {auto_sync false/true} × {disabled, optional, mandatory, degraded}; sync classification test; doctor auto-sync state test; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml commit_hooks sync doctor`. + - Context synchronization: pending + +- [ ] T08: `Skip Claude-native telemetry install in setup without telemetry consent` (status:todo) + - Task ID: T08 + - Scope: In — `setup/command.rs::render_claude_telemetry_section` (or its caller) resolving the policy for the setup repository and skipping `install_claude_telemetry` with a fixed `Claude telemetry: skipped; SCE telemetry is disabled by config.` line when not `Enabled`. Out — removing or reconciling existing Claude settings, setup prompts, writing config keys. + - Dependencies: T02 + - Done when: setup with the Claude target leaves user Claude settings byte-unchanged and prints the skip line when telemetry is not `Enabled`, and installs exactly as today when it is. + - Verify: tests alongside `setup_claude_telemetry_installs_when_claude_is_selected` for enabled and disabled policies asserting file bytes and report text; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup_claude_telemetry`. + - Context synchronization: pending + +## Open questions + +- Existing logged-in users silently lose managed SCE export on upgrade, because a missing `telemetry.enabled` means disabled. Doctor and login now say so, but nothing prompts the user. Is that acceptable, or should the release ship with the future setup consent question? Inferring consent from an existing `telemetry-ready.json` was rejected because it makes hidden state decide consent. +- `mandatory` changes very little today. Cloud commands already require credentials, and hooks must never block, so the only enforced difference is a nonzero unauthenticated `whoami`. It is kept so the future setup and auto-login work has a stable mode to build on. If no near-term consumer exists, shipping only `disabled | optional` would be the smaller version. +- Telemetry opt-out does not stop Claude-native export from settings written by earlier setups, and those settings are user-level, shared across repositories. Should a follow-up plan for SCE-owned Claude settings reconciliation be scheduled now, so the opt-out can eventually be described as complete? +- Repository-layer discovery uses `/.sce/config.json`. A Claude hook or headers helper launched from a subdirectory sees only the user layer, so a repository opt-out can be missed there. Fixing this means Git-root-relative discovery for every config consumer, which is broader than this plan. From eecbf29b7abf3c76889760b1391c457812f23dd8 Mon Sep 17 00:00:00 2001 From: David Abram Date: Tue, 20 Oct 2026 14:01:55 +0200 Subject: [PATCH 2/9] config: Resolve consent-gated access policy from config layers Resolve auth and telemetry settings across user and repository config layers so repository files cannot grant access or telemetry without user consent. Most-restrictive auth resolution, deterministic telemetry states and contradiction warnings, degraded-config shutdown, and projected runtime policy exposure now share one resolver; durable context documents the contract and decision. Plan: `auth-telemetry-policy-config` Task: `T02` Co-authored-by: SCE --- cli/src/services/config/resolver.rs | 630 +++++++++++++++++- cli/src/services/config/schema.rs | 2 - cli/src/services/config/types.rs | 62 ++ context/cli/access-policy.md | 73 ++ context/cli/config-precedence-contract.md | 2 +- context/context-map.md | 1 + ...-consent-gated-access-policy-precedence.md | 75 +++ context/glossary.md | 2 +- context/plans/auth-telemetry-policy-config.md | 10 +- 9 files changed, 846 insertions(+), 11 deletions(-) create mode 100644 context/cli/access-policy.md create mode 100644 context/decisions/2026-10-20-consent-gated-access-policy-precedence.md diff --git a/cli/src/services/config/resolver.rs b/cli/src/services/config/resolver.rs index bfc5e4a7b..bc844e8e1 100644 --- a/cli/src/services/config/resolver.rs +++ b/cli/src/services/config/resolver.rs @@ -17,10 +17,11 @@ use crate::services::managed_telemetry::MANAGED_OTLP_DEFAULTS; use super::policy::{build_validation_warnings, resolve_bash_policy_config, BashPolicyConfig}; use super::schema; use super::types::{ - parse_bool_value_from, ConfigPathSource, ConfigRequest, DatabaseRetryConfig, LoadedConfigPath, - LogFormat, LogLevel, ReportFormat, ResolvedAgentTraceStorageRuntimeConfig, - ResolvedAuthRuntimeConfig, ResolvedHookRuntimeConfig, ResolvedObservabilityRuntimeConfig, - ResolvedOptionalValue, ResolvedValue, ValueSource, DEFAULT_LOG_FILE_RETENTION_LIMIT, + parse_bool_value_from, AuthMode, ConfigPathSource, ConfigRequest, DatabaseRetryConfig, + LoadedConfigPath, LogFormat, LogLevel, PolicyLayer, ReportFormat, ResolvedAccessPolicy, + ResolvedAgentTraceStorageRuntimeConfig, ResolvedAuthRuntimeConfig, ResolvedHookRuntimeConfig, + ResolvedObservabilityRuntimeConfig, ResolvedOptionalValue, ResolvedValue, + TelemetryDisabledReason, TelemetryPolicyState, ValueSource, DEFAULT_LOG_FILE_RETENTION_LIMIT, ENV_ATTRIBUTION_HOOKS_DISABLED, ENV_LOG_DIR, ENV_LOG_FORMAT, ENV_LOG_LEVEL, }; @@ -38,6 +39,14 @@ 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 = + "agent_trace.auto_sync is true but auth.mode resolves to disabled; post-commit auto-sync is skipped."; +pub(crate) const WARNING_REPOSITORY_MANDATORY_OVERRIDDEN_BY_USER_DISABLED: &str = "auth.mode is mandatory in the repository config but disabled in the user config; auth.mode resolves to disabled."; +pub(crate) const WARNING_INVALID_LAYER_DISABLES_CLOUD: &str = "A discovered config file was skipped as invalid; SCE telemetry and background cloud operations are disabled."; + pub(crate) const CONTROL_PLANE_BASE_URL_KEY: AuthConfigKeySpec = AuthConfigKeySpec { config_key: "control_plane_base_url", env_key: CONTROL_PLANE_BASE_URL_ENV, @@ -122,6 +131,7 @@ pub(super) struct RuntimeConfig { pub(super) otel: ResolvedOtelConfig, pub(super) bash_policies: ResolvedOptionalValue, pub(super) database_retry: ResolvedOptionalValue, + pub(super) access_policy: ResolvedAccessPolicy, pub(super) validation_errors: Vec, pub(super) validation_warnings: Vec, } @@ -283,6 +293,7 @@ where Ok(ResolvedAuthRuntimeConfig { workos_client_id: runtime.workos_client_id, control_plane_base_url: runtime.control_plane_base_url, + access_policy: runtime.access_policy, }) } @@ -319,6 +330,7 @@ where log_file_retention_limit: runtime.log_file_retention_limit.value, loaded_config_paths: runtime.loaded_config_paths, validation_errors: runtime.validation_errors, + access_policy: runtime.access_policy, }) } @@ -350,6 +362,7 @@ where Ok(ResolvedHookRuntimeConfig { attribution_hooks_enabled: runtime.attribution_hooks_enabled.value, agent_trace_auto_sync: runtime.agent_trace_auto_sync.value, + access_policy: runtime.access_policy, }) } @@ -410,6 +423,8 @@ where integrations: None, }; let mut validation_errors = Vec::new(); + let mut user_policy_layer = AccessPolicyLayer::default(); + let mut repository_policy_layer = AccessPolicyLayer::default(); for loaded_path in &loaded_config_paths { let raw = read_file(&loaded_path.path)?; let layer = match schema::parse_file_config(&raw, &loaded_path.path, loaded_path.source) { @@ -420,6 +435,12 @@ where } Err(error) => return Err(error), }; + let policy_layer = match PolicyLayer::from_config_path_source(loaded_path.source) { + PolicyLayer::User => &mut user_policy_layer, + PolicyLayer::Repository => &mut repository_policy_layer, + }; + policy_layer.auth_mode = layer.auth_mode; + policy_layer.telemetry_enabled = layer.telemetry_enabled; if let Some(log_level) = layer.log_level { file_config.log_level = Some(log_level); } @@ -612,7 +633,18 @@ where file_config.bash_policy_presets.as_ref(), file_config.bash_policy_custom.as_ref(), ); - let validation_warnings = build_validation_warnings(&resolved_bash_policies); + let mut validation_warnings = build_validation_warnings(&resolved_bash_policies); + + let degraded = !validation_errors.is_empty(); + let access_policy = + resolve_access_policy(&user_policy_layer, &repository_policy_layer, degraded); + validation_warnings.extend(build_access_policy_warnings( + &user_policy_layer, + &repository_policy_layer, + &access_policy, + resolved_agent_trace_auto_sync.value, + degraded, + )); let resolved_database_retry = resolve_database_retry_config(file_config.database_retry.as_ref()); @@ -633,11 +665,137 @@ where otel: resolve_otel_config(file_config.otel), bash_policies: resolved_bash_policies, database_retry: resolved_database_retry, + access_policy, validation_errors, validation_warnings, }) } +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub(super) struct AccessPolicyLayer { + pub(super) auth_mode: Option>, + pub(super) telemetry_enabled: Option>, +} + +impl AccessPolicyLayer { + fn telemetry(&self) -> Option { + self.telemetry_enabled.as_ref().map(|value| value.value) + } + + fn auth_mode(&self) -> Option { + self.auth_mode.as_ref().map(|value| value.value) + } +} + +const fn auth_mode_restriction_rank(mode: AuthMode) -> u8 { + match mode { + AuthMode::Optional => 0, + AuthMode::Mandatory => 1, + AuthMode::Disabled => 2, + } +} + +fn resolve_effective_auth_mode( + user: &AccessPolicyLayer, + repository: &AccessPolicyLayer, +) -> ResolvedValue { + let mut resolved = ResolvedValue { + value: AuthMode::Optional, + source: ValueSource::Default, + }; + let mut deciding_rank = None; + for value in [user.auth_mode.as_ref(), repository.auth_mode.as_ref()] + .into_iter() + .flatten() + { + let rank = auth_mode_restriction_rank(value.value); + if deciding_rank.is_none_or(|deciding| rank >= deciding) { + deciding_rank = Some(rank); + resolved = ResolvedValue { + value: value.value, + source: ValueSource::ConfigFile(value.source), + }; + } + } + resolved +} + +pub(super) fn resolve_access_policy( + user: &AccessPolicyLayer, + repository: &AccessPolicyLayer, + degraded: bool, +) -> ResolvedAccessPolicy { + let auth_mode = resolve_effective_auth_mode(user, repository); + let auth_disabled = auth_mode.value == AuthMode::Disabled; + + let telemetry_enabled = match 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 = if degraded { + TelemetryPolicyState::Disabled(TelemetryDisabledReason::InvalidConfig) + } else if auth_disabled { + TelemetryPolicyState::Disabled(TelemetryDisabledReason::AuthDisabled) + } else if user.telemetry() == Some(false) { + TelemetryPolicyState::Disabled(TelemetryDisabledReason::UserOptOut) + } else if repository.telemetry() == Some(false) { + TelemetryPolicyState::Disabled(TelemetryDisabledReason::RepositoryOptOut) + } else if user.telemetry() == Some(true) { + TelemetryPolicyState::Enabled + } else if repository.telemetry() == Some(true) { + TelemetryPolicyState::Disabled(TelemetryDisabledReason::NoUserConsent) + } else { + TelemetryPolicyState::Disabled(TelemetryDisabledReason::NotEnabled) + }; + + ResolvedAccessPolicy { + auth_mode, + telemetry_enabled, + telemetry, + background_cloud_allowed: !auth_disabled && !degraded, + } +} + +fn build_access_policy_warnings( + user: &AccessPolicyLayer, + repository: &AccessPolicyLayer, + policy: &ResolvedAccessPolicy, + agent_trace_auto_sync: bool, + degraded: bool, +) -> Vec { + let auth_disabled = policy.auth_mode.value == AuthMode::Disabled; + let mut warnings = Vec::new(); + if repository.telemetry() == Some(true) && user.telemetry() != Some(true) { + warnings.push(WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT.to_string()); + } + if auth_disabled && (user.telemetry() == Some(true) || repository.telemetry() == Some(true)) { + warnings.push(WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED.to_string()); + } + if auth_disabled && agent_trace_auto_sync { + warnings.push(WARNING_AUTO_SYNC_WITH_AUTH_DISABLED.to_string()); + } + if repository.auth_mode() == Some(AuthMode::Mandatory) + && user.auth_mode() == Some(AuthMode::Disabled) + { + warnings.push(WARNING_REPOSITORY_MANDATORY_OVERRIDDEN_BY_USER_DISABLED.to_string()); + } + if degraded { + warnings.push(WARNING_INVALID_LAYER_DISABLES_CLOUD.to_string()); + } + warnings +} + fn merge_otel_layer(target: &mut schema::OtelFileConfig, layer: schema::OtelFileConfig) { if layer.endpoint.is_some() { target.endpoint = layer.endpoint; @@ -870,6 +1028,7 @@ mod tests { Ok(ResolvedHookRuntimeConfig { attribution_hooks_enabled: runtime.attribution_hooks_enabled.value, agent_trace_auto_sync: runtime.agent_trace_auto_sync.value, + access_policy: runtime.access_policy, }) } @@ -1200,3 +1359,464 @@ mod tests { ); } } + +#[cfg(test)] +mod access_policy_tests { + use std::path::{Path, PathBuf}; + + use super::*; + + const GLOBAL_PATH: &str = "/tmp/policy-global/sce/config.json"; + const LOCAL_PATH: &str = "/tmp/policy-repo/.sce/config.json"; + const EXPLICIT_PATH: &str = "/tmp/policy-explicit.json"; + + #[derive(Clone, Copy, Debug)] + enum Decider { + Default, + User, + Repository, + } + + fn layer( + source: ConfigPathSource, + auth_mode: Option, + telemetry: Option, + ) -> AccessPolicyLayer { + AccessPolicyLayer { + auth_mode: auth_mode.map(|value| schema::FileConfigValue { value, source }), + telemetry_enabled: telemetry.map(|value| schema::FileConfigValue { value, source }), + } + } + + fn user(auth_mode: Option, telemetry: Option) -> AccessPolicyLayer { + layer( + ConfigPathSource::DefaultDiscoveredGlobal, + auth_mode, + telemetry, + ) + } + + fn repository(auth_mode: Option, telemetry: Option) -> AccessPolicyLayer { + layer( + ConfigPathSource::DefaultDiscoveredLocal, + auth_mode, + telemetry, + ) + } + + fn decider_source(decider: Decider) -> ValueSource { + match decider { + Decider::Default => ValueSource::Default, + Decider::User => ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal), + Decider::Repository => { + ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal) + } + } + } + + #[test] + fn access_policy_auth_mode_most_restrictive_layer_wins() { + use AuthMode::{Disabled, Mandatory, Optional}; + use Decider::{Default, Repository, User}; + + let cases = [ + (None, None, Optional, Default), + (None, Some(Disabled), Disabled, Repository), + (None, Some(Optional), Optional, Repository), + (None, Some(Mandatory), Mandatory, Repository), + (Some(Disabled), None, Disabled, User), + (Some(Disabled), Some(Disabled), Disabled, Repository), + (Some(Disabled), Some(Optional), Disabled, User), + (Some(Disabled), Some(Mandatory), Disabled, User), + (Some(Optional), None, Optional, User), + (Some(Optional), Some(Disabled), Disabled, Repository), + (Some(Optional), Some(Optional), Optional, Repository), + (Some(Optional), Some(Mandatory), Mandatory, Repository), + (Some(Mandatory), None, Mandatory, User), + (Some(Mandatory), Some(Disabled), Disabled, Repository), + (Some(Mandatory), Some(Optional), Mandatory, User), + (Some(Mandatory), Some(Mandatory), Mandatory, Repository), + ]; + + for (user_mode, repository_mode, expected_mode, decider) in cases { + for degraded in [false, true] { + let policy = resolve_access_policy( + &user(user_mode, None), + &repository(repository_mode, None), + degraded, + ); + let case = format!( + "user={user_mode:?} repository={repository_mode:?} degraded={degraded}" + ); + + assert_eq!(policy.auth_mode.value, expected_mode, "{case}"); + assert_eq!(policy.auth_mode.source, decider_source(decider), "{case}"); + assert_eq!(policy.auth_allowed(), expected_mode != Disabled, "{case}"); + assert_eq!( + policy.background_cloud_allowed, + expected_mode != Disabled && !degraded, + "{case}" + ); + assert_eq!( + policy.auto_sync_allowed(true), + policy.background_cloud_allowed, + "{case}" + ); + assert!(!policy.auto_sync_allowed(false), "{case}"); + } + } + } + + #[test] + fn access_policy_telemetry_requires_user_consent_and_honors_opt_outs() { + use TelemetryDisabledReason::{ + AuthDisabled, InvalidConfig, NoUserConsent, NotEnabled, RepositoryOptOut, UserOptOut, + }; + use TelemetryPolicyState::{Disabled, Enabled}; + + let base_cases = [ + (None, None, Disabled(NotEnabled), false, Decider::Default), + ( + None, + Some(true), + Disabled(NoUserConsent), + true, + Decider::Repository, + ), + ( + None, + Some(false), + Disabled(RepositoryOptOut), + false, + Decider::Repository, + ), + (Some(true), None, Enabled, true, Decider::User), + (Some(true), Some(true), Enabled, true, Decider::Repository), + ( + Some(true), + Some(false), + Disabled(RepositoryOptOut), + false, + Decider::Repository, + ), + ( + Some(false), + None, + Disabled(UserOptOut), + false, + Decider::User, + ), + ( + Some(false), + Some(true), + Disabled(UserOptOut), + true, + Decider::Repository, + ), + ( + Some(false), + Some(false), + Disabled(UserOptOut), + false, + Decider::Repository, + ), + ]; + + for (user_telemetry, repository_telemetry, base_state, configured, decider) in base_cases { + for degraded in [false, true] { + for auth_disabled in [false, true] { + let user_mode = auth_disabled.then_some(AuthMode::Disabled); + let policy = resolve_access_policy( + &user(user_mode, user_telemetry), + &repository(None, repository_telemetry), + degraded, + ); + let expected = if degraded { + Disabled(InvalidConfig) + } else if auth_disabled { + Disabled(AuthDisabled) + } else { + base_state + }; + let case = format!( + "user={user_telemetry:?} repository={repository_telemetry:?} degraded={degraded} auth_disabled={auth_disabled}" + ); + + assert_eq!(policy.telemetry, expected, "{case}"); + assert_eq!(policy.telemetry_enabled(), expected == Enabled, "{case}"); + assert_eq!(policy.telemetry_enabled.value, configured, "{case}"); + assert_eq!( + policy.telemetry_enabled.source, + decider_source(decider), + "{case}" + ); + } + } + } + } + + #[test] + fn access_policy_repository_auth_disabled_forces_telemetry_off() { + let policy = resolve_access_policy( + &user(None, Some(true)), + &repository(Some(AuthMode::Disabled), None), + false, + ); + + assert_eq!( + policy.telemetry, + TelemetryPolicyState::Disabled(TelemetryDisabledReason::AuthDisabled) + ); + assert!(!policy.background_cloud_allowed); + } + + #[test] + fn access_policy_warnings_are_deterministic_and_ordered() { + let user_layer = user(Some(AuthMode::Disabled), None); + let repository_layer = repository(Some(AuthMode::Mandatory), Some(true)); + let policy = resolve_access_policy(&user_layer, &repository_layer, true); + + assert_eq!( + build_access_policy_warnings(&user_layer, &repository_layer, &policy, true, true), + vec![ + WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT.to_string(), + WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED.to_string(), + WARNING_AUTO_SYNC_WITH_AUTH_DISABLED.to_string(), + WARNING_REPOSITORY_MANDATORY_OVERRIDDEN_BY_USER_DISABLED.to_string(), + WARNING_INVALID_LAYER_DISABLES_CLOUD.to_string(), + ] + ); + + let consenting_user = user(Some(AuthMode::Optional), Some(true)); + let consenting_policy = resolve_access_policy(&consenting_user, &repository_layer, false); + assert!(build_access_policy_warnings( + &consenting_user, + &repository_layer, + &consenting_policy, + true, + false, + ) + .is_empty()); + } + + fn discovered_paths_exist(path: &Path) -> bool { + path == Path::new(GLOBAL_PATH) || path == Path::new(LOCAL_PATH) + } + + fn explicit_path_exists(path: &Path) -> bool { + path == Path::new(EXPLICIT_PATH) + } + + fn resolve_discovered(global: &'static str, local: &'static str) -> RuntimeConfig { + resolve_runtime_config_with( + &ConfigRequest { + report_format: ReportFormat::Text, + config_path: None, + log_level: None, + }, + Path::new("/tmp/policy-repo"), + |_| None, + move |path| { + if path == Path::new(GLOBAL_PATH) { + Ok(global.to_string()) + } else { + Ok(local.to_string()) + } + }, + discovered_paths_exist, + || Ok(PathBuf::from(GLOBAL_PATH)), + ) + .unwrap() + } + + #[test] + fn access_policy_explicit_config_file_acts_as_user_layer() { + let config = r#"{"auth":{"mode":"mandatory"},"telemetry":{"enabled":true}}"#; + let flag = resolve_runtime_config_with( + &ConfigRequest { + report_format: ReportFormat::Text, + config_path: Some(PathBuf::from(EXPLICIT_PATH)), + log_level: None, + }, + Path::new("/tmp/policy-repo"), + |_| None, + |_| Ok(config.to_string()), + explicit_path_exists, + || Ok(PathBuf::from(GLOBAL_PATH)), + ) + .unwrap(); + let env = resolve_runtime_config_with( + &ConfigRequest { + report_format: ReportFormat::Text, + config_path: None, + log_level: None, + }, + Path::new("/tmp/policy-repo"), + |key| (key == "SCE_CONFIG_FILE").then(|| EXPLICIT_PATH.to_string()), + |_| Ok(config.to_string()), + explicit_path_exists, + || Ok(PathBuf::from(GLOBAL_PATH)), + ) + .unwrap(); + + for (runtime, source) in [(flag, ConfigPathSource::Flag), (env, ConfigPathSource::Env)] { + let policy = runtime.access_policy; + assert_eq!(policy.telemetry, TelemetryPolicyState::Enabled); + assert_eq!(policy.auth_mode.value, AuthMode::Mandatory); + assert_eq!(policy.auth_mode.source, ValueSource::ConfigFile(source)); + assert_eq!( + policy.telemetry_enabled.source, + ValueSource::ConfigFile(source) + ); + assert!(policy.background_cloud_allowed); + assert!(runtime.validation_warnings.is_empty()); + } + } + + #[test] + fn access_policy_invalid_global_layer_is_skipped_and_degrades_policy() { + let runtime = resolve_discovered( + r#"{"auth":{"mode":"sometimes"}}"#, + r#"{"telemetry":{"enabled":true}}"#, + ); + + assert_eq!(runtime.validation_errors.len(), 1); + assert_eq!( + runtime.access_policy.telemetry, + TelemetryPolicyState::Disabled(TelemetryDisabledReason::InvalidConfig) + ); + assert_eq!(runtime.access_policy.auth_mode.value, AuthMode::Optional); + assert!(!runtime.access_policy.background_cloud_allowed); + assert_eq!( + runtime.validation_warnings, + vec![ + WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT.to_string(), + WARNING_INVALID_LAYER_DISABLES_CLOUD.to_string(), + ] + ); + } + + #[test] + fn access_policy_invalid_local_layer_is_skipped_and_degrades_policy() { + let runtime = resolve_discovered( + r#"{"auth":{"mode":"mandatory"},"telemetry":{"enabled":true}}"#, + r#"{"telemetry":{"enabled":"yes"}}"#, + ); + + assert_eq!(runtime.validation_errors.len(), 1); + assert_eq!( + runtime.access_policy.telemetry, + TelemetryPolicyState::Disabled(TelemetryDisabledReason::InvalidConfig) + ); + assert_eq!(runtime.access_policy.auth_mode.value, AuthMode::Mandatory); + assert_eq!( + runtime.access_policy.auth_mode.source, + ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal) + ); + assert!(!runtime.access_policy.background_cloud_allowed); + assert_eq!( + runtime.validation_warnings, + vec![WARNING_INVALID_LAYER_DISABLES_CLOUD.to_string()] + ); + } + + #[test] + fn access_policy_merge_loop_routes_layers_and_appends_ordered_warnings() { + let runtime = resolve_discovered( + r#"{"auth":{"mode":"disabled"}}"#, + r#"{"auth":{"mode":"mandatory"},"telemetry":{"enabled":true},"agent_trace":{"auto_sync":true}}"#, + ); + + assert!(runtime.validation_errors.is_empty()); + assert_eq!(runtime.access_policy.auth_mode.value, AuthMode::Disabled); + assert_eq!( + runtime.access_policy.auth_mode.source, + ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal) + ); + assert_eq!( + runtime.access_policy.telemetry, + TelemetryPolicyState::Disabled(TelemetryDisabledReason::AuthDisabled) + ); + assert_eq!( + runtime.validation_warnings, + vec![ + WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT.to_string(), + WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED.to_string(), + WARNING_AUTO_SYNC_WITH_AUTH_DISABLED.to_string(), + WARNING_REPOSITORY_MANDATORY_OVERRIDDEN_BY_USER_DISABLED.to_string(), + ] + ); + } + + #[test] + fn access_policy_defaults_when_no_config_files_exist() { + let runtime = resolve_runtime_config_with( + &ConfigRequest { + report_format: ReportFormat::Text, + config_path: None, + log_level: None, + }, + Path::new("/tmp/policy-repo"), + |_| None, + |_| Ok("{}".to_string()), + |_| false, + || Ok(PathBuf::from(GLOBAL_PATH)), + ) + .unwrap(); + + assert_eq!( + runtime.access_policy, + ResolvedAccessPolicy { + auth_mode: ResolvedValue { + value: AuthMode::Optional, + source: ValueSource::Default, + }, + telemetry_enabled: ResolvedValue { + value: false, + source: ValueSource::Default, + }, + telemetry: TelemetryPolicyState::Disabled(TelemetryDisabledReason::NotEnabled), + background_cloud_allowed: true, + } + ); + assert!(runtime.validation_warnings.is_empty()); + } + + #[test] + fn access_policy_is_exposed_on_projected_runtime_configs() { + let expected = resolve_discovered( + r#"{"telemetry":{"enabled":true}}"#, + r#"{"auth":{"mode":"mandatory"}}"#, + ) + .access_policy; + let read = |path: &Path| { + if path == Path::new(GLOBAL_PATH) { + Ok(r#"{"telemetry":{"enabled":true}}"#.to_string()) + } else { + Ok(r#"{"auth":{"mode":"mandatory"}}"#.to_string()) + } + }; + let cwd = Path::new("/tmp/policy-repo"); + let global = || Ok(PathBuf::from(GLOBAL_PATH)); + + let auth = + resolve_auth_runtime_config_with(cwd, |_| None, read, discovered_paths_exist, global) + .unwrap(); + let hook = + resolve_hook_runtime_config_with(cwd, |_| None, read, discovered_paths_exist, global) + .unwrap(); + let observability = resolve_observability_runtime_config_with( + cwd, + |_| None, + read, + discovered_paths_exist, + global, + ) + .unwrap(); + + assert_eq!(expected.telemetry, TelemetryPolicyState::Enabled); + assert_eq!(auth.access_policy, expected); + assert_eq!(hook.access_policy, expected); + assert_eq!(observability.access_policy, expected); + } +} diff --git a/cli/src/services/config/schema.rs b/cli/src/services/config/schema.rs index d756b57e1..80836673e 100644 --- a/cli/src/services/config/schema.rs +++ b/cli/src/services/config/schema.rs @@ -222,9 +222,7 @@ pub(crate) struct FileConfig { pub(crate) agent_trace_repository_id: Option>, pub(crate) agent_trace_repository_remote: Option>, pub(crate) agent_trace_auto_sync: Option>, - #[allow(dead_code)] pub(crate) auth_mode: Option>, - #[allow(dead_code)] pub(crate) telemetry_enabled: Option>, pub(crate) otel: OtelFileConfig, pub(crate) bash_policy_presets: Option>>, diff --git a/cli/src/services/config/types.rs b/cli/src/services/config/types.rs index dd5b76e28..faf81b198 100644 --- a/cli/src/services/config/types.rs +++ b/cli/src/services/config/types.rs @@ -115,6 +115,62 @@ impl AuthMode { } } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum PolicyLayer { + User, + Repository, +} + +impl PolicyLayer { + pub(crate) const fn from_config_path_source(source: ConfigPathSource) -> Self { + match source { + ConfigPathSource::Flag + | ConfigPathSource::Env + | ConfigPathSource::DefaultDiscoveredGlobal => Self::User, + ConfigPathSource::DefaultDiscoveredLocal => Self::Repository, + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum TelemetryPolicyState { + Enabled, + Disabled(TelemetryDisabledReason), +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum TelemetryDisabledReason { + NotEnabled, + UserOptOut, + NoUserConsent, + RepositoryOptOut, + AuthDisabled, + InvalidConfig, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct ResolvedAccessPolicy { + pub(crate) auth_mode: ResolvedValue, + pub(crate) telemetry_enabled: ResolvedValue, + pub(crate) telemetry: TelemetryPolicyState, + pub(crate) background_cloud_allowed: bool, +} + +#[allow(dead_code)] +impl ResolvedAccessPolicy { + pub(crate) fn telemetry_enabled(&self) -> bool { + self.telemetry == TelemetryPolicyState::Enabled + } + + pub(crate) fn auth_allowed(&self) -> bool { + self.auth_mode.value != AuthMode::Disabled + } + + pub(crate) fn auto_sync_allowed(&self, configured: bool) -> bool { + configured && self.background_cloud_allowed + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum ValueSource { Flag, @@ -202,6 +258,8 @@ pub(crate) struct LoadedConfigPath { pub(crate) struct ResolvedAuthRuntimeConfig { pub(crate) workos_client_id: ResolvedOptionalValue, pub(crate) control_plane_base_url: ResolvedOptionalValue, + #[allow(dead_code)] + pub(crate) access_policy: ResolvedAccessPolicy, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -213,12 +271,16 @@ pub(crate) struct ResolvedObservabilityRuntimeConfig { pub(crate) log_file_retention_limit: usize, pub(crate) loaded_config_paths: Vec, pub(crate) validation_errors: Vec, + #[allow(dead_code)] + pub(crate) access_policy: ResolvedAccessPolicy, } #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) struct ResolvedHookRuntimeConfig { pub(crate) attribution_hooks_enabled: bool, pub(crate) agent_trace_auto_sync: bool, + #[allow(dead_code)] + pub(crate) access_policy: ResolvedAccessPolicy, } #[derive(Clone, Debug, Eq, PartialEq)] diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md new file mode 100644 index 000000000..31add979e --- /dev/null +++ b/context/cli/access-policy.md @@ -0,0 +1,73 @@ +# Effective Access Policy + +## 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). + +Status: the resolver computes and exposes the policy. `sce config show`/`validate` rendering and consumer enforcement (managed telemetry, the headers helper, auth commands, sync, auto-sync, setup) are not wired yet. Until they are, the policy has no runtime effect beyond the warnings it adds to config resolution. + +## Terms + +- **Auth mode** (`AuthMode`): `disabled | optional | mandatory`. Omitted means `optional`. +- **Policy layer** (`PolicyLayer`): how a config file is classified for access policy. + - **User layer:** a `DefaultDiscoveredGlobal` file, or the single explicit file (`Flag` / `Env`). + - **Repository layer:** a `DefaultDiscoveredLocal` file (`/.sce/config.json`). + - Neither key has an environment-variable or CLI-flag layer. +- **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`: the effective state, `TelemetryPolicyState` (`Enabled`, or `Disabled(reason)`). + - `background_cloud_allowed`. +- **Degraded:** at least one default-discovered file was skipped as invalid. + +## Resolution + +`resolve_runtime_config_with` records each parsed layer's `auth_mode` / `telemetry_enabled` into a user or a repository `AccessPolicyLayer` during the merge loop. It then calls the pure `resolve_access_policy(user, repository, degraded)` (`cli/src/services/config/resolver.rs`). + +```mermaid +flowchart TD + D{degraded?} -- yes --> I[Disabled InvalidConfig] + D -- no --> A{effective auth disabled?} + A -- yes --> AD[Disabled AuthDisabled] + A -- no --> U0{user false?} + U0 -- yes --> UO[Disabled UserOptOut] + U0 -- no --> R0{repository false?} + R0 -- yes --> RO[Disabled RepositoryOptOut] + R0 -- no --> U1{user true?} + U1 -- yes --> E[Enabled] + U1 -- no --> R1{repository true?} + R1 -- yes --> NC[Disabled NoUserConsent] + R1 -- no --> NE[Disabled NotEnabled] +``` + +- **Auth mode:** the most restrictive layer wins (`disabled > mandatory > optional`). + - The source is the deciding layer. When both layers carry the same mode, the repository layer is the source. + - When neither layer sets it, the result is `optional` with `source: default`. +- **`telemetry_enabled` value:** the repository value if set, otherwise the user value, otherwise `false` with `source: default`. This is the configured value, not the effective state. +- **`background_cloud_allowed`:** `!auth_disabled && !degraded`. +- **Helpers:** + - `telemetry_enabled()` is true only for `Enabled`. + - `auth_allowed()` is true when the mode is not `disabled`. + - `auto_sync_allowed(configured)` is `configured && background_cloud_allowed`. +- **Explicit config files:** an invalid explicit config file stays fatal, so it never produces a degraded policy. + +## 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-layer `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`: + `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`: + `agent_trace.auto_sync is true but auth.mode resolves to disabled; post-commit auto-sync is skipped.` +4. Repository `mandatory` while the user layer is `disabled`: + `auth.mode is mandatory in the repository config but disabled in the user config; auth.mode resolves to disabled.` +5. 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`. + +## Exposure + +`ResolvedAuthRuntimeConfig`, `ResolvedHookRuntimeConfig`, and `ResolvedObservabilityRuntimeConfig` each carry `access_policy`, cloned from the same resolution that produced the rest of the projection. No consumer resolves config a second time to get the policy. diff --git a/context/cli/config-precedence-contract.md b/context/cli/config-precedence-contract.md index f4d68ec83..ad9179681 100644 --- a/context/cli/config-precedence-contract.md +++ b/context/cli/config-precedence-contract.md @@ -99,7 +99,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. -- 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 does not yet merge or consume either value, so they have no runtime effect and do not appear in `sce config show`. +- 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 or explicit file; repository = repo-local) and resolves them into the effective access policy with consent-gated precedence and fixed contradiction warnings; see [effective access policy](access-policy.md). Neither value is rendered by `sce config show` or enforced by consumers yet. - `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. - `integrations` must be an object when present and currently allows `target` and `optional_workflows`; either key alone yields a parsed `IntegrationsConfig` with the other defaulting to empty. diff --git a/context/context-map.md b/context/context-map.md index 48bd7ff95..88a53fe90 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -25,6 +25,7 @@ Feature/domain context: - `context/cli/async-persistence-guarantees.md` (verified guarantees and named limits of the directly awaited Turso persistence migration — exclusive `&mut` transactions, deferred rollback, credential-rotation and terminal-sync behavior, lease/descriptor protection — plus PR1–PR4 staging and the PR3 cleanup ledger) - `context/cli/agent-trace-sync-command.md` (composed local-to-control-plane `sce sync` architecture: the `hooks/plugins → repository Agent Trace DB → AgentTraceExportReader → sce sync → HTTPS + WorkOS Bearer → control plane` data flow, the `sce auth login` / `cd ` / `sce sync` user flow, the no-local-cursor/no-`agent-trace-sync.db`/no-Turso-Sync/no-`BridgeLock`/no-local-DWH invariants, the four-local-capture-streams versus three-remote-streams boundary with its `diff_traces` release gate, the optional `commitPatchId` field on the existing `agent_traces` stream with its Control Plane release dependency and no-backfill limit, and `401`/`409`/ambiguous-batch-failure recovery semantics) - `context/cli/config-precedence-contract.md` (implemented `sce config` show/validate command contract, deterministic `flags > env > config file > defaults` resolution order, focused `config/resolver.rs` ownership for config discovery/merge/runtime precedence plus default-discovered invalid-file degradation, focused `config/render.rs` ownership for `show`/`validate` text+JSON output construction, canonical `$schema` acceptance for startup-loaded `sce/config.json` files, shared auth-key env/config/optional baked-default support starting with `workos_client_id`, shared runtime resolution for flat logging observability keys including config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` with `/sce/logs` defaulting plus config-file/default-only positive `log_file_retention_limit`, config-file-only `agent_trace.repository_id`/`agent_trace.repository_remote` repository-identity keys with default remote `origin`, `agent_trace.auto_sync` resolution with omitted-value fallback `false`, explicit-false opt-out, and setup-written explicit `true` bootstrap behavior for the post-commit trigger boundary, the catalog-derived `integrations.optional_workflows` optional-workflow selection key, schema-validated per-layer `auth.mode` / `telemetry.enabled` sections, JSON-pointer-prefixed schema-validation errors, canonical Pkl-generated `sce/config.json` schema ownership plus CLI embedding/reuse contract including `policies.attribution_hooks.enabled` default-true/explicit-false opt-out metadata, config-file selection order, `show` provenance output, and trimmed `validate` output contract) +- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, and exposure on the auth/hook/observability runtime projections; decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) - `context/cli/capability-traits.md` (current broad CLI capability seam in `cli/src/services/capabilities.rs`, including `FsOps`/`StdFsOps` (method-less marker), `GitOps`/`ProcessGitOps` (command execution and availability), compile-time-typed borrowed AppContext wiring with scoped borrowing across directly awaited commands with associated-type narrow capability accessors plus `ContextWithRepoRoot` repo-root-scoped context derivation, generic command execution bounds, and test-only unimplemented stubs; current service internals do not consume fs/git traits until later lifecycle migration tasks) - `context/cli/service-lifecycle.md` (current async lifecycle seam in `cli/src/services/lifecycle.rs`, including default no-op `ServiceLifecycle` diagnose/fix/setup methods against narrow `HasRepoRoot`, lifecycle-owned health/fix/setup result types with generic setup messages, doctor/setup adapter boundaries, the static `LifecycleProvider` enum catalog/dispatcher, hook/config/local_db/auth_db/agent_trace_db lifecycle providers including setup-time repository-scoped Agent Trace DB initialization plus checkout identity diagnostics, implemented doctor aggregation over diagnose/fix providers, and implemented setup aggregation over `setup` providers in order config → local_db → auth_db → agent_trace_db → hooks when requested) - `context/cli/mutation-trace-protocol.md` (pure, dependency-free `cli/src/services/mutation_trace/` refinement of the verified `spec/mutation_cursor.qnt` mutation-cursor protocol: the full pure action set — `prepare`/`commit` transition logic, attribution/mutation-event materialization, snapshot-failure/database-failure taint actions, scope abandonment, and recovery with an explicit observed-tree input — plus cross-action sequence/invariant tests and a module-level Quint refinement matrix are all complete (`types.rs`, `protocol.rs`, `mod.rs`, `tests.rs`, registered with `#[allow(dead_code)]`); opaque-newtype identity refinement decisions vs. the Quint model's bounded enums, and the `coordinator.rs` target end-state seam this layout leaves room for but does not create — `store.rs`, `runtime/git_snapshot.rs`, and `runtime/coordinator.rs` (including its public `coordinate()` entrypoint) now exist, built out by the `mutation-cursor-store-persistence` and `mutation-cursor-runtime-coordinator` plans respectively; `protocol.rs` is invoked only through the runtime, and the runtime is now driven by the generic `sce hooks mutation-scope` CLI ingress and a first Claude Code adapter driver, registered by `sce setup` and reachable by a real Claude Code session, now proven against real Git repositories and a real Agent Trace DB by the `claude-mutation-scope-integration` plan's T08 regressions) 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 new file mode 100644 index 000000000..e07348263 --- /dev/null +++ b/context/decisions/2026-10-20-consent-gated-access-policy-precedence.md @@ -0,0 +1,75 @@ +# Decision: Consent-gated precedence for the effective access policy + +Date: 2026-10-20 +Status: Accepted +Plan: `context/plans/auth-telemetry-policy-config.md` +Task: `T02` + +## 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. + +## Decision + +SCE resolves one effective access policy from two config layers, using consent-gated precedence. + +**Layers:** +- The user layer is the default-discovered global config, or the single explicit `--config` / `SCE_CONFIG_FILE` file. +- The repository layer is the default-discovered `/.sce/config.json`. +- Neither key has an environment-variable or flag layer. + +**`auth.mode`:** the most restrictive layer wins. The order is `disabled > mandatory > optional`, and the default is `optional`. When both layers agree, the repository layer is recorded as the source. + +**`telemetry.enabled`:** the first matching rule applies: +1. Any skipped invalid discovered layer → `Disabled(InvalidConfig)`. +2. Effective auth is `disabled` → `Disabled(AuthDisabled)`. +3. User layer is `false` → `UserOptOut`. +4. Repository layer is `false` → `RepositoryOptOut`. +5. User layer is `true` → `Enabled`. +6. Repository layer is `true` with no user `true` → `NoUserConsent`. +7. Otherwise → `NotEnabled`. + +**Background cloud operations** are allowed only when auth is not `disabled` and no discovered layer was skipped as invalid. + +Contradictions between layers produce deterministic `validation_warnings`, never errors. The pure `resolve_access_policy` in `cli/src/services/config/resolver.rs` computes the policy once, inside the existing resolver. `ResolvedAuthRuntimeConfig`, `ResolvedHookRuntimeConfig`, and `ResolvedObservabilityRuntimeConfig` expose it. + +## Rationale + +Telemetry export is a privacy-sensitive action that belongs to the user, so only the user layer can grant consent. Either layer can withdraw consent or restrict access. A repository can therefore opt itself out, but it can never opt a user in or override a user's prohibition. If a config file is invalid and skipped, falling back to defaults must not silently re-enable anything that file might have prohibited, so the policy degrades to off. Computing the policy once, in the existing resolver, keeps one authoritative answer for every consumer. + +## Alternatives considered + +- **Plain last-layer-wins merge for both keys:** rejected. A repository could enable telemetry or override a user's `disabled` mode. +- **Inferring consent from an existing `telemetry-ready.json` or `auth.db`:** rejected. Hidden state would decide consent. +- **Treating cross-layer contradictions as validation errors:** rejected. Each file is valid on its own, and errors would drop unrelated settings. +- **A separate policy resolver or service:** rejected. It would duplicate config discovery and risk diverging answers. + +## Compatibility and risks + +- Telemetry becomes opt-in. Existing logged-in installations without an explicit user-layer `telemetry.enabled: true` lose managed SCE export once consumers enforce the policy. +- Repository discovery uses the cwd. A process launched from a subdirectory sees only the user layer, which fails open toward the user's own consent. +- Older SCE binaries reject the new keys and skip the whole discovered file as invalid. + +## Guardrails + +- Consent comes only from the user layer. A repository value can only restrict. +- There is no env-var or CLI-flag override for `auth.mode` or `telemetry.enabled`. +- There is no global mutable policy state and no second resolver. +- Warnings are fixed strings, emitted in a fixed order. + +## Consequences + +- Consumers (rendering, managed telemetry, the headers helper, auth commands, sync, auto-sync, and setup) read one `ResolvedAccessPolicy` instead of deciding from credential state. +- A degraded config disables telemetry and background cloud operations. Explicit commands still use the auth mode resolved from the remaining valid layers. + +## Follow-up + +- Plan tasks T03–T08 render and enforce the policy at each consumer. + +## References + +- Plan: [`auth-telemetry-policy-config`](../plans/auth-telemetry-policy-config.md) +- Task: `T02` +- Current-state context: [`config-precedence-contract`](../cli/config-precedence-contract.md) +- Current-state context: [`access-policy`](../cli/access-policy.md) +- Evidence: [`resolver.rs`](../../cli/src/services/config/resolver.rs) diff --git a/context/glossary.md b/context/glossary.md index f42dfe56b..23637eca4 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). +- CLI execution terminology: [command dispatch, runtime dependencies and telemetry](cli/execution-glossary.md). Auth mode, policy layer (user/repository), and effective access policy: [effective access policy](cli/access-policy.md). - `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/`. diff --git a/context/plans/auth-telemetry-policy-config.md b/context/plans/auth-telemetry-policy-config.md index 4d453b33d..933f2f585 100644 --- a/context/plans/auth-telemetry-policy-config.md +++ b/context/plans/auth-telemetry-policy-config.md @@ -283,13 +283,19 @@ Persist this field in every plan; this is durable plan state, not chat state: - Context impact: localized — config schema and file model only; no runtime behavior change until T02 merges the fields. Durable docs (`context/cli/config-precedence-contract.md`) gain the new keys and layer rules with T02/T03. - Context synchronization: synced -- [ ] T02: `Resolve the effective access policy from user and repository layers` (status:todo) +- [x] T02: `Resolve the effective access policy from user and repository layers` (status:done) - Task ID: T02 - Scope: In — `PolicyLayer`, `TelemetryPolicyState`, `TelemetryDisabledReason`, `ResolvedAccessPolicy` in `config/types.rs`; per-layer capture inside the `resolve_runtime_config_with` merge loop; pure `resolve_access_policy(user, repo, degraded)` in `config/resolver.rs`; `RuntimeConfig.access_policy`; contradiction strings appended to `validation_warnings`; exposing the policy on `ResolvedAuthRuntimeConfig`, `ResolvedHookRuntimeConfig`, and `ResolvedObservabilityRuntimeConfig`. Out — rendering and consumer enforcement. - Dependencies: T01 - Done when: the resolver implements the precedence rules in Design exactly, with source/provenance of the deciding layer; explicit config files act as the user layer; a skipped invalid discovered layer yields `Disabled(InvalidConfig)` and `background_cloud_allowed = false`; contradiction warnings are deterministic and ordered. - Verify: one table-driven test over user {absent, disabled, optional, mandatory} × repository {same} for auth and user {absent, true, false} × repository {absent, true, false} × degraded {false, true} × auth-disabled for telemetry; integration tests through `resolve_runtime_config_with` for explicit-file-as-user-layer, invalid-global-skipped, and invalid-local-skipped; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml access_policy`. - - Context synchronization: pending + - Completed: 2026-10-20 + - Files changed: `cli/src/services/config/types.rs`, `cli/src/services/config/resolver.rs`, `cli/src/services/config/schema.rs`, `context/plans/auth-telemetry-policy-config.md` + - Result: Added `PolicyLayer` (with `from_config_path_source`: `Flag`/`Env`/`DefaultDiscoveredGlobal` → `User`, `DefaultDiscoveredLocal` → `Repository`), `TelemetryPolicyState`, `TelemetryDisabledReason`, and `ResolvedAccessPolicy` (`telemetry_enabled()`, `auth_allowed()`, `auto_sync_allowed(configured)`) in `types.rs`. `resolve_runtime_config_with` captures per-layer `AccessPolicyLayer` values in the merge loop and calls the pure `resolve_access_policy(user, repository, degraded)`. Auth mode: most restrictive wins (`disabled > mandatory > optional`), with ties sourced from the repository layer and `Default` when unset. `telemetry_enabled` is the merged value, repository over user. Telemetry state follows the Design rule chain, and `background_cloud_allowed = !auth_disabled && !degraded`. `RuntimeConfig.access_policy` is exposed on `ResolvedAuthRuntimeConfig`, `ResolvedHookRuntimeConfig`, and `ResolvedObservabilityRuntimeConfig`. Five fixed warning constants (`WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT`, `WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED`, `WARNING_AUTO_SYNC_WITH_AUTH_DISABLED`, `WARNING_REPOSITORY_MANDATORY_OVERRIDDEN_BY_USER_DISABLED`, `WARNING_INVALID_LAYER_DISABLES_CLOUD`) are appended to `validation_warnings` in Design order, after the bash-policy warnings. Removed T01's `#[allow(dead_code)]` from `FileConfig.auth_mode`/`telemetry_enabled`. + - Verify outcome: `access_policy` filter passed (15 passed, 0 failed: 10 new `resolver::access_policy_tests` covering the 4×4 auth table × degraded, the 3×3 telemetry table × degraded × auth-disabled, repository auth-disabled, warning order, explicit flag/env file as user layer, invalid-global-skipped, invalid-local-skipped, merge-loop warning order, defaults, and projection exposure; plus 5 T01 schema tests). `config::` tests passed (60 passed, 0 failed). `cargo clippy --all-targets -- -D warnings` via `run-cli-cargo.sh` passed. + - Deviation: `AuthMode::as_str`, the `ResolvedAccessPolicy` helper methods, and the new `access_policy` fields on the three projected structs carry `#[allow(dead_code)]` until consumers (T03 rendering; T04–T08 enforcement) read them. Those tasks should remove the attributes. + - Context impact: localized — config resolver and types only; no rendering or runtime enforcement change yet. The fixed warning strings and layer classification are durable contract material for `context/cli/config-precedence-contract.md`; T03 renders them. + - Context synchronization: synced - [ ] T03: `Report auth and telemetry policy in config show and validate` (status:todo) - Task ID: T03 From 647ba14aa4ca8c0c8e8720aecf192d6c9c4082c7 Mon Sep 17 00:00:00 2001 From: David Abram Date: Tue, 20 Oct 2026 14:08:49 +0200 Subject: [PATCH 3/9] config: Report auth and telemetry policy in config output Expose resolved auth mode and telemetry consent state in `config show` text and JSON, including provenance, disabled reasons, and the Claude settings compatibility note. Preserve `config validate`'s existing field shape while surfacing policy warnings, and document the reporting contract. Plan: auth-telemetry-policy-config (T03) Co-authored-by: SCE --- cli/src/services/config/render.rs | 337 +++++++++++++++++- cli/src/services/config/resolver.rs | 2 +- cli/src/services/config/types.rs | 30 +- context/cli/access-policy.md | 17 +- context/cli/config-precedence-contract.md | 3 +- context/context-map.md | 2 +- context/plans/auth-telemetry-policy-config.md | 10 +- 7 files changed, 393 insertions(+), 8 deletions(-) diff --git a/cli/src/services/config/render.rs b/cli/src/services/config/render.rs index b2583ac3e..d2b7332fa 100644 --- a/cli/src/services/config/render.rs +++ b/cli/src/services/config/render.rs @@ -7,9 +7,13 @@ use super::resolver::{ AuthConfigKeySpec, RuntimeConfig, CONTROL_PLANE_BASE_URL_KEY, PRECEDENCE_DESCRIPTION, WORKOS_CLIENT_ID_KEY, }; -use super::types::{AgentTraceDbRetryConfig, DatabaseRetryConfig}; +use super::types::{ + AgentTraceDbRetryConfig, DatabaseRetryConfig, ResolvedAccessPolicy, TelemetryDisabledReason, +}; use super::{ConfigPathSource, ReportFormat, ResolvedOptionalValue, ResolvedValue, ValueSource}; +const TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE: &str = "Claude Code telemetry settings written by earlier sce setup runs are not changed by telemetry.enabled."; + #[allow(clippy::too_many_lines)] pub(super) fn format_show_output(runtime: &RuntimeConfig, report_format: ReportFormat) -> String { let warnings = build_show_warnings(runtime); @@ -49,6 +53,7 @@ pub(super) fn format_show_output(runtime: &RuntimeConfig, report_format: ReportF &runtime.agent_trace_auto_sync.value.to_string(), runtime.agent_trace_auto_sync.source, ), + format_access_policy_text(&runtime.access_policy), format_otel_text(runtime), format_bash_policies_text(&runtime.bash_policies), format_database_retry_text(&runtime.database_retry), @@ -95,6 +100,8 @@ pub(super) fn format_show_output(runtime: &RuntimeConfig, report_format: ReportF runtime.agent_trace_auto_sync.source, ), }, + "auth": format_auth_policy_json(&runtime.access_policy), + "telemetry": format_telemetry_policy_json(&runtime.access_policy), "otel": format_otel_json(runtime), "policies": { "bash": format_bash_policies_json(&runtime.bash_policies), @@ -109,6 +116,73 @@ pub(super) fn format_show_output(runtime: &RuntimeConfig, report_format: ReportF } } +fn format_access_policy_text(policy: &ResolvedAccessPolicy) -> String { + let mut lines = vec![ + format_resolved_value_text( + "auth.mode", + policy.auth_mode.value.as_str(), + policy.auth_mode.source, + ), + format_resolved_value_text( + "telemetry.enabled", + &policy.telemetry_enabled.value.to_string(), + policy.telemetry_enabled.source, + ), + ]; + let effective = match policy.telemetry.disabled_reason() { + Some(reason) => format!( + "- {}: {} (reason: {})", + style::label("telemetry.effective"), + style::value(policy.telemetry.as_str()), + style::label(reason.as_str()) + ), + None => format!( + "- {}: {}", + style::label("telemetry.effective"), + style::value(policy.telemetry.as_str()) + ), + }; + lines.push(effective); + if let Some(note) = telemetry_policy_note(policy) { + lines.push(format!( + "- {}: {}", + style::label("telemetry.note"), + style::value(note) + )); + } + lines.join("\n") +} + +fn format_auth_policy_json(policy: &ResolvedAccessPolicy) -> Value { + json!({ + "mode": format_resolved_value_json( + policy.auth_mode.value.as_str(), + policy.auth_mode.source, + ), + }) +} + +fn format_telemetry_policy_json(policy: &ResolvedAccessPolicy) -> Value { + json!({ + "enabled": format_resolved_value_json( + policy.telemetry_enabled.value, + policy.telemetry_enabled.source, + ), + "effective": { + "state": policy.telemetry.as_str(), + "reason": policy.telemetry.disabled_reason().map(TelemetryDisabledReason::as_str), + }, + "note": telemetry_policy_note(policy), + }) +} + +fn telemetry_policy_note(policy: &ResolvedAccessPolicy) -> Option<&'static str> { + policy + .telemetry + .disabled_reason() + .map(|_| TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE) +} + fn otel_fields(runtime: &RuntimeConfig) -> [(&'static str, &ResolvedValue); 5] { let otel = &runtime.otel; [ @@ -588,3 +662,264 @@ 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 std::path::{Path, PathBuf}; + + use serde_json::{json, Value}; + + use super::{ + format_show_output, format_validate_output, TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE, + }; + use crate::services::config::resolver::{ + resolve_runtime_config_with, RuntimeConfig, + WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT, + WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED, + }; + use crate::services::config::{ConfigRequest, ReportFormat}; + + const GLOBAL_PATH: &str = "/tmp/render-policy-global/sce/config.json"; + const LOCAL_PATH: &str = "/tmp/render-policy-repo/.sce/config.json"; + + struct PolicyCase { + name: &'static str, + global: &'static str, + local: &'static str, + text_lines: Vec, + auth_json: Value, + telemetry_json: Value, + warnings: Vec, + } + + fn discovered_paths_exist(path: &Path) -> bool { + path == Path::new(GLOBAL_PATH) || path == Path::new(LOCAL_PATH) + } + + fn resolve(global: &'static str, local: &'static str) -> RuntimeConfig { + resolve_runtime_config_with( + &ConfigRequest { + report_format: ReportFormat::Text, + config_path: None, + log_level: None, + }, + Path::new("/tmp/render-policy-repo"), + |_| None, + move |path| { + if path == Path::new(GLOBAL_PATH) { + Ok(global.to_string()) + } else { + Ok(local.to_string()) + } + }, + discovered_paths_exist, + || Ok(PathBuf::from(GLOBAL_PATH)), + ) + .unwrap() + } + + fn strip_ansi(text: &str) -> String { + let mut stripped = String::with_capacity(text.len()); + let mut chars = text.chars(); + while let Some(ch) = chars.next() { + if ch == '\u{1b}' { + for next in chars.by_ref() { + if next == 'm' { + break; + } + } + } else { + stripped.push(ch); + } + } + stripped + } + + fn policy_text_block(output: &str) -> Vec { + let lines = strip_ansi(output) + .lines() + .map(str::to_string) + .collect::>(); + let start = lines + .iter() + .position(|line| line.starts_with("- agent_trace.auto_sync:")) + .expect("show output should list agent_trace.auto_sync") + + 1; + let end = lines + .iter() + .position(|line| line.starts_with("- otel.endpoint:")) + .expect("show output should list otel.endpoint"); + lines[start..end].to_vec() + } + + fn resolved_json(source: &str, config_source: Option<&str>, value: &Value) -> Value { + json!({ + "value": value, + "source": source, + "config_source": config_source, + }) + } + + fn policy_cases() -> Vec { + let note_line = format!("- telemetry.note: {TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE}"); + vec![ + PolicyCase { + name: "default", + global: "{}", + local: "{}", + text_lines: vec![ + "- auth.mode: optional (source: default)".to_string(), + "- telemetry.enabled: false (source: default)".to_string(), + "- telemetry.effective: disabled (reason: not_enabled)".to_string(), + note_line.clone(), + ], + auth_json: json!({ + "mode": resolved_json("default", None, &json!("optional")), + }), + telemetry_json: json!({ + "enabled": resolved_json("default", None, &json!(false)), + "effective": {"state": "disabled", "reason": "not_enabled"}, + "note": TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE, + }), + warnings: Vec::new(), + }, + PolicyCase { + name: "user-enabled", + global: r#"{"telemetry":{"enabled":true}}"#, + local: "{}", + text_lines: vec![ + "- auth.mode: optional (source: default)".to_string(), + "- telemetry.enabled: true (source: config_file, config_source: default_discovered_global)".to_string(), + "- telemetry.effective: enabled".to_string(), + ], + auth_json: json!({ + "mode": resolved_json("default", None, &json!("optional")), + }), + telemetry_json: json!({ + "enabled": resolved_json("config_file", Some("default_discovered_global"), &json!(true)), + "effective": {"state": "enabled", "reason": null}, + "note": null, + }), + warnings: Vec::new(), + }, + PolicyCase { + name: "repo-only-enabled", + global: "{}", + local: r#"{"auth":{"mode":"mandatory"},"telemetry":{"enabled":true}}"#, + text_lines: vec![ + "- auth.mode: mandatory (source: config_file, config_source: default_discovered_local)".to_string(), + "- telemetry.enabled: true (source: config_file, config_source: default_discovered_local)".to_string(), + "- telemetry.effective: disabled (reason: no_user_consent)".to_string(), + note_line.clone(), + ], + auth_json: json!({ + "mode": resolved_json("config_file", Some("default_discovered_local"), &json!("mandatory")), + }), + telemetry_json: json!({ + "enabled": resolved_json("config_file", Some("default_discovered_local"), &json!(true)), + "effective": {"state": "disabled", "reason": "no_user_consent"}, + "note": TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE, + }), + warnings: vec![WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT.to_string()], + }, + PolicyCase { + name: "auth-disabled-with-telemetry", + global: r#"{"auth":{"mode":"disabled"},"telemetry":{"enabled":true}}"#, + local: "{}", + text_lines: vec![ + "- auth.mode: disabled (source: config_file, config_source: default_discovered_global)".to_string(), + "- telemetry.enabled: true (source: config_file, config_source: default_discovered_global)".to_string(), + "- telemetry.effective: disabled (reason: auth_disabled)".to_string(), + note_line, + ], + auth_json: json!({ + "mode": resolved_json("config_file", Some("default_discovered_global"), &json!("disabled")), + }), + telemetry_json: json!({ + "enabled": resolved_json("config_file", Some("default_discovered_global"), &json!(true)), + "effective": {"state": "disabled", "reason": "auth_disabled"}, + "note": TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE, + }), + warnings: vec![WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED.to_string()], + }, + ] + } + + fn warnings_text_line(warnings: &[String]) -> String { + if warnings.is_empty() { + "Validation warnings: none".to_string() + } else { + format!("Validation warnings: {}", warnings.join(" | ")) + } + } + + #[test] + fn show_text_reports_access_policy_after_agent_trace_and_lists_policy_warnings() { + for case in policy_cases() { + let runtime = resolve(case.global, case.local); + let output = format_show_output(&runtime, ReportFormat::Text); + + assert_eq!(policy_text_block(&output), case.text_lines, "{}", case.name); + assert_eq!( + strip_ansi(&output).lines().last(), + Some(warnings_text_line(&case.warnings).as_str()), + "{}", + case.name + ); + } + } + + #[test] + fn show_json_reports_resolved_auth_and_telemetry_policy() { + for case in policy_cases() { + let runtime = resolve(case.global, case.local); + let payload: Value = + serde_json::from_str(&format_show_output(&runtime, ReportFormat::Json)).unwrap(); + let resolved = &payload["result"]["resolved"]; + + assert_eq!(resolved["auth"], case.auth_json, "{}", case.name); + assert_eq!(resolved["telemetry"], case.telemetry_json, "{}", case.name); + assert_eq!( + payload["result"]["warnings"], + json!(case.warnings), + "{}", + case.name + ); + } + } + + #[test] + fn validate_lists_policy_warnings_without_policy_fields() { + for case in policy_cases() { + let runtime = resolve(case.global, case.local); + let text = strip_ansi(&format_validate_output(&runtime, ReportFormat::Text)); + let payload: Value = + serde_json::from_str(&format_validate_output(&runtime, ReportFormat::Json)) + .unwrap(); + + assert_eq!( + text, + format!( + "SCE config validation: valid\nValidation issues: none\n{}", + warnings_text_line(&case.warnings) + ), + "{}", + case.name + ); + assert_eq!( + payload, + json!({ + "status": "ok", + "result": { + "command": "config_validate", + "valid": true, + "issues": [], + "warnings": case.warnings, + } + }), + "{}", + case.name + ); + } + } +} diff --git a/cli/src/services/config/resolver.rs b/cli/src/services/config/resolver.rs index bc844e8e1..5a730f9c9 100644 --- a/cli/src/services/config/resolver.rs +++ b/cli/src/services/config/resolver.rs @@ -381,7 +381,7 @@ pub(super) fn resolve_runtime_config(request: &ConfigRequest, cwd: &Path) -> Res } #[allow(clippy::too_many_lines)] -fn resolve_runtime_config_with( +pub(super) fn resolve_runtime_config_with( request: &ConfigRequest, cwd: &Path, env_lookup: FEnv, diff --git a/cli/src/services/config/types.rs b/cli/src/services/config/types.rs index faf81b198..b7331197a 100644 --- a/cli/src/services/config/types.rs +++ b/cli/src/services/config/types.rs @@ -105,7 +105,6 @@ impl AuthMode { } } - #[allow(dead_code)] pub(crate) fn as_str(self) -> &'static str { match self { Self::Disabled => "disabled", @@ -138,6 +137,22 @@ pub(crate) enum TelemetryPolicyState { Disabled(TelemetryDisabledReason), } +impl TelemetryPolicyState { + pub(crate) fn as_str(self) -> &'static str { + match self { + Self::Enabled => "enabled", + Self::Disabled(_) => "disabled", + } + } + + pub(crate) fn disabled_reason(self) -> Option { + match self { + Self::Enabled => None, + Self::Disabled(reason) => Some(reason), + } + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum TelemetryDisabledReason { NotEnabled, @@ -148,6 +163,19 @@ pub(crate) enum TelemetryDisabledReason { InvalidConfig, } +impl TelemetryDisabledReason { + pub(crate) fn as_str(self) -> &'static str { + 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", + } + } +} + #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) struct ResolvedAccessPolicy { pub(crate) auth_mode: ResolvedValue, diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md index 31add979e..942cdaca9 100644 --- a/context/cli/access-policy.md +++ b/context/cli/access-policy.md @@ -4,7 +4,7 @@ This file describes how the CLI turns the per-layer `auth.mode` and `telemetry.enabled` config values into one effective access policy (`ResolvedAccessPolicy`). Key syntax and schema validation are in [config precedence contract](config-precedence-contract.md). The precedence model is recorded in [ADR: consent-gated access policy precedence](../decisions/2026-10-20-consent-gated-access-policy-precedence.md). -Status: the resolver computes and exposes the policy. `sce config show`/`validate` rendering and consumer enforcement (managed telemetry, the headers helper, auth commands, sync, auto-sync, setup) are not wired yet. Until they are, the policy has no runtime effect beyond the warnings it adds to config resolution. +Status: the resolver computes and exposes the policy, and `sce config show` / `validate` report it (see [Reporting](#reporting)). Consumer enforcement (managed telemetry, the headers helper, auth commands, sync, auto-sync, setup) is not wired yet. Until it is, the policy has no runtime effect beyond what config inspection reports. ## Terms @@ -68,6 +68,21 @@ The resolver appends these fixed strings to `validation_warnings`, after the bas Each string is a `WARNING_*` constant in `resolver.rs`. The skipped file's own error still appears in `validation_errors`. +## Reporting + +`sce config show` reports the policy (`cli/src/services/config/render.rs`). + +- **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.effective: enabled`, or `- telemetry.effective: disabled (reason: )` + - only when disabled: `- telemetry.note: Claude Code telemetry settings written by earlier sce setup runs are not changed by telemetry.enabled.` +- **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`. +- **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: telemetry opt-out does not remove Claude-native telemetry settings already written to user-level Claude settings. + ## Exposure `ResolvedAuthRuntimeConfig`, `ResolvedHookRuntimeConfig`, and `ResolvedObservabilityRuntimeConfig` each carry `access_policy`, cloned from the same resolution that produced the rest of the projection. No consumer resolves config a second time to get the policy. diff --git a/context/cli/config-precedence-contract.md b/context/cli/config-precedence-contract.md index ad9179681..ac87c2e83 100644 --- a/context/cli/config-precedence-contract.md +++ b/context/cli/config-precedence-contract.md @@ -99,7 +99,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. -- 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 or explicit file; repository = repo-local) and resolves them into the effective access policy with consent-gated precedence and fixed contradiction warnings; see [effective access policy](access-policy.md). Neither value is rendered by `sce config show` or enforced by consumers yet. +- 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 or explicit file; repository = repo-local) 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; consumers do not enforce them yet. - `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. - `integrations` must be an object when present and currently allows `target` and `optional_workflows`; either key alone yields a parsed `IntegrationsConfig` with the other defaulting to empty. @@ -136,6 +136,7 @@ When a default-discovered global or repo-local config file exists but fails JSON - `validate` text output is limited to `SCE config validation`, `Validation issues`, and `Validation warnings` lines. - `validate` JSON output is limited to `result.command`, `result.valid`, `result.issues`, and `result.warnings`. - `show` includes resolved Agent Trace configuration under `result.resolved.agent_trace` (JSON: `repository_id` optional-value shape, `repository_remote` and `auto_sync` resolved-value shapes) and as per-key text lines, reporting `(unset)` for a missing `repository_id`, `source: default` for the `origin` remote fallback, and `source: default` for omitted `auto_sync`. +- `show` includes the effective access policy after the Agent Trace keys and before `otel.*`: JSON `result.resolved.auth` (`mode`) and `result.resolved.telemetry` (`enabled`, `effective` `{state, reason}`, `note`), and the matching `auth.mode`, `telemetry.enabled`, `telemetry.effective`, and conditional `telemetry.note` text lines. The [effective access policy](access-policy.md#reporting) file owns the exact shape. - `show` includes `policies.database_retry` overrides with provenance; for `agent_trace_db` it also renders configured `busy_timeout_ms` and `contention_deadline_ms` (JSON integers under `agent_trace_db`, text lines suffixed `(busy_timeout_ms)` / `(contention_deadline_ms)`). Unset keys are omitted; their defaults apply at resolution. - Doctor consumes the same resolved `agent_trace.auto_sync` value and source metadata; its separate `post_commit_auto_sync` report fact documents hook readiness without launching synchronization. - `show` includes resolved bash-tool policies under `result.resolved.policies.bash`. diff --git a/context/context-map.md b/context/context-map.md index 88a53fe90..463d14f04 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -25,7 +25,7 @@ Feature/domain context: - `context/cli/async-persistence-guarantees.md` (verified guarantees and named limits of the directly awaited Turso persistence migration — exclusive `&mut` transactions, deferred rollback, credential-rotation and terminal-sync behavior, lease/descriptor protection — plus PR1–PR4 staging and the PR3 cleanup ledger) - `context/cli/agent-trace-sync-command.md` (composed local-to-control-plane `sce sync` architecture: the `hooks/plugins → repository Agent Trace DB → AgentTraceExportReader → sce sync → HTTPS + WorkOS Bearer → control plane` data flow, the `sce auth login` / `cd ` / `sce sync` user flow, the no-local-cursor/no-`agent-trace-sync.db`/no-Turso-Sync/no-`BridgeLock`/no-local-DWH invariants, the four-local-capture-streams versus three-remote-streams boundary with its `diff_traces` release gate, the optional `commitPatchId` field on the existing `agent_traces` stream with its Control Plane release dependency and no-backfill limit, and `401`/`409`/ambiguous-batch-failure recovery semantics) - `context/cli/config-precedence-contract.md` (implemented `sce config` show/validate command contract, deterministic `flags > env > config file > defaults` resolution order, focused `config/resolver.rs` ownership for config discovery/merge/runtime precedence plus default-discovered invalid-file degradation, focused `config/render.rs` ownership for `show`/`validate` text+JSON output construction, canonical `$schema` acceptance for startup-loaded `sce/config.json` files, shared auth-key env/config/optional baked-default support starting with `workos_client_id`, shared runtime resolution for flat logging observability keys including config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` with `/sce/logs` defaulting plus config-file/default-only positive `log_file_retention_limit`, config-file-only `agent_trace.repository_id`/`agent_trace.repository_remote` repository-identity keys with default remote `origin`, `agent_trace.auto_sync` resolution with omitted-value fallback `false`, explicit-false opt-out, and setup-written explicit `true` bootstrap behavior for the post-commit trigger boundary, the catalog-derived `integrations.optional_workflows` optional-workflow selection key, schema-validated per-layer `auth.mode` / `telemetry.enabled` sections, JSON-pointer-prefixed schema-validation errors, canonical Pkl-generated `sce/config.json` schema ownership plus CLI embedding/reuse contract including `policies.attribution_hooks.enabled` default-true/explicit-false opt-out metadata, config-file selection order, `show` provenance output, and trimmed `validate` output contract) -- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, and exposure on the auth/hook/observability runtime projections; decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) +- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, and exposure on the auth/hook/observability runtime projections; decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) - `context/cli/capability-traits.md` (current broad CLI capability seam in `cli/src/services/capabilities.rs`, including `FsOps`/`StdFsOps` (method-less marker), `GitOps`/`ProcessGitOps` (command execution and availability), compile-time-typed borrowed AppContext wiring with scoped borrowing across directly awaited commands with associated-type narrow capability accessors plus `ContextWithRepoRoot` repo-root-scoped context derivation, generic command execution bounds, and test-only unimplemented stubs; current service internals do not consume fs/git traits until later lifecycle migration tasks) - `context/cli/service-lifecycle.md` (current async lifecycle seam in `cli/src/services/lifecycle.rs`, including default no-op `ServiceLifecycle` diagnose/fix/setup methods against narrow `HasRepoRoot`, lifecycle-owned health/fix/setup result types with generic setup messages, doctor/setup adapter boundaries, the static `LifecycleProvider` enum catalog/dispatcher, hook/config/local_db/auth_db/agent_trace_db lifecycle providers including setup-time repository-scoped Agent Trace DB initialization plus checkout identity diagnostics, implemented doctor aggregation over diagnose/fix providers, and implemented setup aggregation over `setup` providers in order config → local_db → auth_db → agent_trace_db → hooks when requested) - `context/cli/mutation-trace-protocol.md` (pure, dependency-free `cli/src/services/mutation_trace/` refinement of the verified `spec/mutation_cursor.qnt` mutation-cursor protocol: the full pure action set — `prepare`/`commit` transition logic, attribution/mutation-event materialization, snapshot-failure/database-failure taint actions, scope abandonment, and recovery with an explicit observed-tree input — plus cross-action sequence/invariant tests and a module-level Quint refinement matrix are all complete (`types.rs`, `protocol.rs`, `mod.rs`, `tests.rs`, registered with `#[allow(dead_code)]`); opaque-newtype identity refinement decisions vs. the Quint model's bounded enums, and the `coordinator.rs` target end-state seam this layout leaves room for but does not create — `store.rs`, `runtime/git_snapshot.rs`, and `runtime/coordinator.rs` (including its public `coordinate()` entrypoint) now exist, built out by the `mutation-cursor-store-persistence` and `mutation-cursor-runtime-coordinator` plans respectively; `protocol.rs` is invoked only through the runtime, and the runtime is now driven by the generic `sce hooks mutation-scope` CLI ingress and a first Claude Code adapter driver, registered by `sce setup` and reachable by a real Claude Code session, now proven against real Git repositories and a real Agent Trace DB by the `claude-mutation-scope-integration` plan's T08 regressions) diff --git a/context/plans/auth-telemetry-policy-config.md b/context/plans/auth-telemetry-policy-config.md index 933f2f585..c6fa88368 100644 --- a/context/plans/auth-telemetry-policy-config.md +++ b/context/plans/auth-telemetry-policy-config.md @@ -297,13 +297,19 @@ Persist this field in every plan; this is durable plan state, not chat state: - Context impact: localized — config resolver and types only; no rendering or runtime enforcement change yet. The fixed warning strings and layer classification are durable contract material for `context/cli/config-precedence-contract.md`; T03 renders them. - Context synchronization: synced -- [ ] T03: `Report auth and telemetry policy in config show and validate` (status:todo) +- [x] T03: `Report auth and telemetry policy in config show and validate` (status:done) - Task ID: T03 - Scope: In — `config/render.rs` text lines and JSON objects for `auth.mode` and `telemetry.enabled` (value, `source`, `config_source`) plus effective telemetry state and reason (`result.resolved.auth`, `result.resolved.telemetry`); contradiction warnings in `show` warnings and `validate` warnings; a fixed note when telemetry is disabled that Claude settings written by earlier setups are not changed. Out — enforcement. - Dependencies: T02 - Done when: `show` text and JSON include the new fields in a deterministic position for defaults, global-only, local-only, and contradictory layers; `validate` stays limited to its existing fields and lists the new warnings. - Verify: exact-output tests in `config/render.rs` for default, user-enabled, repo-only-enabled, and auth-disabled-with-telemetry cases in both formats; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml config::render`. - - Context synchronization: pending + - Completed: 2026-10-20 + - Files changed: `cli/src/services/config/render.rs`, `cli/src/services/config/types.rs`, `cli/src/services/config/resolver.rs`, `context/plans/auth-telemetry-policy-config.md` + - Result: `config show` text now lists, directly after `agent_trace.auto_sync` and before `otel.*`, `- auth.mode: (source: …[, config_source: …])`, `- telemetry.enabled: (source: …[, config_source: …])`, `- telemetry.effective: enabled` or `- telemetry.effective: disabled (reason: )`, and, only when disabled, `- telemetry.note: Claude Code telemetry settings written by earlier sce setup runs are not changed by telemetry.enabled.` JSON adds `result.resolved.auth.mode` (`value`/`source`/`config_source`) and `result.resolved.telemetry` with `enabled` (`value`/`source`/`config_source`), `effective` (`state`, `reason` or `null`), and `note` (fixed string, or `null` when enabled). Added `TelemetryPolicyState::as_str`/`disabled_reason` and `TelemetryDisabledReason::as_str` (`not_enabled`, `user_opt_out`, `no_user_consent`, `repository_opt_out`, `auth_disabled`, `invalid_config`). Removed `#[allow(dead_code)]` from `AuthMode::as_str`. `resolve_runtime_config_with` is now `pub(super)` so render tests resolve real layered configs. Contradiction warnings already flow through `validation_warnings` into `show` and `validate`, so no warning code changed. `validate` output fields are unchanged. + - Verify outcome: `config::render` passed (3 passed, 0 failed). The new `render::tests` module covers default, user-enabled, repo-only-enabled (with repo `mandatory`), and auth-disabled-with-telemetry cases. For each, it checks the exact text policy block and its position, the exact JSON `auth`/`telemetry` objects, show warnings in both formats, and exact `validate` text and JSON. `config::` passed (63 passed, 0 failed). `cargo clippy --all-targets -- -D warnings` via `run-cli-cargo.sh` passed. + - Deviation: none in scope. Test text assertions strip ANSI escapes so they hold when stdout is a TTY. + - Context impact: localized — `config show` and `config validate` output contract. `context/cli/config-precedence-contract.md` should document the new show text lines, the JSON `resolved.auth`/`resolved.telemetry` shape, the reason strings, and the fixed telemetry note. + - Context synchronization: synced - [ ] T04: `Gate managed telemetry startup and doctor health on telemetry policy` (status:todo) - Task ID: T04 From d15fc1071495f45a5b3dab559f74209fe73e8d98 Mon Sep 17 00:00:00 2001 From: David Abram Date: Tue, 20 Oct 2026 14:30:02 +0200 Subject: [PATCH 4/9] runtime: Gate managed telemetry on telemetry policy Prevent managed telemetry startup from probing readiness or credentials when the effective policy disables telemetry, and report that state as a passing doctor result with stable text and JSON output. Add command, doctor, and Claude-hook regressions, and document the enforced policy boundary. Plan: auth-telemetry-policy-config T04 Co-authored-by: SCE --- cli/src/app.rs | 11 +- .../app/doctor_reconciliation_cli_tests.rs | 81 +++++++++++- .../services/auth_db/multiprocess_tests.rs | 79 ++++++++++- cli/src/services/config/types.rs | 4 +- cli/src/services/doctor/managed_telemetry.rs | 37 +++++- cli/src/services/doctor/mod.rs | 10 +- cli/src/services/doctor/render.rs | 39 ++++++ cli/src/services/doctor/types.rs | 1 + cli/src/services/managed_telemetry.rs | 124 +++++++++++++++--- context/cli/access-policy.md | 7 +- context/context-map.md | 2 +- context/plans/auth-telemetry-policy-config.md | 10 +- context/sce/cli-observability-contract.md | 4 +- context/sce/telemetry-credential.md | 7 +- 14 files changed, 382 insertions(+), 34 deletions(-) diff --git a/cli/src/app.rs b/cli/src/app.rs index 2a863fc0d..7430d742a 100644 --- a/cli/src/app.rs +++ b/cli/src/app.rs @@ -28,6 +28,7 @@ struct StartupContext { struct AppRuntime { logger: services::observability::Logger, telemetry: RuntimeTelemetry, + telemetry_enabled: bool, fs: services::capabilities::StdFsOps, git: services::capabilities::ProcessGitOps, registry: services::command_registry::CommandRegistry, @@ -297,7 +298,8 @@ where ); } }; - runtime.telemetry = RuntimeTelemetry::resolve(span_kind, &runtime.logger).await; + runtime.telemetry = + RuntimeTelemetry::resolve(span_kind, runtime.telemetry_enabled, &runtime.logger).await; let rendered = run_command_lifecycle(args, &runtime, stdout, stderr).await; runtime.telemetry.shutdown().await; app_support::exit_code_for(&rendered) @@ -363,6 +365,10 @@ fn initialize_runtime(startup: StartupContext) -> Result { Ok(AppRuntime { logger, telemetry: RuntimeTelemetry::Noop(NoopTelemetry), + telemetry_enabled: startup + .observability_config + .access_policy + .telemetry_enabled(), fs: services::capabilities::StdFsOps, git: services::capabilities::ProcessGitOps, registry: services::command_registry::build_default_registry(), @@ -1142,7 +1148,8 @@ pub(crate) mod tests { #[tokio::test] async fn disallowed_managed_telemetry_resolves_to_noop_without_credential_lookup() { let telemetry = - RuntimeTelemetry::resolve(None, &services::observability::traits::NoopLogger).await; + RuntimeTelemetry::resolve(None, true, &services::observability::traits::NoopLogger) + .await; assert!(matches!(telemetry, RuntimeTelemetry::Noop(_))); } } diff --git a/cli/src/app/doctor_reconciliation_cli_tests.rs b/cli/src/app/doctor_reconciliation_cli_tests.rs index bc798c2a0..0e1f2c301 100644 --- a/cli/src/app/doctor_reconciliation_cli_tests.rs +++ b/cli/src/app/doctor_reconciliation_cli_tests.rs @@ -20,6 +20,8 @@ const AUTH_DB_TEST_SECRET: &str = "doctor-cli-test-secret"; const UNREADABLE_AUTH_DB: &[u8] = b"not an encrypted auth database"; const FAR_FUTURE_READINESS: &[u8] = br#"{"expires_at_unix_seconds":4102444800}"#; +const TELEMETRY_ENABLED_CONFIG: &str = r#"{"telemetry":{"enabled":true}}"#; +const TELEMETRY_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."; const EXIT_SUCCESS: &str = "success"; const EXIT_FAILURE: &str = "failure"; @@ -142,6 +144,12 @@ impl Sandbox { .expect("state JSON") } + fn telemetry_enabled_config(&self) -> String { + let path = self.dir.path().join("telemetry-enabled.json"); + std::fs::write(&path, TELEMETRY_ENABLED_CONFIG).expect("telemetry config"); + path.to_string_lossy().into_owned() + } + fn run(&self, args: &[&str]) -> CliRun { self.run_with_env(args, &[]) } @@ -620,11 +628,15 @@ fn global_state_warnings(report: &Value) -> Vec { async fn doctor_on_fresh_state_reports_unconfigured_telemetry_without_a_warning() { let sandbox = Sandbox::new("https://example.invalid/org/repo-a.git"); let auth_dir = sandbox.state_root().join("sce"); + let config = sandbox.telemetry_enabled_config(); let report = sandbox .run_with_env( &["doctor", "--format", "json"], - &[(AUTH_DB_ENCRYPTION_KEY_ENV, "")], + &[ + (AUTH_DB_ENCRYPTION_KEY_ENV, ""), + ("SCE_CONFIG_FILE", config.as_str()), + ], ) .json(); @@ -644,7 +656,11 @@ async fn doctor_fix_reports_unreadable_telemetry_credentials_without_auth_side_e let readiness = auth_dir.join("telemetry-ready.json"); std::fs::write(&auth_db, UNREADABLE_AUTH_DB).expect("auth DB"); std::fs::write(&readiness, FAR_FUTURE_READINESS).expect("readiness"); - let env = [(AUTH_DB_ENCRYPTION_KEY_ENV, AUTH_DB_TEST_SECRET)]; + let config = sandbox.telemetry_enabled_config(); + let env = [ + (AUTH_DB_ENCRYPTION_KEY_ENV, AUTH_DB_TEST_SECRET), + ("SCE_CONFIG_FILE", config.as_str()), + ]; let fix = sandbox.run_with_env(&["doctor", "--fix", "--format", "json"], &env); let report = fix.json(); @@ -690,3 +706,64 @@ async fn doctor_fix_reports_unreadable_telemetry_credentials_without_auth_side_e assert!(!fix.stdout.contains(AUTH_DB_TEST_SECRET)); assert!(!fix.stderr.contains(AUTH_DB_TEST_SECRET)); } + +#[tokio::test(flavor = "multi_thread")] +async fn doctor_with_telemetry_disabled_by_config_never_reads_the_auth_db() { + let sandbox = Sandbox::new("https://example.invalid/org/repo-a.git"); + let auth_dir = sandbox.state_root().join("sce"); + let env = [(AUTH_DB_ENCRYPTION_KEY_ENV, "")]; + + let fresh = sandbox.run_with_env(&["doctor"], &env); + assert!( + fresh + .stdout + .contains("[PASS] Managed telemetry (disabled by config)\n"), + "{}", + fresh.stdout + ); + assert!( + !fresh.stdout.contains(TELEMETRY_OPT_IN_NOTE), + "{}", + fresh.stdout + ); + assert!(!auth_dir.join("auth.db").exists()); + + std::fs::create_dir_all(&auth_dir).expect("auth dir"); + let auth_db = auth_dir.join("auth.db"); + let readiness = auth_dir.join("telemetry-ready.json"); + std::fs::write(&auth_db, UNREADABLE_AUTH_DB).expect("auth DB"); + std::fs::write(&readiness, FAR_FUTURE_READINESS).expect("readiness"); + + let report = sandbox + .run_with_env(&["doctor", "--format", "json"], &env) + .json(); + assert_eq!( + report["managed_telemetry"], + serde_json::json!({ + "state": "disabled_by_config", + "reason": "disabled_by_config", + "kind": null, + "severity": null, + "next_action": null, + }) + ); + let warnings = global_state_warnings(&report); + assert!(warnings.is_empty(), "{warnings:#?}"); + + let text = sandbox.run_with_env(&["doctor"], &env); + assert!( + text.stdout.contains(&format!( + "[PASS] Managed telemetry (disabled by config)\n {TELEMETRY_OPT_IN_NOTE}\n" + )), + "{}", + text.stdout + ); + assert_eq!( + std::fs::read(&auth_db).expect("auth DB kept"), + UNREADABLE_AUTH_DB + ); + assert_eq!( + std::fs::read(&readiness).expect("readiness kept"), + FAR_FUTURE_READINESS + ); +} diff --git a/cli/src/services/auth_db/multiprocess_tests.rs b/cli/src/services/auth_db/multiprocess_tests.rs index e35be5e2a..630cf91bb 100644 --- a/cli/src/services/auth_db/multiprocess_tests.rs +++ b/cli/src/services/auth_db/multiprocess_tests.rs @@ -72,6 +72,8 @@ const UNBOUND_REPOSITORY: &str = "unbound-repo"; const HEADERS_AUTHORIZATION: &str = r#"{"Authorization":"Bearer tok-multiprocess"}"#; const HEADERS_UNAVAILABLE: &str = "Telemetry credential is unavailable."; const STDIN_SECRET: &str = "SECRET_STDIN_VALUE"; +const TELEMETRY_FALLBACK_EVENT: &str = "event_id=sce.telemetry.fallback"; +const FALLBACK_REASON_PREFIX: &str = "reason="; const FAIL_OPEN_HOOK_COMMANDS: [ClaudeHookCommand; 3] = [ ClaudeHookCommand::DiffTrace, ClaudeHookCommand::ConversationTrace, @@ -596,6 +598,72 @@ fn assert_headers_unavailable(helper: Child) { assert!(stderr.contains(HEADERS_UNAVAILABLE), "{stderr}"); } +fn policy_hook_fallback_reasons(sandbox: &Sandbox, telemetry_enabled: bool) -> Vec { + let root = sandbox.dir.path(); + let work = root.join("work"); + std::fs::create_dir_all(&work).expect("work dir"); + let config = root.join(format!("policy-{telemetry_enabled}.json")); + std::fs::write( + &config, + serde_json::json!({ "telemetry": { "enabled": telemetry_enabled } }).to_string(), + ) + .expect("policy config"); + let log_dir = root.join(format!("logs-{telemetry_enabled}")); + std::fs::create_dir_all(&log_dir).expect("log dir"); + wait_success( + "policy-hook", + sandbox + .command("policy-hook") + .current_dir(&work) + .env(AUTH_DB_ENCRYPTION_KEY_ENV, "") + .env("SCE_CONFIG_FILE", &config) + .env("SCE_LOG_LEVEL", "debug") + .env("SCE_LOG_FORMAT", "text") + .env("SCE_LOG_DIR", &log_dir) + .env("CLAUDECODE", "1") + .env("CLAUDE_PROJECT_DIR", &work) + .spawn() + .expect("spawn policy hook"), + ); + let mut reasons = Vec::new(); + for entry in std::fs::read_dir(&log_dir).expect("log entries") { + let log = std::fs::read_to_string(entry.expect("log entry").path()).expect("log file"); + reasons.extend( + log.lines() + .filter(|line| line.contains(TELEMETRY_FALLBACK_EVENT)) + .filter_map(|line| { + line.split_whitespace() + .find_map(|token| token.strip_prefix(FALLBACK_REASON_PREFIX)) + .map(ToString::to_string) + }), + ); + } + reasons +} + +#[test] +fn claude_hook_with_telemetry_disabled_by_config_never_resolves_the_credential() { + let _fan_out = serialize_fan_out(); + let sandbox = Sandbox::new(); + sandbox.seed(); + let state = sandbox.sce_state_dir(); + let auth_db = std::fs::read(state.join("auth.db")).expect("seeded auth DB"); + assert!(state.join("telemetry-ready.json").is_file()); + + assert_eq!( + policy_hook_fallback_reasons(&sandbox, false), + ["disabled_by_config"] + ); + assert_eq!( + policy_hook_fallback_reasons(&sandbox, true), + ["database_error"] + ); + assert_eq!( + std::fs::read(state.join("auth.db")).expect("auth DB"), + auth_db + ); +} + #[test] fn every_claude_hook_entry_point_records_its_command_identity() { let _fan_out = serialize_fan_out(); @@ -766,9 +834,10 @@ async fn auth_db_child_process() { println!("{TOKEN_PREFIX}{}", credential.token); } "telemetry-health" => { - let label = match inspect_health().await { + let label = match inspect_health(true).await { ManagedTelemetryHealth::Healthy => "healthy", ManagedTelemetryHealth::Disabled(reason) => reason.as_str(), + ManagedTelemetryHealth::DisabledByConfig { .. } => "disabled_by_config", }; println!("{HEALTH_PREFIX}{label}"); } @@ -819,6 +888,14 @@ async fn auth_db_child_process() { "verify-rows" => print_verified_rows().await, "coordinated-writer" => run_coordinated_writer_child().await, "hook-entry" => run_hook_entry_child().await, + "policy-hook" => { + let _ = Box::pin(crate::app::run( + ["sce", "hooks", "claude-model-state"] + .into_iter() + .map(String::from), + )) + .await; + } other => run_binding_child(other).await, } } diff --git a/cli/src/services/config/types.rs b/cli/src/services/config/types.rs index b7331197a..0fe095cfb 100644 --- a/cli/src/services/config/types.rs +++ b/cli/src/services/config/types.rs @@ -184,16 +184,17 @@ pub(crate) struct ResolvedAccessPolicy { pub(crate) background_cloud_allowed: bool, } -#[allow(dead_code)] impl ResolvedAccessPolicy { pub(crate) fn telemetry_enabled(&self) -> bool { self.telemetry == TelemetryPolicyState::Enabled } + #[allow(dead_code)] pub(crate) fn auth_allowed(&self) -> bool { self.auth_mode.value != AuthMode::Disabled } + #[allow(dead_code)] pub(crate) fn auto_sync_allowed(&self, configured: bool) -> bool { configured && self.background_cloud_allowed } @@ -299,7 +300,6 @@ pub(crate) struct ResolvedObservabilityRuntimeConfig { pub(crate) log_file_retention_limit: usize, pub(crate) loaded_config_paths: Vec, pub(crate) validation_errors: Vec, - #[allow(dead_code)] pub(crate) access_policy: ResolvedAccessPolicy, } diff --git a/cli/src/services/doctor/managed_telemetry.rs b/cli/src/services/doctor/managed_telemetry.rs index 825e67ee9..4d051f880 100644 --- a/cli/src/services/doctor/managed_telemetry.rs +++ b/cli/src/services/doctor/managed_telemetry.rs @@ -12,9 +12,11 @@ use super::types::{ const STATE_HEALTHY: &str = "healthy"; const STATE_NOT_CONFIGURED: &str = "not_configured"; const STATE_DISABLED: &str = "disabled"; +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 HOOK_IMPACT: &str = "Claude Code hooks continue working, but telemetry export is disabled."; const MACOS_INACCESSIBLE_SUMMARY: &str = @@ -63,7 +65,9 @@ fn diagnostic_for_platform( return None; }; let (kind, summary, remediation, next_action) = match reason { - TelemetryFallbackReason::NotConfigured => return None, + TelemetryFallbackReason::DisabledByConfig | TelemetryFallbackReason::NotConfigured => { + return None + } TelemetryFallbackReason::CredentialInaccessible => { let (summary, remediation) = inaccessible_guidance(platform); ( @@ -173,6 +177,13 @@ pub(super) fn json(health: ManagedTelemetryHealth) -> Value { "severity": null, "next_action": null, }), + (ManagedTelemetryHealth::DisabledByConfig { .. }, None) => json!({ + "state": STATE_DISABLED_BY_CONFIG, + "reason": TelemetryFallbackReason::DisabledByConfig.as_str(), + "kind": null, + "severity": null, + "next_action": null, + }), (ManagedTelemetryHealth::Disabled(reason), None) => json!({ "state": STATE_NOT_CONFIGURED, "reason": reason.as_str(), @@ -220,6 +231,30 @@ mod tests { ); } + #[test] + fn telemetry_disabled_by_config_reports_no_problem_and_a_stable_json_state() { + for readiness_hint_present in [false, true] { + let health = ManagedTelemetryHealth::DisabledByConfig { + readiness_hint_present, + }; + assert_eq!(problem(health), None); + assert_eq!( + json(health), + json!({ + "state": "disabled_by_config", + "reason": "disabled_by_config", + "kind": null, + "severity": null, + "next_action": null, + }) + ); + } + assert_eq!( + problem(disabled(TelemetryFallbackReason::DisabledByConfig)), + None + ); + } + #[test] fn macos_inaccessible_credential_is_an_actionable_always_allow_warning() { let diagnostic = diagnostic_for_platform( diff --git a/cli/src/services/doctor/mod.rs b/cli/src/services/doctor/mod.rs index 74c5dbb28..5a56a7ccc 100644 --- a/cli/src/services/doctor/mod.rs +++ b/cli/src/services/doctor/mod.rs @@ -126,7 +126,10 @@ async fn execute_doctor_with_context( Ok(resolve_sce_default_locations()?.global_config_file()) }, probe_codex_hook_policy: &codex_hook_policy::probe_default, - managed_telemetry: crate::services::managed_telemetry::inspect_health().await, + managed_telemetry: crate::services::managed_telemetry::inspect_health( + telemetry_enabled_for(repository_root), + ) + .await, }, mutation_scope_seam, reconcile_seam, @@ -135,6 +138,11 @@ async fn execute_doctor_with_context( .await } +fn telemetry_enabled_for(repository_root: &Path) -> bool { + crate::services::config::resolve_observability_runtime_config(repository_root) + .is_ok_and(|config| config.access_policy.telemetry_enabled()) +} + async fn execute_doctor_with_lifecycle_providers( request: DoctorRequest, repository_root: &Path, diff --git a/cli/src/services/doctor/render.rs b/cli/src/services/doctor/render.rs index 25655df8d..49e269827 100644 --- a/cli/src/services/doctor/render.rs +++ b/cli/src/services/doctor/render.rs @@ -314,6 +314,20 @@ fn managed_telemetry_node(health: ManagedTelemetryHealth) -> DoctorDisplayNode { DoctorDisplayStatus::Pass, Vec::new(), ), + ( + ManagedTelemetryHealth::DisabledByConfig { + readiness_hint_present, + }, + None, + ) => top_level_node( + "Managed telemetry (disabled by config)", + DoctorDisplayStatus::Pass, + if readiness_hint_present { + vec![DoctorDisplayDetail::Note(managed_telemetry::OPT_IN_NOTE)] + } else { + Vec::new() + }, + ), } } @@ -656,6 +670,11 @@ fn render_display_node( &node.label, )); if !expand_unhealthy || node.status == DoctorDisplayStatus::Pass { + for detail in &node.details { + if matches!(detail, DoctorDisplayDetail::Note(_)) { + render_display_detail(lines, detail, indent + 2); + } + } return; } @@ -737,6 +756,7 @@ fn render_display_detail(lines: &mut Vec, detail: &DoctorDisplayDetail, lines.push(format!("{prefix}{}", managed_telemetry::HOOK_IMPACT)); lines.extend(remediation.lines().map(|line| format!("{prefix}{line}"))); } + DoctorDisplayDetail::Note(note) => lines.push(format!("{prefix}{note}")), } } @@ -1294,6 +1314,25 @@ mod managed_telemetry_render_tests { ); } + #[test] + fn telemetry_disabled_by_config_renders_pass_row_with_opt_in_line_only_for_ready_hint() { + assert_eq!( + rendered(ManagedTelemetryHealth::DisabledByConfig { + readiness_hint_present: false + }), + [" [PASS] Managed telemetry (disabled by config)"] + ); + assert_eq!( + rendered(ManagedTelemetryHealth::DisabledByConfig { + readiness_hint_present: true + }), + [ + " [PASS] Managed telemetry (disabled by config)", + " Managed telemetry export is off because telemetry.enabled is not true; set telemetry.enabled: true in the global SCE config to resume it.", + ] + ); + } + #[test] fn inaccessible_credentials_render_reason_impact_and_login_steps() { let lines = rendered(ManagedTelemetryHealth::Disabled( diff --git a/cli/src/services/doctor/types.rs b/cli/src/services/doctor/types.rs index 57ea0fa51..8ac9499cd 100644 --- a/cli/src/services/doctor/types.rs +++ b/cli/src/services/doctor/types.rs @@ -283,6 +283,7 @@ pub(super) enum DoctorDisplayDetail { summary: String, remediation: String, }, + Note(&'static str), } #[derive(Clone, Copy, Debug, Eq, PartialEq)] diff --git a/cli/src/services/managed_telemetry.rs b/cli/src/services/managed_telemetry.rs index 6b9a5ac16..c8368b8c4 100644 --- a/cli/src/services/managed_telemetry.rs +++ b/cli/src/services/managed_telemetry.rs @@ -10,6 +10,7 @@ use crate::services::error::CliError; use crate::services::observability::traits::{Logger, NoopTelemetry, Telemetry}; use trace_export::{ManagedSpanKind, ManagedTraceTelemetry}; +use crate::services::default_paths::telemetry_readiness_path; use crate::services::telemetry_credential_storage::{ load_telemetry_credential, TelemetryCredential, }; @@ -116,6 +117,7 @@ where #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum TelemetryFallbackReason { + DisabledByConfig, NotConfigured, CredentialInaccessible, CredentialUnavailable, @@ -129,6 +131,7 @@ pub(crate) enum TelemetryFallbackReason { impl TelemetryFallbackReason { pub(crate) const fn as_str(self) -> &'static str { match self { + Self::DisabledByConfig => "disabled_by_config", Self::NotConfigured => "not_configured", Self::CredentialInaccessible => "credential_inaccessible", Self::CredentialUnavailable => "credential_unavailable", @@ -143,7 +146,8 @@ impl TelemetryFallbackReason { const fn is_failure(self) -> bool { !matches!( self, - Self::NotConfigured + Self::DisabledByConfig + | Self::NotConfigured | Self::CredentialInaccessible | Self::CredentialUnavailable | Self::CredentialExpired @@ -226,24 +230,45 @@ where pub(crate) enum ManagedTelemetryHealth { Healthy, Disabled(TelemetryFallbackReason), + DisabledByConfig { readiness_hint_present: bool }, } -pub(crate) async fn inspect_health() -> ManagedTelemetryHealth { +pub(crate) async fn inspect_health(telemetry_enabled: bool) -> ManagedTelemetryHealth { let now = now_unix_seconds(); - let Ok(readiness) = telemetry_readiness::state(now) else { - return ManagedTelemetryHealth::Disabled(TelemetryFallbackReason::PathResolutionError); - }; - inspect_health_with(readiness, load_telemetry_credential(), now).await + inspect_health_with( + telemetry_enabled, + || telemetry_readiness::state(now), + readiness_hint_present, + load_telemetry_credential(), + now, + ) + .await +} + +fn readiness_hint_present() -> bool { + telemetry_readiness_path().is_ok_and(|path| path.is_file()) } -pub(crate) async fn inspect_health_with( - readiness: ReadinessState, +pub(crate) async fn inspect_health_with( + telemetry_enabled: bool, + readiness: R, + hint_present: H, lookup: Fut, now_unix_seconds: u64, ) -> ManagedTelemetryHealth where + R: FnOnce() -> anyhow::Result, + H: FnOnce() -> bool, Fut: Future, TokenStorageError>> + Send + 'static, { + if !telemetry_enabled { + return ManagedTelemetryHealth::DisabledByConfig { + readiness_hint_present: hint_present(), + }; + } + let Ok(readiness) = readiness() else { + return ManagedTelemetryHealth::Disabled(TelemetryFallbackReason::PathResolutionError); + }; match readiness { ReadinessState::NotConfigured => { ManagedTelemetryHealth::Disabled(TelemetryFallbackReason::NotConfigured) @@ -275,12 +300,17 @@ pub enum RuntimeTelemetry { } impl RuntimeTelemetry { - pub async fn resolve(span_kind: Option, logger: &impl Logger) -> Self { + pub async fn resolve( + span_kind: Option, + telemetry_enabled: bool, + logger: &impl Logger, + ) -> Self { let Some(span_kind) = span_kind else { return Self::Noop(NoopTelemetry); }; let (telemetry, fallback) = Self::resolve_when_ready( - telemetry_readiness::is_ready(now_unix_seconds()), + telemetry_enabled, + || telemetry_readiness::is_ready(now_unix_seconds()), load_telemetry_credential(), span_kind, ) @@ -291,17 +321,27 @@ impl RuntimeTelemetry { telemetry } - pub(crate) async fn resolve_when_ready( - ready: bool, + pub(crate) async fn resolve_when_ready( + telemetry_enabled: bool, + ready: R, lookup: Fut, span_kind: ManagedSpanKind, ) -> (Self, Option) where + R: FnOnce() -> bool, Fut: Future, TokenStorageError>> + Send + 'static, { - if !ready { + if !telemetry_enabled { + return ( + Self::Noop(NoopTelemetry), + Some(TelemetryFallback::new( + TelemetryFallbackReason::DisabledByConfig, + )), + ); + } + if !ready() { return ( Self::Noop(NoopTelemetry), Some(TelemetryFallback::new( @@ -439,7 +479,8 @@ mod tests { let flag = looked_up.clone(); let (telemetry, fallback) = RuntimeTelemetry::resolve_when_ready( - false, + true, + || false, async move { flag.store(true, std::sync::atomic::Ordering::SeqCst); Ok(None) @@ -455,10 +496,55 @@ mod tests { assert!(!looked_up.load(std::sync::atomic::Ordering::SeqCst)); } + fn forbidden_lookup() -> Result, TokenStorageError> { + panic!("credential lookup must not run when telemetry is disabled by config") + } + + #[tokio::test] + async fn telemetry_disabled_by_config_never_probes_readiness_or_looks_up_credentials() { + for span_kind in [ManagedSpanKind::Command, ManagedSpanKind::ClaudeHook] { + let (telemetry, fallback) = RuntimeTelemetry::resolve_when_ready( + false, + || panic!("readiness must not be probed when telemetry is disabled by config"), + async { forbidden_lookup() }, + span_kind, + ) + .await; + + assert!(matches!(telemetry, RuntimeTelemetry::Noop(_))); + let fallback = fallback.expect("policy-disabled telemetry is diagnosed"); + assert_eq!(fallback.reason, TelemetryFallbackReason::DisabledByConfig); + assert_eq!(fallback.reason.as_str(), "disabled_by_config"); + assert!(!fallback.reason.is_failure()); + assert_eq!(fallback.detail, None); + } + } + + #[tokio::test] + async fn health_disabled_by_config_never_probes_readiness_or_looks_up_credentials() { + for hint in [false, true] { + let health = inspect_health_with( + false, + || panic!("readiness must not be probed when telemetry is disabled by config"), + || hint, + async { forbidden_lookup() }, + NOW, + ) + .await; + assert_eq!( + health, + ManagedTelemetryHealth::DisabledByConfig { + readiness_hint_present: hint + } + ); + } + } + #[tokio::test] async fn claude_hook_with_inaccessible_credential_store_skips_quietly() { let (telemetry, fallback) = RuntimeTelemetry::resolve_when_ready( true, + || true, async { Err(TokenStorageError::CredentialAccessUnavailable) }, ManagedSpanKind::ClaudeHook, ) @@ -551,7 +637,7 @@ mod tests { ), ] { let (looked_up, lookup) = tracked_lookup(Ok(Some(credential("bao-token", NOW + 60)))); - let health = inspect_health_with(readiness, lookup, NOW).await; + let health = inspect_health_with(true, || Ok(readiness), || false, lookup, NOW).await; assert_eq!(health, ManagedTelemetryHealth::Disabled(reason)); assert!(!looked_up.load(std::sync::atomic::Ordering::SeqCst)); } @@ -590,7 +676,9 @@ mod tests { ]; for (result, expected) in cases { let (looked_up, lookup) = tracked_lookup(result); - let health = inspect_health_with(ReadinessState::Ready, lookup, NOW).await; + let health = + inspect_health_with(true, || Ok(ReadinessState::Ready), || false, lookup, NOW) + .await; assert_eq!(health, expected); assert!(looked_up.load(std::sync::atomic::Ordering::SeqCst)); } @@ -600,7 +688,9 @@ mod tests { async fn health_lookup_is_bounded_by_the_credential_lookup_deadline() { let started = std::time::Instant::now(); let health = inspect_health_with( - ReadinessState::Ready, + true, + || Ok(ReadinessState::Ready), + || false, std::future::pending::, TokenStorageError>>(), NOW, ) diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md index 942cdaca9..2f52c7bb6 100644 --- a/context/cli/access-policy.md +++ b/context/cli/access-policy.md @@ -4,7 +4,7 @@ This file describes how the CLI turns the per-layer `auth.mode` and `telemetry.enabled` config values into one effective access policy (`ResolvedAccessPolicy`). Key syntax and schema validation are in [config precedence contract](config-precedence-contract.md). The precedence model is recorded in [ADR: consent-gated access policy precedence](../decisions/2026-10-20-consent-gated-access-policy-precedence.md). -Status: the resolver computes and exposes the policy, and `sce config show` / `validate` report it (see [Reporting](#reporting)). Consumer enforcement (managed telemetry, the headers helper, auth commands, sync, auto-sync, setup) is not wired yet. Until it is, the policy has no runtime effect beyond what config inspection reports. +Status: the resolver computes and exposes the policy, and `sce config show` / `validate` report it (see [Reporting](#reporting)). Managed telemetry startup and `sce doctor`'s managed-telemetry health enforce the telemetry state (see [Enforcement](#enforcement)). The headers helper, auth commands, sync, auto-sync, and setup do not enforce the policy yet. ## Terms @@ -86,3 +86,8 @@ The note documents a coverage limit: telemetry opt-out does not remove Claude-na ## Exposure `ResolvedAuthRuntimeConfig`, `ResolvedHookRuntimeConfig`, and `ResolvedObservabilityRuntimeConfig` each carry `access_policy`, cloned from the same resolution that produced the rest of the projection. No consumer resolves config a second time to get the policy. + +## 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 the readiness hint is read, `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 the readiness hint file exists, but never reads it or touches `auth.db`. See [telemetry credential: doctor health check](../sce/telemetry-credential.md#doctor-health-check). diff --git a/context/context-map.md b/context/context-map.md index 463d14f04..d9e8d502a 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -25,7 +25,7 @@ Feature/domain context: - `context/cli/async-persistence-guarantees.md` (verified guarantees and named limits of the directly awaited Turso persistence migration — exclusive `&mut` transactions, deferred rollback, credential-rotation and terminal-sync behavior, lease/descriptor protection — plus PR1–PR4 staging and the PR3 cleanup ledger) - `context/cli/agent-trace-sync-command.md` (composed local-to-control-plane `sce sync` architecture: the `hooks/plugins → repository Agent Trace DB → AgentTraceExportReader → sce sync → HTTPS + WorkOS Bearer → control plane` data flow, the `sce auth login` / `cd ` / `sce sync` user flow, the no-local-cursor/no-`agent-trace-sync.db`/no-Turso-Sync/no-`BridgeLock`/no-local-DWH invariants, the four-local-capture-streams versus three-remote-streams boundary with its `diff_traces` release gate, the optional `commitPatchId` field on the existing `agent_traces` stream with its Control Plane release dependency and no-backfill limit, and `401`/`409`/ambiguous-batch-failure recovery semantics) - `context/cli/config-precedence-contract.md` (implemented `sce config` show/validate command contract, deterministic `flags > env > config file > defaults` resolution order, focused `config/resolver.rs` ownership for config discovery/merge/runtime precedence plus default-discovered invalid-file degradation, focused `config/render.rs` ownership for `show`/`validate` text+JSON output construction, canonical `$schema` acceptance for startup-loaded `sce/config.json` files, shared auth-key env/config/optional baked-default support starting with `workos_client_id`, shared runtime resolution for flat logging observability keys including config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` with `/sce/logs` defaulting plus config-file/default-only positive `log_file_retention_limit`, config-file-only `agent_trace.repository_id`/`agent_trace.repository_remote` repository-identity keys with default remote `origin`, `agent_trace.auto_sync` resolution with omitted-value fallback `false`, explicit-false opt-out, and setup-written explicit `true` bootstrap behavior for the post-commit trigger boundary, the catalog-derived `integrations.optional_workflows` optional-workflow selection key, schema-validated per-layer `auth.mode` / `telemetry.enabled` sections, JSON-pointer-prefixed schema-validation errors, canonical Pkl-generated `sce/config.json` schema ownership plus CLI embedding/reuse contract including `policies.attribution_hooks.enabled` default-true/explicit-false opt-out metadata, config-file selection order, `show` provenance output, and trimmed `validate` output contract) -- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, and exposure on the auth/hook/observability runtime projections; decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) +- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, exposure on the auth/hook/observability runtime projections, and enforcement in managed telemetry startup and `sce doctor` health (`disabled_by_config`); decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) - `context/cli/capability-traits.md` (current broad CLI capability seam in `cli/src/services/capabilities.rs`, including `FsOps`/`StdFsOps` (method-less marker), `GitOps`/`ProcessGitOps` (command execution and availability), compile-time-typed borrowed AppContext wiring with scoped borrowing across directly awaited commands with associated-type narrow capability accessors plus `ContextWithRepoRoot` repo-root-scoped context derivation, generic command execution bounds, and test-only unimplemented stubs; current service internals do not consume fs/git traits until later lifecycle migration tasks) - `context/cli/service-lifecycle.md` (current async lifecycle seam in `cli/src/services/lifecycle.rs`, including default no-op `ServiceLifecycle` diagnose/fix/setup methods against narrow `HasRepoRoot`, lifecycle-owned health/fix/setup result types with generic setup messages, doctor/setup adapter boundaries, the static `LifecycleProvider` enum catalog/dispatcher, hook/config/local_db/auth_db/agent_trace_db lifecycle providers including setup-time repository-scoped Agent Trace DB initialization plus checkout identity diagnostics, implemented doctor aggregation over diagnose/fix providers, and implemented setup aggregation over `setup` providers in order config → local_db → auth_db → agent_trace_db → hooks when requested) - `context/cli/mutation-trace-protocol.md` (pure, dependency-free `cli/src/services/mutation_trace/` refinement of the verified `spec/mutation_cursor.qnt` mutation-cursor protocol: the full pure action set — `prepare`/`commit` transition logic, attribution/mutation-event materialization, snapshot-failure/database-failure taint actions, scope abandonment, and recovery with an explicit observed-tree input — plus cross-action sequence/invariant tests and a module-level Quint refinement matrix are all complete (`types.rs`, `protocol.rs`, `mod.rs`, `tests.rs`, registered with `#[allow(dead_code)]`); opaque-newtype identity refinement decisions vs. the Quint model's bounded enums, and the `coordinator.rs` target end-state seam this layout leaves room for but does not create — `store.rs`, `runtime/git_snapshot.rs`, and `runtime/coordinator.rs` (including its public `coordinate()` entrypoint) now exist, built out by the `mutation-cursor-store-persistence` and `mutation-cursor-runtime-coordinator` plans respectively; `protocol.rs` is invoked only through the runtime, and the runtime is now driven by the generic `sce hooks mutation-scope` CLI ingress and a first Claude Code adapter driver, registered by `sce setup` and reachable by a real Claude Code session, now proven against real Git repositories and a real Agent Trace DB by the `claude-mutation-scope-integration` plan's T08 regressions) diff --git a/context/plans/auth-telemetry-policy-config.md b/context/plans/auth-telemetry-policy-config.md index c6fa88368..a26c597d7 100644 --- a/context/plans/auth-telemetry-policy-config.md +++ b/context/plans/auth-telemetry-policy-config.md @@ -311,13 +311,19 @@ Persist this field in every plan; this is durable plan state, not chat state: - Context impact: localized — `config show` and `config validate` output contract. `context/cli/config-precedence-contract.md` should document the new show text lines, the JSON `resolved.auth`/`resolved.telemetry` shape, the reason strings, and the fixed telemetry note. - Context synchronization: synced -- [ ] T04: `Gate managed telemetry startup and doctor health on telemetry policy` (status:todo) +- [x] T04: `Gate managed telemetry startup and doctor health on telemetry policy` (status:done) - Task ID: T04 - Scope: In — `TelemetryFallbackReason::DisabledByConfig` (`disabled_by_config`, non-failure, `debug` log); `RuntimeTelemetry::resolve` / `resolve_when_ready` taking the policy state and returning Noop before the readiness hint or lookup when not `Enabled`; `app.rs` passing the policy from `StartupContext` (the existing `resolve_observability_runtime_config` result); `inspect_health` / `inspect_health_with` and `doctor/managed_telemetry.rs` rendering `[PASS] Managed telemetry (disabled by config)` / JSON `disabled_by_config` plus the fixed opt-in line when a ready hint exists; multiprocess hook regression. Out — headers helper, login, sync. - Dependencies: T02 - Done when: with telemetry not `Enabled`, command and Claude-hook startup and doctor never call `telemetry_readiness` or the credential lookup; with telemetry `Enabled`, behavior and fallback reasons are unchanged. - Verify: unit tests with a lookup future that panics if polled and a readiness probe that fails if called; doctor JSON/text tests; multiprocess test in `auth_db/multiprocess_tests.rs` running a Claude hook via `app::run` with a seeded credential, ready hint, empty `SCE_AUTH_DB_ENCRYPTION_KEY`, and `telemetry.enabled: false`, asserting no exported spans; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_telemetry doctor multiprocess`. - - Context synchronization: pending + - Completed: 2026-10-20 + - Files changed: `cli/src/services/managed_telemetry.rs`, `cli/src/app.rs`, `cli/src/services/config/types.rs`, `cli/src/services/doctor/mod.rs`, `cli/src/services/doctor/managed_telemetry.rs`, `cli/src/services/doctor/render.rs`, `cli/src/services/doctor/types.rs`, `cli/src/app/doctor_reconciliation_cli_tests.rs`, `cli/src/services/auth_db/multiprocess_tests.rs`, `context/plans/auth-telemetry-policy-config.md` + - Result: Added `TelemetryFallbackReason::DisabledByConfig` (`disabled_by_config`, non-failure, logged at `debug`). `RuntimeTelemetry::resolve(span_kind, telemetry_enabled, logger)` and `resolve_when_ready(telemetry_enabled, ready_probe, lookup, span_kind)` now return Noop with `disabled_by_config` before the readiness probe closure runs or the lookup future is polled. `AppRuntime.telemetry_enabled` is taken from `StartupContext.observability_config.access_policy.telemetry_enabled()`. `inspect_health(telemetry_enabled)` / `inspect_health_with(telemetry_enabled, readiness_probe, hint_present, lookup, now)` return the new `ManagedTelemetryHealth::DisabledByConfig { readiness_hint_present }` before any readiness read or credential lookup. Hint presence is a file-existence check on `telemetry-ready.json` only; the file is not read. Doctor resolves the policy from the inspected repository root, and a resolution failure counts as not enabled. Text renders `[PASS] Managed telemetry (disabled by config)`, plus, when the hint file exists, the 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.` through a new `DoctorDisplayDetail::Note`, which renders even on PASS rows. JSON reports `state`/`reason` `disabled_by_config` with null kind, severity, and next_action, and no doctor problem. Removed `#[allow(dead_code)]` from `ResolvedObservabilityRuntimeConfig.access_policy` and `ResolvedAccessPolicy::telemetry_enabled`. The allow now sits only on `auth_allowed` and `auto_sync_allowed`. + - Verify outcome: `managed_telemetry` passed (42 passed, 0 failed), including new tests whose readiness probe panics if called and whose lookup panics if polled, for command and Claude-hook span kinds and for doctor health. `doctor` passed (34 passed, 0 failed), including render and JSON unit tests and a new CLI test, `doctor_with_telemetry_disabled_by_config_never_reads_the_auth_db`. That test covers a fresh state, then an unreadable `auth.db` plus a ready hint under default config, and checks that the auth DB and hint stay byte-identical and no warnings appear. `multiprocess` passed (18 passed, 0 failed), including the new `claude_hook_with_telemetry_disabled_by_config_never_resolves_the_credential`. Full CLI test suite passed (682 passed, 0 failed). `cargo clippy --all-targets -- -D warnings` via `run-cli-cargo.sh` passed. `cargo fmt` applied. + - Deviation: The managed endpoint is hard-coded and cannot be redirected to a loopback collector. The multiprocess regression therefore proves "no export" through the hook's debug log: with a seeded credential, ready hint, and empty encryption key, `telemetry.enabled: false` logs only fallback reason `disabled_by_config` (Noop telemetry, no lookup). The contrast run with `enabled: true` logs `database_error`, which shows the test detects a lookup. The auth DB stays byte-identical. The doctor opt-in line keys off hint-file presence rather than hint validity, so AC4's "never reads the readiness hint" still holds. Two existing doctor CLI tests now pass an explicit `telemetry.enabled: true` config, because the default policy disables telemetry. + - Context impact: localized — managed telemetry startup and doctor health contract. `context/sce/cli-observability-contract.md` should list the `disabled_by_config` fallback reason and the startup policy gate. `context/sce/telemetry-credential.md` should record the policy gate before the readiness hint and lookup. The doctor managed-telemetry output contract gains the `disabled_by_config` row, JSON state, and fixed opt-in line. + - Context synchronization: synced - [ ] T05: `Fail closed in the telemetry headers helper when telemetry is disabled` (status:todo) - Task ID: T05 diff --git a/context/sce/cli-observability-contract.md b/context/sce/cli-observability-contract.md index 89d95865d..ce6cc5318 100644 --- a/context/sce/cli-observability-contract.md +++ b/context/sce/cli-observability-contract.md @@ -50,7 +50,7 @@ Runtime observability consumes the shared resolved observability config from `cl - `sce.command.dispatch_start` (debug level - logged before dispatch) - `sce.command.dispatch_end` (debug level - logged after successful dispatch) - `sce.command.completed` - - `sce.telemetry.fallback` (`warn` for credential lookup failures, `debug` for a missing or expired credential - emitted once when managed telemetry resolution falls back to Noop after a lookup; fields `reason` and, for database or path errors, `error`) + - `sce.telemetry.fallback` (`warn` for credential lookup failures, `debug` for policy-disabled telemetry or a missing or expired credential - emitted once when managed telemetry resolution falls back to Noop after a lookup; fields `reason` and, for database or path errors, `error`) - Error logging uses the pattern `sce.error.{code}` where `{code}` is the classified error code (e.g., `sce.error.SCE-ERR-RUNTIME`). - All `CliError` instances are logged via `Logger::log_cli_error()` before user-facing stderr diagnostics are written; observability retains full technical detail independently of what is rendered to the terminal, and never writes a second competing stderr diagnostic for the same error. - Event records include deterministic metadata keys used by automation (`command`, `failure_class`, `component` when applicable). @@ -95,7 +95,7 @@ Runtime observability consumes the shared resolved observability config from `cl ## Managed trace export -- Defined in `cli/src/services/managed_telemetry.rs` and `cli/src/services/managed_telemetry/trace_export.rs` (plus `log_export.rs`). After startup, `RuntimeTelemetry::resolve` returns Noop (`not_configured`) without opening the auth DB unless the non-secret telemetry readiness hint is present ([telemetry-credential.md](telemetry-credential.md)). Otherwise it loads the stored telemetry credential from the encrypted auth DB, with non-interactive credential-store access, in a spawned task bounded by `CREDENTIAL_LOOKUP_DEADLINE` (2s); absent, expired, malformed, unavailable, ownerless (no stored WorkOS session), or timed-out credentials select `NoopTelemetry`. Startup never issues or refreshes a credential. The fallback is not silent: `RuntimeTelemetry::resolve` logs one `sce.telemetry.fallback` record with `reason` = `not_configured`, `credential_inaccessible`, `credential_unavailable`, `credential_expired`, `lookup_timeout`, `database_error`, `path_resolution_error`, or `exporter_init_failed`, at forced `warn` for failures and `debug` otherwise. Database and path errors add the redacted storage error text as `error`; no credential, bearer, key, or payload is logged, and the record never reaches stdout or, with `log_to_file=true`, stderr. +- Defined in `cli/src/services/managed_telemetry.rs` and `cli/src/services/managed_telemetry/trace_export.rs` (plus `log_export.rs`). After startup, `RuntimeTelemetry::resolve` returns Noop (`disabled_by_config`) before any hint or auth DB access when the effective access policy's telemetry state is not `Enabled` ([access-policy.md](../cli/access-policy.md)); otherwise it returns Noop (`not_configured`) without opening the auth DB unless the non-secret telemetry readiness hint is present ([telemetry-credential.md](telemetry-credential.md)). Otherwise it loads the stored telemetry credential from the encrypted auth DB, with non-interactive credential-store access, in a spawned task bounded by `CREDENTIAL_LOOKUP_DEADLINE` (2s); absent, expired, malformed, unavailable, ownerless (no stored WorkOS session), or timed-out credentials select `NoopTelemetry`. Startup never issues or refreshes a credential. The fallback is not silent: `RuntimeTelemetry::resolve` logs one `sce.telemetry.fallback` record with `reason` = `disabled_by_config`, `not_configured`, `credential_inaccessible`, `credential_unavailable`, `credential_expired`, `lookup_timeout`, `database_error`, `path_resolution_error`, or `exporter_init_failed`, at forced `warn` for failures and `debug` otherwise. Database and path errors add the redacted storage error text as `error`; no credential, bearer, key, or payload is logged, and the record never reaches stdout or, with `log_to_file=true`, stderr. - Admission (`managed_span_kind` in `cli/src/app.rs`, decided from argv before credential lookup): Claude-invoked SCE hooks resolve the `sce.hook` span kind, every other hook and the hidden `sce auth telemetry-headers` helper use `NoopTelemetry` without a credential lookup, and all remaining commands use the `sce.command` span kind. `sce hooks claude-mutation-scope` and `sce hooks claude-model-state` are admitted from argv alone. The shared `sce hooks diff-trace`, `sce hooks conversation-trace`, and `sce policy bash` are admitted only when both `CLAUDECODE` and `CLAUDE_PROJECT_DIR` are present in the environment (checked for presence only; values never read); `CLAUDE_PROJECT_DIR` is set for Claude command hooks but not for the Claude Bash tool (evidence: [claude-hook-trace-propagation.md](claude-hook-trace-propagation.md)). Other hooks (commit hooks, Codex, OpenCode, Pi) stay Noop. Admitted hooks use the same `CREDENTIAL_LOOKUP_DEADLINE`, `SHUTDOWN_TIMEOUT`, and runtime grace bounds as commands. Decision record: [2026-10-17-claude-hook-managed-trace-admission.md](../decisions/2026-10-17-claude-hook-managed-trace-admission.md). - Export is OTLP/HTTP protobuf to the hardcoded `https://otel.crocoderlab.dev/v1/traces`. A pinned HTTP client sets `Authorization: Bearer ` (token only, never the accessor), disables redirects, rebuilds the request to the fixed endpoint, and bounds requests to 3s. Ambient `OTEL_EXPORTER_OTLP_*` values cannot redirect it. - Each command emits one `sce.command` span with `sce.command.name`, `sce.outcome` (`success`/`failure`), and `sce.error.class` (the `SCE-ERR-*` code on failure); resource attributes are `service.name=sce` and `service.version`. Raw arguments, paths, and error chains are not exported. diff --git a/context/sce/telemetry-credential.md b/context/sce/telemetry-credential.md index 8226d690e..1eb4e9f23 100644 --- a/context/sce/telemetry-credential.md +++ b/context/sce/telemetry-credential.md @@ -34,19 +34,21 @@ flowchart LR ## Runtime use -- `managed_telemetry::RuntimeTelemetry::resolve` first checks the readiness hint. Without it, the result is Noop with reason `not_configured` (logged at `debug`), and the auth DB is not opened. With the hint, it reads the stored credential through the non-interactive credential-store path at CLI startup (never issuing one). If the store refuses silent access, the reason is `credential_inaccessible` (logged at `debug`, so a denied Keychain does not flood the log). `sce setup` is excluded from managed telemetry so that it never reaches the credential store. a valid unexpired `token` is used only as the `Authorization: Bearer` credential for managed OTLP trace and log export; the `accessor` is never transmitted. Absent, expired, malformed, or unavailable rows select `NoopTelemetry`. Every Noop fallback is classified (`not_configured`, `credential_inaccessible`, `credential_unavailable`, `credential_expired`, `lookup_timeout`, `database_error`, `path_resolution_error`, `exporter_init_failed`) and logged locally as `sce.telemetry.fallback`; failures log at `warn` (forced, so they reach the log file at the default `error` level, never stderr while `log_to_file=true`), with the redacted `TokenStorageError` text for database and path errors, and a missing hint, an inaccessible credential store, or missing or expired credentials log at `debug`. Concurrent lookups from many hook processes are supported by the auth DB's multiprocess WAL and migration-free current-schema open ([auth-db.md](auth-db.md)). Both this lookup and the header helper's repository lookup are existing-DB reads: a missing `auth.db` yields no credential and creates no DB file or encryption key. Claude-invoked SCE hooks are admitted to this lookup and export one `sce.hook` span. Every other hook and this hidden header helper skip the lookup and stay Noop. See [cli-observability-contract.md](cli-observability-contract.md). +- `managed_telemetry::RuntimeTelemetry::resolve` first checks the effective access policy ([access-policy.md](../cli/access-policy.md)). When telemetry is not `Enabled`, the result is Noop with reason `disabled_by_config` (logged at `debug`), and neither the readiness hint, `auth.db`, nor the credential store is touched. Otherwise it checks the readiness hint. Without it, the result is Noop with reason `not_configured` (logged at `debug`), and the auth DB is not opened. With the hint, it reads the stored credential through the non-interactive credential-store path at CLI startup (never issuing one). If the store refuses silent access, the reason is `credential_inaccessible` (logged at `debug`, so a denied Keychain does not flood the log). `sce setup` is excluded from managed telemetry so that it never reaches the credential store. a valid unexpired `token` is used only as the `Authorization: Bearer` credential for managed OTLP trace and log export; the `accessor` is never transmitted. Absent, expired, malformed, or unavailable rows select `NoopTelemetry`. Every Noop fallback is classified (`disabled_by_config`, `not_configured`, `credential_inaccessible`, `credential_unavailable`, `credential_expired`, `lookup_timeout`, `database_error`, `path_resolution_error`, `exporter_init_failed`) and logged locally as `sce.telemetry.fallback`; failures log at `warn` (forced, so they reach the log file at the default `error` level, never stderr while `log_to_file=true`), with the redacted `TokenStorageError` text for database and path errors, and policy-disabled telemetry, a missing hint, an inaccessible credential store, or missing or expired credentials log at `debug`. Concurrent lookups from many hook processes are supported by the auth DB's multiprocess WAL and migration-free current-schema open ([auth-db.md](auth-db.md)). Both this lookup and the header helper's repository lookup are existing-DB reads: a missing `auth.db` yields no credential and creates no DB file or encryption key. Claude-invoked SCE hooks are admitted to this lookup and export one `sce.hook` span. Every other hook and this hidden header helper skip the lookup and stay Noop. See [cli-observability-contract.md](cli-observability-contract.md). ## 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: - It never issues a credential, contacts the Control Plane, or starts an OTLP exporter. -- It reads the readiness hint first. `NotConfigured` and `Expired` hints return without opening `auth.db` or touching the credential store, so a fresh install never reaches the Keychain. +- 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` without reading the readiness hint, opening `auth.db`, or touching the credential store. It only checks whether `telemetry-ready.json` exists, to decide on the opt-in line. +- Otherwise it reads the readiness hint. `NotConfigured` and `Expired` hints return without opening `auth.db` or touching the credential store, so a fresh install never reaches the Keychain. - With a `Ready` hint it runs the runtime lookup: `load_telemetry_credential` (existing DB only, `CredentialAccess::NonInteractive`) under `CREDENTIAL_LOOKUP_DEADLINE`. Errors are classified by the same `TelemetryFallbackReason` mapping the runtime uses. - `--fix` adds no repair for it. The problem is `manual_only`, so fix mode reports one `manual` fix result. Doctor never runs `sce auth login`, changes Keychain ACLs, or recreates a key. | 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 hint or no `auth.db` | `[PASS] Managed telemetry (not configured)` | `not_configured` / `not_configured` | none | none | | Credential valid | `[PASS] Managed telemetry` | `healthy` / `null` | none | none | | Store refuses silent access | `[WARN]` | `disabled` / `credential_inaccessible` | `managed_telemetry_credential_inaccessible` | `auth_login` | @@ -58,6 +60,7 @@ 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 `telemetry-ready.json` exists (an earlier login provisioned telemetry), 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.` - 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`). From 851ea53e23c03a7fd9b4a069ca8b40c67f398e42 Mon Sep 17 00:00:00 2001 From: David Abram Date: Tue, 20 Oct 2026 14:39:16 +0200 Subject: [PATCH 5/9] auth: Gate telemetry headers on effective access policy Prevent the hidden telemetry header helper from reading readiness or resolving repository credentials when the effective policy disables telemetry. Resolve the auth runtime config from the working directory, make readiness probing lazy, and cover disabled and invalid-config behavior in unit and multiprocess tests. Plan: auth-telemetry-policy-config (T05) Co-authored-by: SCE --- cli/src/app.rs | 3 +- cli/src/services/auth_command/mod.rs | 171 ++++++++++++++---- .../services/auth_db/multiprocess_tests.rs | 29 ++- cli/src/services/config/types.rs | 1 - .../services/telemetry_credential_storage.rs | 3 +- context/cli/access-policy.md | 3 +- context/context-map.md | 2 +- context/overview.md | 2 +- context/plans/auth-telemetry-policy-config.md | 30 ++- context/sce/telemetry-credential.md | 1 + 10 files changed, 196 insertions(+), 49 deletions(-) diff --git a/cli/src/app.rs b/cli/src/app.rs index 7430d742a..00f749123 100644 --- a/cli/src/app.rs +++ b/cli/src/app.rs @@ -986,8 +986,9 @@ pub(crate) mod tests { let runtime = build_runtime().unwrap(); let result = runtime.block_on(services::auth_command::telemetry_headers_with( Some(repo.path().to_path_buf()), - false, true, + false, + || true, |_: &std::path::Path| Some("repository-a".to_string()), |_: String| stalled_keychain_lookup(), )); diff --git a/cli/src/services/auth_command/mod.rs b/cli/src/services/auth_command/mod.rs index 384fc9643..6f2527982 100644 --- a/cli/src/services/auth_command/mod.rs +++ b/cli/src/services/auth_command/mod.rs @@ -105,24 +105,34 @@ where } async fn run_telemetry_headers() -> Result { + let working_dir = std::env::current_dir().ok(); + let telemetry_enabled = working_dir.as_deref().is_some_and(telemetry_enabled_for); telemetry_headers_with( - std::env::current_dir().ok(), + working_dir, + telemetry_enabled, visible_destination_conflict(|key| std::env::var(key).ok()), - telemetry_readiness::is_ready(current_unix_seconds()), + || telemetry_readiness::is_ready(current_unix_seconds()), repository_id_for, telemetry_credential_storage::load_repository_telemetry_credential, ) .await } -pub(crate) async fn telemetry_headers_with( +fn telemetry_enabled_for(working_dir: &Path) -> bool { + config::resolve_auth_runtime_config(working_dir) + .is_ok_and(|config| config.access_policy.telemetry_enabled()) +} + +pub(crate) async fn telemetry_headers_with( working_dir: Option, + telemetry_enabled: bool, destination_conflict: bool, - ready: bool, + ready_probe: P, resolve_repository: R, lookup: L, ) -> Result where + P: FnOnce() -> bool, R: FnOnce(&Path) -> Option + Send + 'static, L: FnOnce(String) -> Fut + Send + 'static, Fut: Future< @@ -133,7 +143,10 @@ where > + Send + 'static, { - let Some(working_dir) = working_dir.filter(|_| ready && !destination_conflict) else { + if !telemetry_enabled || destination_conflict { + return Err(telemetry_headers_unavailable()); + } + let Some(working_dir) = working_dir.filter(|_| ready_probe()) else { return Err(telemetry_headers_unavailable()); }; let credential = run_with_deadline(CREDENTIAL_LOOKUP_DEADLINE, async move { @@ -877,48 +890,93 @@ mod tests { #[tokio::test] async fn telemetry_headers_fail_closed_before_lookup_without_repository_or_on_conflict() { - let lookup_called = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let lookup = |called: std::sync::Arc| { - move |_repository_id: String| async move { - called.store(true, std::sync::atomic::Ordering::SeqCst); - Ok(Some(telemetry_credential("tok-scoped"))) - } - }; - let working_dir = Some(PathBuf::from("/workspace/repo")); + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Arc; - let error = telemetry_headers_with( - working_dir.clone(), - false, - false, - |_: &Path| Some("repo-a".to_string()), - lookup(std::sync::Arc::clone(&lookup_called)), - ) - .await - .expect_err("helper must fail closed without telemetry readiness"); - assert_eq!(error.to_string(), TELEMETRY_HEADERS_UNAVAILABLE); - - for (dir, conflict, repository) in [ - (working_dir.clone(), true, Some("repo-a")), - (None, false, Some("repo-a")), - (working_dir.clone(), false, None), - ] { + let working_dir = Some(PathBuf::from("/workspace/repo")); + let cases = [ + ( + "policy disabled", + working_dir.clone(), + false, + false, + true, + Some("repo-a"), + ), + ( + "not ready", + working_dir.clone(), + true, + false, + false, + Some("repo-a"), + ), + ( + "destination conflict", + working_dir.clone(), + true, + true, + true, + Some("repo-a"), + ), + ("no working dir", None, true, false, true, Some("repo-a")), + ( + "no repository", + working_dir.clone(), + true, + false, + true, + None, + ), + ]; + for (case, dir, telemetry_enabled, conflict, ready, repository) in cases { + let probed = Arc::new(AtomicBool::new(false)); + let resolved = Arc::new(AtomicBool::new(false)); + let looked_up = Arc::new(AtomicBool::new(false)); let error = telemetry_headers_with( dir, + telemetry_enabled, conflict, - true, - move |_: &Path| repository.map(str::to_string), - lookup(std::sync::Arc::clone(&lookup_called)), + { + let probed = Arc::clone(&probed); + move || { + probed.store(true, Ordering::SeqCst); + ready + } + }, + { + let resolved = Arc::clone(&resolved); + move |_: &Path| { + resolved.store(true, Ordering::SeqCst); + repository.map(str::to_string) + } + }, + { + let looked_up = Arc::clone(&looked_up); + move |_repository_id: String| async move { + looked_up.store(true, Ordering::SeqCst); + Ok(Some(telemetry_credential("tok-scoped"))) + } + }, ) .await - .expect_err("helper must fail closed"); - assert_eq!(error.to_string(), TELEMETRY_HEADERS_UNAVAILABLE); + .expect_err(case); + assert_eq!(error.to_string(), TELEMETRY_HEADERS_UNAVAILABLE, "{case}"); + assert!(!looked_up.load(Ordering::SeqCst), "{case}: lookup ran"); + if !telemetry_enabled { + assert!(!probed.load(Ordering::SeqCst), "{case}: readiness probed"); + assert!( + !resolved.load(Ordering::SeqCst), + "{case}: repository resolved" + ); + } } - assert!(!lookup_called.load(std::sync::atomic::Ordering::SeqCst)); let headers = telemetry_headers_with( working_dir, - false, true, + false, + || true, |dir: &Path| (dir == Path::new("/workspace/repo")).then(|| "repo-a".to_string()), |repository_id: String| async move { assert_eq!(repository_id, "repo-a"); @@ -930,6 +988,47 @@ mod tests { assert_eq!(headers, r#"{"Authorization":"Bearer tok-scoped"}"#); } + #[test] + fn telemetry_headers_policy_follows_auth_and_invalid_config() { + let dir = tempfile::tempdir().unwrap(); + let global = dir.path().join("global.json"); + let local_dir = dir.path().join(".sce"); + std::fs::create_dir_all(&local_dir).unwrap(); + let local = local_dir.join("config.json"); + let enabled = |global_json: &str, local_json: Option<&str>| { + std::fs::write(&global, global_json).unwrap(); + match local_json { + Some(json) => std::fs::write(&local, json).unwrap(), + None => { + let _ = std::fs::remove_file(&local); + } + } + config::resolver::resolve_auth_runtime_config_with( + dir.path(), + |_| None, + |path| std::fs::read_to_string(path).map_err(anyhow::Error::from), + Path::exists, + || Ok(global.clone()), + ) + .is_ok_and(|config| config.access_policy.telemetry_enabled()) + }; + + assert!(enabled(r#"{"telemetry":{"enabled":true}}"#, None)); + assert!(!enabled("{}", None)); + assert!(!enabled( + r#"{"telemetry":{"enabled":true},"auth":{"mode":"disabled"}}"#, + None + )); + assert!(!enabled( + r#"{"telemetry":{"enabled":true}}"#, + Some(r#"{"auth":{"mode":"disabled"}}"#) + )); + assert!(!enabled( + r#"{"telemetry":{"enabled":true}}"#, + Some(r#"{"telemetry":{"enabled":"yes"}}"#) + )); + } + #[test] fn telemetry_headers_failures_use_fixed_secret_free_diagnostic() { let missing = render_telemetry_headers(Ok(None)).expect_err("missing should fail"); diff --git a/cli/src/services/auth_db/multiprocess_tests.rs b/cli/src/services/auth_db/multiprocess_tests.rs index 630cf91bb..5be0143db 100644 --- a/cli/src/services/auth_db/multiprocess_tests.rs +++ b/cli/src/services/auth_db/multiprocess_tests.rs @@ -546,8 +546,9 @@ fn concurrent_telemetry_headers_on_missing_auth_db_fail_closed_without_creating_ "https://github.com/acme/bound-repo", ); + let config = headers_policy_config(&sandbox, true); let helpers = (0..CONCURRENT_PROCESSES) - .map(|_| spawn_headers(&sandbox, &repository)) + .map(|_| spawn_headers(&sandbox, &repository, &config)) .collect::>(); for helper in helpers { assert_headers_unavailable(helper); @@ -574,17 +575,35 @@ fn telemetry_headers_serve_only_the_bound_repository() { bind.current_dir(&bound); wait_success("bind", bind.spawn().expect("spawn bind")); - let output = spawn_headers(&sandbox, &bound) + let enabled = headers_policy_config(&sandbox, true); + let disabled = headers_policy_config(&sandbox, false); + let output = spawn_headers(&sandbox, &bound, &enabled) .wait_with_output() .expect("bound headers output"); assert!(output.status.success(), "bound headers failed"); assert!(String::from_utf8_lossy(&output.stdout).contains(HEADERS_AUTHORIZATION)); - assert_headers_unavailable(spawn_headers(&sandbox, &unbound)); + assert_headers_unavailable(spawn_headers(&sandbox, &unbound, &enabled)); + assert_headers_unavailable(spawn_headers(&sandbox, &bound, &disabled)); } -fn spawn_headers(sandbox: &Sandbox, repository: &Path) -> Child { +fn headers_policy_config(sandbox: &Sandbox, telemetry_enabled: bool) -> PathBuf { + let config = sandbox + .dir + .path() + .join(format!("headers-policy-{telemetry_enabled}.json")); + std::fs::write( + &config, + serde_json::json!({ "telemetry": { "enabled": telemetry_enabled } }).to_string(), + ) + .expect("headers policy config"); + config +} + +fn spawn_headers(sandbox: &Sandbox, repository: &Path, config: &Path) -> Child { let mut helper = sandbox.command("headers"); - helper.current_dir(repository); + helper + .current_dir(repository) + .env("SCE_CONFIG_FILE", config); helper.spawn().expect("spawn headers") } diff --git a/cli/src/services/config/types.rs b/cli/src/services/config/types.rs index 0fe095cfb..750c627b6 100644 --- a/cli/src/services/config/types.rs +++ b/cli/src/services/config/types.rs @@ -287,7 +287,6 @@ pub(crate) struct LoadedConfigPath { pub(crate) struct ResolvedAuthRuntimeConfig { pub(crate) workos_client_id: ResolvedOptionalValue, pub(crate) control_plane_base_url: ResolvedOptionalValue, - #[allow(dead_code)] pub(crate) access_policy: ResolvedAccessPolicy, } diff --git a/cli/src/services/telemetry_credential_storage.rs b/cli/src/services/telemetry_credential_storage.rs index 557cdd04d..1d1afeeee 100644 --- a/cli/src/services/telemetry_credential_storage.rs +++ b/cli/src/services/telemetry_credential_storage.rs @@ -916,8 +916,9 @@ mod tests { let headers_for = |working_dir: std::path::PathBuf| { telemetry_headers_with( Some(working_dir), - visible_destination_conflict(claude_helper_env), true, + visible_destination_conflict(claude_helper_env), + || true, repository_id_for, |repository_id: String| async move { let db = TestDb::new() diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md index 2f52c7bb6..a34c25232 100644 --- a/context/cli/access-policy.md +++ b/context/cli/access-policy.md @@ -4,7 +4,7 @@ This file describes how the CLI turns the per-layer `auth.mode` and `telemetry.enabled` config values into one effective access policy (`ResolvedAccessPolicy`). Key syntax and schema validation are in [config precedence contract](config-precedence-contract.md). The precedence model is recorded in [ADR: consent-gated access policy precedence](../decisions/2026-10-20-consent-gated-access-policy-precedence.md). -Status: the resolver computes and exposes the policy, and `sce config show` / `validate` report it (see [Reporting](#reporting)). Managed telemetry startup and `sce doctor`'s managed-telemetry health enforce the telemetry state (see [Enforcement](#enforcement)). The headers helper, auth commands, sync, auto-sync, and setup do not enforce the policy yet. +Status: the resolver computes and exposes the policy, and `sce config show` / `validate` report it (see [Reporting](#reporting)). Managed telemetry startup, `sce doctor`'s managed-telemetry health, and the hidden `sce auth telemetry-headers` helper enforce the telemetry state (see [Enforcement](#enforcement)). Auth commands, sync, auto-sync, and setup do not enforce the policy yet. ## Terms @@ -91,3 +91,4 @@ The note documents a coverage limit: telemetry opt-out does not remove Claude-na - **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 the readiness hint is read, `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 the readiness hint file exists, but never reads it or touches `auth.db`. See [telemetry credential: doctor health check](../sce/telemetry-credential.md#doctor-health-check). +- **`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 readiness hint, repository resolution, and the `auth.db` lookup. See [telemetry credential: hidden header helper](../sce/telemetry-credential.md#hidden-header-helper). diff --git a/context/context-map.md b/context/context-map.md index d9e8d502a..0a1d261e2 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -25,7 +25,7 @@ Feature/domain context: - `context/cli/async-persistence-guarantees.md` (verified guarantees and named limits of the directly awaited Turso persistence migration — exclusive `&mut` transactions, deferred rollback, credential-rotation and terminal-sync behavior, lease/descriptor protection — plus PR1–PR4 staging and the PR3 cleanup ledger) - `context/cli/agent-trace-sync-command.md` (composed local-to-control-plane `sce sync` architecture: the `hooks/plugins → repository Agent Trace DB → AgentTraceExportReader → sce sync → HTTPS + WorkOS Bearer → control plane` data flow, the `sce auth login` / `cd ` / `sce sync` user flow, the no-local-cursor/no-`agent-trace-sync.db`/no-Turso-Sync/no-`BridgeLock`/no-local-DWH invariants, the four-local-capture-streams versus three-remote-streams boundary with its `diff_traces` release gate, the optional `commitPatchId` field on the existing `agent_traces` stream with its Control Plane release dependency and no-backfill limit, and `401`/`409`/ambiguous-batch-failure recovery semantics) - `context/cli/config-precedence-contract.md` (implemented `sce config` show/validate command contract, deterministic `flags > env > config file > defaults` resolution order, focused `config/resolver.rs` ownership for config discovery/merge/runtime precedence plus default-discovered invalid-file degradation, focused `config/render.rs` ownership for `show`/`validate` text+JSON output construction, canonical `$schema` acceptance for startup-loaded `sce/config.json` files, shared auth-key env/config/optional baked-default support starting with `workos_client_id`, shared runtime resolution for flat logging observability keys including config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` with `/sce/logs` defaulting plus config-file/default-only positive `log_file_retention_limit`, config-file-only `agent_trace.repository_id`/`agent_trace.repository_remote` repository-identity keys with default remote `origin`, `agent_trace.auto_sync` resolution with omitted-value fallback `false`, explicit-false opt-out, and setup-written explicit `true` bootstrap behavior for the post-commit trigger boundary, the catalog-derived `integrations.optional_workflows` optional-workflow selection key, schema-validated per-layer `auth.mode` / `telemetry.enabled` sections, JSON-pointer-prefixed schema-validation errors, canonical Pkl-generated `sce/config.json` schema ownership plus CLI embedding/reuse contract including `policies.attribution_hooks.enabled` default-true/explicit-false opt-out metadata, config-file selection order, `show` provenance output, and trimmed `validate` output contract) -- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, exposure on the auth/hook/observability runtime projections, and enforcement in managed telemetry startup and `sce doctor` health (`disabled_by_config`); decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) +- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, exposure on the auth/hook/observability runtime projections, and enforcement in managed telemetry startup, `sce doctor` health (`disabled_by_config`), and the hidden `sce auth telemetry-headers` helper (fail closed before readiness, repository resolution, and `auth.db`); decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) - `context/cli/capability-traits.md` (current broad CLI capability seam in `cli/src/services/capabilities.rs`, including `FsOps`/`StdFsOps` (method-less marker), `GitOps`/`ProcessGitOps` (command execution and availability), compile-time-typed borrowed AppContext wiring with scoped borrowing across directly awaited commands with associated-type narrow capability accessors plus `ContextWithRepoRoot` repo-root-scoped context derivation, generic command execution bounds, and test-only unimplemented stubs; current service internals do not consume fs/git traits until later lifecycle migration tasks) - `context/cli/service-lifecycle.md` (current async lifecycle seam in `cli/src/services/lifecycle.rs`, including default no-op `ServiceLifecycle` diagnose/fix/setup methods against narrow `HasRepoRoot`, lifecycle-owned health/fix/setup result types with generic setup messages, doctor/setup adapter boundaries, the static `LifecycleProvider` enum catalog/dispatcher, hook/config/local_db/auth_db/agent_trace_db lifecycle providers including setup-time repository-scoped Agent Trace DB initialization plus checkout identity diagnostics, implemented doctor aggregation over diagnose/fix providers, and implemented setup aggregation over `setup` providers in order config → local_db → auth_db → agent_trace_db → hooks when requested) - `context/cli/mutation-trace-protocol.md` (pure, dependency-free `cli/src/services/mutation_trace/` refinement of the verified `spec/mutation_cursor.qnt` mutation-cursor protocol: the full pure action set — `prepare`/`commit` transition logic, attribution/mutation-event materialization, snapshot-failure/database-failure taint actions, scope abandonment, and recovery with an explicit observed-tree input — plus cross-action sequence/invariant tests and a module-level Quint refinement matrix are all complete (`types.rs`, `protocol.rs`, `mod.rs`, `tests.rs`, registered with `#[allow(dead_code)]`); opaque-newtype identity refinement decisions vs. the Quint model's bounded enums, and the `coordinator.rs` target end-state seam this layout leaves room for but does not create — `store.rs`, `runtime/git_snapshot.rs`, and `runtime/coordinator.rs` (including its public `coordinate()` entrypoint) now exist, built out by the `mutation-cursor-store-persistence` and `mutation-cursor-runtime-coordinator` plans respectively; `protocol.rs` is invoked only through the runtime, and the runtime is now driven by the generic `sce hooks mutation-scope` CLI ingress and a first Claude Code adapter driver, registered by `sce setup` and reachable by a real Claude Code session, now proven against real Git repositories and a real Agent Trace DB by the `claude-mutation-scope-integration` plan's T08 regressions) diff --git a/context/overview.md b/context/overview.md index cef3d0f8b..686cf50a3 100644 --- a/context/overview.md +++ b/context/overview.md @@ -65,7 +65,7 @@ Its command loop is implemented with `clap` derive-based argument parsing and `a The current doctor presentation contract supersedes the earlier output-shape scaffolding wording above: human text uses the compact Environment/Repository/Integrations hierarchy with healthy rows collapsed and unhealthy branches expanded, while JSON retains complete path, identity, problem, and fix-result detail. See `context/sce/doctor-human-text-contract.md`. The command loop now enforces a stable exit-code contract in `cli/src/app.rs`: `2` parse failures, `3` invocation validation failures, `4` runtime failures, and `5` dependency startup failures. Auth command orchestration routes authenticated Control Plane authentication failures, token-storage failures, and approved user-facing fallback failures through typed `CliError::User` catalog entries (`NotAuthenticated`, `AuthStorageUnavailable`, `NotGitRepository`, and `UnexpectedFailure`) while retaining technical sources for observability; missing-credential logout/whoami state queries succeed with their documented text/JSON reports, and internal auth failures remain runtime errors. The same runtime also emits stable CLI stderr diagnostics: internal failures use `SCE-ERR-PARSE`, `SCE-ERR-VALIDATION`, `SCE-ERR-RUNTIME`, or `SCE-ERR-DEPENDENCY` in deterministic `Error []: ...` diagnostics with class-default `Try:` remediation appended when missing, while expected failures emit only their redacted, unstyled catalog messages. The command boundary's former flat, string-only `ClassifiedError` has been replaced by typed `CliError` in `cli/src/services/error.rs`: `CliError::User` carries a closed catalog (`NotAuthenticated`, `NotGitRepository`, `NotGitRemote`, authentication-storage `AuthStorageUnavailable`, and general `UnexpectedFailure`) for expected, deliberately-explained failures rendered without the technical source, wrapper, styling, or automatic `Try:` guidance; the general entry renders one fixed static log-files guidance sentence without dynamic path text. `CliError::Internal` carries a live `anyhow::Error` source rendered as the real error chain with the existing styled wrapper and class-default remediation; `app_support` is the sole owner of the distinct terminal paths, and `sce sync` classifies authentication, credential-storage, and all other sync failures as cataloged user errors while preserving their technical sources for observability. Setup preflight errors preserve technical sources, including the configured remote name, while raw remote URLs remain out of user-facing diagnostics. See `context/sce/cli-error-code-taxonomy.md` for the full contract. -The app runtime now also includes a structured observability baseline in `cli/src/services/observability.rs`: deterministic env-controlled log threshold/format (`SCE_LOG_LEVEL` defaults to `error`; `SCE_LOG_FORMAT` defaults to `text`), default-backed log-directory routing (`SCE_LOG_DIR` / config-file `log_dir` / `/sce/logs`) with per-operation machine-local dated file selection, optional session filename partitioning, and creation-triggered retention of direct regular `*.log` files to 10 entries, stable lifecycle event IDs, normal logger records routed only to files when file logging is enabled and only error-level logger records routed to `stderr` when file logging is disabled, direct file-write diagnostics remaining on `stderr`, and `observability::traits` boundaries for logger and telemetry behavior. When the encrypted auth DB holds a valid unexpired telemetry credential, commands also export `sce.command` spans (Claude-invoked SCE hooks export one root `sce.hook` span instead, with `sce.mutation_scope`/`sce.git_snapshot`/`sce.persistence` children only for operations that ran; other hooks export nothing) and allowlisted logger events as OTLP/HTTP protobuf to the hardcoded `https://otel.crocoderlab.dev` `/v1/traces` and `/v1/logs` paths (bearer token only, redirects disabled, ambient `OTEL_EXPORTER_OTLP_*` and repo config cannot redirect it, fail-open and bounded); without a credential nothing is exported, and `/v1/metrics` is reserved with no metrics pipeline. +The app runtime now also includes a structured observability baseline in `cli/src/services/observability.rs`: deterministic env-controlled log threshold/format (`SCE_LOG_LEVEL` defaults to `error`; `SCE_LOG_FORMAT` defaults to `text`), default-backed log-directory routing (`SCE_LOG_DIR` / config-file `log_dir` / `/sce/logs`) with per-operation machine-local dated file selection, optional session filename partitioning, and creation-triggered retention of direct regular `*.log` files to 10 entries, stable lifecycle event IDs, normal logger records routed only to files when file logging is enabled and only error-level logger records routed to `stderr` when file logging is disabled, direct file-write diagnostics remaining on `stderr`, and `observability::traits` boundaries for logger and telemetry behavior. When the effective access policy enables telemetry (`telemetry.enabled`, see `context/cli/access-policy.md`) and the encrypted auth DB holds a valid unexpired telemetry credential, commands also export `sce.command` spans (Claude-invoked SCE hooks export one root `sce.hook` span instead, with `sce.mutation_scope`/`sce.git_snapshot`/`sce.persistence` children only for operations that ran; other hooks export nothing) and allowlisted logger events as OTLP/HTTP protobuf to the hardcoded `https://otel.crocoderlab.dev` `/v1/traces` and `/v1/logs` paths (bearer token only, redirects disabled, ambient `OTEL_EXPORTER_OTLP_*` and repo config cannot redirect it, fail-open and bounded); with telemetry not enabled by policy or without a credential nothing is exported, and `/v1/metrics` is reserved with no metrics pipeline. One application-level multi-thread Tokio runtime directly awaits static command dispatch through async credentials, lifecycle providers, hooks, sync/export, and Turso persistence. The shared Turso adapters own no runtime or executor bridge, and foreground hooks return after required persistence completes. See [application execution runtime](architecture.md#application-execution-runtime). The app command dispatcher now enforces a centralized stdout/stderr stream contract in `cli/src/app.rs`: command success payloads are emitted on stdout only, while redacted user-facing diagnostics and text-mode sync progress are emitted on stderr; JSON sync remains silent. `cli/src/app.rs` also now runs through explicit startup phases — dependency check, observability config resolution, runtime initialization, command parse/execute, and output rendering — with the app runtime carrying logger/telemetry plus static command-catalog state across those phases while preserving the existing exit-code and degraded-startup contracts. Within that lifecycle, `parse_command_phase` delegates clap-to-runtime conversion to `cli/src/services/parse/command_runtime.rs`, which returns a static `RuntimeCommand` enum, `services::app_support::execute_command_phase` logs around enum-owned `execute_with_stderr(...)` dispatch, and generic `RunOutcome` rendering logs classified errors through the logger trait boundary without coupling render support to the production logger type. Command payload structs for `help`, `version`, `completion`, `auth`, `config`, `setup`, `doctor`, `hooks`, and `sync` live in service-owned `command.rs` files; `cli/src/services/command_registry.rs` owns the deterministic static command-name catalog and enum variants instead of boxed command trait objects. The CLI now also enforces a shared output-format parser contract in `cli/src/services/output_format.rs`, with canonical `--format ` parsing and command-specific actionable invalid-value guidance reused by `config` and `version` services. A compile-safe service lifecycle seam also exists in `cli/src/services/lifecycle.rs`: `ServiceLifecycle` exposes default no-op `diagnose`, `fix`, and `setup` methods against the narrow `HasRepoRoot` accessor, uses lifecycle-owned health/fix/setup result types, and owns the shared static `LifecycleProvider` enum catalog/factory with deterministic config → local*db → auth_db → agent_trace_db → hooks ordering and no boxed provider aggregation. Hooks has a `services/hooks/lifecycle.rs` provider for hook rollout diagnosis/fix/setup, config has a `services/config/lifecycle.rs` provider for global/repo-local config validation plus repo-local config bootstrap, local_db has a `services/local_db/lifecycle.rs` provider for canonical local DB path health, parent-directory readiness/bootstrap, and `LocalDb::new()` setup, auth_db has a `services/auth_db/lifecycle.rs` provider for canonical auth DB path health, parent-directory readiness/bootstrap, and `AuthDb::new()` setup, and agent_trace_db has a `services/agent_trace_db/lifecycle.rs` provider for repository-scoped Agent Trace DB setup and repository DB path health/parent readiness from resolved repository identity, returning an actionable "requires a Git repository" diagnostic outside repository context (no global/checkout fallback path). Doctor runtime aggregates the full shared provider catalog for `diagnose` and `fix` and adapts lifecycle records into doctor-owned output records; setup command aggregates the shared provider catalog for `setup` with hooks included only when requested and adapts lifecycle setup outcomes before rendering setup-owned messages. diff --git a/context/plans/auth-telemetry-policy-config.md b/context/plans/auth-telemetry-policy-config.md index a26c597d7..a50c203cd 100644 --- a/context/plans/auth-telemetry-policy-config.md +++ b/context/plans/auth-telemetry-policy-config.md @@ -325,13 +325,39 @@ Persist this field in every plan; this is durable plan state, not chat state: - Context impact: localized — managed telemetry startup and doctor health contract. `context/sce/cli-observability-contract.md` should list the `disabled_by_config` fallback reason and the startup policy gate. `context/sce/telemetry-credential.md` should record the policy gate before the readiness hint and lookup. The doctor managed-telemetry output contract gains the `disabled_by_config` row, JSON state, and fixed opt-in line. - Context synchronization: synced -- [ ] T05: `Fail closed in the telemetry headers helper when telemetry is disabled` (status:todo) +- [x] T05: `Fail closed in the telemetry headers helper when telemetry is disabled` (status:done) - Task ID: T05 - Scope: In — `auth_command::run_telemetry_headers` resolving the policy from the working directory and `telemetry_headers_with` taking a `telemetry_enabled` input checked before readiness, repository resolution, and lookup. Out — Claude settings changes. - Dependencies: T02 - Done when: telemetry not `Enabled` (including `auth.mode: disabled` and invalid discovered config) yields the existing fixed `Telemetry credential is unavailable.` with empty stdout, without calling the repository resolver or lookup; enabled behavior is unchanged. - Verify: extend `telemetry_headers_fail_closed_before_lookup_without_repository_or_on_conflict` into a table including the policy-disabled row with resolver/lookup closures that fail if called; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml telemetry_headers`. - - Context synchronization: pending + - Completed: 2026-10-20 + - Files changed: `cli/src/services/auth_command/mod.rs`, `cli/src/services/config/types.rs`, `cli/src/app.rs`, `cli/src/services/telemetry_credential_storage.rs`, `cli/src/services/auth_db/multiprocess_tests.rs`, `context/plans/auth-telemetry-policy-config.md` + - Result: + - `run_telemetry_headers` resolves the policy from the current directory through `config::resolve_auth_runtime_config`. A missing working directory or a resolution failure counts as not enabled. + - `telemetry_headers_with(working_dir, telemetry_enabled, destination_conflict, ready_probe, resolve_repository, lookup)` checks `telemetry_enabled` (and the destination conflict) first. It then checks the working directory, then runs the readiness probe, then calls the repository resolver and the lookup. + - Readiness is now a lazy `FnOnce() -> bool` probe, so `telemetry-ready.json` is never read when the policy is off. + - The failure path still returns the fixed `Telemetry credential is unavailable.` runtime error, with empty stdout. + - Removed `#[allow(dead_code)]` from `ResolvedAuthRuntimeConfig.access_policy`. + - Updated the existing call sites in the app stall test and the storage headers test to pass `telemetry_enabled = true` and `|| true`. + - Verify outcome: + - `telemetry_headers` passed (11 passed, 0 failed). The rewritten `telemetry_headers_fail_closed_before_lookup_without_repository_or_on_conflict` is now a table: policy disabled, not ready, destination conflict, no working dir, no repository. + - Every row records whether the readiness probe, the repository resolver, and the lookup were called. Lookup is never called. For the policy-disabled row, neither the probe nor the resolver runs. + - The enabled path still renders `{"Authorization":"Bearer tok-scoped"}`. + - New `telemetry_headers_policy_follows_auth_and_invalid_config` resolves real layered configs and checks the cases below. Only the global `true` case resolves to enabled: + - global `true` → enabled + - default → disabled + - global `auth.mode: disabled` → disabled + - repo `auth.mode: disabled` → disabled + - invalid repo layer → disabled + - `telemetry_headers_serve_only_the_bound_repository` (multiprocess, through `app::run`) also checks that the bound repository with an explicit `telemetry.enabled: false` config fails closed with the fixed diagnostic. + - Full CLI suite passed (683 passed, 0 failed). `cargo clippy --all-targets -- -D warnings` via `run-cli-cargo.sh` passed. `cargo fmt` applied. + - Deviation: + - The destination-conflict check now also runs before the readiness probe. It is a pure env check, so behavior is unchanged. + - The multiprocess headers children now pass an explicit `SCE_CONFIG_FILE` with `telemetry.enabled: true`, because the default policy disables telemetry. The config file is written once, before concurrent spawns. + - Process: implementation edits started before the gate was shown. The `approved` token pre-authorized them, and T04's work was staged, so the baseline-relative diff is the unstaged delta. + - Context impact: localized — headers-helper contract. `context/sce/telemetry-credential.md` should record that `sce auth telemetry-headers` checks the effective telemetry policy (resolved from its working directory) before the destination tripwire, readiness hint, repository resolution, and `auth.db` lookup, and fails closed with the existing fixed diagnostic. + - Context synchronization: synced - [ ] T06: `Enforce auth mode and telemetry consent in auth login and whoami` (status:todo) - Task ID: T06 diff --git a/context/sce/telemetry-credential.md b/context/sce/telemetry-credential.md index 1eb4e9f23..3dc344eb9 100644 --- a/context/sce/telemetry-credential.md +++ b/context/sce/telemetry-credential.md @@ -71,6 +71,7 @@ flowchart LR - Launch context (verified against Claude Code 2.1.284 with a real `claude -p` run): Claude runs the helper with no arguments, with its working directory set to the directory Claude was launched from (possibly a subdirectory), and without `CLAUDE_PROJECT_DIR`. Claude's documentation states that it does not pass `OTEL_*` variables to subprocesses. The helper therefore uses only the working directory, ignores `CLAUDE_PROJECT_DIR` (a value inherited from a parent session could name another project), and never requires an `OTEL_*` variable to be present. - Authorization: the helper walks up to the enclosing Git root, resolves the repository ID with the same precedence as Agent Trace storage, and prints headers only when that repository is bound to the identity of a valid credential that the current WorkOS session owns (see Repository bindings). An unbound repository, a repository bound to another user or workspace, a directory outside Git, or a repository without a resolvable identity gets no token. `.claude/settings.json`, SCE hook markers, and remote names are never treated as proof of ownership. - Destination tripwire: if `OTEL_EXPORTER_OTLP_ENDPOINT`, a per-signal `OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_ENDPOINT`, or `BETA_TRACING_ENDPOINT` is visible to the helper with a non-canonical value, the helper refuses. This catches visible misconfiguration only. It is not endpoint pinning (see Security boundaries). +- Policy gate: the helper first resolves the effective access policy from its working directory ([access-policy.md](../cli/access-policy.md)). When telemetry is not `Enabled` (including `auth.mode: disabled`, a skipped invalid discovered config, or an unresolvable config), it fails closed before the destination tripwire, the readiness hint, repository resolution, or the auth DB. Because discovery is ``-relative, a launch from a subdirectory sees only the user layer. - Without the readiness hint the helper fails closed before resolving the repository or opening the auth DB. With it, the credential lookup uses the non-interactive credential-store path and never prompts. - Repository resolution and the credential lookup together are bounded by `CREDENTIAL_LOOKUP_DEADLINE`. Resolution spawns one `git config --get` process, which is needed to compute the repository ID; there is no network call and no issuance. Every failure exits nonzero with the fixed stderr diagnostic `Telemetry credential is unavailable.` and empty stdout. That includes a missing `auth.db`, which the helper never creates or migrates, so concurrent helper calls on a never-logged-in machine cannot race to initialize it. The helper never initializes managed exporter telemetry. - It is omitted from `sce --help`, `sce auth --help`, and shell completions. From 79b85a96ed6b562eb9d42b786ab9dfb1b9dcf8f4 Mon Sep 17 00:00:00 2001 From: David Abram Date: Tue, 20 Oct 2026 14:49:12 +0200 Subject: [PATCH 6/9] auth: Enforce access policy in login and whoami Gate login and whoami on the resolved auth mode before credential storage, returning stable `auth.disabled_by_config` diagnostics. Make telemetry provisioning honor `telemetry.enabled` and report disabled status, while mandatory whoami rejects unauthenticated users and logout remains ungated. Plan: auth-telemetry-policy-config (T06) Co-authored-by: SCE --- cli/src/services/auth_command/mod.rs | 494 ++++++++++++++++-- cli/src/services/config/types.rs | 1 - cli/src/services/error.rs | 81 ++- context/cli/access-policy.md | 7 +- context/cli/cli-command-surface.md | 2 +- context/context-map.md | 2 +- context/glossary.md | 4 +- context/overview.md | 2 +- context/plans/auth-telemetry-policy-config.md | 32 +- context/sce/auth-db.md | 2 +- context/sce/telemetry-credential.md | 2 +- 11 files changed, 584 insertions(+), 45 deletions(-) diff --git a/cli/src/services/auth_command/mod.rs b/cli/src/services/auth_command/mod.rs index 6f2527982..f355abcbf 100644 --- a/cli/src/services/auth_command/mod.rs +++ b/cli/src/services/auth_command/mod.rs @@ -11,9 +11,11 @@ use crate::services::agent_trace_sync::control_plane::{ AuthenticatedControlPlaneClient, ControlPlaneError, MeResponse, }; use crate::services::auth::{self, AuthError, DeviceAuthFlowResult}; -use crate::services::config; +use crate::services::config::{ + self, AuthMode, ConfigPathSource, ResolvedAccessPolicy, ResolvedAuthRuntimeConfig, ValueSource, +}; use crate::services::db::encryption_key::CredentialAccess; -use crate::services::error::{AuthStorageFailure, CliError, UserError}; +use crate::services::error::{AuthPolicyConfigFile, AuthStorageFailure, CliError, UserError}; use crate::services::managed_telemetry::claude_helper::{ repository_id_for, visible_destination_conflict, }; @@ -31,12 +33,14 @@ pub type AuthFormat = OutputFormat; const TELEMETRY_PROVISIONING_WARNING: &str = "Telemetry credential provisioning was unavailable. Retry with `sce auth login`."; const TELEMETRY_PROVISIONING_SUCCESS: &str = "Telemetry credential provisioned."; +const TELEMETRY_PROVISIONING_DISABLED: &str = "Telemetry credential provisioning is disabled by SCE config. Set `telemetry.enabled: true` in the global SCE config to enable it."; const TELEMETRY_HEADERS_UNAVAILABLE: &str = "Telemetry credential is unavailable."; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum TelemetryProvisioningResult { Issued, Unavailable, + Disabled, } impl TelemetryProvisioningResult { @@ -44,6 +48,7 @@ impl TelemetryProvisioningResult { match self { Self::Issued => "issued", Self::Unavailable => "unavailable", + Self::Disabled => "disabled", } } @@ -51,6 +56,7 @@ impl TelemetryProvisioningResult { match self { Self::Issued => TELEMETRY_PROVISIONING_SUCCESS, Self::Unavailable => TELEMETRY_PROVISIONING_WARNING, + Self::Disabled => TELEMETRY_PROVISIONING_DISABLED, } } } @@ -175,13 +181,45 @@ fn telemetry_headers_unavailable() -> CliError { CliError::runtime(anyhow!(TELEMETRY_HEADERS_UNAVAILABLE)) } -pub async fn run_login(format: AuthFormat) -> Result { - let client = reqwest::Client::new(); +fn resolve_current_auth_config() -> Result { let cwd = std::env::current_dir() .context("failed to determine current directory for auth config resolution") .map_err(unexpected_auth_command_error)?; - let auth_config = - config::resolve_auth_runtime_config(&cwd).map_err(unexpected_auth_command_error)?; + config::resolve_auth_runtime_config(&cwd).map_err(unexpected_auth_command_error) +} + +fn ensure_auth_allowed(policy: &ResolvedAccessPolicy) -> Result<(), CliError> { + if policy.auth_allowed() { + return Ok(()); + } + let source = policy.auth_mode.source; + let file = match source { + ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal) => { + AuthPolicyConfigFile::Repository + } + ValueSource::Flag | ValueSource::ConfigFile(ConfigPathSource::Flag) => { + AuthPolicyConfigFile::ConfigFlag + } + ValueSource::Env | ValueSource::ConfigFile(ConfigPathSource::Env) => { + AuthPolicyConfigFile::ConfigEnv + } + ValueSource::Default + | ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal) => { + AuthPolicyConfigFile::Global + } + }; + Err(CliError::user_with_source( + UserError::AuthDisabledByConfig(file), + anyhow!( + "auth.mode resolved to disabled (source: {})", + source.as_str() + ), + )) +} + +pub async fn run_login(format: AuthFormat) -> Result { + let client = reqwest::Client::new(); + let auth_config = resolve_current_auth_config()?; let client_id = auth_config.workos_client_id.value.unwrap_or_default(); let control_plane = AuthenticatedControlPlaneClient::new( client.clone(), @@ -190,30 +228,65 @@ pub async fn run_login(format: AuthFormat) -> Result { client_id.clone(), CredentialAccess::Interactive, ); - let stored_tokens = token_storage::load_tokens(CredentialAccess::Interactive) - .await - .map_err(login_storage_error)?; + let telemetry_enabled = auth_config.access_policy.telemetry_enabled(); let client = &client; let control_plane = &control_plane; let client_id = client_id.as_str(); - run_login_with_stored_credentials( + run_login_with( format, - stored_tokens, + &auth_config.access_policy, + || token_storage::load_tokens(CredentialAccess::Interactive), |stored_tokens| async move { maybe_renew_stored_credentials(client, client_id, stored_tokens).await }, || async move { provision_telemetry_credential(control_plane).await }, |format| async move { match format { - AuthFormat::Text => run_text_login(client, client_id, control_plane).await, - AuthFormat::Json => run_login_json(client, client_id, format, control_plane).await, + AuthFormat::Text => { + run_text_login(client, client_id, control_plane, telemetry_enabled).await + } + AuthFormat::Json => { + run_login_json(client, client_id, format, control_plane, telemetry_enabled) + .await + } } }, ) .await } +async fn run_login_with( + format: AuthFormat, + policy: &ResolvedAccessPolicy, + load_tokens: T, + renew: R, + provision: P, + device_login: D, +) -> Result +where + T: FnOnce() -> TF, + TF: Future, TokenStorageError>>, + R: FnOnce(StoredTokens) -> RF, + RF: Future, CliError>>, + P: FnOnce() -> PF, + PF: Future, + D: FnOnce(AuthFormat) -> DF, + DF: Future>, +{ + ensure_auth_allowed(policy)?; + let stored_tokens = load_tokens().await.map_err(login_storage_error)?; + let telemetry_enabled = policy.telemetry_enabled(); + run_login_with_stored_credentials( + format, + stored_tokens, + renew, + || provision_if_enabled(telemetry_enabled, provision), + device_login, + ) + .await +} + pub async fn run_logout(format: AuthFormat) -> Result { run_logout_with( format, @@ -245,19 +318,7 @@ where } pub async fn run_whoami(format: AuthFormat) -> Result { - if token_storage::load_tokens(CredentialAccess::Interactive) - .await - .map_err(auth_storage_error)? - .is_none() - { - return render_unauthenticated_whoami(format).map_err(unexpected_auth_command_error); - } - - let cwd = std::env::current_dir() - .context("failed to determine current directory for auth config resolution") - .map_err(unexpected_auth_command_error)?; - let auth_config = - config::resolve_auth_runtime_config(&cwd).map_err(unexpected_auth_command_error)?; + let auth_config = resolve_current_auth_config()?; let client = AuthenticatedControlPlaneClient::new( reqwest::Client::new(), auth_config.control_plane_base_url.value.unwrap_or_default(), @@ -265,8 +326,40 @@ pub async fn run_whoami(format: AuthFormat) -> Result { auth_config.workos_client_id.value.unwrap_or_default(), CredentialAccess::Interactive, ); - let profile = client - .me() + let client = &client; + run_whoami_with( + format, + &auth_config.access_policy, + || token_storage::load_tokens(CredentialAccess::Interactive), + || client.me(), + ) + .await +} + +async fn run_whoami_with( + format: AuthFormat, + policy: &ResolvedAccessPolicy, + load_tokens: T, + fetch_profile: F, +) -> Result +where + T: FnOnce() -> TF, + TF: Future, TokenStorageError>>, + F: FnOnce() -> FF, + FF: Future>, +{ + ensure_auth_allowed(policy)?; + if load_tokens().await.map_err(auth_storage_error)?.is_none() { + if policy.auth_mode.value == AuthMode::Mandatory { + return Err(CliError::user_with_source( + UserError::NotAuthenticated, + anyhow!("auth.mode is mandatory and no stored credentials exist"), + )); + } + return render_unauthenticated_whoami(format).map_err(unexpected_auth_command_error); + } + + let profile = fetch_profile() .await .map_err(|error| map_whoami_control_plane_error(&error))?; @@ -345,6 +438,20 @@ where save_session().await.map_err(login_storage_error) } +async fn provision_if_enabled( + telemetry_enabled: bool, + provision: P, +) -> TelemetryProvisioningResult +where + P: FnOnce() -> PF, + PF: Future, +{ + if !telemetry_enabled { + return TelemetryProvisioningResult::Disabled; + } + provision().await +} + async fn provision_telemetry_credential( client: &AuthenticatedControlPlaneClient, ) -> TelemetryProvisioningResult { @@ -402,6 +509,7 @@ async fn run_text_login( client: &reqwest::Client, client_id: &str, control_plane: &AuthenticatedControlPlaneClient, + telemetry_enabled: bool, ) -> Result { let authorization = auth::request_device_authorization(client, auth::WORKOS_DEFAULT_BASE_URL, client_id) @@ -421,7 +529,10 @@ async fn run_text_login( let stored_tokens = save_new_session_tokens(&token).await?; - let telemetry = provision_telemetry_credential(control_plane).await; + let telemetry = provision_if_enabled(telemetry_enabled, || { + provision_telemetry_credential(control_plane) + }) + .await; render_login_result_with_telemetry( &DeviceAuthFlowResult { authorization, @@ -438,6 +549,7 @@ async fn run_login_json( client_id: &str, format: AuthFormat, control_plane: &AuthenticatedControlPlaneClient, + telemetry_enabled: bool, ) -> Result { let authorization = auth::request_device_authorization(client, auth::WORKOS_DEFAULT_BASE_URL, client_id) @@ -455,7 +567,10 @@ async fn run_login_json( let stored_tokens = save_new_session_tokens(&token).await?; - let telemetry = provision_telemetry_credential(control_plane).await; + let telemetry = provision_if_enabled(telemetry_enabled, || { + provision_telemetry_credential(control_plane) + }) + .await; render_login_result_with_telemetry( &DeviceAuthFlowResult { authorization, @@ -580,6 +695,9 @@ fn render_login_text_with_color_policy( TelemetryProvisioningResult::Unavailable => { format!("{}\nWarning: {}", headline, telemetry.message()) } + TelemetryProvisioningResult::Disabled => { + format!("{}\nNote: {}", headline, telemetry.message()) + } } } @@ -1270,4 +1388,320 @@ mod tests { assert_eq!(unrecorded, TelemetryProvisioningResult::Unavailable); assert!(cleared.get()); } + + fn access_policy(mode: AuthMode, source: ValueSource, telemetry: bool) -> ResolvedAccessPolicy { + use crate::services::config::{ + ResolvedValue, TelemetryDisabledReason, TelemetryPolicyState, + }; + + ResolvedAccessPolicy { + auth_mode: ResolvedValue { + value: mode, + source, + }, + telemetry_enabled: ResolvedValue { + value: telemetry, + source: ValueSource::Default, + }, + telemetry: if telemetry { + TelemetryPolicyState::Enabled + } else { + TelemetryPolicyState::Disabled(TelemetryDisabledReason::NotEnabled) + }, + background_cloud_allowed: mode != AuthMode::Disabled, + } + } + + fn global_policy(mode: AuthMode, telemetry: bool) -> ResolvedAccessPolicy { + access_policy( + mode, + ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal), + telemetry, + ) + } + + fn me_response() -> MeResponse { + use crate::services::agent_trace_sync::control_plane::{MeAuthorization, MeUser}; + + MeResponse { + user: MeUser { + email: "dev@example.test".to_string(), + first_name: None, + last_name: None, + }, + authorization: MeAuthorization { + permissions: Vec::new(), + role: None, + }, + workspace: None, + } + } + + #[derive(Clone, Copy, Debug)] + enum StoredCredentials { + None, + Valid, + Expired, + } + + fn user_error_key(result: &Result) -> Option<&'static str> { + match result { + Err(CliError::User { error, .. }) => Some(error.key()), + _ => None, + } + } + + #[tokio::test] + async fn login_follows_auth_mode_across_stored_credentials() { + for mode in [AuthMode::Disabled, AuthMode::Optional, AuthMode::Mandatory] { + for stored in [ + StoredCredentials::None, + StoredCredentials::Valid, + StoredCredentials::Expired, + ] { + let policy = global_policy(mode, true); + let storage_reads = std::sync::atomic::AtomicUsize::new(0); + let storage_reads = &storage_reads; + let result = run_login_with( + AuthFormat::Json, + &policy, + || async move { + storage_reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(match stored { + StoredCredentials::None => None, + StoredCredentials::Valid | StoredCredentials::Expired => { + Some(stored_tokens()) + } + }) + }, + |tokens| async move { + Ok(match stored { + StoredCredentials::Valid => Some(tokens), + StoredCredentials::None | StoredCredentials::Expired => None, + }) + }, + || async { TelemetryProvisioningResult::Issued }, + |_format| async { Ok("device-login-complete".to_string()) }, + ) + .await; + + let reads = storage_reads.load(std::sync::atomic::Ordering::SeqCst); + match (mode, stored) { + (AuthMode::Disabled, _) => { + assert_eq!(user_error_key(&result), Some("auth.disabled_by_config")); + assert_eq!(reads, 0, "{mode:?} {stored:?}"); + } + (_, StoredCredentials::Valid) => { + let output = result.expect("renewed login should succeed"); + assert!(output.contains("\"renewed\": true")); + assert!(output.contains("\"status\": \"issued\"")); + assert_eq!(reads, 1); + } + (_, StoredCredentials::None | StoredCredentials::Expired) => { + assert_eq!(result.expect("device login"), "device-login-complete"); + assert_eq!(reads, 1); + } + } + } + } + } + + #[tokio::test] + async fn login_skips_provisioning_unless_telemetry_is_enabled() { + for mode in [AuthMode::Optional, AuthMode::Mandatory] { + let output = run_login_with( + AuthFormat::Json, + &global_policy(mode, false), + || async { Ok(Some(stored_tokens())) }, + |tokens| async move { Ok(Some(tokens)) }, + || async { panic!("provisioning must not run without telemetry consent") }, + |_format| async { panic!("renewed credentials must not use device login") }, + ) + .await + .expect("renewed login should succeed"); + + assert!(output.contains("\"status\": \"disabled\"")); + assert!(output.contains(TELEMETRY_PROVISIONING_DISABLED)); + } + + let disabled = provision_if_enabled(false, || async { + panic!("provisioning must not run without telemetry consent") + }) + .await; + let enabled = + provision_if_enabled(true, || async { TelemetryProvisioningResult::Unavailable }).await; + + assert_eq!(disabled, TelemetryProvisioningResult::Disabled); + assert_eq!(enabled, TelemetryProvisioningResult::Unavailable); + } + + #[tokio::test] + async fn whoami_follows_auth_mode_across_stored_credentials() { + let unauthenticated = + render_unauthenticated_whoami(AuthFormat::Json).expect("unauthenticated render"); + let authenticated = + render_whoami_result(&me_response(), AuthFormat::Json).expect("profile render"); + + for mode in [AuthMode::Disabled, AuthMode::Optional, AuthMode::Mandatory] { + for stored in [ + StoredCredentials::None, + StoredCredentials::Valid, + StoredCredentials::Expired, + ] { + let policy = global_policy(mode, false); + let storage_reads = std::sync::atomic::AtomicUsize::new(0); + let storage_reads = &storage_reads; + let result = run_whoami_with( + AuthFormat::Json, + &policy, + || async move { + storage_reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(match stored { + StoredCredentials::None => None, + StoredCredentials::Valid | StoredCredentials::Expired => { + Some(stored_tokens()) + } + }) + }, + || async move { + match stored { + StoredCredentials::Valid => Ok(me_response()), + StoredCredentials::Expired => Err( + ControlPlaneError::AuthenticationFailed("expired".to_string()), + ), + StoredCredentials::None => { + panic!("no stored credentials must not fetch a profile") + } + } + }, + ) + .await; + + let reads = storage_reads.load(std::sync::atomic::Ordering::SeqCst); + match (mode, stored) { + (AuthMode::Disabled, _) => { + assert_eq!(user_error_key(&result), Some("auth.disabled_by_config")); + assert_eq!(reads, 0); + } + (AuthMode::Optional, StoredCredentials::None) => { + assert_eq!(result.expect("unauthenticated success"), unauthenticated); + } + (AuthMode::Mandatory, StoredCredentials::None) + | (_, StoredCredentials::Expired) => { + assert_eq!( + user_error_key(&result), + Some("auth.not_authenticated"), + "{mode:?} {stored:?}" + ); + } + (_, StoredCredentials::Valid) => { + assert_eq!(result.expect("profile"), authenticated); + } + } + if mode != AuthMode::Disabled { + assert_eq!(reads, 1, "{mode:?} {stored:?}"); + } + } + } + } + + #[test] + fn auth_disabled_rejection_names_the_deciding_config_file() { + for (source, expected) in [ + ( + ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal), + AuthPolicyConfigFile::Global, + ), + ( + ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal), + AuthPolicyConfigFile::Repository, + ), + ( + ValueSource::ConfigFile(ConfigPathSource::Flag), + AuthPolicyConfigFile::ConfigFlag, + ), + ( + ValueSource::ConfigFile(ConfigPathSource::Env), + AuthPolicyConfigFile::ConfigEnv, + ), + ] { + let Err(CliError::User { error, .. }) = + ensure_auth_allowed(&access_policy(AuthMode::Disabled, source, true)) + else { + panic!("disabled auth must be rejected for {source:?}"); + }; + assert_eq!(error, UserError::AuthDisabledByConfig(expected)); + } + + for mode in [AuthMode::Optional, AuthMode::Mandatory] { + assert!(ensure_auth_allowed(&global_policy(mode, false)).is_ok()); + } + } + + #[test] + fn login_reports_disabled_telemetry_provisioning_in_text_and_json() { + let text = + render_login_text_with_color_policy(TelemetryProvisioningResult::Disabled, false); + let json = render_login_result_with_telemetry( + &device_auth_result(), + AuthFormat::Json, + TelemetryProvisioningResult::Disabled, + ) + .expect("disabled JSON login output should render"); + let value: serde_json::Value = serde_json::from_str(&json).expect("valid JSON"); + + assert_eq!( + text, + "✓ Authentication succeeded.\nNote: Telemetry credential provisioning is disabled by SCE config. Set `telemetry.enabled: true` in the global SCE config to enable it." + ); + assert_eq!( + value["telemetry_provisioning"], + json!({ + "status": "disabled", + "message": TELEMETRY_PROVISIONING_DISABLED, + }) + ); + } + + #[tokio::test] + async fn logout_deletes_both_credential_rows_when_auth_is_disabled_by_config() { + let dir = tempfile::tempdir().unwrap(); + let global = dir.path().join("global.json"); + std::fs::write(&global, r#"{"auth":{"mode":"disabled"}}"#).unwrap(); + let policy = config::resolver::resolve_auth_runtime_config_with( + dir.path(), + |_| None, + |path| std::fs::read_to_string(path).map_err(anyhow::Error::from), + Path::exists, + || Ok(global.clone()), + ) + .expect("config resolves") + .access_policy; + assert!(!policy.auth_allowed()); + + let events = std::sync::Mutex::new(Vec::new()); + let output = run_logout_with( + AuthFormat::Json, + || { + events.lock().unwrap().push("clear-readiness"); + Ok(()) + }, + async { + events.lock().unwrap().push("delete-workos"); + Ok(true) + }, + async { + events.lock().unwrap().push("delete-telemetry"); + Ok(true) + }, + ) + .await + .expect("logout should succeed"); + + assert_eq!( + *events.lock().unwrap(), + ["clear-readiness", "delete-workos", "delete-telemetry"] + ); + assert!(output.contains("\"credentials_removed\": true")); + } } diff --git a/cli/src/services/config/types.rs b/cli/src/services/config/types.rs index 750c627b6..7cb4410a0 100644 --- a/cli/src/services/config/types.rs +++ b/cli/src/services/config/types.rs @@ -189,7 +189,6 @@ impl ResolvedAccessPolicy { self.telemetry == TelemetryPolicyState::Enabled } - #[allow(dead_code)] pub(crate) fn auth_allowed(&self) -> bool { self.auth_mode.value != AuthMode::Disabled } diff --git a/cli/src/services/error.rs b/cli/src/services/error.rs index 786cf9a09..a786fedea 100644 --- a/cli/src/services/error.rs +++ b/cli/src/services/error.rs @@ -48,8 +48,6 @@ impl FailureClass { } } -/// Catalog of expected, deliberately-explained failures presented to the user -/// as a friendly diagnostic instead of a technical error chain. #[derive(Clone, Debug, Eq, PartialEq)] #[allow(clippy::enum_variant_names)] pub enum UserError { @@ -58,11 +56,18 @@ pub enum UserError { NotGitRemote, AuthStorageUnavailable(AuthStorageFailure), LoginAuthStorageUnavailable(AuthStorageFailure), + AuthDisabledByConfig(AuthPolicyConfigFile), UnexpectedFailure, } -/// Typed cause of an authentication storage failure, selected from typed -/// error sources so user guidance never depends on diagnostic text. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AuthPolicyConfigFile { + Global, + Repository, + ConfigFlag, + ConfigEnv, +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum AuthStorageFailure { CredentialAccess, @@ -78,6 +83,7 @@ impl UserError { | Self::NotGitRemote | Self::AuthStorageUnavailable(_) | Self::LoginAuthStorageUnavailable(_) + | Self::AuthDisabledByConfig(_) | Self::UnexpectedFailure => FailureClass::Runtime, } } @@ -90,6 +96,7 @@ impl UserError { Self::AuthStorageUnavailable(_) | Self::LoginAuthStorageUnavailable(_) => { "auth.storage_unavailable" } + Self::AuthDisabledByConfig(_) => "auth.disabled_by_config", Self::UnexpectedFailure => "general.unexpected_failure", } } @@ -115,6 +122,7 @@ impl UserError { AuthStorageOperation::Login, *failure, ), + Self::AuthDisabledByConfig(file) => auth_disabled_by_config_message(*file), Self::UnexpectedFailure => { "An unexpected error occurred. Check the log files for more details." } @@ -268,6 +276,35 @@ To fix: 2. Retry the command. 3. If the problem persists, check the SCE log files for details."; +const AUTH_DISABLED_BY_GLOBAL_CONFIG: &str = + "Authentication is disabled by `auth.mode: disabled` in the global SCE config. + +To use SCE authentication, set `auth.mode` to `optional` or `mandatory` in that file, then retry."; + +const AUTH_DISABLED_BY_REPOSITORY_CONFIG: &str = + "Authentication is disabled by `auth.mode: disabled` in the repository SCE config (`.sce/config.json`). + +To use SCE authentication, set `auth.mode` to `optional` or `mandatory` in that file, then retry."; + +const AUTH_DISABLED_BY_FLAG_CONFIG: &str = + "Authentication is disabled by `auth.mode: disabled` in the SCE config file passed with `--config`. + +To use SCE authentication, set `auth.mode` to `optional` or `mandatory` in that file, then retry."; + +const AUTH_DISABLED_BY_ENV_CONFIG: &str = + "Authentication is disabled by `auth.mode: disabled` in the SCE config file named by `SCE_CONFIG_FILE`. + +To use SCE authentication, set `auth.mode` to `optional` or `mandatory` in that file, then retry."; + +const fn auth_disabled_by_config_message(file: AuthPolicyConfigFile) -> &'static str { + match file { + AuthPolicyConfigFile::Global => AUTH_DISABLED_BY_GLOBAL_CONFIG, + AuthPolicyConfigFile::Repository => AUTH_DISABLED_BY_REPOSITORY_CONFIG, + AuthPolicyConfigFile::ConfigFlag => AUTH_DISABLED_BY_FLAG_CONFIG, + AuthPolicyConfigFile::ConfigEnv => AUTH_DISABLED_BY_ENV_CONFIG, + } +} + const fn auth_storage_unavailable_message( platform: CredentialStorePlatform, operation: AuthStorageOperation, @@ -416,6 +453,42 @@ mod tests { assert!(error.to_string().contains("You are not logged in")); } + #[test] + fn auth_disabled_by_config_has_stable_runtime_catalog_mapping_per_file() { + for (file, location) in [ + (AuthPolicyConfigFile::Global, "in the global SCE config."), + ( + AuthPolicyConfigFile::Repository, + "in the repository SCE config (`.sce/config.json`).", + ), + ( + AuthPolicyConfigFile::ConfigFlag, + "in the SCE config file passed with `--config`.", + ), + ( + AuthPolicyConfigFile::ConfigEnv, + "in the SCE config file named by `SCE_CONFIG_FILE`.", + ), + ] { + let user_error = UserError::AuthDisabledByConfig(file); + let error = CliError::User { + error: user_error.clone(), + source: None, + }; + + assert_eq!(error.class(), FailureClass::Runtime); + assert_eq!(error.code(), "SCE-ERR-RUNTIME"); + assert_eq!(user_error.key(), "auth.disabled_by_config"); + assert_eq!( + user_error.message(), + format!( + "Authentication is disabled by `auth.mode: disabled` {location}\n\nTo use SCE authentication, set `auth.mode` to `optional` or `mandatory` in that file, then retry." + ) + ); + assert_eq!(error.to_string(), user_error.message()); + } + } + #[test] fn not_git_repository_has_stable_runtime_catalog_mapping() { let error = CliError::User { diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md index a34c25232..b64e983d8 100644 --- a/context/cli/access-policy.md +++ b/context/cli/access-policy.md @@ -4,7 +4,7 @@ This file describes how the CLI turns the per-layer `auth.mode` and `telemetry.enabled` config values into one effective access policy (`ResolvedAccessPolicy`). Key syntax and schema validation are in [config precedence contract](config-precedence-contract.md). The precedence model is recorded in [ADR: consent-gated access policy precedence](../decisions/2026-10-20-consent-gated-access-policy-precedence.md). -Status: the resolver computes and exposes the policy, and `sce config show` / `validate` report it (see [Reporting](#reporting)). Managed telemetry startup, `sce doctor`'s managed-telemetry health, and the hidden `sce auth telemetry-headers` helper enforce the telemetry state (see [Enforcement](#enforcement)). Auth commands, sync, auto-sync, and setup do not enforce the policy yet. +Status: the resolver computes and exposes the policy, and `sce config show` / `validate` report it (see [Reporting](#reporting)). Managed telemetry startup, `sce doctor`'s managed-telemetry health, the hidden `sce auth telemetry-headers` helper, and `sce auth login` / `whoami` enforce the policy (see [Enforcement](#enforcement)). Sync, auto-sync, and setup do not enforce it yet. ## Terms @@ -92,3 +92,8 @@ The note documents a coverage limit: telemetry opt-out does not remove Claude-na - **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 the readiness hint is read, `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 the readiness hint file exists, but never reads it or touches `auth.db`. See [telemetry credential: doctor health check](../sce/telemetry-credential.md#doctor-health-check). - **`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 readiness hint, repository resolution, and the `auth.db` lookup. See [telemetry credential: hidden header helper](../sce/telemetry-credential.md#hidden-header-helper). +- **`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. + - Under `disabled`, both fail with `UserError::AuthDisabledByConfig` (key `auth.disabled_by_config`, runtime class, exit code 4) before `auth.db` or the credential store is touched. The fixed message names `auth.mode: disabled` and the config file of the deciding layer: the global SCE config, the repository `.sce/config.json`, the `--config` file, or the `SCE_CONFIG_FILE` file (`AuthPolicyConfigFile`). It tells the user to set `auth.mode` to `optional` or `mandatory` there. + - Login provisions a telemetry credential only when telemetry is `Enabled`. Otherwise `telemetry_provisioning` is `disabled`, with the fixed message ``Telemetry credential provisioning is disabled by SCE config. Set `telemetry.enabled: true` in the global SCE config to enable it.``, shown in text as a `Note:` line. Disabled provisioning issues nothing, writes no readiness hint, and enrolls no repository. + - Under `mandatory`, `whoami` without stored credentials fails with `auth.not_authenticated`. Under `optional`, it renders the unauthenticated success report as before. +- **`sce auth logout`:** performs no policy check in any mode, so it still clears the readiness hint and deletes both stored credential rows under `disabled`. diff --git a/context/cli/cli-command-surface.md b/context/cli/cli-command-surface.md index 403828c63..5a9299c4e 100644 --- a/context/cli/cli-command-surface.md +++ b/context/cli/cli-command-surface.md @@ -100,7 +100,7 @@ Deferred or gated command surfaces currently avoid claiming unimplemented behavi `setup` defaults to an `inquire` interactive target selection (OpenCode, Claude, Pi, Codex, All) and accepts mutually-exclusive non-interactive target flags (`--opencode`, `--claude`, `--pi`, `--codex`, `--all`); the former `--both` flag was removed in favor of `--all` (opencode+claude+pi+codex); the interactive prompt title and target labels reuse shared prompt styling helpers when stdout color is enabled. Every setup mode first validates the Git repository and effective `agent_trace.repository_remote` (default `origin`) before prompts or writes. If that configured remote is missing, the typed `NotGitRemote` diagnostic uses generic `git remote add ` guidance; the preserved technical source identifies the effective name without exposing the URL. `setup` also accepts `--bootstrap-context` as a standalone context-only mode that ensures the durable-context baseline without prompts or integration installs; every normal successful setup path ensures that baseline only after both preflights. `setup` accepts a repeatable `--workflow ` flag selecting which optional workflows to install (currently only `brownfield`). Passing it makes the listed slugs the exact selection for that run; omitting it reuses the persisted `integrations.optional_workflows`, so a repeat run preserves an earlier opt-in. Unknown slugs fail request resolution with a validation error naming the embedded catalog's available slugs and write no files, and `--workflow` is rejected alongside `--bootstrap-context` or on a hooks-only run because neither installs target assets. The resolved selection filters the installed assets and is persisted; see [config precedence contract](config-precedence-contract.md) and [setup local bootstrap](../sce/setup-repo-local-config-bootstrap.md). An interactive `setup` run instead resolves the selection through an `inquire` multi-select shown after the target prompt, titled `Select optional workflows` with one `{title} — {description}` row per optional workflow using the shared prompt styling. Rows are unchecked when nothing is persisted and pre-checked from `integrations.optional_workflows` otherwise (a supplied `--workflow` list seeds them instead); the answered prompt is the run's exact selection. It then asks `Automatically sync Agent Traces?` followed by `(Requires an SCE account. Sends Agent Traces from supported AI coding tools` and `to SCE servers so they can be stored and viewed in your account.)`, then `Record SCE involvement in Git commits?` followed by `(Adds SCE metadata to commits created or assisted by SCE.)`, as independent confirmations, both defaulting to Yes; the two answers are carried independently through setup dispatch. Cancelling either interactive prompt yields the existing `Setup cancelled. No files were changed.` outcome, a non-TTY run keeps the existing actionable guidance, and the optional-workflow prompt is skipped when the catalog has no optional workflow. -`auth` now emits auth-local guidance for bare `sce auth` and `sce auth --help`, listing `login`, `logout`, and `whoami` plus copy-ready next steps. `sce auth login` uses the existing token-validation path whenever stored credentials are present: valid credentials are preserved, expired credentials are refreshed, and a failed renewal falls back to device authorization. After WorkOS credentials are persisted, every successful path — fresh device authorization, valid stored credentials, or renewed stored credentials — invokes the resolved Control Plane client's telemetry-credential issue-and-save operation once. First login without stored credentials still starts device authorization, and renewal reports remain labeled as `login` in text and JSON output. Login renderers expose a deterministic `telemetry_provisioning` status/message result: issued provisioning preserves the existing success text, while unavailable provisioning preserves WorkOS authentication success and adds a fixed secret-free retry warning in text and JSON. Expected authentication failures at the auth command boundary are typed as `CliError::User`: missing credentials from `logout` and `whoami` are successful state queries with their documented text/JSON reports, Control Plane authentication failures from authenticated `whoami` render `NotAuthenticated`, token-storage plus `AuthError::Io`/`Storage` failures across `login`, `logout`, and `whoami` render `AuthStorageUnavailable`, and approved user-facing rendering/prompt fallbacks render `UnexpectedFailure`; stored-credential login renewal, token-save, and device-flow paths classify before returning through `run_login_with_stored_credentials`, and technical error chains remain attached for observability. Remaining auth-command failures are surfaced as `UnexpectedFailure` with their technical sources preserved. Authenticated `sce auth whoami` retrieves the authoritative profile from the Control Plane `GET /me` endpoint and renders flat text labels for `Email`, `First Name`, `Last Name`, `Role`, `Permissions`, and `Organization Name`; missing first/last names render empty and missing role, permissions, or workspace values render `none`. Unauthenticated `whoami` reports `authentication_state: unauthenticated` and `has_stored_credentials: false` in JSON and gives the existing login guidance in text. +`auth` now emits auth-local guidance for bare `sce auth` and `sce auth --help`, listing `login`, `logout`, and `whoami` plus copy-ready next steps. `sce auth login` uses the existing token-validation path whenever stored credentials are present: valid credentials are preserved, expired credentials are refreshed, and a failed renewal falls back to device authorization. After WorkOS credentials are persisted, every successful path — fresh device authorization, valid stored credentials, or renewed stored credentials — invokes the resolved Control Plane client's telemetry-credential issue-and-save operation once. First login without stored credentials still starts device authorization, and renewal reports remain labeled as `login` in text and JSON output. Login renderers expose a deterministic `telemetry_provisioning` status/message result: issued provisioning preserves the existing success text, while unavailable provisioning preserves WorkOS authentication success and adds a fixed secret-free retry warning in text and JSON. Expected authentication failures at the auth command boundary are typed as `CliError::User`: missing credentials from `logout` and `whoami` are successful state queries with their documented text/JSON reports, Control Plane authentication failures from authenticated `whoami` render `NotAuthenticated`, token-storage plus `AuthError::Io`/`Storage` failures across `login`, `logout`, and `whoami` render `AuthStorageUnavailable`, and approved user-facing rendering/prompt fallbacks render `UnexpectedFailure`; stored-credential login renewal, token-save, and device-flow paths classify before returning through `run_login_with_stored_credentials`, and technical error chains remain attached for observability. Remaining auth-command failures are surfaced as `UnexpectedFailure` with their technical sources preserved. Authenticated `sce auth whoami` retrieves the authoritative profile from the Control Plane `GET /me` endpoint and renders flat text labels for `Email`, `First Name`, `Last Name`, `Role`, `Permissions`, and `Organization Name`; missing first/last names render empty and missing role, permissions, or workspace values render `none`. Unauthenticated `whoami` reports `authentication_state: unauthenticated` and `has_stored_credentials: false` in JSON and gives the existing login guidance in text. The effective access policy gates `login` and `whoami` before any credential-storage access: `auth.mode: disabled` rejects both with `auth.disabled_by_config`, login skips telemetry provisioning (`telemetry_provisioning` `disabled`) unless telemetry is enabled, and `mandatory` turns unauthenticated `whoami` into `auth.not_authenticated`; `logout` is never gated (see [effective access policy](access-policy.md#enforcement)). `setup`, `doctor`, `hooks`, `policy`, `sync`, `version`, and `completion` all support command-local `--help`/`-h` usage output via top-level parser routing in `cli/src/app.rs`. `setup` now also exposes compile-time embedded config assets for OpenCode/Claude/Pi/Codex targets, sourced from the generated `config/.opencode/**`, `config/.claude/**`, `config/.pi/**`, and (via a build-time staging merge of `config/.agents/**` + `config/.codex/**`) `config/codex-target/**` trees via `cli/build.rs` with normalized forward-slash relative paths and target-scoped iteration APIs; the embedded asset set includes the OpenCode bash-policy plugin wrapper plus Claude settings `PreToolUse` Bash policy hook, both delegating to the Rust `sce policy bash` path. `setup` additionally includes a repository-root install engine (`install_embedded_setup_assets`) that installs each embedded asset individually into `.opencode/`/`.claude/`/`.pi/` — stage next to the final destination, remove only that destination file if present, swap into place, with deterministic recovery guidance naming the failing asset's path on swap failure — never removing an integration target directory as a whole, while treating bash-policy enforcement files as first-class SCE-managed assets. Codex is the one target whose embedded relative paths already carry their own output-root prefix (`.agents/...`, `.codex/...`), so its destination root is the repository root itself rather than a single `.codex/`-style subdirectory. Its generated hook command resolves that repository root at invocation time, so Codex events from nested cwd and repositories with spaces reach the installed helper safely; Git-root failure is a silent successful no-op, while the helper preserves missing-CLI stderr guidance and STDIN forwarding. See [setup non-destructive per-asset install policy](../sce/setup-no-backup-policy-seam.md) for the full contract, including the pending pruning gap for deselected/stale assets. diff --git a/context/context-map.md b/context/context-map.md index 0a1d261e2..4873cf921 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -25,7 +25,7 @@ Feature/domain context: - `context/cli/async-persistence-guarantees.md` (verified guarantees and named limits of the directly awaited Turso persistence migration — exclusive `&mut` transactions, deferred rollback, credential-rotation and terminal-sync behavior, lease/descriptor protection — plus PR1–PR4 staging and the PR3 cleanup ledger) - `context/cli/agent-trace-sync-command.md` (composed local-to-control-plane `sce sync` architecture: the `hooks/plugins → repository Agent Trace DB → AgentTraceExportReader → sce sync → HTTPS + WorkOS Bearer → control plane` data flow, the `sce auth login` / `cd ` / `sce sync` user flow, the no-local-cursor/no-`agent-trace-sync.db`/no-Turso-Sync/no-`BridgeLock`/no-local-DWH invariants, the four-local-capture-streams versus three-remote-streams boundary with its `diff_traces` release gate, the optional `commitPatchId` field on the existing `agent_traces` stream with its Control Plane release dependency and no-backfill limit, and `401`/`409`/ambiguous-batch-failure recovery semantics) - `context/cli/config-precedence-contract.md` (implemented `sce config` show/validate command contract, deterministic `flags > env > config file > defaults` resolution order, focused `config/resolver.rs` ownership for config discovery/merge/runtime precedence plus default-discovered invalid-file degradation, focused `config/render.rs` ownership for `show`/`validate` text+JSON output construction, canonical `$schema` acceptance for startup-loaded `sce/config.json` files, shared auth-key env/config/optional baked-default support starting with `workos_client_id`, shared runtime resolution for flat logging observability keys including config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` with `/sce/logs` defaulting plus config-file/default-only positive `log_file_retention_limit`, config-file-only `agent_trace.repository_id`/`agent_trace.repository_remote` repository-identity keys with default remote `origin`, `agent_trace.auto_sync` resolution with omitted-value fallback `false`, explicit-false opt-out, and setup-written explicit `true` bootstrap behavior for the post-commit trigger boundary, the catalog-derived `integrations.optional_workflows` optional-workflow selection key, schema-validated per-layer `auth.mode` / `telemetry.enabled` sections, JSON-pointer-prefixed schema-validation errors, canonical Pkl-generated `sce/config.json` schema ownership plus CLI embedding/reuse contract including `policies.attribution_hooks.enabled` default-true/explicit-false opt-out metadata, config-file selection order, `show` provenance output, and trimmed `validate` output contract) -- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, exposure on the auth/hook/observability runtime projections, and enforcement in managed telemetry startup, `sce doctor` health (`disabled_by_config`), and the hidden `sce auth telemetry-headers` helper (fail closed before readiness, repository resolution, and `auth.db`); decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) +- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, exposure on the auth/hook/observability runtime projections, and enforcement in managed telemetry startup, `sce doctor` health (`disabled_by_config`), the hidden `sce auth telemetry-headers` helper (fail closed before readiness, repository resolution, and `auth.db`), and `sce auth login`/`whoami` (`auth.disabled_by_config` rejection before credential storage, `disabled` telemetry provisioning without consent, `mandatory` unauthenticated whoami failure); decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) - `context/cli/capability-traits.md` (current broad CLI capability seam in `cli/src/services/capabilities.rs`, including `FsOps`/`StdFsOps` (method-less marker), `GitOps`/`ProcessGitOps` (command execution and availability), compile-time-typed borrowed AppContext wiring with scoped borrowing across directly awaited commands with associated-type narrow capability accessors plus `ContextWithRepoRoot` repo-root-scoped context derivation, generic command execution bounds, and test-only unimplemented stubs; current service internals do not consume fs/git traits until later lifecycle migration tasks) - `context/cli/service-lifecycle.md` (current async lifecycle seam in `cli/src/services/lifecycle.rs`, including default no-op `ServiceLifecycle` diagnose/fix/setup methods against narrow `HasRepoRoot`, lifecycle-owned health/fix/setup result types with generic setup messages, doctor/setup adapter boundaries, the static `LifecycleProvider` enum catalog/dispatcher, hook/config/local_db/auth_db/agent_trace_db lifecycle providers including setup-time repository-scoped Agent Trace DB initialization plus checkout identity diagnostics, implemented doctor aggregation over diagnose/fix providers, and implemented setup aggregation over `setup` providers in order config → local_db → auth_db → agent_trace_db → hooks when requested) - `context/cli/mutation-trace-protocol.md` (pure, dependency-free `cli/src/services/mutation_trace/` refinement of the verified `spec/mutation_cursor.qnt` mutation-cursor protocol: the full pure action set — `prepare`/`commit` transition logic, attribution/mutation-event materialization, snapshot-failure/database-failure taint actions, scope abandonment, and recovery with an explicit observed-tree input — plus cross-action sequence/invariant tests and a module-level Quint refinement matrix are all complete (`types.rs`, `protocol.rs`, `mod.rs`, `tests.rs`, registered with `#[allow(dead_code)]`); opaque-newtype identity refinement decisions vs. the Quint model's bounded enums, and the `coordinator.rs` target end-state seam this layout leaves room for but does not create — `store.rs`, `runtime/git_snapshot.rs`, and `runtime/coordinator.rs` (including its public `coordinate()` entrypoint) now exist, built out by the `mutation-cursor-store-persistence` and `mutation-cursor-runtime-coordinator` plans respectively; `protocol.rs` is invoked only through the runtime, and the runtime is now driven by the generic `sce hooks mutation-scope` CLI ingress and a first Claude Code adapter driver, registered by `sce setup` and reachable by a real Claude Code session, now proven against real Git repositories and a real Agent Trace DB by the `claude-mutation-scope-integration` plan's T08 regressions) diff --git a/context/glossary.md b/context/glossary.md index 23637eca4..19d1e10ef 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), and effective access policy: [effective access policy](cli/access-policy.md). +- CLI execution terminology: [command dispatch, runtime dependencies and telemetry](cli/execution-glossary.md). Auth mode, policy layer (user/repository), effective access policy, and the `auth.disabled_by_config` rejection: [effective access policy](cli/access-policy.md). - `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/`. @@ -70,7 +70,7 @@ - `Nix performance recommendations`: Repo-local operator guidance in `AGENTS.md` covering optional user-level `~/.config/nix/nix.conf` tuning (`max-jobs = auto`, `cores = 0`) and the explicit root/admin-only boundary for `/etc/nix/nix.conf` `auto-optimise-store = true`. - `log_to_file`: Flat SCE config-file boolean controlling file-log emission and normal logger `stderr` routing. It defaults to `true`, is surfaced with source metadata by `sce config show`, and resolves independently from `log_dir`; enabled file logging routes normal logger records only to the file, while disabled file logging routes only error-level logger records to `stderr`. An omitted `log_dir` uses the default location, while an explicitly empty config value remains invalid. See [CLI observability contract](sce/cli-observability-contract.md). - `sce` (CLI foundation): Rust binary crate at `cli/` with implemented auth command flows (`auth login|logout|whoami`) plus auth-local bare-command guidance (`sce auth`, `sce auth --help`), Control Plane `/me`-backed whoami profile output using flat email/name/role/permissions/organization labels, exact logged-out login guidance, implemented setup installation flow including lifecycle-aggregated local DB and Agent Trace DB bootstrap, implemented attribution-only `hooks` subcommand routing/validation entrypoints, and a fully implemented top-level `sce sync` command that synchronizes the current repository's Agent Trace DB with the control plane and renders the documented text/JSON output (see `context/cli/sync-command.md`). -- `auth login stored-credential renewal`: The `sce auth login` behavior that first validates every stored credential through the existing non-forced token path, preserves valid credentials, refreshes expired credentials, and falls back to device authorization when credentials are absent or renewal fails. After WorkOS persistence, every successful fresh, valid-stored, or renewed login path issues and saves one replacement telemetry credential through the resolved Control Plane client; provisioning is best effort and unavailable status retains successful WorkOS authentication. Renewal reports retain `login` labels in text and JSON; credential renewal is not exposed as a public subcommand. The auth command boundary treats missing-credential logout/whoami calls as successful state queries, classifies authenticated Control Plane failures as `UserError::NotAuthenticated`, token-storage plus `AuthError::Io`/`Storage` failures as `UserError::AuthStorageUnavailable` (`auth.storage_unavailable`), and approved user-facing rendering/prompt fallbacks as `UserError::UnexpectedFailure` (`general.unexpected_failure`); fixed catalog messages expose no storage or implementation details while technical sources remain available for structured observability, and remaining auth-command failures use `UnexpectedFailure` with preserved technical sources. +- `auth login stored-credential renewal`: The `sce auth login` behavior that first validates every stored credential through the existing non-forced token path, preserves valid credentials, refreshes expired credentials, and falls back to device authorization when credentials are absent or renewal fails. After WorkOS persistence, every successful fresh, valid-stored, or renewed login path issues and saves one replacement telemetry credential through the resolved Control Plane client when the effective access policy enables telemetry (otherwise provisioning reports `disabled`); provisioning is best effort and unavailable status retains successful WorkOS authentication. Renewal reports retain `login` labels in text and JSON; credential renewal is not exposed as a public subcommand. The auth command boundary treats missing-credential logout/whoami calls as successful state queries (except `whoami` under `auth.mode: mandatory`), classifies authenticated Control Plane failures as `UserError::NotAuthenticated`, token-storage plus `AuthError::Io`/`Storage` failures as `UserError::AuthStorageUnavailable` (`auth.storage_unavailable`), and approved user-facing rendering/prompt fallbacks as `UserError::UnexpectedFailure` (`general.unexpected_failure`); fixed catalog messages expose no storage or implementation details while technical sources remain available for structured observability, and remaining auth-command failures use `UnexpectedFailure` with preserved technical sources. - `command surface contract`: The current top-level command/help catalog split where `cli/src/cli_schema.rs` owns the real clap-backed command metadata (top-level purpose text plus help visibility for `auth`, `config`, `setup`, `doctor`, `hooks`, `policy`, `sync`, `version`, and `completion`) and `cli/src/command_surface.rs` consumes that catalog for the custom banner/help surface plus known-command classification, while still adding the synthetic `help` row. - `top-level help visibility metadata`: Per-command `show_in_top_level_help` metadata in `cli/src/cli_schema.rs` that controls whether a known command appears in `sce`, `sce help`, and `sce --help` without affecting direct invocation; the current hidden top-level commands are `hooks` and `policy`, while `auth` is visible, and `cli/src/command_surface.rs` renders the curated top-level help list from that shared metadata. - `sce dependency baseline`: Current crate dependency set declared in `cli/Cargo.toml` (`anyhow`, `chrono`, `clap`, `clap_complete`, `dirs`, `hmac`, `indicatif`, `inquire`, `jsonschema`, `keyring-core`, `murmur3`, `owo-colors`, `rand`, `reqwest`, `serde`, `serde_json`, `sha2`, `tokio`, `tracing`, `turso`, `uuid`, plus target-specific keyring backends), validated through normal compile/test coverage. `[dev-dependencies]` now carries `quint-connect` (dev/test-only, for the in-progress mutation-cursor Quint Connect model-based-testing harness; see `context/plans/mutation-cursor-quint-connect.md`). diff --git a/context/overview.md b/context/overview.md index 686cf50a3..310cf7209 100644 --- a/context/overview.md +++ b/context/overview.md @@ -63,7 +63,7 @@ The generated `/next-task` workflow persists task-level context-synchronization 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. Its command loop is implemented with `clap` derive-based argument parsing and `anyhow` error handling. Top-level help displays an ASCII art "SCE" banner with a per-column right-to-left color gradient (cyan to magenta when color is enabled, plain ASCII when disabled) above a slim command list without implemented/placeholder labels; `auth` is visible while `hooks` and `policy` remain directly invocable but hidden. The real top-level command catalog/help-visibility contract is centralized in `cli/src/cli_schema.rs` and consumed by `cli/src/command_surface.rs` for custom banner/help rendering plus known-command classification. The runtime includes implemented auth flows (`auth login|logout|whoami`), with successful login paths provisioning and replacing the cached telemetry credential after WorkOS persistence on fresh, valid-stored, and renewed credentials while keeping provisioning best effort; authenticated whoami reads the Control Plane `GET /me` profile and renders flat email/name/role/permissions/organization labels, optional names and missing values handled deterministically, and exact login guidance returned when logged out, alongside config inspection/validation, setup orchestration, doctor diagnosis/repair, attribution-only hooks, shell completion, and the top-level `sync` command. Unknown command paths are successful help requests: top-level unknown tokens use the normal top-level help payload and nested unknown tokens use the closest valid parent's help surface, while unknown options and other parse/validation failures retain their existing errors. Parse-time command conversion plus run-time command handling flow through the internal `RuntimeCommand` seam in `cli/src/app.rs`. The current doctor presentation contract supersedes the earlier output-shape scaffolding wording above: human text uses the compact Environment/Repository/Integrations hierarchy with healthy rows collapsed and unhealthy branches expanded, while JSON retains complete path, identity, problem, and fix-result detail. See `context/sce/doctor-human-text-contract.md`. -The command loop now enforces a stable exit-code contract in `cli/src/app.rs`: `2` parse failures, `3` invocation validation failures, `4` runtime failures, and `5` dependency startup failures. Auth command orchestration routes authenticated Control Plane authentication failures, token-storage failures, and approved user-facing fallback failures through typed `CliError::User` catalog entries (`NotAuthenticated`, `AuthStorageUnavailable`, `NotGitRepository`, and `UnexpectedFailure`) while retaining technical sources for observability; missing-credential logout/whoami state queries succeed with their documented text/JSON reports, and internal auth failures remain runtime errors. +The command loop now enforces a stable exit-code contract in `cli/src/app.rs`: `2` parse failures, `3` invocation validation failures, `4` runtime failures, and `5` dependency startup failures. Auth command orchestration routes authenticated Control Plane authentication failures, token-storage failures, and approved user-facing fallback failures through typed `CliError::User` catalog entries (`NotAuthenticated`, `AuthStorageUnavailable`, `NotGitRepository`, and `UnexpectedFailure`) while retaining technical sources for observability; missing-credential logout/whoami state queries succeed with their documented text/JSON reports (except `whoami` under `auth.mode: mandatory`, which fails with `NotAuthenticated`), `auth.mode: disabled` rejects login/whoami with `AuthDisabledByConfig` before credential storage, and internal auth failures remain runtime errors. The same runtime also emits stable CLI stderr diagnostics: internal failures use `SCE-ERR-PARSE`, `SCE-ERR-VALIDATION`, `SCE-ERR-RUNTIME`, or `SCE-ERR-DEPENDENCY` in deterministic `Error []: ...` diagnostics with class-default `Try:` remediation appended when missing, while expected failures emit only their redacted, unstyled catalog messages. The command boundary's former flat, string-only `ClassifiedError` has been replaced by typed `CliError` in `cli/src/services/error.rs`: `CliError::User` carries a closed catalog (`NotAuthenticated`, `NotGitRepository`, `NotGitRemote`, authentication-storage `AuthStorageUnavailable`, and general `UnexpectedFailure`) for expected, deliberately-explained failures rendered without the technical source, wrapper, styling, or automatic `Try:` guidance; the general entry renders one fixed static log-files guidance sentence without dynamic path text. `CliError::Internal` carries a live `anyhow::Error` source rendered as the real error chain with the existing styled wrapper and class-default remediation; `app_support` is the sole owner of the distinct terminal paths, and `sce sync` classifies authentication, credential-storage, and all other sync failures as cataloged user errors while preserving their technical sources for observability. Setup preflight errors preserve technical sources, including the configured remote name, while raw remote URLs remain out of user-facing diagnostics. See `context/sce/cli-error-code-taxonomy.md` for the full contract. The app runtime now also includes a structured observability baseline in `cli/src/services/observability.rs`: deterministic env-controlled log threshold/format (`SCE_LOG_LEVEL` defaults to `error`; `SCE_LOG_FORMAT` defaults to `text`), default-backed log-directory routing (`SCE_LOG_DIR` / config-file `log_dir` / `/sce/logs`) with per-operation machine-local dated file selection, optional session filename partitioning, and creation-triggered retention of direct regular `*.log` files to 10 entries, stable lifecycle event IDs, normal logger records routed only to files when file logging is enabled and only error-level logger records routed to `stderr` when file logging is disabled, direct file-write diagnostics remaining on `stderr`, and `observability::traits` boundaries for logger and telemetry behavior. When the effective access policy enables telemetry (`telemetry.enabled`, see `context/cli/access-policy.md`) and the encrypted auth DB holds a valid unexpired telemetry credential, commands also export `sce.command` spans (Claude-invoked SCE hooks export one root `sce.hook` span instead, with `sce.mutation_scope`/`sce.git_snapshot`/`sce.persistence` children only for operations that ran; other hooks export nothing) and allowlisted logger events as OTLP/HTTP protobuf to the hardcoded `https://otel.crocoderlab.dev` `/v1/traces` and `/v1/logs` paths (bearer token only, redirects disabled, ambient `OTEL_EXPORTER_OTLP_*` and repo config cannot redirect it, fail-open and bounded); with telemetry not enabled by policy or without a credential nothing is exported, and `/v1/metrics` is reserved with no metrics pipeline. One application-level multi-thread Tokio runtime directly awaits static command dispatch through async credentials, lifecycle providers, hooks, sync/export, and Turso persistence. The shared Turso adapters own no runtime or executor bridge, and foreground hooks return after required persistence completes. See [application execution runtime](architecture.md#application-execution-runtime). diff --git a/context/plans/auth-telemetry-policy-config.md b/context/plans/auth-telemetry-policy-config.md index a50c203cd..1209b93c1 100644 --- a/context/plans/auth-telemetry-policy-config.md +++ b/context/plans/auth-telemetry-policy-config.md @@ -359,13 +359,41 @@ Persist this field in every plan; this is durable plan state, not chat state: - Context impact: localized — headers-helper contract. `context/sce/telemetry-credential.md` should record that `sce auth telemetry-headers` checks the effective telemetry policy (resolved from its working directory) before the destination tripwire, readiness hint, repository resolution, and `auth.db` lookup, and fails closed with the existing fixed diagnostic. - Context synchronization: synced -- [ ] T06: `Enforce auth mode and telemetry consent in auth login and whoami` (status:todo) +- [x] T06: `Enforce auth mode and telemetry consent in auth login and whoami` (status:done) - Task ID: T06 - Scope: In — `UserError::AuthDisabledByConfig` (`auth.disabled_by_config`) in `error.rs`; `run_login` and `run_whoami` checking the policy from `resolve_auth_runtime_config` before any `token_storage` call; `TelemetryProvisioningResult::Disabled` (status `disabled`, fixed message naming `telemetry.enabled`) and skipping `provision_telemetry_credential` when telemetry is not `Enabled`; `mandatory` unauthenticated `whoami` → `NotAuthenticated`; logout unchanged. Out — sync, setup. - Dependencies: T02 - Done when: the auth rows of the behavior matrix hold for all three modes; `optional` outputs are byte-identical to today; logout under `disabled` still deletes both credential rows. - Verify: table-driven tests over mode × stored credentials {none, valid, expired} using injected storage/provision closures that fail if called where access is forbidden; login text/JSON rendering tests for `disabled` provisioning; `run_logout_with` test under `disabled`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml auth_command error`. - - Context synchronization: pending + - Completed: 2026-10-20 + - Files changed: `cli/src/services/error.rs`, `cli/src/services/auth_command/mod.rs`, `cli/src/services/config/types.rs`, `context/plans/auth-telemetry-policy-config.md` + - Result: + - Added `UserError::AuthDisabledByConfig(AuthPolicyConfigFile)` (key `auth.disabled_by_config`, runtime class). `AuthPolicyConfigFile` is `Global | Repository | ConfigFlag | ConfigEnv`. Each variant has a fixed message: `Authentication is disabled by \`auth.mode: disabled\` in .`, a blank line, then `To use SCE authentication, set \`auth.mode\` to \`optional\` or \`mandatory\` in that file, then retry.` + - `run_login` and `run_whoami` resolve config through `resolve_auth_runtime_config` first. They delegate to the new `run_login_with` / `run_whoami_with`, which call `ensure_auth_allowed` before the injected `load_tokens`. That check maps `auth_mode.source` to the config file named in the message. + - Added `TelemetryProvisioningResult::Disabled` (status `disabled`, message ``Telemetry credential provisioning is disabled by SCE config. Set `telemetry.enabled: true` in the global SCE config to enable it.``). Text login renders it as `Note: ` under the headline. + - `provision_if_enabled` returns `Disabled` without running provisioning (no issuance, no readiness hint, no enrollment) on both the renewal path and the text/JSON device-flow paths. + - `whoami` with no stored credentials returns `UserError::NotAuthenticated` under `mandatory` and keeps the existing unauthenticated success render under `optional`. + - Logout is unchanged. + - Removed `#[allow(dead_code)]` from `ResolvedAccessPolicy::auth_allowed`. + - Removed the doc comments on `UserError`, `AuthStorageFailure`, and the new enum in `error.rs`, at the user's request. + - Verify outcome: + - `auth_command` passed (20 passed, 0 failed). + - New tests: + - `login_follows_auth_mode_across_stored_credentials`: 3 modes × {none, valid, expired}. Under `disabled`, storage is never read. + - `login_skips_provisioning_unless_telemetry_is_enabled`: the provisioning closure panics if called. + - `whoami_follows_auth_mode_across_stored_credentials`: `optional` and unauthenticated gives byte-identical output; `mandatory` and none, or expired, gives `auth.not_authenticated`. + - `auth_disabled_rejection_names_the_deciding_config_file` + - `login_reports_disabled_telemetry_provisioning_in_text_and_json` + - `logout_deletes_both_credential_rows_when_auth_is_disabled_by_config` + - `error` filter: the new `auth_disabled_by_config_has_stable_runtime_catalog_mapping_per_file` passed. In 2 of 5 filtered runs, the unrelated `app::tests::managed_export_marks_failed_output_and_exports_final_error_log` failed intermittently: it runs `sce help` against a loopback collector, hit its 5 s receive timeout, and passed on rerun. It does not touch auth code. + - Full CLI suite passed (690 passed, 0 failed). + - `cargo clippy --all-targets -- -D warnings` via `run-cli-cargo.sh` passed. `cargo fmt` applied. + - Deviation: + - `ResolvedValue` records a layer kind, not a path, so the rejection message names the config layer (global, repository `.sce/config.json`, `--config` file, `SCE_CONFIG_FILE` file) rather than a filesystem path. + - `whoami` now resolves config before reading storage. With an invalid explicit config file, an unauthenticated `whoami` now fails with the config error instead of rendering the unauthenticated success. + - Logout takes no policy input, so its `disabled` test resolves a real `auth.mode: disabled` config and then shows that `run_logout_with` still clears readiness and deletes both rows. + - Context impact: localized — the auth command contract. `context/cli/cli-command-surface.md` should record that `login` and `whoami` are rejected with `auth.disabled_by_config` before credential-store access, `login` reports `telemetry_provisioning` `disabled` without telemetry consent, and unauthenticated `whoami` under `mandatory` fails with `auth.not_authenticated`. `context/sce/telemetry-credential.md` should record that provisioning during login is gated on the telemetry policy. `context/sce/auth-db.md` should note that `login` and `whoami` do not reach `auth.db` under `disabled`. + - Context synchronization: synced - [ ] T07: `Gate sce sync and post-commit auto-sync on auth policy` (status:todo) - Task ID: T07 diff --git a/context/sce/auth-db.md b/context/sce/auth-db.md index e74776f7d..f812f8965 100644 --- a/context/sce/auth-db.md +++ b/context/sce/auth-db.md @@ -138,7 +138,7 @@ Remaining limits: a mixed old/new deployment is still not usable at the same tim - The `auth_credentials` row uses constant integer ID `1` for single-row token storage. - Encryption is required: `encryption_key::get_or_create_encryption_key()` first honors `SCE_AUTH_DB_ENCRYPTION_KEY` by deriving a deterministic 64-character hex Turso key from the non-empty env-secret text, then falls back to the OS credential store when the env var is absent. No plaintext auth DB fallback exists. - Credential access is explicit (`encryption_key::CredentialAccess`): - - `Interactive`: used only by `sce auth login`, `logout`, and `whoami`. It may show the macOS Keychain authorization dialog. It generates and stores a new key only when the keyring reports `NoEntry` and `auth.db` does not exist. Any other read error is returned and never overwrites the stored key. A read or write failure is tagged with the typed `CredentialAccessDenied` marker only when the keyring reports `NoStorageAccess`, or, on macOS, a `PlatformFailure` whose `OSStatus` is `errSecUserCanceled`, `errSecNoAccessForItem`, `errSecAuthFailed`, `errSecInteractionNotAllowed`, or `errSecInteractionRequired`. Classification uses these codes, never error text. + - `Interactive`: used only by `sce auth login`, `logout`, and `whoami`. `login` and `whoami` reach it only after the effective access policy allows auth, so under `auth.mode: disabled` they never open `auth.db` or touch the credential store; `logout` is never policy-gated. It may show the macOS Keychain authorization dialog. It generates and stores a new key only when the keyring reports `NoEntry` and `auth.db` does not exist. Any other read error is returned and never overwrites the stored key. A read or write failure is tagged with the typed `CredentialAccessDenied` marker only when the keyring reports `NoStorageAccess`, or, on macOS, a `PlatformFailure` whose `OSStatus` is `errSecUserCanceled`, `errSecNoAccessForItem`, `errSecAuthFailed`, `errSecInteractionNotAllowed`, or `errSecInteractionRequired`. Classification uses these codes, never error text. - `NonInteractive`: used by Claude hooks, managed telemetry startup, the `sce doctor` telemetry health check, `sce auth telemetry-headers`, and `sce sync` (including post-commit auto-sync). It only reads, never creates. On macOS it wraps the read in `SecKeychain::disable_user_interaction()` (`SecKeychainSetUserInteractionAllowed(false)`, the UI switch for the legacy file-based keychain API that `apple-native-keyring-store`'s `keychain` feature uses through `SecKeychainFindGenericPassword`). An item the binary is not authorized for, or a locked keychain, fails with `errSecInteractionNotAllowed` instead of prompting. Every failure becomes `CredentialAccessUnavailable`. `kSecUseAuthenticationUIFail` and `LAContext.interactionNotAllowed` do not apply, because they belong to the `SecItem`/data-protection keychain and LocalAuthentication-protected items, which this adapter does not use. - The interaction switch is process-wide, so all credential-store reads and writes in one process are serialized by a mutex. Interaction is turned back on before the next caller runs. - Linux Secret Service and Windows have no equivalent switch in the adapter. `NonInteractive` there only guarantees no key creation. Missing/unavailable credential-store failures surface as `TokenStorageError::Database` and include platform-specific remediation for Linux system keyring/Secret Service, macOS Keychain, Windows Credential Store, or unsupported platforms, always mentioning `SCE_AUTH_DB_ENCRYPTION_KEY` for headless/CI use without printing the secret value. diff --git a/context/sce/telemetry-credential.md b/context/sce/telemetry-credential.md index 3dc344eb9..02c6d497a 100644 --- a/context/sce/telemetry-credential.md +++ b/context/sce/telemetry-credential.md @@ -8,7 +8,7 @@ The CLI holds one telemetry-only OpenBao credential, issued by the Control Plane - Identity: the credential is bound to the `(sub, workspace_id)` claims of the exact WorkOS access token sent with the issuance request, the same verified claims Control Plane reads into `CurrentUser` to mint the token. If that bearer has no complete identity (no `workspace_id`, or an undecodable token), issuance fails with the fixed invalid-response error and nothing is saved. - Save-on-issue: `issue_and_save_telemetry_credential` persists only after successful issuance, so any failure leaves previously stored state intact. - Storage: `cli/src/services/telemetry_credential_storage.rs` (`save_telemetry_credential`, `load_telemetry_credential`, `delete_telemetry_credential`) over the shared `AuthDb`; schema in [auth-db.md](auth-db.md). -- Auth login provisioning: every successful `sce auth login` path — fresh device authorization, valid stored credentials, and renewed stored credentials — invokes `AuthenticatedControlPlaneClient::issue_and_save_telemetry_credential` after WorkOS persistence. The deterministic `telemetry_provisioning` result reports `issued` or `unavailable`; unavailable provisioning preserves WorkOS authentication success and gives text callers a fixed secret-free retry warning. +- Auth login provisioning: when the effective access policy enables telemetry, every successful `sce auth login` path — fresh device authorization, valid stored credentials, and renewed stored credentials — invokes `AuthenticatedControlPlaneClient::issue_and_save_telemetry_credential` after WorkOS persistence. The deterministic `telemetry_provisioning` result reports `issued`, `unavailable`, or `disabled`; unavailable provisioning preserves WorkOS authentication success and gives text callers a fixed secret-free retry warning. When telemetry is not enabled the result is `disabled` with a fixed note naming `telemetry.enabled`, and login issues no credential, writes no readiness hint, and enrolls no repository (see [effective access policy](../cli/access-policy.md#enforcement)). ## Lifecycle From 30a52279f475514cde1bd8a0692fada3772423d0 Mon Sep 17 00:00:00 2001 From: David Abram Date: Tue, 20 Oct 2026 15:00:42 +0200 Subject: [PATCH 7/9] auth+sync: Gate cloud sync on access policy Reject sync before Agent Trace storage or credential access when auth is disabled, and map the rejection to the stable auth.disabled_by_config error. Gate post-commit auto-sync and doctor readiness on the same background-cloud policy while preserving optional and mandatory behavior. Share the deciding config-file mapping across auth commands and sync, and record a debug event when configured auto-sync is suppressed. Update the CLI context and T07 completion evidence for the policy boundary. Plan: auth-telemetry-policy-config (T07) Co-authored-by: SCE --- .../app/doctor_reconciliation_cli_tests.rs | 36 +++++ cli/src/services/auth_command/mod.rs | 28 +--- cli/src/services/config/resolver.rs | 4 +- cli/src/services/config/types.rs | 24 +++- cli/src/services/doctor/inspect.rs | 4 +- cli/src/services/hooks/commit_hooks.rs | 131 ++++++++++++++++-- cli/src/services/sync/command.rs | 32 ++++- cli/src/services/sync/sync.rs | 50 ++++++- context/architecture.md | 2 +- context/cli/access-policy.md | 6 +- context/cli/agent-trace-auto-sync.md | 18 ++- context/cli/cli-command-surface.md | 2 +- context/cli/sync-command.md | 7 + context/context-map.md | 2 +- context/glossary.md | 2 +- context/patterns.md | 2 +- context/plans/auth-telemetry-policy-config.md | 30 +++- context/sce/auth-db.md | 2 +- context/sce/doctor-human-text-contract.md | 6 +- 19 files changed, 327 insertions(+), 61 deletions(-) diff --git a/cli/src/app/doctor_reconciliation_cli_tests.rs b/cli/src/app/doctor_reconciliation_cli_tests.rs index 0e1f2c301..7793242d0 100644 --- a/cli/src/app/doctor_reconciliation_cli_tests.rs +++ b/cli/src/app/doctor_reconciliation_cli_tests.rs @@ -707,6 +707,42 @@ async fn doctor_fix_reports_unreadable_telemetry_credentials_without_auth_side_e assert!(!fix.stderr.contains(AUTH_DB_TEST_SECRET)); } +#[tokio::test(flavor = "multi_thread")] +async fn doctor_reports_post_commit_auto_sync_disabled_when_auth_is_disabled() { + let sandbox = Sandbox::new("https://example.invalid/org/repo-a.git"); + let config_dir = sandbox.repo.join(".sce"); + std::fs::create_dir_all(&config_dir).expect("config dir"); + let config = config_dir.join("config.json"); + + std::fs::write(&config, r#"{"agent_trace":{"auto_sync":true}}"#).expect("config"); + let allowed = sandbox.run(&["doctor", "--format", "json"]).json(); + assert_eq!(allowed["post_commit_auto_sync"]["enabled"], true); + assert_ne!(allowed["post_commit_auto_sync"]["state"], "disabled"); + + std::fs::write( + &config, + r#"{"agent_trace":{"auto_sync":true},"auth":{"mode":"disabled"}}"#, + ) + .expect("config"); + let report = sandbox.run(&["doctor", "--format", "json"]).json(); + assert_eq!( + report["post_commit_auto_sync"], + serde_json::json!({ + "state": "disabled", + "enabled": false, + "source": "config_file", + "config_source": "default_discovered_local", + }) + ); + let text = sandbox.run(&["doctor"]); + assert!( + text.stdout + .contains("[PASS] Post-commit Agent Trace auto-sync (disabled by config)\n"), + "{}", + text.stdout + ); +} + #[tokio::test(flavor = "multi_thread")] async fn doctor_with_telemetry_disabled_by_config_never_reads_the_auth_db() { let sandbox = Sandbox::new("https://example.invalid/org/repo-a.git"); diff --git a/cli/src/services/auth_command/mod.rs b/cli/src/services/auth_command/mod.rs index f355abcbf..863ca6786 100644 --- a/cli/src/services/auth_command/mod.rs +++ b/cli/src/services/auth_command/mod.rs @@ -11,11 +11,9 @@ use crate::services::agent_trace_sync::control_plane::{ AuthenticatedControlPlaneClient, ControlPlaneError, MeResponse, }; use crate::services::auth::{self, AuthError, DeviceAuthFlowResult}; -use crate::services::config::{ - self, AuthMode, ConfigPathSource, ResolvedAccessPolicy, ResolvedAuthRuntimeConfig, ValueSource, -}; +use crate::services::config::{self, AuthMode, ResolvedAccessPolicy, ResolvedAuthRuntimeConfig}; use crate::services::db::encryption_key::CredentialAccess; -use crate::services::error::{AuthPolicyConfigFile, AuthStorageFailure, CliError, UserError}; +use crate::services::error::{AuthStorageFailure, CliError, UserError}; use crate::services::managed_telemetry::claude_helper::{ repository_id_for, visible_destination_conflict, }; @@ -189,30 +187,14 @@ fn resolve_current_auth_config() -> Result } fn ensure_auth_allowed(policy: &ResolvedAccessPolicy) -> Result<(), CliError> { - if policy.auth_allowed() { + let Some(file) = policy.auth_disabled_config_file() else { return Ok(()); - } - let source = policy.auth_mode.source; - let file = match source { - ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal) => { - AuthPolicyConfigFile::Repository - } - ValueSource::Flag | ValueSource::ConfigFile(ConfigPathSource::Flag) => { - AuthPolicyConfigFile::ConfigFlag - } - ValueSource::Env | ValueSource::ConfigFile(ConfigPathSource::Env) => { - AuthPolicyConfigFile::ConfigEnv - } - ValueSource::Default - | ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal) => { - AuthPolicyConfigFile::Global - } }; Err(CliError::user_with_source( UserError::AuthDisabledByConfig(file), anyhow!( "auth.mode resolved to disabled (source: {})", - source.as_str() + policy.auth_mode.source.as_str() ), )) } @@ -849,6 +831,8 @@ fn unexpected_auth_command_error(error: anyhow::Error) -> CliError { #[cfg(test)] mod tests { use super::*; + use crate::services::config::{ConfigPathSource, ValueSource}; + use crate::services::error::AuthPolicyConfigFile; fn storage_failure() -> TokenStorageError { TokenStorageError::Database("failed".to_string()) diff --git a/cli/src/services/config/resolver.rs b/cli/src/services/config/resolver.rs index 5a730f9c9..2110abbe3 100644 --- a/cli/src/services/config/resolver.rs +++ b/cli/src/services/config/resolver.rs @@ -179,7 +179,7 @@ pub(crate) fn resolve_hook_runtime_config(cwd: &Path) -> Result Result> { +) -> Result<(ResolvedValue, ResolvedAccessPolicy)> { let runtime = resolve_runtime_config_with( &ConfigRequest { report_format: ReportFormat::Text, @@ -196,7 +196,7 @@ pub(crate) fn resolve_agent_trace_auto_sync_runtime_config( resolve_default_global_config_path, )?; - Ok(runtime.agent_trace_auto_sync) + Ok((runtime.agent_trace_auto_sync, runtime.access_policy)) } pub(crate) fn resolve_agent_trace_storage_runtime_config( diff --git a/cli/src/services/config/types.rs b/cli/src/services/config/types.rs index 7cb4410a0..199010bed 100644 --- a/cli/src/services/config/types.rs +++ b/cli/src/services/config/types.rs @@ -9,6 +9,7 @@ use std::path::PathBuf; use clap::ValueEnum; +use crate::services::error::AuthPolicyConfigFile; use crate::services::output_format::OutputFormat; pub const NAME: &str = "config"; @@ -193,10 +194,30 @@ impl ResolvedAccessPolicy { self.auth_mode.value != AuthMode::Disabled } - #[allow(dead_code)] pub(crate) fn auto_sync_allowed(&self, configured: bool) -> bool { configured && self.background_cloud_allowed } + + pub(crate) fn auth_disabled_config_file(&self) -> Option { + if self.auth_allowed() { + return None; + } + Some(match self.auth_mode.source { + ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal) => { + AuthPolicyConfigFile::Repository + } + ValueSource::Flag | ValueSource::ConfigFile(ConfigPathSource::Flag) => { + AuthPolicyConfigFile::ConfigFlag + } + ValueSource::Env | ValueSource::ConfigFile(ConfigPathSource::Env) => { + AuthPolicyConfigFile::ConfigEnv + } + ValueSource::Default + | ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal) => { + AuthPolicyConfigFile::Global + } + }) + } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -305,7 +326,6 @@ pub(crate) struct ResolvedObservabilityRuntimeConfig { pub(crate) struct ResolvedHookRuntimeConfig { pub(crate) attribution_hooks_enabled: bool, pub(crate) agent_trace_auto_sync: bool, - #[allow(dead_code)] pub(crate) access_policy: ResolvedAccessPolicy, } diff --git a/cli/src/services/doctor/inspect.rs b/cli/src/services/doctor/inspect.rs index 0ea03100d..f2cd3d2ff 100644 --- a/cli/src/services/doctor/inspect.rs +++ b/cli/src/services/doctor/inspect.rs @@ -515,9 +515,9 @@ fn collect_post_commit_auto_sync_health( ) -> PostCommitAutoSyncHealth { let resolved = config::resolve_agent_trace_auto_sync_runtime_config(repository_root).ok(); let (enabled, source, config_source) = - resolved.map_or((true, "unresolved", None), |resolved| { + resolved.map_or((true, "unresolved", None), |(resolved, access_policy)| { ( - resolved.value, + access_policy.auto_sync_allowed(resolved.value), resolved.source.as_str(), resolved .source diff --git a/cli/src/services/hooks/commit_hooks.rs b/cli/src/services/hooks/commit_hooks.rs index 4d2bf2a82..5e360261b 100644 --- a/cli/src/services/hooks/commit_hooks.rs +++ b/cli/src/services/hooks/commit_hooks.rs @@ -13,7 +13,7 @@ use crate::services::agent_trace::{ use crate::services::agent_trace_db::{ AgentTraceInsert, PostCommitPatchIntersectionInsert, RecentDiffTracePatches, }; -use crate::services::config; +use crate::services::config::{self, ResolvedHookRuntimeConfig}; use crate::services::patch::{ combine_patches as combine_patches_fn, intersect_patches as intersect_patches_fn, parse_patch as parse_patch_from_text, ParsedPatch, @@ -126,9 +126,7 @@ pub(crate) async fn run_post_commit_subcommand< remote_url, run_post_commit_intersection_flow, run_post_commit_agent_trace_flow, - |root| { - config::resolve_hook_runtime_config(root).map(|runtime| runtime.agent_trace_auto_sync) - }, + config::resolve_hook_runtime_config, |root| { auto_sync::launch(root); Ok(()) @@ -153,7 +151,7 @@ pub(crate) async fn run_post_commit_subcommand_with< remote_url: &str, run_intersection_flow: F, run_agent_trace_flow: B, - resolve_auto_sync: C, + resolve_hook_config: C, launch_auto_sync: Launch, run_passive_checkpoint: K, logger: Option<&L>, @@ -167,7 +165,7 @@ where &str, Option<&L>, ) -> Result, - C: FnOnce(&Path) -> Result, + C: FnOnce(&Path) -> Result, Launch: FnOnce(&Path) -> Result<()>, K: std::ops::AsyncFnOnce(&Path) -> Result<()>, { @@ -186,8 +184,21 @@ where } } - if resolve_auto_sync(repository_root)? { + let hook_config = resolve_hook_config(repository_root)?; + if hook_config + .access_policy + .auto_sync_allowed(hook_config.agent_trace_auto_sync) + { let _ = launch_auto_sync(repository_root); + } else if hook_config.agent_trace_auto_sync { + if let Some(log) = logger { + log.debug( + AUTO_SYNC_SKIPPED_BY_POLICY_EVENT, + AUTO_SYNC_SKIPPED_BY_POLICY_MESSAGE, + &[], + None, + ); + } } Ok(format!( @@ -207,6 +218,10 @@ pub(crate) async fn run_post_commit_passive_checkpoint(repository_root: &Path) - db.passive_checkpoint().await } +const AUTO_SYNC_SKIPPED_BY_POLICY_EVENT: &str = "sce.agent_trace.auto_sync_skipped_by_policy"; +const AUTO_SYNC_SKIPPED_BY_POLICY_MESSAGE: &str = + "Post-commit auto-sync skipped: background cloud operations are not allowed by SCE config."; + pub(crate) const COMMIT_PATCH_ID_UNAVAILABLE_EVENT: &str = "sce.agent_trace.commit_patch_id_unavailable"; @@ -745,8 +760,9 @@ mod tests { use anyhow::{anyhow, Result}; - use crate::services::agent_trace::{validate_agent_trace_value, AgentTrace}; + use crate::services::agent_trace::{validate_agent_trace_value, AgentTrace, AgentTraceVcsType}; use crate::services::agent_trace_db::AgentTraceInsert; + use crate::services::config::resolver::resolve_hook_runtime_config_with; use crate::services::error::CliError; use crate::services::observability::traits::Logger; use crate::services::patch::ParsedPatch; @@ -754,7 +770,8 @@ mod tests { use super::super::commit_patch_id::compute_commit_patch_id; use super::{ capture_post_commit_patch_from_git, resolve_post_commit_commit_patch_id, - run_post_commit_agent_trace_flow_with, PostCommitIntersectionFlowResult, + run_post_commit_agent_trace_flow_with, run_post_commit_subcommand_with, + PostCommitIntersectionFlowResult, AUTO_SYNC_SKIPPED_BY_POLICY_EVENT, COMMIT_PATCH_ID_UNAVAILABLE_EVENT, }; @@ -766,17 +783,24 @@ mod tests { #[derive(Default)] struct RecordingLogger { warnings: Mutex>, + debugs: Mutex>, } impl RecordingLogger { fn warnings(&self) -> Vec<(String, String)> { self.warnings.lock().unwrap().clone() } + + fn debugs(&self) -> Vec { + self.debugs.lock().unwrap().clone() + } } impl Logger for RecordingLogger { fn info(&self, _: &str, _: &str, _: &[(&str, &str)], _: Option<&str>) {} - fn debug(&self, _: &str, _: &str, _: &[(&str, &str)], _: Option<&str>) {} + fn debug(&self, event_id: &str, _: &str, _: &[(&str, &str)], _: Option<&str>) { + self.debugs.lock().unwrap().push(event_id.to_string()); + } fn warn(&self, event_id: &str, message: &str, _: &[(&str, &str)], _: Option<&str>) { self.warnings .lock() @@ -1016,4 +1040,91 @@ mod tests { .expect_err("persistence failure must propagate"); assert_eq!(persistence_error.to_string(), "persistence rejected"); } + + #[tokio::test] + async fn post_commit_launches_auto_sync_only_when_background_cloud_is_allowed() { + let dir = tempfile::tempdir().expect("temp dir"); + let root = dir.path().join("repo"); + std::fs::create_dir_all(&root).expect("repo dir"); + init_repository_with_commit(&root); + let global = dir.path().join("global.json"); + let local = root.join(".sce").join("config.json"); + std::fs::create_dir_all(local.parent().expect("local config dir")).expect("local dir"); + + for auto_sync in [false, true] { + for (case, auth_mode, degraded) in [ + ("disabled", "disabled", false), + ("optional", "optional", false), + ("mandatory", "mandatory", false), + ("degraded", "optional", true), + ] { + std::fs::write( + &global, + format!( + r#"{{"agent_trace":{{"auto_sync":{auto_sync}}},"auth":{{"mode":"{auth_mode}"}}}}"# + ), + ) + .expect("global config"); + if degraded { + std::fs::write(&local, r#"{"auth":{"mode":"bogus"}}"#).expect("local config"); + } else { + let _ = std::fs::remove_file(&local); + } + + let logger = RecordingLogger::default(); + let launches = RefCell::new(0_usize); + let output = run_post_commit_subcommand_with( + &root, + None, + REMOTE_URL, + async |root: &Path| Ok(flow_result(root)), + async |_: &Path, + result: &PostCommitIntersectionFlowResult, + _: Option, + _: &str, + _: Option<&RecordingLogger>| { + Ok(run_flow_capturing(result, None).await.0) + }, + |root| { + resolve_hook_runtime_config_with( + root, + |_| None, + |path| std::fs::read_to_string(path).map_err(anyhow::Error::from), + Path::exists, + || Ok(global.clone()), + ) + }, + |_| { + *launches.borrow_mut() += 1; + Ok(()) + }, + async |_: &Path| Ok(()), + Some(&logger), + ) + .await + .unwrap_or_else(|error| panic!("{case} auto_sync={auto_sync}: {error:#}")); + + let allowed = auth_mode != "disabled" && !degraded; + assert!( + output.starts_with("post-commit hook processed intersection: commit="), + "{case} auto_sync={auto_sync}: {output}" + ); + assert_eq!( + *launches.borrow(), + usize::from(auto_sync && allowed), + "{case} auto_sync={auto_sync}" + ); + let expected_debugs = if auto_sync && !allowed { + vec![AUTO_SYNC_SKIPPED_BY_POLICY_EVENT.to_string()] + } else { + Vec::new() + }; + assert_eq!( + logger.debugs(), + expected_debugs, + "{case} auto_sync={auto_sync}" + ); + } + } + } } diff --git a/cli/src/services/sync/command.rs b/cli/src/services/sync/command.rs index c83165518..b62f88651 100644 --- a/cli/src/services/sync/command.rs +++ b/cli/src/services/sync/command.rs @@ -33,7 +33,9 @@ where #[allow(clippy::needless_pass_by_value)] fn classify_sync_error(err: TraceSyncError) -> CliError { - if let Some(failure) = err.storage_failure() { + if let TraceSyncError::AuthDisabled(file) = err { + CliError::user_with_source(UserError::AuthDisabledByConfig(file), err) + } else if let Some(failure) = err.storage_failure() { CliError::user_with_source(UserError::AuthStorageUnavailable(failure), err) } else if err.is_authentication_failure() { CliError::user_with_source(UserError::NotAuthenticated, err) @@ -92,3 +94,31 @@ impl SyncCommand { .map_err(|error| CliError::runtime(anyhow::Error::msg(format!("{error:#}")))) } } + +#[cfg(test)] +mod tests { + use super::classify_sync_error; + use crate::services::error::{AuthPolicyConfigFile, CliError, UserError}; + use crate::services::sync::sync::TraceSyncError; + + #[test] + fn classify_sync_error_maps_disabled_auth_to_auth_disabled_by_config() { + for file in [ + AuthPolicyConfigFile::Global, + AuthPolicyConfigFile::Repository, + AuthPolicyConfigFile::ConfigFlag, + AuthPolicyConfigFile::ConfigEnv, + ] { + let error = classify_sync_error(TraceSyncError::AuthDisabled(file)); + let CliError::User { + error: user_error, .. + } = &error + else { + panic!("expected a user-facing error for {file:?}"); + }; + assert_eq!(*user_error, UserError::AuthDisabledByConfig(file)); + assert_eq!(user_error.key(), "auth.disabled_by_config"); + assert_eq!(error.to_string(), user_error.message()); + } + } +} diff --git a/cli/src/services/sync/sync.rs b/cli/src/services/sync/sync.rs index a07ff6a39..d04683962 100644 --- a/cli/src/services/sync/sync.rs +++ b/cli/src/services/sync/sync.rs @@ -26,7 +26,7 @@ use crate::services::agent_trace_sync::{ use crate::services::auth; use crate::services::config; use crate::services::db::encryption_key::CredentialAccess; -use crate::services::error::AuthStorageFailure; +use crate::services::error::{AuthPolicyConfigFile, AuthStorageFailure}; use crate::services::sync::progress::ProgressReporter; #[derive(Clone, Debug, PartialEq, Eq)] @@ -100,6 +100,7 @@ where pub enum TraceSyncError { /// Local repository/storage/config resolution failed. Runtime(String), + AuthDisabled(AuthPolicyConfigFile), /// The initial `/state` call failed terminally. ControlPlane(ControlPlaneError), /// One stream failed to converge. @@ -113,6 +114,7 @@ impl fmt::Display for TraceSyncError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Runtime(reason) => write!(f, "{reason}"), + Self::AuthDisabled(_) => write!(f, "auth.mode resolved to disabled"), Self::ControlPlane(error) => write!(f, "{error}"), Self::Stream { stream, source } => write!(f, "'{stream}' stream sync failed: {source}"), } @@ -129,7 +131,7 @@ impl TraceSyncError { /// authentication failure. pub fn is_authentication_failure(&self) -> bool { match self { - Self::Runtime(_) => false, + Self::Runtime(_) | Self::AuthDisabled(_) => false, Self::ControlPlane(error) => error.is_authentication_failure(), Self::Stream { source, .. } => source.is_authentication_failure(), } @@ -142,7 +144,7 @@ impl TraceSyncError { match self { Self::ControlPlane(error) => error.storage_failure(), Self::Stream { source, .. } => source.storage_failure(), - Self::Runtime(_) => None, + Self::Runtime(_) | Self::AuthDisabled(_) => None, } } } @@ -174,6 +176,11 @@ async fn run_current_sync_without_progress( where S: ProgressReporter, { + let auth_config = config::resolve_auth_runtime_config(repo_root) + .map_err(|error| TraceSyncError::Runtime(format!("{error:#}")))?; + if let Some(file) = auth_config.access_policy.auth_disabled_config_file() { + return Err(TraceSyncError::AuthDisabled(file)); + } let storage_config = config::resolve_agent_trace_storage_runtime_config(repo_root) .map_err(|error| TraceSyncError::Runtime(format!("{error:#}")))?; let context = AgentTraceStorageContext { @@ -184,8 +191,6 @@ where let storage = resolve_agent_trace_storage(&context) .await .map_err(|error| TraceSyncError::Runtime(format!("{error:#}")))?; - let auth_config = config::resolve_auth_runtime_config(repo_root) - .map_err(|error| TraceSyncError::Runtime(format!("{error:#}")))?; let client = AuthenticatedControlPlaneClient::new( reqwest::Client::new(), auth_config.control_plane_base_url.value.unwrap_or_default(), @@ -541,7 +546,10 @@ mod tests { use serde_json::{json, Value}; use tokio::sync::{oneshot, Notify}; - use super::{join_three_to_completion, sync_one_stream, StreamSyncReport, TraceSyncError}; + use super::{ + join_three_to_completion, run_current_sync_with_progress_and_clock, sync_one_stream, + StreamSyncReport, SystemSyncProgressClock, TraceSyncError, + }; use crate::services::agent_trace_db::MessageRole; use crate::services::agent_trace_export::AgentTraceMessageExportRow; use crate::services::agent_trace_sync::control_plane::{ @@ -551,6 +559,7 @@ mod tests { use crate::services::agent_trace_sync::StreamSyncError; use crate::services::auth::TokenResponse; use crate::services::db::encryption_key::CredentialAccess; + use crate::services::error::AuthPolicyConfigFile; use crate::services::sync::progress::NoopProgressReporter; use crate::services::token_storage::StoredTokens; @@ -560,6 +569,35 @@ mod tests { const TEST_DEADLINE: Duration = Duration::from_secs(10); const STALL_SAFETY_BOUND: Duration = Duration::from_secs(10); + #[tokio::test] + async fn sync_rejects_disabled_auth_before_storage_or_credential_access() { + let dir = tempfile::tempdir().expect("temp dir"); + std::fs::create_dir_all(dir.path().join(".sce")).expect("config dir"); + std::fs::write( + dir.path().join(".sce").join("config.json"), + r#"{"auth":{"mode":"disabled"}}"#, + ) + .expect("repository config"); + + let error = run_current_sync_with_progress_and_clock( + dir.path(), + &mut NoopProgressReporter, + &SystemSyncProgressClock, + ) + .await + .expect_err("disabled auth must reject sync"); + + assert!( + matches!( + error, + TraceSyncError::AuthDisabled(AuthPolicyConfigFile::Repository) + ), + "{error:?}" + ); + assert!(!error.is_authentication_failure()); + assert_eq!(error.storage_failure(), None); + } + #[tokio::test] async fn sibling_failure_does_not_cancel_in_flight_credential_save() { let (save_started_tx, save_started_rx) = oneshot::channel::<()>(); diff --git a/context/architecture.md b/context/architecture.md index 6c6d2bbca..e54488b2f 100644 --- a/context/architecture.md +++ b/context/architecture.md @@ -80,7 +80,7 @@ The repository includes a new placeholder Rust binary crate at `cli/`. - `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. - `cli/src/services/sync/progress.rs` owns the sync-local, consumer-typed progress seam: generic `ProgressReporter` supports event delivery plus explicit successful finalization, closure-based collectors, and a no-op implementation alongside the fixed `indicatif` stderr presentation adapter. `cli/src/services/sync/sync.rs` owns `SyncProgressEvent` and its payload semantics for the three remotely synchronized streams (`messages`, `parts`, `agent_traces`; `diff_traces` is captured locally but not synchronized), while `sync/command.rs` selects the terminal adapter for text and the no-op reporter for JSON. There is no top-level `cli/src/services/progress/` module; sync orchestration depends only on its sync-owned contract, so terminal-library details stay at the sync presentation boundary. -- `sce sync [--format text|json]` is implemented: `cli/src/services/sync/sync.rs` resolves repository-scoped Agent Trace storage, authenticates against the control plane with stored WorkOS credentials, uses the config-resolved `control_plane_base_url` with baked default `https://sce.crocoderlab.dev`, calls the ingestion `/state` endpoint once, then starts the three remote `messages`/`parts`/`agent_traces` stream state machines concurrently (`diff_traces` remains a local-only compatibility report) via `AgentTraceExportReader` and a shared per-stream reconciliation engine. Batches and cursor refreshes remain sequential within each stream, while fixed stream order is retained for final and stream-completion reporting; `cli/src/services/sync/render_sync.rs` renders the converged `AgentTraceSyncReport` as concise per-stream text or `camelCase` JSON without a nested subcommand field (see `context/cli/sync-command.md`). Local DB bootstrap and setup-time repository-scoped Agent Trace DB initialization otherwise still flow through lifecycle providers aggregated by setup, while repository-scoped DB health/repair flows through the doctor surface. The former trace database inspection and nested sync surfaces are unavailable. +- `sce sync [--format text|json]` is implemented: `cli/src/services/sync/sync.rs` first rejects an effective `auth.mode: disabled` (`auth.disabled_by_config`, see `context/cli/access-policy.md`), then resolves repository-scoped Agent Trace storage, authenticates against the control plane with stored WorkOS credentials, uses the config-resolved `control_plane_base_url` with baked default `https://sce.crocoderlab.dev`, calls the ingestion `/state` endpoint once, then starts the three remote `messages`/`parts`/`agent_traces` stream state machines concurrently (`diff_traces` remains a local-only compatibility report) via `AgentTraceExportReader` and a shared per-stream reconciliation engine. Batches and cursor refreshes remain sequential within each stream, while fixed stream order is retained for final and stream-completion reporting; `cli/src/services/sync/render_sync.rs` renders the converged `AgentTraceSyncReport` as concise per-stream text or `camelCase` JSON without a nested subcommand field (see `context/cli/sync-command.md`). Local DB bootstrap and setup-time repository-scoped Agent Trace DB initialization otherwise still flow through lifecycle providers aggregated by setup, while repository-scoped DB health/repair flows through the doctor surface. The former trace database inspection and nested sync surfaces are unavailable. - `cli/src/services/patch.rs` defines the standalone patch domain model (`ParsedPatch`, `PatchFileChange`, `FileChangeKind`, `PatchHunk`, `TouchedLine`, `TouchedLineKind`) for in-memory parsed unified-diff representation, capturing only touched lines (added/removed) plus minimal per-file/per-hunk metadata while excluding non-hunk headers and unchanged context lines. All types are `serde`-serializable/deserializable with `snake_case` JSON field naming. The module also provides `parse_patch`, a public parser function that converts raw unified-diff text (both `Index:` SVN-style and `diff --git` git-style formats) into `ParsedPatch` structs, with `ParseError` for actionable malformed-input diagnostics. Storage-agnostic JSON load helper (`load_patch_from_json` for string input) reconstruct `ParsedPatch` from serialized JSON content with `PatchLoadError` for actionable deserialization diagnostics. Its patch-set operations now include deterministic ordered combination plus target-shaped intersection that prefers exact touched-line matches and falls back to historical `kind`+`content` matching when incremental diffs and canonical post-commit diffs have drifted line numbers; `parse_patch`, `combine_patches`, and `intersect_patches` are consumed by the active post-commit hook runtime. - `cli/src/services/structured_patch.rs` defines the synchronous structured editor-hook derivation seam. It derives Claude `PostToolUse` `Write` structured-update hunks, `Write` `tool_input.content` create fallback, and `Edit` structured-patch payloads into canonical `ParsedPatch` values plus Claude session/tool metadata, returning deterministic skip reasons for unsupported events/tools/payload shapes. The module is pure and side-effect-free. It is wired into `sce hooks diff-trace` for Claude payload classification at intake (T04) and into `RepositoryAgentTraceDb::recent_diff_trace_patches` for post-commit structured payload parsing dispatch at read time (T05). - `cli/src/services/` contains module boundaries for command_registry, lifecycle, auth_command, config, setup, doctor, hooks, bash_policy, version, completion, help, patch, sync, SCE web URL helpers, shared database infrastructure, local DB adapters, encrypted auth DB adapters, and Agent Trace DB adapters with explicit trait seams for future implementations. The former `cli/src/services/checkout/` checkout-identity module was removed by the `remove-checkout-id` plan (see `context/cli/checkout-identity.md`); there is no per-clone identity, worktrees are identified by Git topology (`resolve_worktree_id`), active setup/hooks use `agent_trace_storage` to initialize/open the repository-scoped DB, and `sce doctor` surfaces credential-safe repository Agent Trace DB metadata. There is no checkout-scoped discovery or former trace inspection surface; any pre-migration `agent-trace-*.db` files on disk are never touched and no longer inspectable via the CLI. `cli/src/services/bash_policy.rs` owns both the CLI-agnostic evaluator logic and the hidden `sce policy bash` command adapter used by OpenCode, Claude, and Pi callers; Codex delegates in-process to the same evaluator for its native `PreToolUse(Bash)` response. `cli/src/services/command_registry.rs` defines the static `RuntimeCommand` enum, deterministic `CommandRegistry` name catalog, and `build_default_registry()` function for command dispatch metadata. Service-owned command modules own the runtime command payload structs for help/help-text, version, completion, auth, config, setup, doctor, hooks, policy, and sync. diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md index b64e983d8..943d01f9f 100644 --- a/context/cli/access-policy.md +++ b/context/cli/access-policy.md @@ -4,7 +4,7 @@ This file describes how the CLI turns the per-layer `auth.mode` and `telemetry.enabled` config values into one effective access policy (`ResolvedAccessPolicy`). Key syntax and schema validation are in [config precedence contract](config-precedence-contract.md). The precedence model is recorded in [ADR: consent-gated access policy precedence](../decisions/2026-10-20-consent-gated-access-policy-precedence.md). -Status: the resolver computes and exposes the policy, and `sce config show` / `validate` report it (see [Reporting](#reporting)). Managed telemetry startup, `sce doctor`'s managed-telemetry health, the hidden `sce auth telemetry-headers` helper, and `sce auth login` / `whoami` enforce the policy (see [Enforcement](#enforcement)). Sync, auto-sync, and setup do not enforce it yet. +Status: the resolver computes and exposes the policy, and `sce config show` / `validate` report it (see [Reporting](#reporting)). Managed telemetry startup, `sce doctor`'s managed-telemetry and auto-sync health, the hidden `sce auth telemetry-headers` helper, `sce auth login` / `whoami`, `sce sync`, and post-commit auto-sync enforce the policy (see [Enforcement](#enforcement)). Setup does not enforce it yet. ## Terms @@ -49,6 +49,7 @@ flowchart TD - `telemetry_enabled()` is true only for `Enabled`. - `auth_allowed()` is true when the mode is not `disabled`. - `auto_sync_allowed(configured)` is `configured && background_cloud_allowed`. + - `auth_disabled_config_file()` returns the `AuthPolicyConfigFile` of the deciding layer when the mode is `disabled`, otherwise `None`. Every `auth.disabled_by_config` rejection uses it. - **Explicit config files:** an invalid explicit config file stays fatal, so it never produces a degraded policy. ## Contradiction warnings @@ -97,3 +98,6 @@ The note documents a coverage limit: telemetry opt-out does not remove Claude-na - Login provisions a telemetry credential only when telemetry is `Enabled`. Otherwise `telemetry_provisioning` is `disabled`, with the fixed message ``Telemetry credential provisioning is disabled by SCE config. Set `telemetry.enabled: true` in the global SCE config to enable it.``, shown in text as a `Note:` line. Disabled provisioning issues nothing, writes no readiness hint, and enrolls no repository. - Under `mandatory`, `whoami` without stored credentials fails with `auth.not_authenticated`. Under `optional`, it renders the unauthenticated success report as before. - **`sce auth logout`:** performs no policy check in any mode, so it still clears the readiness hint and deletes both stored credential rows under `disabled`. +- **`sce sync`:** resolves the policy from the repository root before it resolves Agent Trace storage or builds the control-plane client. Under `disabled` it fails with `auth.disabled_by_config` (same message and deciding-file naming as login), so `auth.db` and the credential store are never reached. `optional` and `mandatory` keep the existing behavior. See [sync command: error classification](sync-command.md#error-classification). +- **Post-commit auto-sync:** the hook launches `sce sync` only when `auto_sync_allowed(agent_trace.auto_sync)` holds, so auth `disabled` or a degraded config suppresses the launch. A suppressed launch is silent apart from a `debug` log, and the hook still succeeds. See [automatic Agent Trace synchronization](agent-trace-auto-sync.md#trigger-boundary). +- **`sce doctor` auto-sync row:** `post_commit_auto_sync.enabled` is the effective value (`auto_sync_allowed` of the configured value). When the policy suppresses auto-sync, the row reports state `disabled`. `source` / `config_source` still describe `agent_trace.auto_sync`. diff --git a/context/cli/agent-trace-auto-sync.md b/context/cli/agent-trace-auto-sync.md index d7378b0b4..3558582b4 100644 --- a/context/cli/agent-trace-auto-sync.md +++ b/context/cli/agent-trace-auto-sync.md @@ -30,9 +30,14 @@ Non-interactive setup does not change this key in an existing config. The separa ## Trigger boundary The post-commit hook first completes its existing Agent Trace validation and -repository-scoped database persistence. Only after both succeed does it inspect -`agent_trace.auto_sync`. When enabled, the hook asks the sync-owned launcher to -start the current `sce` executable with exactly: +repository-scoped database persistence. Only after both succeed does it resolve +the hook runtime config. It launches only when `agent_trace.auto_sync` is true +and the [effective access policy](access-policy.md#enforcement) allows +background cloud operations: `auth.mode` is not `disabled` and no discovered +config file was skipped as invalid. A launch suppressed by policy spawns +nothing, logs the `debug` event `sce.agent_trace.auto_sync_skipped_by_policy`, +and still returns the hook's normal success. When allowed, the hook asks the +sync-owned launcher to start the current `sce` executable with exactly: ```text sync --format json @@ -55,8 +60,11 @@ second synchronization database. canonical managed block is the hook-side readiness proof, using the same managed-block currency semantics as setup. The report exposes `post_commit_auto_sync` in JSON with `state`, `enabled`, `source`, and -`config_source` fields. Its states are `ready` for enabled/current, -`disabled` for an explicit false opt-out, `not_ready` for enabled but missing, +`config_source` fields. `enabled` is the effective value: the configured +setting gated by the access policy's background-cloud permission, while +`source` and `config_source` describe `agent_trace.auto_sync`. Its states are +`ready` for enabled/current, `disabled` for an explicit false opt-out or a +policy that disallows background cloud operations, `not_ready` for enabled but missing, stale, unreadable, or otherwise non-current hook content, and `not_applicable` outside repository scope. The disabled state is healthy and does not alter the existing problem/remediation or overall readiness rules for unrelated hook diff --git a/context/cli/cli-command-surface.md b/context/cli/cli-command-surface.md index 5a9299c4e..ed3cce184 100644 --- a/context/cli/cli-command-surface.md +++ b/context/cli/cli-command-surface.md @@ -107,7 +107,7 @@ An interactive `setup` run instead resolves the selection through an `inquire` m `setup` now executes end-to-end and prints deterministic completion details including selected target(s) and per-target install count. `setup` with a selected Claude target also merges Claude-native OpenTelemetry settings into user-level Claude `settings.json` (`$CLAUDE_CONFIG_DIR` else `~/.claude`) and prints a fixed telemetry line (configured, authentication pending, or skipped on conflict/malformed JSON) without failing repository setup; see [telemetry credential](../sce/telemetry-credential.md). The hidden auth helper is intentionally not part of the public command listing. `doctor` now executes end-to-end with explicit diagnosis and repair-intent surfaces: `sce doctor` stays read-only and `sce doctor --fix` selects repair-intent mode. The former Agent Trace database inspection routes are unavailable; doctor owns repository-scoped Agent Trace DB health (checkout-identity diagnostics were removed by the `remove-checkout-id` plan; see `context/cli/checkout-identity.md`). The current `doctor` runtime aggregates `ServiceLifecycle::diagnose` and `ServiceLifecycle::fix` calls across all registered service providers (`config`, `local_db`, `auth_db`, `agent_trace_db`, `hooks`) plus integration checks, covering state-root resolution, global and repo-local `sce/config.json` readability/schema validation, local DB and repository-scoped Agent Trace DB path/health, DB-parent readiness barriers, the repo hook rollout slice when a repository target is detected, and post-commit Agent Trace auto-sync readiness derived from canonical managed-block currency plus resolved configuration. The readiness fact reports enabled/current, explicit disabled, not-ready, and not-applicable states in text and JSON without launching synchronization; Claude's inventory is only `Plugins`, `Commands`, and `Skills`, while OpenCode retains `Agents`. Fix mode delegates to each provider's `fix` implementation, which reuses the canonical setup hook install flow to repair missing/stale/non-executable required hooks and missing hooks directories, and it can bootstrap missing canonical database parent directories when the resolved paths match canonical owned locations. -`sce sync [--format text|json]` is the implemented user-invocable synchronization command: it synchronizes the current repository's Agent Trace DB with the control-plane ingestion API; local DB and Agent Trace DB bootstrap continue to happen through `setup`, and DB health/repair continues to happen through `doctor`. See [agent-trace-sync-command.md](agent-trace-sync-command.md) and [sync-command.md](sync-command.md). +`sce sync [--format text|json]` is the implemented user-invocable synchronization command: it synchronizes the current repository's Agent Trace DB with the control-plane ingestion API; local DB and Agent Trace DB bootstrap continue to happen through `setup`, and DB health/repair continues to happen through `doctor`. Under `auth.mode: disabled`, `sce sync` fails with `auth.disabled_by_config` before storage or credential access (see [effective access policy](access-policy.md#enforcement)). See [agent-trace-sync-command.md](agent-trace-sync-command.md) and [sync-command.md](sync-command.md). ## Command loop and error model diff --git a/context/cli/sync-command.md b/context/cli/sync-command.md index 290f262e8..50265a0d9 100644 --- a/context/cli/sync-command.md +++ b/context/cli/sync-command.md @@ -116,6 +116,13 @@ client. The command change does not alter those semantics. ## Error classification +Before resolving storage or building the control-plane client, sync resolves +the [effective access policy](access-policy.md#enforcement) for the repository +root. Under `auth.mode: disabled` it returns `TraceSyncError::AuthDisabled`, +which `classify_sync_error` maps first to +`CliError::User { error: UserError::AuthDisabledByConfig, .. }` +(`auth.disabled_by_config`), so no credential-store access happens. + `cli/src/services/sync/command.rs`'s `classify_sync_error` maps the command's terminal `TraceSyncError` into the typed `CliError` boundary through typed predicates that traverse to `ControlPlaneError`, never string/substring diff --git a/context/context-map.md b/context/context-map.md index 4873cf921..8b5e45561 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -25,7 +25,7 @@ Feature/domain context: - `context/cli/async-persistence-guarantees.md` (verified guarantees and named limits of the directly awaited Turso persistence migration — exclusive `&mut` transactions, deferred rollback, credential-rotation and terminal-sync behavior, lease/descriptor protection — plus PR1–PR4 staging and the PR3 cleanup ledger) - `context/cli/agent-trace-sync-command.md` (composed local-to-control-plane `sce sync` architecture: the `hooks/plugins → repository Agent Trace DB → AgentTraceExportReader → sce sync → HTTPS + WorkOS Bearer → control plane` data flow, the `sce auth login` / `cd ` / `sce sync` user flow, the no-local-cursor/no-`agent-trace-sync.db`/no-Turso-Sync/no-`BridgeLock`/no-local-DWH invariants, the four-local-capture-streams versus three-remote-streams boundary with its `diff_traces` release gate, the optional `commitPatchId` field on the existing `agent_traces` stream with its Control Plane release dependency and no-backfill limit, and `401`/`409`/ambiguous-batch-failure recovery semantics) - `context/cli/config-precedence-contract.md` (implemented `sce config` show/validate command contract, deterministic `flags > env > config file > defaults` resolution order, focused `config/resolver.rs` ownership for config discovery/merge/runtime precedence plus default-discovered invalid-file degradation, focused `config/render.rs` ownership for `show`/`validate` text+JSON output construction, canonical `$schema` acceptance for startup-loaded `sce/config.json` files, shared auth-key env/config/optional baked-default support starting with `workos_client_id`, shared runtime resolution for flat logging observability keys including config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` with `/sce/logs` defaulting plus config-file/default-only positive `log_file_retention_limit`, config-file-only `agent_trace.repository_id`/`agent_trace.repository_remote` repository-identity keys with default remote `origin`, `agent_trace.auto_sync` resolution with omitted-value fallback `false`, explicit-false opt-out, and setup-written explicit `true` bootstrap behavior for the post-commit trigger boundary, the catalog-derived `integrations.optional_workflows` optional-workflow selection key, schema-validated per-layer `auth.mode` / `telemetry.enabled` sections, JSON-pointer-prefixed schema-validation errors, canonical Pkl-generated `sce/config.json` schema ownership plus CLI embedding/reuse contract including `policies.attribution_hooks.enabled` default-true/explicit-false opt-out metadata, config-file selection order, `show` provenance output, and trimmed `validate` output contract) -- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, exposure on the auth/hook/observability runtime projections, and enforcement in managed telemetry startup, `sce doctor` health (`disabled_by_config`), the hidden `sce auth telemetry-headers` helper (fail closed before readiness, repository resolution, and `auth.db`), and `sce auth login`/`whoami` (`auth.disabled_by_config` rejection before credential storage, `disabled` telemetry provisioning without consent, `mandatory` unauthenticated whoami failure); decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) +- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, exposure on the auth/hook/observability runtime projections, and enforcement in managed telemetry startup, `sce doctor` health (`disabled_by_config`), the hidden `sce auth telemetry-headers` helper (fail closed before readiness, repository resolution, and `auth.db`), `sce auth login`/`whoami` (`auth.disabled_by_config` rejection before credential storage, `disabled` telemetry provisioning without consent, `mandatory` unauthenticated whoami failure), `sce sync` (`auth.disabled_by_config` before storage or credentials), and post-commit auto-sync plus its doctor row (launch only when background cloud operations are allowed); decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) - `context/cli/capability-traits.md` (current broad CLI capability seam in `cli/src/services/capabilities.rs`, including `FsOps`/`StdFsOps` (method-less marker), `GitOps`/`ProcessGitOps` (command execution and availability), compile-time-typed borrowed AppContext wiring with scoped borrowing across directly awaited commands with associated-type narrow capability accessors plus `ContextWithRepoRoot` repo-root-scoped context derivation, generic command execution bounds, and test-only unimplemented stubs; current service internals do not consume fs/git traits until later lifecycle migration tasks) - `context/cli/service-lifecycle.md` (current async lifecycle seam in `cli/src/services/lifecycle.rs`, including default no-op `ServiceLifecycle` diagnose/fix/setup methods against narrow `HasRepoRoot`, lifecycle-owned health/fix/setup result types with generic setup messages, doctor/setup adapter boundaries, the static `LifecycleProvider` enum catalog/dispatcher, hook/config/local_db/auth_db/agent_trace_db lifecycle providers including setup-time repository-scoped Agent Trace DB initialization plus checkout identity diagnostics, implemented doctor aggregation over diagnose/fix providers, and implemented setup aggregation over `setup` providers in order config → local_db → auth_db → agent_trace_db → hooks when requested) - `context/cli/mutation-trace-protocol.md` (pure, dependency-free `cli/src/services/mutation_trace/` refinement of the verified `spec/mutation_cursor.qnt` mutation-cursor protocol: the full pure action set — `prepare`/`commit` transition logic, attribution/mutation-event materialization, snapshot-failure/database-failure taint actions, scope abandonment, and recovery with an explicit observed-tree input — plus cross-action sequence/invariant tests and a module-level Quint refinement matrix are all complete (`types.rs`, `protocol.rs`, `mod.rs`, `tests.rs`, registered with `#[allow(dead_code)]`); opaque-newtype identity refinement decisions vs. the Quint model's bounded enums, and the `coordinator.rs` target end-state seam this layout leaves room for but does not create — `store.rs`, `runtime/git_snapshot.rs`, and `runtime/coordinator.rs` (including its public `coordinate()` entrypoint) now exist, built out by the `mutation-cursor-store-persistence` and `mutation-cursor-runtime-coordinator` plans respectively; `protocol.rs` is invoked only through the runtime, and the runtime is now driven by the generic `sce hooks mutation-scope` CLI ingress and a first Claude Code adapter driver, registered by `sce setup` and reachable by a real Claude Code session, now proven against real Git repositories and a real Agent Trace DB by the `claude-mutation-scope-integration` plan's T08 regressions) diff --git a/context/glossary.md b/context/glossary.md index 19d1e10ef..b5d472e1b 100644 --- a/context/glossary.md +++ b/context/glossary.md @@ -83,7 +83,7 @@ - `sce.hook span`: The single root-of-process managed trace span a Claude-invoked SCE hook exports in place of `sce.command`, carrying `sce.agent=claude`, the hook event, tool name, outcome, and the Claude `session_id`/`tool_use_id` as correlation-only attributes. It is parented on a valid Claude-provided `TRACEPARENT` (the `claude_code.interaction` span, so it sits beside `claude_code.tool`) and is otherwise an independent root. Its only exported children are `sce.mutation_scope` (one per adapter seam call) and, beneath it, `sce.git_snapshot` and `sce.persistence`, each emitted only when that operation actually runs and carrying only `sce.outcome`. Admission is Claude-only (Claude-only hook subcommands by argv; shared hook subcommands and `sce policy bash` only with `CLAUDECODE` and `CLAUDE_PROJECT_DIR` present); see `context/sce/cli-observability-contract.md`. - `AuthDbLifecycle`: Lifecycle provider in `cli/src/services/auth_db/lifecycle.rs` that implements `ServiceLifecycle` for encrypted auth DB setup/doctor integration. `diagnose` collects auth DB path health problems, `fix` bootstraps missing auth DB parent directory, and `setup` calls `AuthDb::new()`. Registered as `LifecycleProviderId::AuthDb` in the shared lifecycle catalog. - `agent trace DB adapter`: Modules under `cli/src/services/agent_trace_db/` that define the sole repository-scoped `RepositoryAgentTraceDb = TursoDb` adapter (the checkout-scoped `AgentTraceDb`/`AgentTraceDbSpec` adapter and its 15-file migration chain were removed by the `retire-legacy-agent-trace-db` plan). The repository adapter uses the `agent-trace-repository` migration set (fresh baseline schema plus additive `source_instance_id` and `claude_model_state` migrations) with `repository_metadata`, repository-level `diff_traces`, `post_commit_patch_intersections`, `agent_traces`, `messages`, and `parts` tables, no row-level `checkout_id`, typed parameterized insert helpers, the non-exported `claude_model_state` latest-locally-observed register with exact `(session_id, agent_id)` reads and guarded writes, and chronological recent `diff_traces` query/parse support. `AgentTraceDbLifecycle` initializes/checks repository-scoped storage through `agent_trace_storage`. -- `post-commit Agent Trace auto-sync readiness`: The doctor report fact that explains whether the enabled post-commit trigger is ready without invoking it. Doctor compares the installed `post-commit` hook's SCE managed block using the same currency semantics as setup and resolves config-file-only `agent_trace.auto_sync` with source metadata. JSON states are `ready`, `disabled`, `not_ready`, and `not_applicable`; explicit disable is healthy, while existing hook problems continue to own overall readiness and remediation. See [automatic Agent Trace synchronization](cli/agent-trace-auto-sync.md) and [doctor human text](sce/doctor-human-text-contract.md). +- `post-commit Agent Trace auto-sync readiness`: The doctor report fact that explains whether the enabled post-commit trigger is ready without invoking it. Doctor compares the installed `post-commit` hook's SCE managed block using the same currency semantics as setup and resolves config-file-only `agent_trace.auto_sync` with source metadata. JSON states are `ready`, `disabled`, `not_ready`, and `not_applicable`; `disabled` covers both the explicit opt-out and an access policy that disallows background cloud operations, and is healthy, while existing hook problems continue to own overall readiness and remediation. See [automatic Agent Trace synchronization](cli/agent-trace-auto-sync.md) and [doctor human text](sce/doctor-human-text-contract.md). - `structured patch service`: Pure synchronous Rust service in `cli/src/services/structured_patch.rs` that derives supported structured editor hook payloads into canonical `ParsedPatch` values. The current implemented source is Claude `PostToolUse` payloads for `Write` creates and `Edit` structured patches; wired into `sce hooks diff-trace` for Claude payload classification at intake and into `RepositoryAgentTraceDb::recent_diff_trace_patches` for post-commit structured payload parsing, where persisted row `model_id` is assigned to every hunk and persisted canonical row `session_id` to every touched line before downstream reconstruction. - `MutationLineage` / `causal mutation-lineage attribution`: `cli/src/services/mutation_trace/lineage.rs` is a pure module holding, per repo path, a vector of `(content, LineProvenance)` where `LineProvenance` is `Unknown`, `MutationAi { scope_id }`, or `MutationNonAi`. `MutationLineage::apply(patch, origin)` advances it one reconstructed tree transition at a time, applying hunks structurally: context lines carry provenance forward, removed lines are deleted permanently, added lines take only the introducing `TransitionOrigin` (`MutationAi` for healthy untainted `AiExclusive`, `MutationNonAi` for any other recorded event, `Unobserved` → `Unknown` for gap reloads and the latest-tree→commit-tree tail); a structurally inconsistent transition is a `LineageError` and the caller reloads that file to an all-`Unknown` baseline. Historical mutation patches are never matched independently against the committed patch — that earlier `MutationPatchEvidence` / strict-matcher model let stale evidence resurrect and is removed. `attribution.rs` now only supplies `exclude_direct_coverage` (drop directly covered lines) and `patch_for_locations`. The store supplies events through an exact-worktree-scoped `mutation-event page` ordered by descending 8-byte big-endian revision, continued with an exclusive revision cursor, capped at 32 rows; plus `latest_mutation_event_revision` for the commit attribution cut. The `bounded mutation-history consumer` (`resolve_bounded_mutation_attribution` in `cli/src/services/mutation_trace/runtime/mutation_attribution.rs`) loads the newest ≤128 in-cut events through `MutationEventPageSource` + `TreeReadSource` (`diff_trees` + `file_at_tree`) seams, replays them oldest-to-newest from a conservative baseline through the tail into `commit_tree`, then projects surviving provenance onto the committed patch; it is current-worktree-only and timestamp-independent, owns `MAX_MUTATION_ATTRIBUTION_EVENTS = 128` (event 128 may contribute, 129 is never loaded), tracks database (`loaded_pages`/`loaded_rows`) apart from Git (`inspected_events`/`reconstructed_events`/`gap_resets`) work, and records a `mutation-attribution barrier` on any page-query or reconstruction/tail failure while still returning conservative results. See [mutation-trace store](cli/mutation-trace-store.md) and [mutation-trace Agent Trace attribution](cli/mutation-trace-agent-attribution.md). - `Agent Trace SCE metadata`: Implementation-owned top-level metadata emitted by `build_agent_trace_from_evidence(...)` under `metadata.sce`, carrying `version` (sourced from the compiled `sce` CLI package version via `env!("CARGO_PKG_VERSION")`) and `line_changes` (exact `{ai,mixed,unknown}` × `{added,removed}` `u64` touched-line attribution counts derived from canonical `post_commit_patch` hunks, reusing each hunk's existing `Conversation.contributor.type` classification with no independent second classification pass, `#[serde(default)]` for backward-compatible deserialization of pre-existing payloads); the whole object is schema-validated with the rest of the payload and persisted in AgentTraceDb `agent_traces.trace_json` without changing the top-level Agent Trace payload/schema `version`. diff --git a/context/patterns.md b/context/patterns.md index eb5e1a770..9f76ac40d 100644 --- a/context/patterns.md +++ b/context/patterns.md @@ -133,7 +133,7 @@ - Keep `log_file_retention_limit` flat and config-file/default only: validate it as an integer with minimum `1`, merge global before local, default it to `10`, expose resolved source metadata without adding an environment variable or CLI flag, and pass the resolved value unchanged to primary and v2 creation-triggered logger cleanup. - For runtime CLI configuration, keep precedence deterministic and explicit (`flags > env > config file > defaults`) and expose inspect/validate command entrypoints with stable text/JSON outputs. Config-file-only Agent Trace runtime switches such as `agent_trace.auto_sync` should document the resolver fallback and explicit opt-out, distinguish setup-written bootstrap values, resolve global before local, and expose winning source metadata without adding an environment variable or CLI flag unless the contract explicitly requires one. -- For setup-enabled automatic Agent Trace synchronization, keep the post-commit launcher as a one-shot reuse of `sce sync`: start the current executable after local Agent Trace persistence when the resolved setting is true, use the repository root and null child streams, do not wait, and fail open on launcher errors. Keep manual sync and the control-plane cursor authority as the retry path; do not add daemons, watchers, polling, queues, or high-frequency hook triggers. +- For setup-enabled automatic Agent Trace synchronization, keep the post-commit launcher as a one-shot reuse of `sce sync`: start the current executable after local Agent Trace persistence when the resolved setting is true and the effective access policy allows background cloud operations, use the repository root and null child streams, do not wait, and fail open on launcher errors. Keep manual sync and the control-plane cursor authority as the retry path; do not add daemons, watchers, polling, queues, or high-frequency hook triggers. - For commands that support text/JSON dual output, centralize `--format ` parsing in one shared contract and pass command-specific `--help` guidance into invalid-value errors instead of duplicating parser logic per command. - For setup-style command contracts, keep interactive mode as the zero-flag default and enforce mutually-exclusive explicit target flags for non-interactive automation. - For setup config safety, resolve invalid default-discovered config through the shared degraded layer behavior, preserve the invalid repo-local file byte-for-byte, and allow Git/remote preflight, context bootstrap, lifecycle providers, hooks, and target assets to continue; preserve create-if-missing behavior for absent config, skip target/optional-workflow persistence when the local file is invalid, and keep explicit `--config` / `SCE_CONFIG_FILE` failures fatal. diff --git a/context/plans/auth-telemetry-policy-config.md b/context/plans/auth-telemetry-policy-config.md index 1209b93c1..2ff26d0f0 100644 --- a/context/plans/auth-telemetry-policy-config.md +++ b/context/plans/auth-telemetry-policy-config.md @@ -395,13 +395,39 @@ Persist this field in every plan; this is durable plan state, not chat state: - Context impact: localized — the auth command contract. `context/cli/cli-command-surface.md` should record that `login` and `whoami` are rejected with `auth.disabled_by_config` before credential-store access, `login` reports `telemetry_provisioning` `disabled` without telemetry consent, and unauthenticated `whoami` under `mandatory` fails with `auth.not_authenticated`. `context/sce/telemetry-credential.md` should record that provisioning during login is gated on the telemetry policy. `context/sce/auth-db.md` should note that `login` and `whoami` do not reach `auth.db` under `disabled`. - Context synchronization: synced -- [ ] T07: `Gate sce sync and post-commit auto-sync on auth policy` (status:todo) +- [x] T07: `Gate sce sync and post-commit auto-sync on auth policy` (status:done) - Task ID: T07 - Scope: In — `sync::sync::run_current_sync_without_progress` returning a policy rejection before storage/credential access when auth is `disabled`, mapped by `sync/command.rs::classify_sync_error` to `AuthDisabledByConfig`; `commit_hooks::run_post_commit_subcommand` deciding launch from `ResolvedHookRuntimeConfig` (`auto_sync && background_cloud_allowed`); doctor `post_commit_auto_sync` reporting disabled when auth policy prevents it. Out — changing the auto-sync launcher or sync protocol. - Dependencies: T02, T06 - Done when: `sce sync` under `disabled` fails with `auth.disabled_by_config` and no credential-store access; post-commit with `auto_sync: true` under `disabled` or degraded config never calls the launcher and still succeeds; `optional`/`mandatory` behavior is unchanged. - Verify: `run_post_commit_subcommand_with` table test with a launch closure that records calls across {auto_sync false/true} × {disabled, optional, mandatory, degraded}; sync classification test; doctor auto-sync state test; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml commit_hooks sync doctor`. - - Context synchronization: pending + - Completed: 2026-10-20 + - Files changed: `cli/src/services/sync/sync.rs`, `cli/src/services/sync/command.rs`, `cli/src/services/hooks/commit_hooks.rs`, `cli/src/services/config/types.rs`, `cli/src/services/config/resolver.rs`, `cli/src/services/doctor/inspect.rs`, `cli/src/services/auth_command/mod.rs`, `cli/src/app/doctor_reconciliation_cli_tests.rs`, `context/plans/auth-telemetry-policy-config.md` + - Result: + - Added `TraceSyncError::AuthDisabled(AuthPolicyConfigFile)`. It is not an authentication failure and has no storage failure. + - `run_current_sync_without_progress` now resolves `resolve_auth_runtime_config` first. When auth is disabled it returns `AuthDisabled` before Agent Trace storage resolution and before the control-plane client (and so before any credential-store access) is built. + - `classify_sync_error` maps `AuthDisabled` to `UserError::AuthDisabledByConfig` (key `auth.disabled_by_config`), ahead of the storage and authentication checks. + - Added `ResolvedAccessPolicy::auth_disabled_config_file()`, which maps the deciding `auth.mode` source to `AuthPolicyConfigFile`. `auth_command::ensure_auth_allowed` now uses it, so login, whoami, and sync share one mapping. + - `run_post_commit_subcommand_with` now takes a `ResolvedHookRuntimeConfig` resolver (production: `config::resolve_hook_runtime_config`). It launches auto-sync only when `access_policy.auto_sync_allowed(agent_trace_auto_sync)` is true. When auto-sync is configured but suppressed, it logs debug event `sce.agent_trace.auto_sync_skipped_by_policy`. The hook still succeeds either way. + - `resolve_agent_trace_auto_sync_runtime_config` now also returns the access policy. Doctor's `post_commit_auto_sync.enabled` is now the configured value gated by `background_cloud_allowed`. So auth `disabled`, or a degraded config, reports state `disabled` / `[PASS] Post-commit Agent Trace auto-sync (disabled by config)`. `source` and `config_source` still describe `agent_trace.auto_sync`. + - Removed `#[allow(dead_code)]` from `ResolvedAccessPolicy::auto_sync_allowed` and `ResolvedHookRuntimeConfig.access_policy`; `config/types.rs` now has no `dead_code` allows from this plan. + - Verify outcome: + - `commit_hooks sync doctor` filters passed (78 passed, 0 failed). + - New `post_commit_launches_auto_sync_only_when_background_cloud_is_allowed`: real layered configs across {auto_sync false, true} × {disabled, optional, mandatory, degraded (invalid repo layer)}, with a recording launch closure. Auto-sync launches only for `true` + `optional`/`mandatory`. The skip debug event is logged only when auto-sync is configured but suppressed. Every row returns the success output. + - New `sync_rejects_disabled_auth_before_storage_or_credential_access`: a non-Git temp dir with repository `auth.mode: disabled` yields `AuthDisabled(Repository)` rather than a storage `Runtime` error. This proves the gate runs before storage and the client are built. + - New `classify_sync_error_maps_disabled_auth_to_auth_disabled_by_config`: covers all four config-file variants (key and message). + - New CLI test `doctor_reports_post_commit_auto_sync_disabled_when_auth_is_disabled`: repo `auto_sync: true` reports enabled; adding `auth.mode: disabled` gives JSON `{state: disabled, enabled: false, source: config_file, config_source: default_discovered_local}` and the `(disabled by config)` PASS text row. + - `auth_command` passed (20 passed) after the shared-mapping refactor. + - Full CLI suite passed (694 passed, 0 failed). `cargo clippy --all-targets -- -D warnings` via `run-cli-cargo.sh` passed. `cargo fmt` applied. + - Deviation: + - Sync now resolves the auth config before the Agent Trace storage config. When both would fail, a config error now surfaces before a storage error; both are still runtime failures. + - Doctor JSON `post_commit_auto_sync.enabled` now reports the effective (policy-gated) value instead of the raw configured value. + - `optional`/`mandatory` sync and post-commit behavior is unchanged: the policy check only adds a precondition. + - Context impact: localized — the sync command, the post-commit auto-sync trigger, and the doctor auto-sync row. + - `context/cli/agent-trace-auto-sync.md` should record that post-commit launches only when `auto_sync` is true and background cloud operations are allowed (auth not `disabled`, no skipped invalid layer), with the debug skip event, and that doctor reports `disabled` in those cases. + - `context/cli/cli-command-surface.md` should record that `sce sync` is rejected with `auth.disabled_by_config` before storage or credential access. + - `context/sce/auth-db.md` should note that `sync` does not reach `auth.db` under `disabled`. + - Context synchronization: synced - [ ] T08: `Skip Claude-native telemetry install in setup without telemetry consent` (status:todo) - Task ID: T08 diff --git a/context/sce/auth-db.md b/context/sce/auth-db.md index f812f8965..796563303 100644 --- a/context/sce/auth-db.md +++ b/context/sce/auth-db.md @@ -139,7 +139,7 @@ Remaining limits: a mixed old/new deployment is still not usable at the same tim - Encryption is required: `encryption_key::get_or_create_encryption_key()` first honors `SCE_AUTH_DB_ENCRYPTION_KEY` by deriving a deterministic 64-character hex Turso key from the non-empty env-secret text, then falls back to the OS credential store when the env var is absent. No plaintext auth DB fallback exists. - Credential access is explicit (`encryption_key::CredentialAccess`): - `Interactive`: used only by `sce auth login`, `logout`, and `whoami`. `login` and `whoami` reach it only after the effective access policy allows auth, so under `auth.mode: disabled` they never open `auth.db` or touch the credential store; `logout` is never policy-gated. It may show the macOS Keychain authorization dialog. It generates and stores a new key only when the keyring reports `NoEntry` and `auth.db` does not exist. Any other read error is returned and never overwrites the stored key. A read or write failure is tagged with the typed `CredentialAccessDenied` marker only when the keyring reports `NoStorageAccess`, or, on macOS, a `PlatformFailure` whose `OSStatus` is `errSecUserCanceled`, `errSecNoAccessForItem`, `errSecAuthFailed`, `errSecInteractionNotAllowed`, or `errSecInteractionRequired`. Classification uses these codes, never error text. - - `NonInteractive`: used by Claude hooks, managed telemetry startup, the `sce doctor` telemetry health check, `sce auth telemetry-headers`, and `sce sync` (including post-commit auto-sync). It only reads, never creates. On macOS it wraps the read in `SecKeychain::disable_user_interaction()` (`SecKeychainSetUserInteractionAllowed(false)`, the UI switch for the legacy file-based keychain API that `apple-native-keyring-store`'s `keychain` feature uses through `SecKeychainFindGenericPassword`). An item the binary is not authorized for, or a locked keychain, fails with `errSecInteractionNotAllowed` instead of prompting. Every failure becomes `CredentialAccessUnavailable`. `kSecUseAuthenticationUIFail` and `LAContext.interactionNotAllowed` do not apply, because they belong to the `SecItem`/data-protection keychain and LocalAuthentication-protected items, which this adapter does not use. + - `NonInteractive`: used by Claude hooks, managed telemetry startup, the `sce doctor` telemetry health check, `sce auth telemetry-headers`, and `sce sync` (including post-commit auto-sync). Under `auth.mode: disabled`, `sce sync` is rejected before it builds a credential-reading client and post-commit never launches it. It only reads, never creates. On macOS it wraps the read in `SecKeychain::disable_user_interaction()` (`SecKeychainSetUserInteractionAllowed(false)`, the UI switch for the legacy file-based keychain API that `apple-native-keyring-store`'s `keychain` feature uses through `SecKeychainFindGenericPassword`). An item the binary is not authorized for, or a locked keychain, fails with `errSecInteractionNotAllowed` instead of prompting. Every failure becomes `CredentialAccessUnavailable`. `kSecUseAuthenticationUIFail` and `LAContext.interactionNotAllowed` do not apply, because they belong to the `SecItem`/data-protection keychain and LocalAuthentication-protected items, which this adapter does not use. - The interaction switch is process-wide, so all credential-store reads and writes in one process are serialized by a mutex. Interaction is turned back on before the next caller runs. - Linux Secret Service and Windows have no equivalent switch in the adapter. `NonInteractive` there only guarantees no key creation. Missing/unavailable credential-store failures surface as `TokenStorageError::Database` and include platform-specific remediation for Linux system keyring/Secret Service, macOS Keychain, Windows Credential Store, or unsupported platforms, always mentioning `SCE_AUTH_DB_ENCRYPTION_KEY` for headless/CI use without printing the secret value. diff --git a/context/sce/doctor-human-text-contract.md b/context/sce/doctor-human-text-contract.md index 1ce0250d0..c3c84ea44 100644 --- a/context/sce/doctor-human-text-contract.md +++ b/context/sce/doctor-human-text-contract.md @@ -53,8 +53,10 @@ The post-commit Agent Trace auto-sync row uses these stable labels and states: - `[PASS] Post-commit Agent Trace auto-sync` means the canonical post-commit managed block is current and the resolved setting is enabled. - `[PASS] Post-commit Agent Trace auto-sync (disabled by config)` means the - explicit `agent_trace.auto_sync: false` opt-out is active; it does not make - overall doctor readiness fail. + explicit `agent_trace.auto_sync: false` opt-out is active, or the effective + access policy disallows background cloud operations (`auth.mode: disabled` + or a skipped invalid config file); it does not make overall doctor readiness + fail. - `[FAIL] Post-commit Agent Trace auto-sync` means the enabled capability is not ready because the post-commit managed block is missing, stale, unreadable, or otherwise not current. From 8108a318cd3d95aad834b43e7bec7a70562ac626 Mon Sep 17 00:00:00 2001 From: David Abram Date: Tue, 20 Oct 2026 15:12:48 +0200 Subject: [PATCH 8/9] setup: Gate Claude telemetry installation on effective policy Prevent `sce setup` from modifying user-level Claude settings when telemetry is not enabled by resolving the layered access policy for the setup repository. Preserve the existing enabled install behavior and document the fixed skip output and unchanged-settings contract. Plan: auth-telemetry-policy-config (T08) Co-authored-by: SCE --- cli/src/services/setup/command.rs | 112 ++++++++++++++++-- context/cli/access-policy.md | 1 + context/cli/cli-command-surface.md | 2 +- context/context-map.md | 2 +- context/plans/auth-telemetry-policy-config.md | 81 +++++++++++-- context/sce/telemetry-credential.md | 1 + 6 files changed, 179 insertions(+), 20 deletions(-) diff --git a/cli/src/services/setup/command.rs b/cli/src/services/setup/command.rs index f05f5a9fd..fdfa73cdf 100644 --- a/cli/src/services/setup/command.rs +++ b/cli/src/services/setup/command.rs @@ -7,6 +7,9 @@ use crate::services::lifecycle::{ }; use crate::services::{config, setup}; +const CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE: &str = + "Claude telemetry: skipped; SCE telemetry is disabled by config."; + pub struct SetupCommand { pub request: setup::SetupRequest, } @@ -100,7 +103,7 @@ impl SetupCommand { sections.push(setup_message); if claude_telemetry_selected { - sections.push(claude_telemetry_report()); + sections.push(claude_telemetry_report(&repository_root)); } } @@ -116,14 +119,19 @@ fn dispatch_targets_claude(dispatch: Option<&setup::SetupDispatch>) -> bool { ) } -fn claude_telemetry_report() -> String { +fn claude_telemetry_report(repository_root: &std::path::Path) -> String { + let telemetry_enabled = config::resolve_auth_runtime_config(repository_root) + .is_ok_and(|config| config.access_policy.telemetry_enabled()); + render_claude_telemetry_section( + telemetry_enabled, setup::claude_telemetry::resolve_claude_settings_path().as_deref(), &setup::claude_telemetry::managed_claude_settings_path(), ) } fn render_claude_telemetry_section( + telemetry_enabled: bool, settings_path: Option<&std::path::Path>, managed_settings_path: &std::path::Path, ) -> String { @@ -131,6 +139,10 @@ fn render_claude_telemetry_section( format_claude_telemetry_report, install_claude_telemetry, ClaudeTelemetryInstallOutcome, }; + if !telemetry_enabled { + return CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE.to_string(); + } + let installed = match settings_path { Some(settings_path) => install_claude_telemetry(settings_path, managed_settings_path) .unwrap_or(ClaudeTelemetryInstallOutcome::SkippedInvalid), @@ -247,9 +259,14 @@ mod tests { .expect("dispatch should resolve") } - fn run_claude_telemetry_stage(dispatch: Option<&SetupDispatch>, root: &Path) -> Option { + fn run_claude_telemetry_stage( + dispatch: Option<&SetupDispatch>, + telemetry_enabled: bool, + root: &Path, + ) -> Option { dispatch_targets_claude(dispatch).then(|| { render_claude_telemetry_section( + telemetry_enabled, Some(&root.join("settings.json")), &root.join("managed.json"), ) @@ -262,8 +279,11 @@ mod tests { let settings = dir.path().join("settings.json"); fs::write(&settings, r#"{"otelHeadersHelper":"my-helper"}"#).unwrap(); - let report = - render_claude_telemetry_section(Some(&settings), &dir.path().join("managed.json")); + let report = render_claude_telemetry_section( + true, + Some(&settings), + &dir.path().join("managed.json"), + ); assert!(report.contains("skipped")); assert!(!report.contains("authentication pending")); @@ -274,6 +294,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let report = render_claude_telemetry_section( + true, Some(&dir.path().join("settings.json")), &dir.path().join("managed.json"), ); @@ -305,11 +326,88 @@ mod tests { ] { let dir = tempfile::tempdir().unwrap(); - assert!(run_claude_telemetry_stage(Some(&dispatch), dir.path()).is_some()); + assert!(run_claude_telemetry_stage(Some(&dispatch), true, dir.path()).is_some()); assert_installed(dir.path()); } } + #[test] + fn setup_claude_telemetry_skips_install_when_telemetry_is_disabled_by_config() { + let dispatch = dispatch_for(SetupMode::NonInteractive(SetupTarget::Claude), None); + + let dir = tempfile::tempdir().unwrap(); + assert_eq!( + run_claude_telemetry_stage(Some(&dispatch), false, dir.path()).as_deref(), + Some(CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE) + ); + assert_untouched(dir.path()); + + let dir = tempfile::tempdir().unwrap(); + let existing = br#"{"env":{"FOO":"bar"},"model":"opus"}"#; + fs::write(dir.path().join("settings.json"), existing).unwrap(); + assert_eq!( + run_claude_telemetry_stage(Some(&dispatch), false, dir.path()).as_deref(), + Some("Claude telemetry: skipped; SCE telemetry is disabled by config.") + ); + assert_eq!( + fs::read(dir.path().join("settings.json")).unwrap(), + existing + ); + + let report = run_claude_telemetry_stage(Some(&dispatch), true, dir.path()).unwrap(); + assert_eq!( + report, + "Claude telemetry: configured in user-level Claude settings for native OpenTelemetry export.\nClaude telemetry: authentication pending for this repository; run 'sce auth login' in this repository to start exporting." + ); + assert_installed(dir.path()); + let parsed: Value = + serde_json::from_slice(&fs::read(dir.path().join("settings.json")).unwrap()).unwrap(); + assert_eq!(parsed["model"], "opus"); + assert_eq!(parsed["env"]["FOO"], "bar"); + } + + #[test] + fn setup_claude_telemetry_policy_follows_layered_config() { + let dir = tempfile::tempdir().unwrap(); + let global = dir.path().join("global.json"); + let local_dir = dir.path().join(".sce"); + fs::create_dir_all(&local_dir).unwrap(); + let local = local_dir.join("config.json"); + let enabled = |global_json: &str, local_json: Option<&str>| { + fs::write(&global, global_json).unwrap(); + match local_json { + Some(json) => fs::write(&local, json).unwrap(), + None => { + let _ = fs::remove_file(&local); + } + } + config::resolver::resolve_auth_runtime_config_with( + dir.path(), + |_| None, + |path| fs::read_to_string(path).map_err(anyhow::Error::from), + Path::exists, + || Ok(global.clone()), + ) + .is_ok_and(|config| config.access_policy.telemetry_enabled()) + }; + + assert!(enabled(r#"{"telemetry":{"enabled":true}}"#, None)); + assert!(!enabled("{}", None)); + assert!(!enabled("{}", Some(r#"{"telemetry":{"enabled":true}}"#))); + assert!(!enabled( + r#"{"telemetry":{"enabled":true}}"#, + Some(r#"{"telemetry":{"enabled":false}}"#) + )); + assert!(!enabled( + r#"{"telemetry":{"enabled":true}}"#, + Some(r#"{"auth":{"mode":"disabled"}}"#) + )); + assert!(!enabled( + r#"{"telemetry":{"enabled":true}}"#, + Some(r#"{"telemetry":{"enabled":"yes"}}"#) + )); + } + #[test] fn setup_claude_telemetry_leaves_settings_untouched_when_claude_is_not_installed() { let hooks_only = resolve_setup_request(SetupCliOptions { @@ -336,7 +434,7 @@ mod tests { for dispatch in &dispatches { let dir = tempfile::tempdir().unwrap(); - assert!(run_claude_telemetry_stage(dispatch.as_ref(), dir.path()).is_none()); + assert!(run_claude_telemetry_stage(dispatch.as_ref(), true, dir.path()).is_none()); assert_untouched(dir.path()); } } diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md index 943d01f9f..ac1160c2b 100644 --- a/context/cli/access-policy.md +++ b/context/cli/access-policy.md @@ -93,6 +93,7 @@ The note documents a coverage limit: telemetry opt-out does not remove Claude-na - **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 the readiness hint is read, `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 the readiness hint file exists, but never reads it or touches `auth.db`. See [telemetry credential: doctor health check](../sce/telemetry-credential.md#doctor-health-check). - **`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 readiness hint, 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. 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. - Under `disabled`, both fail with `UserError::AuthDisabledByConfig` (key `auth.disabled_by_config`, runtime class, exit code 4) before `auth.db` or the credential store is touched. The fixed message names `auth.mode: disabled` and the config file of the deciding layer: the global SCE config, the repository `.sce/config.json`, the `--config` file, or the `SCE_CONFIG_FILE` file (`AuthPolicyConfigFile`). It tells the user to set `auth.mode` to `optional` or `mandatory` there. - Login provisions a telemetry credential only when telemetry is `Enabled`. Otherwise `telemetry_provisioning` is `disabled`, with the fixed message ``Telemetry credential provisioning is disabled by SCE config. Set `telemetry.enabled: true` in the global SCE config to enable it.``, shown in text as a `Note:` line. Disabled provisioning issues nothing, writes no readiness hint, and enrolls no repository. diff --git a/context/cli/cli-command-surface.md b/context/cli/cli-command-surface.md index ed3cce184..2979b4a4b 100644 --- a/context/cli/cli-command-surface.md +++ b/context/cli/cli-command-surface.md @@ -105,7 +105,7 @@ An interactive `setup` run instead resolves the selection through an `inquire` m `setup` now also exposes compile-time embedded config assets for OpenCode/Claude/Pi/Codex targets, sourced from the generated `config/.opencode/**`, `config/.claude/**`, `config/.pi/**`, and (via a build-time staging merge of `config/.agents/**` + `config/.codex/**`) `config/codex-target/**` trees via `cli/build.rs` with normalized forward-slash relative paths and target-scoped iteration APIs; the embedded asset set includes the OpenCode bash-policy plugin wrapper plus Claude settings `PreToolUse` Bash policy hook, both delegating to the Rust `sce policy bash` path. `setup` additionally includes a repository-root install engine (`install_embedded_setup_assets`) that installs each embedded asset individually into `.opencode/`/`.claude/`/`.pi/` — stage next to the final destination, remove only that destination file if present, swap into place, with deterministic recovery guidance naming the failing asset's path on swap failure — never removing an integration target directory as a whole, while treating bash-policy enforcement files as first-class SCE-managed assets. Codex is the one target whose embedded relative paths already carry their own output-root prefix (`.agents/...`, `.codex/...`), so its destination root is the repository root itself rather than a single `.codex/`-style subdirectory. Its generated hook command resolves that repository root at invocation time, so Codex events from nested cwd and repositories with spaces reach the installed helper safely; Git-root failure is a silent successful no-op, while the helper preserves missing-CLI stderr guidance and STDIN forwarding. See [setup non-destructive per-asset install policy](../sce/setup-no-backup-policy-seam.md) for the full contract, including the pending pruning gap for deselected/stale assets. `setup` now executes end-to-end and prints deterministic completion details including selected target(s) and per-target install count. -`setup` with a selected Claude target also merges Claude-native OpenTelemetry settings into user-level Claude `settings.json` (`$CLAUDE_CONFIG_DIR` else `~/.claude`) and prints a fixed telemetry line (configured, authentication pending, or skipped on conflict/malformed JSON) without failing repository setup; see [telemetry credential](../sce/telemetry-credential.md). The hidden auth helper is intentionally not part of the public command listing. +`setup` with a selected Claude target also merges Claude-native OpenTelemetry settings into user-level Claude `settings.json` (`$CLAUDE_CONFIG_DIR` else `~/.claude`) and prints a fixed telemetry line (configured, authentication pending, skipped on conflict/malformed JSON, or skipped because the effective access policy does not enable telemetry, in which case settings are untouched) without failing repository setup; see [telemetry credential](../sce/telemetry-credential.md). The hidden auth helper is intentionally not part of the public command listing. `doctor` now executes end-to-end with explicit diagnosis and repair-intent surfaces: `sce doctor` stays read-only and `sce doctor --fix` selects repair-intent mode. The former Agent Trace database inspection routes are unavailable; doctor owns repository-scoped Agent Trace DB health (checkout-identity diagnostics were removed by the `remove-checkout-id` plan; see `context/cli/checkout-identity.md`). The current `doctor` runtime aggregates `ServiceLifecycle::diagnose` and `ServiceLifecycle::fix` calls across all registered service providers (`config`, `local_db`, `auth_db`, `agent_trace_db`, `hooks`) plus integration checks, covering state-root resolution, global and repo-local `sce/config.json` readability/schema validation, local DB and repository-scoped Agent Trace DB path/health, DB-parent readiness barriers, the repo hook rollout slice when a repository target is detected, and post-commit Agent Trace auto-sync readiness derived from canonical managed-block currency plus resolved configuration. The readiness fact reports enabled/current, explicit disabled, not-ready, and not-applicable states in text and JSON without launching synchronization; Claude's inventory is only `Plugins`, `Commands`, and `Skills`, while OpenCode retains `Agents`. Fix mode delegates to each provider's `fix` implementation, which reuses the canonical setup hook install flow to repair missing/stale/non-executable required hooks and missing hooks directories, and it can bootstrap missing canonical database parent directories when the resolved paths match canonical owned locations. `sce sync [--format text|json]` is the implemented user-invocable synchronization command: it synchronizes the current repository's Agent Trace DB with the control-plane ingestion API; local DB and Agent Trace DB bootstrap continue to happen through `setup`, and DB health/repair continues to happen through `doctor`. Under `auth.mode: disabled`, `sce sync` fails with `auth.disabled_by_config` before storage or credential access (see [effective access policy](access-policy.md#enforcement)). See [agent-trace-sync-command.md](agent-trace-sync-command.md) and [sync-command.md](sync-command.md). diff --git a/context/context-map.md b/context/context-map.md index 8b5e45561..b5f5c1faf 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -25,7 +25,7 @@ Feature/domain context: - `context/cli/async-persistence-guarantees.md` (verified guarantees and named limits of the directly awaited Turso persistence migration — exclusive `&mut` transactions, deferred rollback, credential-rotation and terminal-sync behavior, lease/descriptor protection — plus PR1–PR4 staging and the PR3 cleanup ledger) - `context/cli/agent-trace-sync-command.md` (composed local-to-control-plane `sce sync` architecture: the `hooks/plugins → repository Agent Trace DB → AgentTraceExportReader → sce sync → HTTPS + WorkOS Bearer → control plane` data flow, the `sce auth login` / `cd ` / `sce sync` user flow, the no-local-cursor/no-`agent-trace-sync.db`/no-Turso-Sync/no-`BridgeLock`/no-local-DWH invariants, the four-local-capture-streams versus three-remote-streams boundary with its `diff_traces` release gate, the optional `commitPatchId` field on the existing `agent_traces` stream with its Control Plane release dependency and no-backfill limit, and `401`/`409`/ambiguous-batch-failure recovery semantics) - `context/cli/config-precedence-contract.md` (implemented `sce config` show/validate command contract, deterministic `flags > env > config file > defaults` resolution order, focused `config/resolver.rs` ownership for config discovery/merge/runtime precedence plus default-discovered invalid-file degradation, focused `config/render.rs` ownership for `show`/`validate` text+JSON output construction, canonical `$schema` acceptance for startup-loaded `sce/config.json` files, shared auth-key env/config/optional baked-default support starting with `workos_client_id`, shared runtime resolution for flat logging observability keys including config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` with `/sce/logs` defaulting plus config-file/default-only positive `log_file_retention_limit`, config-file-only `agent_trace.repository_id`/`agent_trace.repository_remote` repository-identity keys with default remote `origin`, `agent_trace.auto_sync` resolution with omitted-value fallback `false`, explicit-false opt-out, and setup-written explicit `true` bootstrap behavior for the post-commit trigger boundary, the catalog-derived `integrations.optional_workflows` optional-workflow selection key, schema-validated per-layer `auth.mode` / `telemetry.enabled` sections, JSON-pointer-prefixed schema-validation errors, canonical Pkl-generated `sce/config.json` schema ownership plus CLI embedding/reuse contract including `policies.attribution_hooks.enabled` default-true/explicit-false opt-out metadata, config-file selection order, `show` provenance output, and trimmed `validate` output contract) -- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, exposure on the auth/hook/observability runtime projections, and enforcement in managed telemetry startup, `sce doctor` health (`disabled_by_config`), the hidden `sce auth telemetry-headers` helper (fail closed before readiness, repository resolution, and `auth.db`), `sce auth login`/`whoami` (`auth.disabled_by_config` rejection before credential storage, `disabled` telemetry provisioning without consent, `mandatory` unauthenticated whoami failure), `sce sync` (`auth.disabled_by_config` before storage or credentials), and post-commit auto-sync plus its doctor row (launch only when background cloud operations are allowed); decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) +- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, exposure on the auth/hook/observability runtime projections, and enforcement in managed telemetry startup, `sce doctor` health (`disabled_by_config`), the hidden `sce auth telemetry-headers` helper (fail closed before readiness, repository resolution, and `auth.db`), `sce auth login`/`whoami` (`auth.disabled_by_config` rejection before credential storage, `disabled` telemetry provisioning without consent, `mandatory` unauthenticated whoami failure), `sce sync` (`auth.disabled_by_config` before storage or credentials), post-commit auto-sync plus its doctor row (launch only when background cloud operations are allowed), and the `sce setup` Claude-native telemetry install (skipped with a fixed line unless telemetry is enabled); decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) - `context/cli/capability-traits.md` (current broad CLI capability seam in `cli/src/services/capabilities.rs`, including `FsOps`/`StdFsOps` (method-less marker), `GitOps`/`ProcessGitOps` (command execution and availability), compile-time-typed borrowed AppContext wiring with scoped borrowing across directly awaited commands with associated-type narrow capability accessors plus `ContextWithRepoRoot` repo-root-scoped context derivation, generic command execution bounds, and test-only unimplemented stubs; current service internals do not consume fs/git traits until later lifecycle migration tasks) - `context/cli/service-lifecycle.md` (current async lifecycle seam in `cli/src/services/lifecycle.rs`, including default no-op `ServiceLifecycle` diagnose/fix/setup methods against narrow `HasRepoRoot`, lifecycle-owned health/fix/setup result types with generic setup messages, doctor/setup adapter boundaries, the static `LifecycleProvider` enum catalog/dispatcher, hook/config/local_db/auth_db/agent_trace_db lifecycle providers including setup-time repository-scoped Agent Trace DB initialization plus checkout identity diagnostics, implemented doctor aggregation over diagnose/fix providers, and implemented setup aggregation over `setup` providers in order config → local_db → auth_db → agent_trace_db → hooks when requested) - `context/cli/mutation-trace-protocol.md` (pure, dependency-free `cli/src/services/mutation_trace/` refinement of the verified `spec/mutation_cursor.qnt` mutation-cursor protocol: the full pure action set — `prepare`/`commit` transition logic, attribution/mutation-event materialization, snapshot-failure/database-failure taint actions, scope abandonment, and recovery with an explicit observed-tree input — plus cross-action sequence/invariant tests and a module-level Quint refinement matrix are all complete (`types.rs`, `protocol.rs`, `mod.rs`, `tests.rs`, registered with `#[allow(dead_code)]`); opaque-newtype identity refinement decisions vs. the Quint model's bounded enums, and the `coordinator.rs` target end-state seam this layout leaves room for but does not create — `store.rs`, `runtime/git_snapshot.rs`, and `runtime/coordinator.rs` (including its public `coordinate()` entrypoint) now exist, built out by the `mutation-cursor-store-persistence` and `mutation-cursor-runtime-coordinator` plans respectively; `protocol.rs` is invoked only through the runtime, and the runtime is now driven by the generic `sce hooks mutation-scope` CLI ingress and a first Claude Code adapter driver, registered by `sce setup` and reachable by a real Claude Code session, now proven against real Git repositories and a real Agent Trace DB by the `claude-mutation-scope-integration` plan's T08 regressions) diff --git a/context/plans/auth-telemetry-policy-config.md b/context/plans/auth-telemetry-policy-config.md index 2ff26d0f0..c3a6f285f 100644 --- a/context/plans/auth-telemetry-policy-config.md +++ b/context/plans/auth-telemetry-policy-config.md @@ -203,23 +203,23 @@ Repository binding, credential identity (`sub`, `workspace_id`), expiry checks, ## Acceptance criteria -- [ ] AC1: `auth.mode` (`disabled|optional|mandatory`) and `telemetry.enabled` (boolean) are accepted in global and repo-local config, unknown sub-keys and wrong types fail validation with JSON-pointer-prefixed errors, and configs without the sections remain valid. +- [x] AC1: `auth.mode` (`disabled|optional|mandatory`) and `telemetry.enabled` (boolean) are accepted in global and repo-local config, unknown sub-keys and wrong types fail validation with JSON-pointer-prefixed errors, and configs without the sections remain valid. - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml config::schema`; `nix run .#pkl-check-generated`. -- [ ] AC2: Effective policy follows the precedence rules exactly: user telemetry opt-out always wins, repository `true` alone never enables telemetry, repository `false` disables it, user `disabled` auth cannot be overridden by the repository, `auth.mode: disabled` forces telemetry and auto-sync off, and any skipped invalid discovered layer forces telemetry and background cloud operations off. +- [x] AC2: Effective policy follows the precedence rules exactly: user telemetry opt-out always wins, repository `true` alone never enables telemetry, repository `false` disables it, user `disabled` auth cannot be overridden by the repository, `auth.mode: disabled` forces telemetry and auto-sync off, and any skipped invalid discovered layer forces telemetry and background cloud operations off. - Validate: table-driven `resolve_access_policy` test in `cli/src/services/config/resolver.rs` covering every user × repository × degraded combination; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml access_policy`. -- [ ] AC3: `sce config show` reports `auth.mode`, `telemetry.enabled` (value, `source`, `config_source`), and the effective telemetry state with its reason in text and JSON; `sce config validate` and `show` report the defined contradiction warnings verbatim. +- [x] AC3: `sce config show` reports `auth.mode`, `telemetry.enabled` (value, `source`, `config_source`), and the effective telemetry state with its reason in text and JSON; `sce config validate` and `show` report the defined contradiction warnings verbatim. - Validate: exact-output render tests in `cli/src/services/config/render.rs`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml config::render`. -- [ ] AC4: With telemetry not `Enabled`, no SCE process (command, Claude hook, doctor, headers helper) reads the readiness hint, opens `auth.db`, resolves the encryption key, issues a telemetry credential, or exports managed spans — even when a valid `auth.db`, telemetry credential, and readiness hint exist. +- [x] AC4: With telemetry not `Enabled`, no SCE process (command, Claude hook, doctor, headers helper) reads the readiness hint, opens `auth.db`, resolves the encryption key, issues a telemetry credential, or exports managed spans — even when a valid `auth.db`, telemetry credential, and readiness hint exist. - Validate: unit tests with lookups that fail the test if invoked; multiprocess test in `cli/src/services/auth_db/multiprocess_tests.rs` running a Claude hook through `app::run` with an existing credential and `telemetry.enabled: false`, asserting zero exported spans at the loopback collector and an empty-key environment that would fail any key resolution. -- [ ] AC5: With `auth.mode: disabled`, `sce auth login`, `whoami`, and `sync` fail with `auth.disabled_by_config` before any credential-store access, post-commit does not spawn auto-sync, and `sce auth logout` still deletes stored credentials. +- [x] AC5: With `auth.mode: disabled`, `sce auth login`, `whoami`, and `sync` fail with `auth.disabled_by_config` before any credential-store access, post-commit does not spawn auto-sync, and `sce auth logout` still deletes stored credentials. - Validate: auth-command, sync-command, and `run_post_commit_subcommand_with` tests with injected storage/spawn closures; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml auth_command sync commit_hooks`. -- [ ] AC6: With `auth.mode: mandatory`, unauthenticated `sce auth whoami` exits nonzero with `auth.not_authenticated`, while hooks and auto-sync behave as in `optional`; with `optional`, current outputs are byte-identical. +- [x] AC6: With `auth.mode: mandatory`, unauthenticated `sce auth whoami` exits nonzero with `auth.not_authenticated`, while hooks and auto-sync behave as in `optional`; with `optional`, current outputs are byte-identical. - Validate: auth-command tests for both modes with missing and expired stored credentials. -- [ ] AC7: Login with telemetry not `Enabled` reports `telemetry_provisioning` `disabled` (text and JSON), makes no issuance request, writes no readiness hint, and enrolls no repository; with telemetry `Enabled` the existing issued/unavailable behavior is unchanged. +- [x] AC7: Login with telemetry not `Enabled` reports `telemetry_provisioning` `disabled` (text and JSON), makes no issuance request, writes no readiness hint, and enrolls no repository; with telemetry `Enabled` the existing issued/unavailable behavior is unchanged. - Validate: `run_login_with_stored_credentials` / provisioning tests with a provisioning closure that fails if called. -- [ ] AC8: `sce setup` with the Claude target skips the Claude-native telemetry install with a fixed "disabled by SCE config" line when telemetry is not `Enabled`, leaving user Claude settings byte-unchanged, and installs as today when it is. +- [x] AC8: `sce setup` with the Claude target skips the Claude-native telemetry install with a fixed "disabled by SCE config" line when telemetry is not `Enabled`, leaving user Claude settings byte-unchanged, and installs as today when it is. - Validate: `cli/src/services/setup/command.rs` tests around `render_claude_telemetry_section`. -- [ ] AC9: `sce doctor` reports `[PASS] Managed telemetry (disabled by config)` / JSON `state: disabled_by_config` without reading `auth.db` when telemetry is not `Enabled`, and post-commit auto-sync readiness reports disabled when auth is disabled. +- [x] AC9: `sce doctor` reports `[PASS] Managed telemetry (disabled by config)` / JSON `state: disabled_by_config` without reading `auth.db` when telemetry is not `Enabled`, and post-commit auto-sync readiness reports disabled when auth is disabled. - Validate: `inspect_health_with` and doctor rendering tests; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml doctor`. ### Full validation @@ -429,13 +429,28 @@ Persist this field in every plan; this is durable plan state, not chat state: - `context/sce/auth-db.md` should note that `sync` does not reach `auth.db` under `disabled`. - Context synchronization: synced -- [ ] T08: `Skip Claude-native telemetry install in setup without telemetry consent` (status:todo) +- [x] T08: `Skip Claude-native telemetry install in setup without telemetry consent` (status:done) - Task ID: T08 - Scope: In — `setup/command.rs::render_claude_telemetry_section` (or its caller) resolving the policy for the setup repository and skipping `install_claude_telemetry` with a fixed `Claude telemetry: skipped; SCE telemetry is disabled by config.` line when not `Enabled`. Out — removing or reconciling existing Claude settings, setup prompts, writing config keys. - Dependencies: T02 - Done when: setup with the Claude target leaves user Claude settings byte-unchanged and prints the skip line when telemetry is not `Enabled`, and installs exactly as today when it is. - Verify: tests alongside `setup_claude_telemetry_installs_when_claude_is_selected` for enabled and disabled policies asserting file bytes and report text; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup_claude_telemetry`. - - Context synchronization: pending + - Completed: 2026-10-20 + - Files changed: `cli/src/services/setup/command.rs`, `context/plans/auth-telemetry-policy-config.md` + - Result: + - Added the fixed constant `CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE` (`Claude telemetry: skipped; SCE telemetry is disabled by config.`) in `setup/command.rs`. + - `render_claude_telemetry_section(telemetry_enabled, settings_path, managed_settings_path)` returns that line before `install_claude_telemetry` runs when telemetry is not enabled, so user Claude settings are neither read nor written. + - `claude_telemetry_report(repository_root)` resolves `config::resolve_auth_runtime_config(repository_root)` (global layer plus `/.sce/config.json`); a resolution failure counts as not enabled. + - The enabled path is unchanged. + - Verify outcome: + - `setup_claude_telemetry` passed (6 passed, 0 failed). + - New `setup_claude_telemetry_skips_install_when_telemetry_is_disabled_by_config`: the disabled policy returns exactly the skip line, creates no settings file when none exists, and leaves an existing settings file byte-identical. The enabled policy on the same file installs with the exact configured and authentication-pending report and keeps existing keys. + - New `setup_claude_telemetry_policy_follows_layered_config`: through the resolver seam, only global `telemetry.enabled: true` is enabled. Default, repo-only `true`, repo `false` opt-out, repo `auth.mode: disabled`, and an invalid repo layer are all disabled. + - Existing setup telemetry tests now pass `telemetry_enabled = true`. + - Full CLI suite passed (696 passed, 0 failed). `cargo clippy --all-targets -- -D warnings` via `run-cli-cargo.sh` passed. `cargo fmt` applied. + - Deviation: none. The baseline was a clean tree at `9674e199`. + - Context impact: localized — the setup Claude telemetry install step. `context/sce/telemetry-credential.md` (or the setup context it references) should record that setup installs Claude-native telemetry only when the effective telemetry policy for the setup repository is `Enabled`; otherwise it prints the fixed skip line and leaves user Claude settings unchanged. Settings written by earlier setups are not removed. + - Context synchronization: synced ## Open questions @@ -443,3 +458,47 @@ Persist this field in every plan; this is durable plan state, not chat state: - `mandatory` changes very little today. Cloud commands already require credentials, and hooks must never block, so the only enforced difference is a nonzero unauthenticated `whoami`. It is kept so the future setup and auto-login work has a stable mode to build on. If no near-term consumer exists, shipping only `disabled | optional` would be the smaller version. - Telemetry opt-out does not stop Claude-native export from settings written by earlier setups, and those settings are user-level, shared across repositories. Should a follow-up plan for SCE-owned Claude settings reconciliation be scheduled now, so the opt-out can eventually be described as complete? - Repository-layer discovery uses `/.sce/config.json`. A Claude hook or headers helper launched from a subdirectory sees only the user layer, so a repository opt-out can be missed there. Fixing this means Git-root-relative discovery for every config consumer, which is broader than this plan. + +## Validation Report + +**Status:** validated +**Date:** 2026-10-20 + +### Commands run + +- `nix flake check` -> exit 0 (all 6 checks passed: cli-tests, cli-clippy, cli-fmt, pkl-generated-check, sce-cli-generated-input-check, codex-hook-command-check) +- `nix run .#pkl-check-generated` -> exit 0 (ephemeral Pkl generation passed, 142 files) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml config::schema` -> exit 0 (28 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml access_policy` -> exit 0 (16 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml config::render` -> exit 0 (3 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml auth_command` -> exit 0 (20 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml sync` -> exit 0 (40 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml commit_hooks` -> exit 0 (5 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml doctor` -> exit 0 (35 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup_claude_telemetry` -> exit 0 (6 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml multiprocess` -> exit 0 (18 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml telemetry_headers` -> exit 0 (11 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_telemetry` -> exit 0 (42 passed) +- Manual macOS Keychain check -> not run (validation host is x86_64-linux; plan marks it as not covered by CI) + +### Success-criteria verification + +- [x] AC1: auth/telemetry config sections accepted, invalid shapes rejected with pointers, absent sections valid -> `config::schema` `access_policy_config_tests` (5 tests) passed; `pkl-check-generated` passed +- [x] AC2: effective policy precedence -> `config::resolver::access_policy_tests` (consent/opt-out, most-restrictive auth, repo auth disabled forces telemetry off, invalid global/local layers degrade policy) passed +- [x] AC3: config show/validate report policy and warnings -> `show_json_reports_resolved_auth_and_telemetry_policy`, `show_text_reports_access_policy_after_agent_trace_and_lists_policy_warnings`, `validate_lists_policy_warnings_without_policy_fields` passed +- [x] AC4: no readiness/auth.db/key/credential/export access without telemetry consent -> `claude_hook_with_telemetry_disabled_by_config_never_resolves_the_credential` (multiprocess), `telemetry_disabled_by_config_never_probes_readiness_or_looks_up_credentials`, `health_disabled_by_config_never_probes_readiness_or_looks_up_credentials`, `telemetry_headers_policy_follows_auth_and_invalid_config` passed +- [x] AC5: `auth.mode: disabled` rejects login/whoami/sync before storage, no post-commit auto-sync, logout still deletes -> `whoami_follows_auth_mode_across_stored_credentials` (0 storage reads when disabled), `auth_disabled_rejection_names_the_deciding_config_file`, `sync_rejects_disabled_auth_before_storage_or_credential_access`, `classify_sync_error_maps_disabled_auth_to_auth_disabled_by_config`, `post_commit_launches_auto_sync_only_when_background_cloud_is_allowed`, `logout_deletes_both_credential_rows_when_auth_is_disabled_by_config` passed +- [x] AC6: `mandatory` unauthenticated whoami fails with `auth.not_authenticated`; `optional` unchanged -> `whoami_follows_auth_mode_across_stored_credentials` covers all modes × none/valid/expired credentials; passed +- [x] AC7: login without telemetry consent reports `disabled` provisioning and makes no issuance -> `login_skips_provisioning_unless_telemetry_is_enabled`, `login_reports_disabled_telemetry_provisioning_in_text_and_json` passed +- [x] AC8: setup skips Claude telemetry install without consent, settings byte-unchanged -> `setup_claude_telemetry_skips_install_when_telemetry_is_disabled_by_config`, `setup_claude_telemetry_policy_follows_layered_config` passed +- [x] AC9: doctor reports disabled_by_config without reading auth.db; auto-sync readiness disabled when auth disabled -> `doctor_with_telemetry_disabled_by_config_never_reads_the_auth_db`, `doctor_reports_post_commit_auto_sync_disabled_when_auth_is_disabled`, `telemetry_disabled_by_config_reports_no_problem_and_a_stable_json_state`, `telemetry_disabled_by_config_renders_pass_row_with_opt_in_line_only_for_ready_hint` passed + +### Failed checks and follow-ups + +- None. + +### Residual risks + +- The manual macOS check (locked login Keychain, no Keychain dialog, no `sce.hook` spans, at most one logout prompt) was not run; macOS Keychain behavior is unverified on real hardware. +- Flake checks ran only for x86_64-linux; darwin and aarch64-linux systems were omitted. +- Open questions in this plan (silent loss of managed export on upgrade, minimal `mandatory` semantics, legacy Claude-native settings, ``-relative repository discovery) remain unresolved product decisions. diff --git a/context/sce/telemetry-credential.md b/context/sce/telemetry-credential.md index 02c6d497a..e125e7582 100644 --- a/context/sce/telemetry-credential.md +++ b/context/sce/telemetry-credential.md @@ -90,6 +90,7 @@ flowchart LR Claude Code's own OpenTelemetry export is separate from the SCE-CLI managed exporter above. `sce setup` configures it; the SCE CLI exporter is unchanged. - Install: when the Claude target is selected and setup proceeds (`--claude`, `--all`, interactive Claude/All, with or without `--non-interactive`), `cli/src/services/setup/claude_telemetry.rs` merges settings into Claude's user-level `settings.json` (`$CLAUDE_CONFIG_DIR/settings.json`, else `~/.claude/settings.json`). OpenCode/Codex/Pi-only, `--hooks`-only, `--bootstrap-context`, and cancelled runs leave it untouched. Scope is user-level, not repository-level. +- Policy gate: setup installs only when the effective access policy resolved for the setup repository root enables telemetry ([access-policy.md](../cli/access-policy.md)); a resolution failure counts as not enabled. Otherwise it prints the fixed line `Claude telemetry: skipped; SCE telemetry is disabled by config.` and neither reads nor writes Claude settings. Settings written by earlier setups are not removed. - Written keys: `otelHeadersHelper` set to `sce auth telemetry-headers`, plus an `env` block with `CLAUDE_CODE_ENABLE_TELEMETRY=1`, `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1` (required by Claude Code for span tracing), `OTEL_{TRACES,METRICS,LOGS}_EXPORTER=otlp`, `OTEL_EXPORTER_OTLP_PROTOCOL` / `OTEL_EXPORTER_OTLP_ENDPOINT` from `MANAGED_OTLP_PROTOCOL` / `MANAGED_OTLP_ENDPOINT`, `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS=300000`, and `OTEL_METRICS_INCLUDE_REPOSITORY=true` (unconditional because the Claude Code version cannot be detected during setup; unknown variables are ignored). - Authentication: no token is ever written to settings, generated assets, or setup output, and `OTEL_EXPORTER_OTLP_HEADERS` is never set. Claude runs the hidden helper (see Hidden header helper) and uses its `Authorization` header. - Rotation: Claude re-runs the helper at most every five minutes (debounce 300000 ms), so a credential replaced by a later `sce auth login` is picked up without rewriting settings. `sce auth logout` deletes the stored credential, after which the helper fails and Claude export stops authenticating; local deletion does not revoke the OpenBao token. From 323c74b10bd02f3959fe19b491cbdc50d3cb8c86 Mon Sep 17 00:00:00 2001 From: David Abram Date: Wed, 21 Oct 2026 09:44:10 +0200 Subject: [PATCH 9/9] config: Resolve access policy from Git-root and explicit layers Load global and repository policy files alongside an explicitly selected config so explicit runs cannot bypass global or repository auth restrictions or telemetry opt-outs while retaining explicit ordinary-key overrides. Discover repository configuration at the enclosing Git root and use the shared root for repository identity and all policy consumers. Add coverage and update the access-policy contracts for nested repositories, worktrees, explicit precedence, and degraded discovered configuration. Plan: auth-telemetry-policy-config (T08) Co-authored-by: SCE --- cli/src/services/auth_command/mod.rs | 1 + .../services/auth_db/multiprocess_tests.rs | 267 ++++++++- cli/src/services/config/resolver.rs | 515 +++++++++++++++--- cli/src/services/config/types.rs | 6 +- cli/src/services/default_paths.rs | 16 +- .../managed_telemetry/claude_helper.rs | 6 +- cli/src/services/setup/command.rs | 1 + cli/src/services/sync/sync.rs | 1 + context/cli/access-policy.md | 56 +- context/cli/config-precedence-contract.md | 17 +- context/context-map.md | 2 +- ...-consent-gated-access-policy-precedence.md | 42 +- context/plans/auth-telemetry-policy-config.md | 6 +- context/sce/telemetry-credential.md | 2 +- 14 files changed, 792 insertions(+), 146 deletions(-) diff --git a/cli/src/services/auth_command/mod.rs b/cli/src/services/auth_command/mod.rs index 863ca6786..f75ccfafe 100644 --- a/cli/src/services/auth_command/mod.rs +++ b/cli/src/services/auth_command/mod.rs @@ -1093,6 +1093,7 @@ mod tests { #[test] fn telemetry_headers_policy_follows_auth_and_invalid_config() { let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join(".git")).unwrap(); let global = dir.path().join("global.json"); let local_dir = dir.path().join(".sce"); std::fs::create_dir_all(&local_dir).unwrap(); diff --git a/cli/src/services/auth_db/multiprocess_tests.rs b/cli/src/services/auth_db/multiprocess_tests.rs index 5be0143db..659be9b8b 100644 --- a/cli/src/services/auth_db/multiprocess_tests.rs +++ b/cli/src/services/auth_db/multiprocess_tests.rs @@ -74,6 +74,12 @@ const HEADERS_UNAVAILABLE: &str = "Telemetry credential is unavailable."; const STDIN_SECRET: &str = "SECRET_STDIN_VALUE"; const TELEMETRY_FALLBACK_EVENT: &str = "event_id=sce.telemetry.fallback"; const FALLBACK_REASON_PREFIX: &str = "reason="; +const CLI_ARGS_ENV: &str = "SCE_AUTH_DB_TEST_CLI_ARGS"; +const CLI_SUCCESS_PREFIX: &str = "SCE_AUTH_DB_CHILD_CLI_SUCCESS="; +const AUTH_DISABLED_BY_REPOSITORY: &str = + "Authentication is disabled by `auth.mode: disabled` in the repository SCE config"; +const AUTH_DISABLED_BY_GLOBAL: &str = + "Authentication is disabled by `auth.mode: disabled` in the global SCE config"; const FAIL_OPEN_HOOK_COMMANDS: [ClaudeHookCommand; 3] = [ ClaudeHookCommand::DiffTrace, ClaudeHookCommand::ConversationTrace, @@ -174,6 +180,20 @@ impl Sandbox { state_root.join("sce") } + fn global_config_file(&self) -> PathBuf { + let root = self.dir.path(); + let config_root = if cfg!(target_os = "macos") { + root.join("Library").join("Application Support") + } else { + root.join("config") + }; + config_root.join("sce").join("config.json") + } + + fn write_global_config(&self, config: &serde_json::Value) { + write_config_file(&self.global_config_file(), config); + } + fn auth_db_files(&self) -> Vec { let state = self.sce_state_dir(); AUTH_DB_FILES @@ -548,7 +568,7 @@ fn concurrent_telemetry_headers_on_missing_auth_db_fail_closed_without_creating_ let config = headers_policy_config(&sandbox, true); let helpers = (0..CONCURRENT_PROCESSES) - .map(|_| spawn_headers(&sandbox, &repository, &config)) + .map(|_| spawn_headers(&sandbox, &repository, Some(&config))) .collect::>(); for helper in helpers { assert_headers_unavailable(helper); @@ -577,13 +597,14 @@ fn telemetry_headers_serve_only_the_bound_repository() { let enabled = headers_policy_config(&sandbox, true); let disabled = headers_policy_config(&sandbox, false); - let output = spawn_headers(&sandbox, &bound, &enabled) - .wait_with_output() - .expect("bound headers output"); - assert!(output.status.success(), "bound headers failed"); - assert!(String::from_utf8_lossy(&output.stdout).contains(HEADERS_AUTHORIZATION)); - assert_headers_unavailable(spawn_headers(&sandbox, &unbound, &enabled)); - assert_headers_unavailable(spawn_headers(&sandbox, &bound, &disabled)); + assert_headers_served(spawn_headers(&sandbox, &bound, Some(&enabled))); + assert_headers_unavailable(spawn_headers(&sandbox, &unbound, Some(&enabled))); + assert_headers_unavailable(spawn_headers(&sandbox, &bound, Some(&disabled))); +} + +fn write_config_file(path: &Path, config: &serde_json::Value) { + std::fs::create_dir_all(path.parent().expect("config parent")).expect("config dir"); + std::fs::write(path, config.to_string()).expect("config file"); } fn headers_policy_config(sandbox: &Sandbox, telemetry_enabled: bool) -> PathBuf { @@ -599,14 +620,25 @@ fn headers_policy_config(sandbox: &Sandbox, telemetry_enabled: bool) -> PathBuf config } -fn spawn_headers(sandbox: &Sandbox, repository: &Path, config: &Path) -> Child { +fn spawn_headers(sandbox: &Sandbox, repository: &Path, config: Option<&Path>) -> Child { let mut helper = sandbox.command("headers"); - helper - .current_dir(repository) - .env("SCE_CONFIG_FILE", config); + helper.current_dir(repository); + if let Some(config) = config { + helper.env("SCE_CONFIG_FILE", config); + } helper.spawn().expect("spawn headers") } +fn assert_headers_served(helper: Child) { + let output = helper.wait_with_output().expect("headers output"); + assert!(output.status.success(), "headers child failed"); + assert!( + String::from_utf8_lossy(&output.stdout).contains(HEADERS_AUTHORIZATION), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} + fn assert_headers_unavailable(helper: Child) { let output = helper.wait_with_output().expect("headers output"); let stdout = String::from_utf8_lossy(&output.stdout); @@ -627,23 +659,34 @@ fn policy_hook_fallback_reasons(sandbox: &Sandbox, telemetry_enabled: bool) -> V serde_json::json!({ "telemetry": { "enabled": telemetry_enabled } }).to_string(), ) .expect("policy config"); - let log_dir = root.join(format!("logs-{telemetry_enabled}")); + hook_fallback_reasons( + sandbox, + &work, + Some(&config), + &format!("logs-{telemetry_enabled}"), + ) +} + +fn hook_fallback_reasons( + sandbox: &Sandbox, + working_dir: &Path, + explicit_config: Option<&Path>, + log_label: &str, +) -> Vec { + let log_dir = sandbox.dir.path().join(log_label); std::fs::create_dir_all(&log_dir).expect("log dir"); - wait_success( - "policy-hook", - sandbox - .command("policy-hook") - .current_dir(&work) - .env(AUTH_DB_ENCRYPTION_KEY_ENV, "") - .env("SCE_CONFIG_FILE", &config) - .env("SCE_LOG_LEVEL", "debug") - .env("SCE_LOG_FORMAT", "text") - .env("SCE_LOG_DIR", &log_dir) - .env("CLAUDECODE", "1") - .env("CLAUDE_PROJECT_DIR", &work) - .spawn() - .expect("spawn policy hook"), - ); + let mut hook = sandbox.command("policy-hook"); + hook.current_dir(working_dir) + .env(AUTH_DB_ENCRYPTION_KEY_ENV, "") + .env("SCE_LOG_LEVEL", "debug") + .env("SCE_LOG_FORMAT", "text") + .env("SCE_LOG_DIR", &log_dir) + .env("CLAUDECODE", "1") + .env("CLAUDE_PROJECT_DIR", working_dir); + if let Some(config) = explicit_config { + hook.env("SCE_CONFIG_FILE", config); + } + wait_success("policy-hook", hook.spawn().expect("spawn policy hook")); let mut reasons = Vec::new(); for entry in std::fs::read_dir(&log_dir).expect("log entries") { let log = std::fs::read_to_string(entry.expect("log entry").path()).expect("log file"); @@ -660,6 +703,165 @@ fn policy_hook_fallback_reasons(sandbox: &Sandbox, telemetry_enabled: bool) -> V reasons } +struct CliRun { + success: bool, + stdout: String, + stderr: String, +} + +fn run_cli( + sandbox: &Sandbox, + working_dir: &Path, + args: &[&str], + explicit_config: Option<&Path>, +) -> CliRun { + let mut command = sandbox.command("cli"); + command + .current_dir(working_dir) + .env(CLI_ARGS_ENV, args.join("\n")); + if let Some(config) = explicit_config { + command.env("SCE_CONFIG_FILE", config); + } + let output = command + .spawn() + .expect("spawn cli") + .wait_with_output() + .expect("cli output"); + let stdout = String::from_utf8_lossy(&output.stdout).into_owned(); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + assert!(output.status.success(), "cli child failed: {stderr}"); + CliRun { + success: stdout.contains(&format!("{CLI_SUCCESS_PREFIX}true")), + stdout, + stderr, + } +} + +fn bound_repository(sandbox: &Sandbox) -> PathBuf { + let repository = git_repository_with_remote( + sandbox.dir.path(), + HEADERS_REPOSITORY, + "https://github.com/acme/bound-repo", + ); + sandbox.seed(); + let mut bind = sandbox.command("bind"); + bind.current_dir(&repository); + wait_success("bind", bind.spawn().expect("spawn bind")); + repository +} + +#[test] +fn cli_launched_from_a_repository_subdirectory_honors_repository_policy() { + let _fan_out = serialize_fan_out(); + let sandbox = Sandbox::new(); + sandbox.write_global_config(&serde_json::json!({ + "auth": { "mode": "optional" }, + "telemetry": { "enabled": true }, + })); + let repository = bound_repository(&sandbox); + let nested = repository.join("src").join("module"); + let repository_config = repository.join(".sce").join("config.json"); + + assert_headers_served(spawn_headers(&sandbox, &nested, None)); + assert_eq!( + hook_fallback_reasons(&sandbox, &nested, None, "logs-consented"), + ["database_error"] + ); + + write_config_file( + &repository_config, + &serde_json::json!({ "telemetry": { "enabled": false } }), + ); + assert_headers_unavailable(spawn_headers(&sandbox, &nested, None)); + assert_eq!( + hook_fallback_reasons(&sandbox, &nested, None, "logs-repository-opt-out"), + ["disabled_by_config"] + ); + + write_config_file( + &repository_config, + &serde_json::json!({ "auth": { "mode": "disabled" } }), + ); + let sync = run_cli( + &sandbox, + &nested, + &["sce", "sync", "--format", "json"], + None, + ); + assert!(!sync.success, "{}", sync.stdout); + assert!( + sync.stderr.contains(AUTH_DISABLED_BY_REPOSITORY), + "{}", + sync.stderr + ); + assert_headers_unavailable(spawn_headers(&sandbox, &nested, None)); +} + +#[test] +fn explicit_config_cannot_enable_access_the_global_config_forbids() { + let _fan_out = serialize_fan_out(); + let sandbox = Sandbox::new(); + let repository = bound_repository(&sandbox); + let explicit = sandbox.dir.path().join("explicit-config.json"); + write_config_file( + &explicit, + &serde_json::json!({ + "auth": { "mode": "optional" }, + "telemetry": { "enabled": true }, + }), + ); + assert_headers_served(spawn_headers(&sandbox, &repository, Some(&explicit))); + + sandbox.write_global_config(&serde_json::json!({ + "auth": { "mode": "disabled" }, + "telemetry": { "enabled": false }, + })); + assert_headers_unavailable(spawn_headers(&sandbox, &repository, Some(&explicit))); + assert_eq!( + hook_fallback_reasons(&sandbox, &repository, Some(&explicit), "logs-explicit"), + ["disabled_by_config"] + ); + let sync = run_cli( + &sandbox, + &repository, + &["sce", "sync", "--format", "json"], + Some(&explicit), + ); + assert!(!sync.success, "{}", sync.stdout); + assert!( + sync.stderr.contains(AUTH_DISABLED_BY_GLOBAL), + "{}", + sync.stderr + ); + + let show = run_cli( + &sandbox, + &repository, + &[ + "sce", + "config", + "show", + "--config", + explicit.to_str().expect("utf-8 path"), + "--format", + "json", + ], + None, + ); + assert!(show.success, "{}", show.stderr); + for expected in [ + r#""state": "disabled""#, + r#""reason": "auth_disabled""#, + r#""config_source": "default_discovered_global""#, + ] { + assert!( + show.stdout.contains(expected), + "{expected}: {}", + show.stdout + ); + } +} + #[test] fn claude_hook_with_telemetry_disabled_by_config_never_resolves_the_credential() { let _fan_out = serialize_fan_out(); @@ -944,6 +1146,15 @@ async fn run_binding_child(role: &str) { .expect("binding succeeds") ); } + "cli" => { + let args = std::env::var(CLI_ARGS_ENV).expect("cli args"); + let code = Box::pin(crate::app::run(args.split('\n').map(String::from))).await; + println!(); + println!( + "{CLI_SUCCESS_PREFIX}{}", + code == std::process::ExitCode::SUCCESS + ); + } "headers" => { let code = Box::pin(crate::app::run( ["sce", "auth", "telemetry-headers"] diff --git a/cli/src/services/config/resolver.rs b/cli/src/services/config/resolver.rs index 2110abbe3..eba25bdfe 100644 --- a/cli/src/services/config/resolver.rs +++ b/cli/src/services/config/resolver.rs @@ -9,7 +9,7 @@ use std::path::{Path, PathBuf}; use anyhow::{anyhow, bail, Context, Result}; use crate::services::default_paths::{ - observability_log_dir, resolve_sce_default_locations, RepoPaths, + enclosing_repository_root_with, observability_log_dir, resolve_sce_default_locations, RepoPaths, }; use crate::services::managed_telemetry::MANAGED_OTLP_DEFAULTS; @@ -45,6 +45,8 @@ pub(crate) const WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED: &str = pub(crate) const WARNING_AUTO_SYNC_WITH_AUTH_DISABLED: &str = "agent_trace.auto_sync is true but auth.mode resolves to disabled; post-commit auto-sync is skipped."; pub(crate) const WARNING_REPOSITORY_MANDATORY_OVERRIDDEN_BY_USER_DISABLED: &str = "auth.mode is mandatory in the repository config but disabled in the user config; auth.mode resolves to disabled."; +pub(crate) const WARNING_EXPLICIT_AUTH_MODE_OVERRIDDEN: &str = "auth.mode in the explicitly selected config is less restrictive than the global or repository config; the most restrictive auth.mode applies."; +pub(crate) const WARNING_EXPLICIT_TELEMETRY_OVERRIDDEN: &str = "telemetry.enabled is true in the explicitly selected config but false in the global or repository config; SCE telemetry is disabled."; pub(crate) const WARNING_INVALID_LAYER_DISABLES_CLOUD: &str = "A discovered config file was skipped as invalid; SCE telemetry and background cloud operations are disabled."; pub(crate) const CONTROL_PLANE_BASE_URL_KEY: AuthConfigKeySpec = AuthConfigKeySpec { @@ -425,6 +427,10 @@ where let mut validation_errors = Vec::new(); let mut user_policy_layer = AccessPolicyLayer::default(); let mut repository_policy_layer = AccessPolicyLayer::default(); + let mut explicit_policy_layer = AccessPolicyLayer::default(); + let explicit_config_selected = loaded_config_paths + .iter() + .any(|loaded_path| !loaded_path.source.is_default_discovered()); for loaded_path in &loaded_config_paths { let raw = read_file(&loaded_path.path)?; let layer = match schema::parse_file_config(&raw, &loaded_path.path, loaded_path.source) { @@ -438,9 +444,13 @@ where let policy_layer = match PolicyLayer::from_config_path_source(loaded_path.source) { PolicyLayer::User => &mut user_policy_layer, PolicyLayer::Repository => &mut repository_policy_layer, + PolicyLayer::Explicit => &mut explicit_policy_layer, }; policy_layer.auth_mode = layer.auth_mode; policy_layer.telemetry_enabled = layer.telemetry_enabled; + if explicit_config_selected && loaded_path.source.is_default_discovered() { + continue; + } if let Some(log_level) = layer.log_level { file_config.log_level = Some(log_level); } @@ -636,11 +646,16 @@ where let mut validation_warnings = build_validation_warnings(&resolved_bash_policies); let degraded = !validation_errors.is_empty(); - let access_policy = - resolve_access_policy(&user_policy_layer, &repository_policy_layer, degraded); + let access_policy = resolve_access_policy( + &user_policy_layer, + &repository_policy_layer, + &explicit_policy_layer, + degraded, + ); validation_warnings.extend(build_access_policy_warnings( &user_policy_layer, &repository_policy_layer, + &explicit_policy_layer, &access_policy, resolved_agent_trace_auto_sync.value, degraded, @@ -698,15 +713,20 @@ const fn auth_mode_restriction_rank(mode: AuthMode) -> u8 { fn resolve_effective_auth_mode( user: &AccessPolicyLayer, repository: &AccessPolicyLayer, + explicit: &AccessPolicyLayer, ) -> ResolvedValue { let mut resolved = ResolvedValue { value: AuthMode::Optional, source: ValueSource::Default, }; let mut deciding_rank = None; - for value in [user.auth_mode.as_ref(), repository.auth_mode.as_ref()] - .into_iter() - .flatten() + for value in [ + user.auth_mode.as_ref(), + repository.auth_mode.as_ref(), + explicit.auth_mode.as_ref(), + ] + .into_iter() + .flatten() { let rank = auth_mode_restriction_rank(value.value); if deciding_rank.is_none_or(|deciding| rank >= deciding) { @@ -723,14 +743,16 @@ fn resolve_effective_auth_mode( pub(super) fn resolve_access_policy( user: &AccessPolicyLayer, repository: &AccessPolicyLayer, + explicit: &AccessPolicyLayer, degraded: bool, ) -> ResolvedAccessPolicy { - let auth_mode = resolve_effective_auth_mode(user, repository); + let auth_mode = resolve_effective_auth_mode(user, repository, explicit); let auth_disabled = auth_mode.value == AuthMode::Disabled; - let telemetry_enabled = match repository + let telemetry_enabled = match explicit .telemetry_enabled .as_ref() + .or(repository.telemetry_enabled.as_ref()) .or(user.telemetry_enabled.as_ref()) { Some(value) => ResolvedValue { @@ -747,11 +769,11 @@ pub(super) fn resolve_access_policy( TelemetryPolicyState::Disabled(TelemetryDisabledReason::InvalidConfig) } else if auth_disabled { TelemetryPolicyState::Disabled(TelemetryDisabledReason::AuthDisabled) - } else if user.telemetry() == Some(false) { + } else if user_telemetry_opt_out(user, explicit) { TelemetryPolicyState::Disabled(TelemetryDisabledReason::UserOptOut) } else if repository.telemetry() == Some(false) { TelemetryPolicyState::Disabled(TelemetryDisabledReason::RepositoryOptOut) - } else if user.telemetry() == Some(true) { + } else if user_telemetry_consent(user, explicit) { TelemetryPolicyState::Enabled } else if repository.telemetry() == Some(true) { TelemetryPolicyState::Disabled(TelemetryDisabledReason::NoUserConsent) @@ -767,29 +789,50 @@ 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 build_access_policy_warnings( user: &AccessPolicyLayer, repository: &AccessPolicyLayer, + explicit: &AccessPolicyLayer, policy: &ResolvedAccessPolicy, agent_trace_auto_sync: bool, degraded: bool, ) -> Vec { 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() != Some(true) { + if repository.telemetry() == Some(true) && !user_telemetry_consent(user, explicit) { warnings.push(WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT.to_string()); } - if auth_disabled && (user.telemetry() == Some(true) || repository.telemetry() == Some(true)) { + if auth_disabled && layers.iter().any(|layer| layer.telemetry() == Some(true)) { warnings.push(WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED.to_string()); } if auth_disabled && agent_trace_auto_sync { warnings.push(WARNING_AUTO_SYNC_WITH_AUTH_DISABLED.to_string()); } if repository.auth_mode() == Some(AuthMode::Mandatory) - && user.auth_mode() == Some(AuthMode::Disabled) + && (user.auth_mode() == Some(AuthMode::Disabled) + || explicit.auth_mode() == Some(AuthMode::Disabled)) { warnings.push(WARNING_REPOSITORY_MANDATORY_OVERRIDDEN_BY_USER_DISABLED.to_string()); } + if explicit.auth_mode().is_some_and(|mode| { + auth_mode_restriction_rank(mode) < auth_mode_restriction_rank(policy.auth_mode.value) + }) { + warnings.push(WARNING_EXPLICIT_AUTH_MODE_OVERRIDDEN.to_string()); + } + if explicit.telemetry() == Some(true) + && (user.telemetry() == Some(false) || repository.telemetry() == Some(false)) + { + warnings.push(WARNING_EXPLICIT_TELEMETRY_OVERRIDDEN.to_string()); + } if degraded { warnings.push(WARNING_INVALID_LAYER_DISABLES_CLOUD.to_string()); } @@ -872,6 +915,39 @@ fn resolve_config_paths( where FEnv: Fn(&str) -> Option, FGlobalPath: Fn() -> Result, +{ + let explicit_path = resolve_explicit_config_path(request, env_lookup, path_exists)?; + + let mut loaded_paths = Vec::new(); + + let global_path = resolve_global_config_path()?; + if path_exists(&global_path) { + loaded_paths.push(LoadedConfigPath { + path: global_path, + source: ConfigPathSource::DefaultDiscoveredGlobal, + }); + } + + let repository_root = enclosing_repository_root_with(cwd, path_exists).unwrap_or(cwd); + let local_path = RepoPaths::new(repository_root).sce_config_file(); + if path_exists(&local_path) { + loaded_paths.push(LoadedConfigPath { + path: local_path, + source: ConfigPathSource::DefaultDiscoveredLocal, + }); + } + + loaded_paths.extend(explicit_path); + Ok(loaded_paths) +} + +fn resolve_explicit_config_path( + request: &ConfigRequest, + env_lookup: &FEnv, + path_exists: fn(&Path) -> bool, +) -> Result> +where + FEnv: Fn(&str) -> Option, { if let Some(path) = request.config_path.as_ref() { if !path_exists(path) { @@ -880,10 +956,10 @@ where path.display() ); } - return Ok(vec![LoadedConfigPath { + return Ok(Some(LoadedConfigPath { path: path.clone(), source: ConfigPathSource::Flag, - }]); + })); } if let Some(raw) = env_lookup("SCE_CONFIG_FILE") { @@ -894,31 +970,13 @@ where path.display() ); } - return Ok(vec![LoadedConfigPath { + return Ok(Some(LoadedConfigPath { path, source: ConfigPathSource::Env, - }]); - } - - let mut discovered_paths = Vec::new(); - - let global_path = resolve_global_config_path()?; - if path_exists(&global_path) { - discovered_paths.push(LoadedConfigPath { - path: global_path, - source: ConfigPathSource::DefaultDiscoveredGlobal, - }); + })); } - let local_path = RepoPaths::new(cwd).sce_config_file(); - if path_exists(&local_path) { - discovered_paths.push(LoadedConfigPath { - path: local_path, - source: ConfigPathSource::DefaultDiscoveredLocal, - }); - } - - Ok(discovered_paths) + Ok(None) } fn resolve_default_global_config_path() -> Result { @@ -1443,6 +1501,7 @@ mod access_policy_tests { let policy = resolve_access_policy( &user(user_mode, None), &repository(repository_mode, None), + &AccessPolicyLayer::default(), degraded, ); let case = format!( @@ -1529,6 +1588,7 @@ mod access_policy_tests { let policy = resolve_access_policy( &user(user_mode, user_telemetry), &repository(None, repository_telemetry), + &AccessPolicyLayer::default(), degraded, ); let expected = if degraded { @@ -1560,6 +1620,7 @@ mod access_policy_tests { let policy = resolve_access_policy( &user(None, Some(true)), &repository(Some(AuthMode::Disabled), None), + &AccessPolicyLayer::default(), false, ); @@ -1574,10 +1635,18 @@ mod access_policy_tests { fn access_policy_warnings_are_deterministic_and_ordered() { let user_layer = user(Some(AuthMode::Disabled), None); let repository_layer = repository(Some(AuthMode::Mandatory), Some(true)); - let policy = resolve_access_policy(&user_layer, &repository_layer, true); + let explicit_layer = AccessPolicyLayer::default(); + let policy = resolve_access_policy(&user_layer, &repository_layer, &explicit_layer, true); assert_eq!( - build_access_policy_warnings(&user_layer, &repository_layer, &policy, true, true), + build_access_policy_warnings( + &user_layer, + &repository_layer, + &explicit_layer, + &policy, + true, + true + ), vec![ WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT.to_string(), WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED.to_string(), @@ -1588,25 +1657,48 @@ mod access_policy_tests { ); let consenting_user = user(Some(AuthMode::Optional), Some(true)); - let consenting_policy = resolve_access_policy(&consenting_user, &repository_layer, false); + let consenting_policy = + resolve_access_policy(&consenting_user, &repository_layer, &explicit_layer, false); assert!(build_access_policy_warnings( &consenting_user, &repository_layer, + &explicit_layer, &consenting_policy, true, false, ) .is_empty()); + + let restricting_user = user(Some(AuthMode::Mandatory), Some(false)); + let silent_repository = repository(None, None); + let permissive_explicit = + layer(ConfigPathSource::Flag, Some(AuthMode::Optional), Some(true)); + let overridden_policy = resolve_access_policy( + &restricting_user, + &silent_repository, + &permissive_explicit, + false, + ); + assert_eq!( + build_access_policy_warnings( + &restricting_user, + &silent_repository, + &permissive_explicit, + &overridden_policy, + false, + false, + ), + vec![ + WARNING_EXPLICIT_AUTH_MODE_OVERRIDDEN.to_string(), + WARNING_EXPLICIT_TELEMETRY_OVERRIDDEN.to_string(), + ] + ); } fn discovered_paths_exist(path: &Path) -> bool { path == Path::new(GLOBAL_PATH) || path == Path::new(LOCAL_PATH) } - fn explicit_path_exists(path: &Path) -> bool { - path == Path::new(EXPLICIT_PATH) - } - fn resolve_discovered(global: &'static str, local: &'static str) -> RuntimeConfig { resolve_runtime_config_with( &ConfigRequest { @@ -1629,47 +1721,326 @@ mod access_policy_tests { .unwrap() } - #[test] - fn access_policy_explicit_config_file_acts_as_user_layer() { - let config = r#"{"auth":{"mode":"mandatory"},"telemetry":{"enabled":true}}"#; - let flag = resolve_runtime_config_with( - &ConfigRequest { - report_format: ReportFormat::Text, - config_path: Some(PathBuf::from(EXPLICIT_PATH)), - log_level: None, - }, + fn all_policy_paths_exist(path: &Path) -> bool { + [GLOBAL_PATH, LOCAL_PATH, EXPLICIT_PATH] + .iter() + .any(|candidate| path == Path::new(candidate)) + } + + fn resolve_with_explicit( + source: ConfigPathSource, + global: &'static str, + repository: &'static str, + explicit: &'static str, + ) -> RuntimeConfig { + let request = ConfigRequest { + config_path: (source == ConfigPathSource::Flag).then(|| PathBuf::from(EXPLICIT_PATH)), + report_format: ReportFormat::Text, + log_level: None, + }; + resolve_runtime_config_with( + &request, Path::new("/tmp/policy-repo"), - |_| None, - |_| Ok(config.to_string()), - explicit_path_exists, + move |key| { + (source == ConfigPathSource::Env && key == "SCE_CONFIG_FILE") + .then(|| EXPLICIT_PATH.to_string()) + }, + move |path| { + Ok(if path == Path::new(GLOBAL_PATH) { + global + } else if path == Path::new(LOCAL_PATH) { + repository + } else { + explicit + } + .to_string()) + }, + all_policy_paths_exist, || Ok(PathBuf::from(GLOBAL_PATH)), ) - .unwrap(); - let env = resolve_runtime_config_with( + .unwrap() + } + + #[test] + fn explicit_config_cannot_bypass_global_or_repository_restrictions() { + use TelemetryDisabledReason::{AuthDisabled, InvalidConfig, RepositoryOptOut, UserOptOut}; + use TelemetryPolicyState::{Disabled, Enabled}; + + #[derive(Clone, Copy, Debug)] + enum Deciding { + Default, + Global, + Repository, + Explicit, + } + + const TELEMETRY_ON: &str = r#"{"telemetry":{"enabled":true}}"#; + const TELEMETRY_OFF: &str = r#"{"telemetry":{"enabled":false}}"#; + let cases = [ + ( + TELEMETRY_OFF, + "{}", + TELEMETRY_ON, + AuthMode::Optional, + Deciding::Default, + Disabled(UserOptOut), + ), + ( + r#"{"auth":{"mode":"disabled"}}"#, + "{}", + r#"{"auth":{"mode":"optional"},"telemetry":{"enabled":true}}"#, + AuthMode::Disabled, + Deciding::Global, + Disabled(AuthDisabled), + ), + ( + TELEMETRY_ON, + TELEMETRY_OFF, + TELEMETRY_ON, + AuthMode::Optional, + Deciding::Default, + Disabled(RepositoryOptOut), + ), + ( + r#"{"auth":{"mode":"optional"}}"#, + r#"{"auth":{"mode":"disabled"}}"#, + r#"{"auth":{"mode":"mandatory"},"telemetry":{"enabled":true}}"#, + AuthMode::Disabled, + Deciding::Repository, + Disabled(AuthDisabled), + ), + ( + TELEMETRY_OFF, + TELEMETRY_ON, + TELEMETRY_ON, + AuthMode::Optional, + Deciding::Default, + Disabled(UserOptOut), + ), + ( + "{}", + "{}", + r#"{"auth":{"mode":"mandatory"},"telemetry":{"enabled":true}}"#, + AuthMode::Mandatory, + Deciding::Explicit, + Enabled, + ), + ( + r#"{"telemetry":{"enabled":"no"}}"#, + "{}", + TELEMETRY_ON, + AuthMode::Optional, + Deciding::Default, + Disabled(InvalidConfig), + ), + ]; + + for (global, repository, explicit, auth_mode, deciding, telemetry) in cases { + for source in [ConfigPathSource::Flag, ConfigPathSource::Env] { + let runtime = resolve_with_explicit(source, global, repository, explicit); + let policy = &runtime.access_policy; + let case = format!( + "global={global} repository={repository} explicit={explicit} source={source:?}" + ); + let expected_auth_source = match deciding { + Deciding::Default => ValueSource::Default, + Deciding::Global => { + ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal) + } + Deciding::Repository => { + ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal) + } + Deciding::Explicit => ValueSource::ConfigFile(source), + }; + let cloud_allowed = + auth_mode != AuthMode::Disabled && telemetry != Disabled(InvalidConfig); + + assert_eq!(policy.auth_mode.value, auth_mode, "{case}"); + assert_eq!(policy.auth_mode.source, expected_auth_source, "{case}"); + assert_eq!(policy.telemetry, telemetry, "{case}"); + assert_eq!(policy.background_cloud_allowed, cloud_allowed, "{case}"); + } + } + } + + #[test] + fn explicit_config_keeps_replacing_discovered_ordinary_values() { + for source in [ConfigPathSource::Flag, ConfigPathSource::Env] { + let runtime = resolve_with_explicit( + source, + r#"{"log_level":"warn","agent_trace":{"auto_sync":true}}"#, + r#"{"agent_trace":{"repository_remote":"upstream"}}"#, + r#"{"log_level":"debug"}"#, + ); + + assert_eq!(runtime.log_level.value, LogLevel::Debug); + assert_eq!(runtime.log_level.source, ValueSource::ConfigFile(source)); + assert_eq!(runtime.agent_trace_auto_sync.source, ValueSource::Default); + assert_eq!( + runtime.agent_trace_repository_remote.source, + ValueSource::Default + ); + assert_eq!( + runtime + .loaded_config_paths + .iter() + .map(|loaded| loaded.source) + .collect::>(), + vec![ + ConfigPathSource::DefaultDiscoveredGlobal, + ConfigPathSource::DefaultDiscoveredLocal, + source, + ] + ); + } + } + + fn git(dir: &Path, args: &[&str]) { + let status = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .args([ + "-c", + "user.name=SCE Test", + "-c", + "user.email=sce@example.invalid", + "-c", + "commit.gpgsign=false", + ]) + .args(args) + .env_remove("GIT_DIR") + .env_remove("GIT_WORK_TREE") + .env_remove("GIT_INDEX_FILE") + .status() + .unwrap(); + assert!(status.success(), "git {args:?} in {}", dir.display()); + } + + fn write_repository_config(dir: &Path, contents: &str) -> PathBuf { + let path = RepoPaths::new(dir).sce_config_file(); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, contents).unwrap(); + path + } + + #[test] + fn repository_policy_outside_git_is_discovered_from_the_working_directory_only() { + let at_directory = resolve_discovered( + r#"{"telemetry":{"enabled":true}}"#, + r#"{"telemetry":{"enabled":false}}"#, + ); + assert_eq!( + at_directory.access_policy.telemetry, + TelemetryPolicyState::Disabled(TelemetryDisabledReason::RepositoryOptOut) + ); + + let below_directory = resolve_runtime_config_with( &ConfigRequest { report_format: ReportFormat::Text, config_path: None, log_level: None, }, - Path::new("/tmp/policy-repo"), - |key| (key == "SCE_CONFIG_FILE").then(|| EXPLICIT_PATH.to_string()), - |_| Ok(config.to_string()), - explicit_path_exists, + Path::new("/tmp/policy-repo/src"), + |_| None, + |_| Ok(r#"{"telemetry":{"enabled":true}}"#.to_string()), + discovered_paths_exist, || Ok(PathBuf::from(GLOBAL_PATH)), ) .unwrap(); + assert_eq!(below_directory.loaded_config_paths.len(), 1); + assert_eq!( + below_directory.access_policy.telemetry, + TelemetryPolicyState::Enabled + ); + } - for (runtime, source) in [(flag, ConfigPathSource::Flag), (env, ConfigPathSource::Env)] { - let policy = runtime.access_policy; - assert_eq!(policy.telemetry, TelemetryPolicyState::Enabled); - assert_eq!(policy.auth_mode.value, AuthMode::Mandatory); - assert_eq!(policy.auth_mode.source, ValueSource::ConfigFile(source)); - assert_eq!( - policy.telemetry_enabled.source, - ValueSource::ConfigFile(source) - ); - assert!(policy.background_cloud_allowed); - assert!(runtime.validation_warnings.is_empty()); + #[test] + fn repository_policy_is_discovered_from_the_enclosing_git_root() { + let dir = tempfile::tempdir().unwrap(); + let base = dir.path(); + let global = base.join("global-config.json"); + std::fs::write( + &global, + r#"{"auth":{"mode":"optional"},"telemetry":{"enabled":true}}"#, + ) + .unwrap(); + + let repo = base.join("repo"); + std::fs::create_dir_all(&repo).unwrap(); + git(&repo, &["init", "--quiet"]); + let repo_config = write_repository_config(&repo, r#"{"telemetry":{"enabled":false}}"#); + git(&repo, &["add", ".sce/config.json"]); + git(&repo, &["commit", "--quiet", "-m", "init"]); + let worktree = base.join("worktree"); + git( + &repo, + &["worktree", "add", "--quiet", worktree.to_str().unwrap()], + ); + let worktree_config = RepoPaths::new(&worktree).sce_config_file(); + + let inner = repo.join("vendor").join("inner"); + std::fs::create_dir_all(&inner).unwrap(); + git(&inner, &["init", "--quiet"]); + let inner_config = write_repository_config(&inner, r#"{"auth":{"mode":"disabled"}}"#); + + for nested in [&repo, &worktree, &inner] { + std::fs::create_dir_all(nested.join("src").join("module")).unwrap(); + } + + let resolve = |cwd: &Path| { + resolve_runtime_config_with( + &ConfigRequest { + report_format: ReportFormat::Text, + config_path: None, + log_level: None, + }, + cwd, + |_| None, + |path| Ok(std::fs::read_to_string(path)?), + Path::exists, + || Ok(global.clone()), + ) + .unwrap() + }; + let repository_opt_out = + TelemetryPolicyState::Disabled(TelemetryDisabledReason::RepositoryOptOut); + let auth_disabled = TelemetryPolicyState::Disabled(TelemetryDisabledReason::AuthDisabled); + let cases = [ + ( + &repo, + Some(&repo_config), + AuthMode::Optional, + repository_opt_out, + ), + ( + &worktree, + Some(&worktree_config), + AuthMode::Optional, + repository_opt_out, + ), + ( + &inner, + Some(&inner_config), + AuthMode::Disabled, + auth_disabled, + ), + ]; + + for (root, config, auth_mode, telemetry) in cases { + for cwd in [root.clone(), root.join("src").join("module")] { + let runtime = resolve(&cwd); + let case = cwd.display().to_string(); + assert_eq!( + runtime + .loaded_config_paths + .last() + .map(|loaded| &loaded.path), + config, + "{case}" + ); + assert_eq!(runtime.access_policy.auth_mode.value, auth_mode, "{case}"); + assert_eq!(runtime.access_policy.telemetry, telemetry, "{case}"); + } } } diff --git a/cli/src/services/config/types.rs b/cli/src/services/config/types.rs index 199010bed..210272acb 100644 --- a/cli/src/services/config/types.rs +++ b/cli/src/services/config/types.rs @@ -119,15 +119,15 @@ impl AuthMode { pub(crate) enum PolicyLayer { User, Repository, + Explicit, } impl PolicyLayer { pub(crate) const fn from_config_path_source(source: ConfigPathSource) -> Self { match source { - ConfigPathSource::Flag - | ConfigPathSource::Env - | ConfigPathSource::DefaultDiscoveredGlobal => Self::User, + ConfigPathSource::DefaultDiscoveredGlobal => Self::User, ConfigPathSource::DefaultDiscoveredLocal => Self::Repository, + ConfigPathSource::Flag | ConfigPathSource::Env => Self::Explicit, } } } diff --git a/cli/src/services/default_paths.rs b/cli/src/services/default_paths.rs index 5f9a3eae3..d0e42c61d 100644 --- a/cli/src/services/default_paths.rs +++ b/cli/src/services/default_paths.rs @@ -1,4 +1,4 @@ -use std::path::PathBuf; +use std::path::{Path, PathBuf}; pub(crate) use roots::{resolve_sce_default_locations, resolve_state_data_root}; @@ -297,6 +297,19 @@ pub fn observability_log_dir() -> anyhow::Result { Ok(sce_state_dir()?.join("logs")) } +pub(crate) fn enclosing_repository_root(start: &Path) -> Option<&Path> { + enclosing_repository_root_with(start, Path::exists) +} + +pub(crate) fn enclosing_repository_root_with( + start: &Path, + git_entry_exists: impl Fn(&Path) -> bool, +) -> Option<&Path> { + start + .ancestors() + .find(|dir| git_entry_exists(&dir.join(repo_dir::GIT))) +} + fn sce_state_dir() -> anyhow::Result { Ok(resolve_sce_default_locations()? .roots() @@ -310,6 +323,7 @@ pub(crate) mod repo_dir { pub const CLAUDE: &str = ".claude"; pub const PI: &str = ".pi"; pub const CODEX: &str = ".codex"; + pub const GIT: &str = ".git"; } pub(crate) mod repo_file { diff --git a/cli/src/services/managed_telemetry/claude_helper.rs b/cli/src/services/managed_telemetry/claude_helper.rs index 8dea4f180..91ab3cda6 100644 --- a/cli/src/services/managed_telemetry/claude_helper.rs +++ b/cli/src/services/managed_telemetry/claude_helper.rs @@ -5,9 +5,9 @@ use super::{ MANAGED_OTLP_TRACES_ENDPOINT, }; use crate::services::config; +use crate::services::default_paths::enclosing_repository_root; use crate::services::repository_identity::resolve::resolve_repository_identity; -const GIT_DIR_NAME: &str = ".git"; const DESTINATION_ENVS: [(&str, &str); 5] = [ ("OTEL_EXPORTER_OTLP_ENDPOINT", MANAGED_OTLP_ENDPOINT), ( @@ -39,9 +39,7 @@ where } pub fn repository_id_for(working_dir: &Path) -> Option { - let root = working_dir - .ancestors() - .find(|dir| dir.join(GIT_DIR_NAME).exists())?; + let root = enclosing_repository_root(working_dir)?; let storage_config = config::resolve_agent_trace_storage_runtime_config(root).ok()?; resolve_repository_identity( root, diff --git a/cli/src/services/setup/command.rs b/cli/src/services/setup/command.rs index fdfa73cdf..74eaca0c5 100644 --- a/cli/src/services/setup/command.rs +++ b/cli/src/services/setup/command.rs @@ -369,6 +369,7 @@ mod tests { #[test] fn setup_claude_telemetry_policy_follows_layered_config() { let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join(".git")).unwrap(); let global = dir.path().join("global.json"); let local_dir = dir.path().join(".sce"); fs::create_dir_all(&local_dir).unwrap(); diff --git a/cli/src/services/sync/sync.rs b/cli/src/services/sync/sync.rs index d04683962..1557b02ba 100644 --- a/cli/src/services/sync/sync.rs +++ b/cli/src/services/sync/sync.rs @@ -572,6 +572,7 @@ mod tests { #[tokio::test] async fn sync_rejects_disabled_auth_before_storage_or_credential_access() { let dir = tempfile::tempdir().expect("temp dir"); + std::fs::create_dir(dir.path().join(".git")).expect("repository marker"); std::fs::create_dir_all(dir.path().join(".sce")).expect("config dir"); std::fs::write( dir.path().join(".sce").join("config.json"), diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md index ac1160c2b..5b4d8a017 100644 --- a/context/cli/access-policy.md +++ b/context/cli/access-policy.md @@ -10,9 +10,11 @@ Status: the resolver computes and exposes the policy, and `sce config show` / `v - **Auth mode** (`AuthMode`): `disabled | optional | mandatory`. Omitted means `optional`. - **Policy layer** (`PolicyLayer`): how a config file is classified for access policy. - - **User layer:** a `DefaultDiscoveredGlobal` file, or the single explicit file (`Flag` / `Env`). - - **Repository layer:** a `DefaultDiscoveredLocal` file (`/.sce/config.json`). - - Neither key has an environment-variable or CLI-flag layer. + - **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. + - 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. @@ -20,20 +22,34 @@ Status: the resolver computes and exposes the policy, and `sce config show` / `v - `background_cloud_allowed`. - **Degraded:** at least one default-discovered file was skipped as invalid. +## Repository discovery + +`resolve_config_paths` locates the repository layer at `enclosing_repository_root_with(cwd, path_exists)` (`cli/src/services/default_paths.rs`): the nearest ancestor of the working directory, inclusive, that contains a `.git` entry (directory or file). That is the worktree root for ordinary repositories, linked worktrees, and submodules; in a nested repository it is the innermost repository. Outside a Git repository it falls back to the working directory. The walk only probes the filesystem, so no Git subprocess runs on hook paths. `GIT_DIR` / `GIT_WORK_TREE` are not consulted. `repository_id_for` (the headers helper's repository identity) uses the same helper, so policy and repository identity always describe the same root. + +Every consumer goes through this one resolver, so running from the repository root or any subdirectory yields the same effective policy: startup and managed telemetry, `sce auth login` / `whoami`, `sce auth telemetry-headers`, `sce sync`, post-commit auto-sync, `sce doctor`, and `sce config show` / `validate`. + +## Explicit config files + +`--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. +- 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 -`resolve_runtime_config_with` records each parsed layer's `auth_mode` / `telemetry_enabled` into a user or a repository `AccessPolicyLayer` during the merge loop. It then calls the pure `resolve_access_policy(user, repository, degraded)` (`cli/src/services/config/resolver.rs`). +`resolve_runtime_config_with` records each parsed layer's `auth_mode` / `telemetry_enabled` into a user, repository, or explicit `AccessPolicyLayer` during the merge loop. It then calls the pure `resolve_access_policy(user, repository, explicit, degraded)` (`cli/src/services/config/resolver.rs`). ```mermaid flowchart TD D{degraded?} -- yes --> I[Disabled InvalidConfig] D -- no --> A{effective auth disabled?} A -- yes --> AD[Disabled AuthDisabled] - A -- no --> U0{user false?} + A -- no --> U0{user or explicit false?} U0 -- yes --> UO[Disabled UserOptOut] U0 -- no --> R0{repository false?} R0 -- yes --> RO[Disabled RepositoryOptOut] - R0 -- no --> U1{user true?} + R0 -- no --> U1{user or explicit true?} U1 -- yes --> E[Enabled] U1 -- no --> R1{repository true?} R1 -- yes --> NC[Disabled NoUserConsent] @@ -41,9 +57,9 @@ flowchart TD ``` - **Auth mode:** the most restrictive layer wins (`disabled > mandatory > optional`). - - The source is the deciding layer. When both layers carry the same mode, the repository layer is the source. - - When neither layer sets it, the result is `optional` with `source: default`. -- **`telemetry_enabled` value:** the repository value if set, otherwise the user value, otherwise `false` with `source: default`. This is the configured value, not the effective state. + - 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. - **`background_cloud_allowed`:** `!auth_disabled && !degraded`. - **Helpers:** - `telemetry_enabled()` is true only for `Enabled`. @@ -52,19 +68,35 @@ flowchart TD - `auth_disabled_config_file()` returns the `AuthPolicyConfigFile` of the deciding layer when the mode is `disabled`, otherwise `None`. Every `auth.disabled_by_config` rejection uses it. - **Explicit config files:** an invalid explicit config file stays fatal, so it never produces a degraded policy. +### Precedence examples + +| Global | Repository | Explicit | Effective | +|---|---|---|---| +| `telemetry.enabled: false` | absent | `telemetry.enabled: true` | telemetry disabled (`user_opt_out`) | +| `auth.mode: disabled` | absent | `auth.mode: optional` | auth `disabled` (source global), telemetry `auth_disabled` | +| `telemetry.enabled: true` | `telemetry.enabled: false` | `telemetry.enabled: true` | telemetry disabled (`repository_opt_out`) | +| `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 | +| 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-layer `true`: +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`: `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`: `agent_trace.auto_sync is true but auth.mode resolves to disabled; post-commit auto-sync is skipped.` -4. Repository `mandatory` while the user layer is `disabled`: +4. 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. Degraded: +5. 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`: + `telemetry.enabled is true in the explicitly selected config but false in the global or repository config; SCE telemetry is disabled.` +7. 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`. diff --git a/context/cli/config-precedence-contract.md b/context/cli/config-precedence-contract.md index ac87c2e83..0d9a5672e 100644 --- a/context/cli/config-precedence-contract.md +++ b/context/cli/config-precedence-contract.md @@ -59,15 +59,16 @@ The control-plane default is separate from the config schema declaration (`https When a supported auth-adjacent key omits a baked default, the same resolver still reports `value: null` / `(unset)` with no resolved source when both env and config inputs are absent. -Config file selection follows this deterministic order: +Config files are selected and loaded in this deterministic order: -1. `--config ` -2. `SCE_CONFIG_FILE` -3. discovered defaults when no explicit path/env override is provided: +1. discovered defaults, always: - global: `${config_root}/sce/config.json`, where `config_root` comes from the shared default-path policy seam in `cli/src/services/default_paths.rs` and resolves to `dirs::config_dir()` on supported platforms (Linux fallback: `~/.config` when `XDG_CONFIG_HOME` is unset) - - local: `.sce/config.json` under current working directory + - local: `.sce/config.json` at the enclosing Git worktree root, the nearest ancestor of the current working directory (inclusive) that contains a `.git` directory or file (`default_paths::enclosing_repository_root_with`). This covers ordinary repositories, linked worktrees, submodules, and nested repositories (the innermost root wins). Outside a Git repository, it is `.sce/config.json` under the current working directory. Discovery probes only the filesystem; it runs no Git subprocess and does not consult `GIT_DIR` / `GIT_WORK_TREE`. +2. one explicit file, when selected: `--config `, otherwise `SCE_CONFIG_FILE`. -When both discovered defaults exist, they are merged in memory in deterministic order `global -> local`, and local values override global values per key. +Without an explicit file, the discovered defaults are merged in memory in deterministic order `global -> local`, and local values override global values per key. + +With an explicit file, ordinary keys keep their existing behavior: they come only from the explicit file, and the discovered files contribute nothing to them. The discovered files are still read for the access-policy keys `auth.mode` and `telemetry.enabled`, which resolve across all three layers with restriction- and consent-gated precedence (see [effective access policy](access-policy.md#explicit-config-files)). An explicit file can override ordinary configuration but cannot lift a global or repository restriction or opt-out. When a default-discovered global or repo-local config file exists but fails JSON parsing, top-level-object validation, or schema validation, runtime resolution now skips that file, collects the failure text in `validation_errors`, and continues with remaining discovered layers plus defaults. Explicit `--config ` and `SCE_CONFIG_FILE` selections remain fatal on those errors. This means normal command startup still reaches dispatch for commands such as `sce version`, `sce doctor`, and `sce hooks commit-msg` even when discovered config is invalid. Setup and Agent Trace storage consume the same degraded result: setup continues after Git-root and remote preflight, preserves an invalid local file, and skips local target/optional-workflow persistence for that run, while storage uses remaining identity values or the default remote. See [the degraded discovered-config boundary decision](../decisions/2026-09-04-setup-storage-degrade-invalid-discovered-config.md). @@ -99,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. -- 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 or explicit file; repository = repo-local) 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; consumers do not enforce them yet. +- 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. - `integrations` must be an object when present and currently allows `target` and `optional_workflows`; either key alone yields a parsed `IntegrationsConfig` with the other defaulting to empty. @@ -129,7 +130,7 @@ When a default-discovered global or repo-local config file exists but fails JSON - `show` and `validate` support deterministic `text` and `json` outputs. - JSON responses include a top-level `status` and nested `result` object. - `show` text output includes the canonical precedence string: `flags > env > config file > defaults`. -- `show` reports discovered config files as `config_paths` (JSON) / `Config files:` (text). +- `show` reports loaded config files as `config_paths` (JSON) / `Config files:` (text), in load order: discovered global, discovered local, then the explicit file. With an explicit file, discovered files are listed too because they feed the access policy; each resolved value's `config_source` shows which file supplied it. - Resolved values in `show` continue to report `source`; when source is `config_file`, output also reports a deterministic `config_source` value (`flag`, `env`, `default_discovered_global`, `default_discovered_local`). - `show` includes migrated supported auth keys in `result.resolved`. - `show` includes resolved observability values directly in `result.resolved`, preserving flat logging keys (`log_level`, `log_format`, `log_to_file`, `log_dir`, `log_file_retention_limit`) and their source metadata. diff --git a/context/context-map.md b/context/context-map.md index b5f5c1faf..2b46e22e7 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -25,7 +25,7 @@ Feature/domain context: - `context/cli/async-persistence-guarantees.md` (verified guarantees and named limits of the directly awaited Turso persistence migration — exclusive `&mut` transactions, deferred rollback, credential-rotation and terminal-sync behavior, lease/descriptor protection — plus PR1–PR4 staging and the PR3 cleanup ledger) - `context/cli/agent-trace-sync-command.md` (composed local-to-control-plane `sce sync` architecture: the `hooks/plugins → repository Agent Trace DB → AgentTraceExportReader → sce sync → HTTPS + WorkOS Bearer → control plane` data flow, the `sce auth login` / `cd ` / `sce sync` user flow, the no-local-cursor/no-`agent-trace-sync.db`/no-Turso-Sync/no-`BridgeLock`/no-local-DWH invariants, the four-local-capture-streams versus three-remote-streams boundary with its `diff_traces` release gate, the optional `commitPatchId` field on the existing `agent_traces` stream with its Control Plane release dependency and no-backfill limit, and `401`/`409`/ambiguous-batch-failure recovery semantics) - `context/cli/config-precedence-contract.md` (implemented `sce config` show/validate command contract, deterministic `flags > env > config file > defaults` resolution order, focused `config/resolver.rs` ownership for config discovery/merge/runtime precedence plus default-discovered invalid-file degradation, focused `config/render.rs` ownership for `show`/`validate` text+JSON output construction, canonical `$schema` acceptance for startup-loaded `sce/config.json` files, shared auth-key env/config/optional baked-default support starting with `workos_client_id`, shared runtime resolution for flat logging observability keys including config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` with `/sce/logs` defaulting plus config-file/default-only positive `log_file_retention_limit`, config-file-only `agent_trace.repository_id`/`agent_trace.repository_remote` repository-identity keys with default remote `origin`, `agent_trace.auto_sync` resolution with omitted-value fallback `false`, explicit-false opt-out, and setup-written explicit `true` bootstrap behavior for the post-commit trigger boundary, the catalog-derived `integrations.optional_workflows` optional-workflow selection key, schema-validated per-layer `auth.mode` / `telemetry.enabled` sections, JSON-pointer-prefixed schema-validation errors, canonical Pkl-generated `sce/config.json` schema ownership plus CLI embedding/reuse contract including `policies.attribution_hooks.enabled` default-true/explicit-false opt-out metadata, config-file selection order, `show` provenance output, and trimmed `validate` output contract) -- `context/cli/access-policy.md` (effective access policy resolved from user and repository config layers: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, exposure on the auth/hook/observability runtime projections, and enforcement in managed telemetry startup, `sce doctor` health (`disabled_by_config`), the hidden `sce auth telemetry-headers` helper (fail closed before readiness, repository resolution, and `auth.db`), `sce auth login`/`whoami` (`auth.disabled_by_config` rejection before credential storage, `disabled` telemetry provisioning without consent, `mandatory` unauthenticated whoami failure), `sce sync` (`auth.disabled_by_config` before storage or credentials), post-commit auto-sync plus its doctor row (launch only when background cloud operations are allowed), and the `sce setup` Claude-native telemetry install (skipped with a fixed line unless telemetry is enabled); decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) +- `context/cli/access-policy.md` (effective access policy resolved from user (global), repository (Git-root `.sce/config.json`), and explicit (`--config` / `SCE_CONFIG_FILE`) config layers, where an explicit file cannot lift a global or repository restriction: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, exposure on the auth/hook/observability runtime projections, and enforcement in managed telemetry startup, `sce doctor` health (`disabled_by_config`), the hidden `sce auth telemetry-headers` helper (fail closed before readiness, repository resolution, and `auth.db`), `sce auth login`/`whoami` (`auth.disabled_by_config` rejection before credential storage, `disabled` telemetry provisioning without consent, `mandatory` unauthenticated whoami failure), `sce sync` (`auth.disabled_by_config` before storage or credentials), post-commit auto-sync plus its doctor row (launch only when background cloud operations are allowed), and the `sce setup` Claude-native telemetry install (skipped with a fixed line unless telemetry is enabled); decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) - `context/cli/capability-traits.md` (current broad CLI capability seam in `cli/src/services/capabilities.rs`, including `FsOps`/`StdFsOps` (method-less marker), `GitOps`/`ProcessGitOps` (command execution and availability), compile-time-typed borrowed AppContext wiring with scoped borrowing across directly awaited commands with associated-type narrow capability accessors plus `ContextWithRepoRoot` repo-root-scoped context derivation, generic command execution bounds, and test-only unimplemented stubs; current service internals do not consume fs/git traits until later lifecycle migration tasks) - `context/cli/service-lifecycle.md` (current async lifecycle seam in `cli/src/services/lifecycle.rs`, including default no-op `ServiceLifecycle` diagnose/fix/setup methods against narrow `HasRepoRoot`, lifecycle-owned health/fix/setup result types with generic setup messages, doctor/setup adapter boundaries, the static `LifecycleProvider` enum catalog/dispatcher, hook/config/local_db/auth_db/agent_trace_db lifecycle providers including setup-time repository-scoped Agent Trace DB initialization plus checkout identity diagnostics, implemented doctor aggregation over diagnose/fix providers, and implemented setup aggregation over `setup` providers in order config → local_db → auth_db → agent_trace_db → hooks when requested) - `context/cli/mutation-trace-protocol.md` (pure, dependency-free `cli/src/services/mutation_trace/` refinement of the verified `spec/mutation_cursor.qnt` mutation-cursor protocol: the full pure action set — `prepare`/`commit` transition logic, attribution/mutation-event materialization, snapshot-failure/database-failure taint actions, scope abandonment, and recovery with an explicit observed-tree input — plus cross-action sequence/invariant tests and a module-level Quint refinement matrix are all complete (`types.rs`, `protocol.rs`, `mod.rs`, `tests.rs`, registered with `#[allow(dead_code)]`); opaque-newtype identity refinement decisions vs. the Quint model's bounded enums, and the `coordinator.rs` target end-state seam this layout leaves room for but does not create — `store.rs`, `runtime/git_snapshot.rs`, and `runtime/coordinator.rs` (including its public `coordinate()` entrypoint) now exist, built out by the `mutation-cursor-store-persistence` and `mutation-cursor-runtime-coordinator` plans respectively; `protocol.rs` is invoked only through the runtime, and the runtime is now driven by the generic `sce hooks mutation-scope` CLI ingress and a first Claude Code adapter driver, registered by `sce setup` and reachable by a real Claude Code session, now proven against real Git repositories and a real Agent Trace DB by the `claude-mutation-scope-integration` plan's T08 regressions) 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 e07348263..b29d45b45 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 @@ -11,31 +11,41 @@ Before this decision, credential state alone decided whether SCE exported teleme ## Decision -SCE resolves one effective access policy from two config layers, using consent-gated precedence. +SCE resolves one effective access policy from up to three config layers, using consent-gated precedence. **Layers:** -- The user layer is the default-discovered global config, or the single explicit `--config` / `SCE_CONFIG_FILE` file. -- The repository layer is the default-discovered `/.sce/config.json`. -- Neither key has an environment-variable or flag layer. +- The user layer is the default-discovered global config. +- The repository layer is the default-discovered `.sce/config.json` at the enclosing Git worktree root: the nearest ancestor of the working directory (inclusive) that contains a `.git` entry. Outside a Git repository, it is `/.sce/config.json`. +- The explicit layer is the single file selected with `--config` or `SCE_CONFIG_FILE` (the flag wins when both are given). +- The global and repository files are always discovered, also when an explicit file is selected. The explicit file is added on top of them; it never replaces them. +- Neither key has an environment-variable or flag layer of its own. -**`auth.mode`:** the most restrictive layer wins. The order is `disabled > mandatory > optional`, and the default is `optional`. When both layers agree, the repository layer is recorded as the source. +**Ordinary keys versus access-policy keys:** When an explicit file is selected, ordinary keys (logging, Agent Trace, `otel`, `policies`, `integrations`, auth-adjacent URLs and IDs) still come only from that file, exactly as before. The discovered files feed only `auth.mode` and `telemetry.enabled`. An explicit file can therefore override ordinary configuration, but it cannot lift a security or consent restriction set in the global or repository config. -**`telemetry.enabled`:** the first matching rule applies: +**`auth.mode`:** the most restrictive layer wins. The order is `disabled > mandatory > optional`, and the default is `optional`. Layers are compared in the order user, repository, explicit; when layers tie, the later one is recorded as the source. + +**`telemetry.enabled`:** the first matching rule applies. "User-side" means the user layer or the explicit layer, because both are the user's own choice. 1. Any skipped invalid discovered layer → `Disabled(InvalidConfig)`. 2. Effective auth is `disabled` → `Disabled(AuthDisabled)`. -3. User layer is `false` → `UserOptOut`. +3. User layer or explicit layer is `false` → `UserOptOut`. 4. Repository layer is `false` → `RepositoryOptOut`. -5. User layer is `true` → `Enabled`. -6. Repository layer is `true` with no user `true` → `NoUserConsent`. +5. User layer or explicit layer is `true` → `Enabled`. +6. Repository layer is `true` with no user-side `true` → `NoUserConsent`. 7. Otherwise → `NotEnabled`. +Any opt-out wins over any consent, so an explicit `true` cannot override a global or repository `false`, and an explicit `false` overrides a global `true`. + **Background cloud operations** are allowed only when auth is not `disabled` and no discovered layer was skipped as invalid. Contradictions between layers produce deterministic `validation_warnings`, never errors. The pure `resolve_access_policy` in `cli/src/services/config/resolver.rs` computes the policy once, inside the existing resolver. `ResolvedAuthRuntimeConfig`, `ResolvedHookRuntimeConfig`, and `ResolvedObservabilityRuntimeConfig` expose it. ## Rationale -Telemetry export is a privacy-sensitive action that belongs to the user, so only the user layer can grant consent. Either layer can withdraw consent or restrict access. A repository can therefore opt itself out, but it can never opt a user in or override a user's prohibition. If a config file is invalid and skipped, falling back to defaults must not silently re-enable anything that file might have prohibited, so the policy degrades to off. Computing the policy once, in the existing resolver, keeps one authoritative answer for every consumer. +Telemetry export is a privacy-sensitive action that belongs to the user, so only the user side (global or explicit file) can grant consent. Every layer can withdraw consent or restrict access. A repository can therefore opt itself out, but it can never opt a user in or override a user's prohibition. If a config file is invalid and skipped, falling back to defaults must not silently re-enable anything that file might have prohibited, so the policy degrades to off. Computing the policy once, in the existing resolver, keeps one authoritative answer for every consumer. + +An explicit config file is commonly used for scripted or isolated runs, so it keeps replacing discovered ordinary values. But it is a per-invocation choice that anything able to set an environment variable can make, so it must not silently undo a standing global prohibition or a repository opt-out. Treating it as an additional, restriction-only-against-others layer keeps both properties. + +Locating the repository layer at the Git worktree root makes the policy independent of which subdirectory a tool (Claude hooks, the headers helper, a terminal) was started from. The lookup probes only the filesystem for `.git`, so hot hook paths add no Git subprocess. ## Alternatives considered @@ -43,17 +53,23 @@ Telemetry export is a privacy-sensitive action that belongs to the user, so only - **Inferring consent from an existing `telemetry-ready.json` or `auth.db`:** rejected. Hidden state would decide consent. - **Treating cross-layer contradictions as validation errors:** rejected. Each file is valid on its own, and errors would drop unrelated settings. - **A separate policy resolver or service:** rejected. It would duplicate config discovery and risk diverging answers. +- **Explicit file replaces discovery entirely (the original rule):** rejected. `--config` or `SCE_CONFIG_FILE` could enable telemetry or authentication the global config forbids, or bypass a repository opt-out. +- **Merging all ordinary keys from discovered files under an explicit file:** rejected. It would change the long-standing meaning of `--config` for non-security settings. +- **`git rev-parse --show-toplevel` for repository discovery:** rejected. It costs a subprocess on every hook invocation; the `.git` ancestor walk gives the same worktree root for ordinary repositories, linked worktrees, submodules, and nested repositories. ## Compatibility and risks - Telemetry becomes opt-in. Existing logged-in installations without an explicit user-layer `telemetry.enabled: true` lose managed SCE export once consumers enforce the policy. -- Repository discovery uses the cwd. A process launched from a subdirectory sees only the user layer, which fails open toward the user's own consent. +- Repository discovery is Git-root relative. A process launched from a subdirectory now applies the repository opt-out it previously missed. A `.sce/config.json` in a non-root subdirectory of a repository is no longer discovered from that subdirectory. In a nested repository, the inner repository's root is used. Outside a Git repository, discovery still uses the working directory. +- `GIT_DIR` / `GIT_WORK_TREE` are not consulted; discovery follows the working directory's ancestors. +- With `--config` / `SCE_CONFIG_FILE`, the global and repository files are now read. Their access-policy keys apply, they appear in `sce config show` config paths, and if one is invalid it is reported and disables telemetry and background cloud operations (the explicit file itself stays fatal when invalid). Explicit runs now also need a resolvable global config location, as discovered runs already did. - Older SCE binaries reject the new keys and skip the whole discovered file as invalid. ## Guardrails -- Consent comes only from the user layer. A repository value can only restrict. -- There is no env-var or CLI-flag override for `auth.mode` or `telemetry.enabled`. +- Consent comes only from the user side (global or explicit file). A repository value can only restrict. +- An explicit file can only add restrictions or consent; it can never lift a global or repository restriction. +- There is no env-var or CLI-flag override for `auth.mode` or `telemetry.enabled` beyond selecting the explicit file. - There is no global mutable policy state and no second resolver. - Warnings are fixed strings, emitted in a fixed order. diff --git a/context/plans/auth-telemetry-policy-config.md b/context/plans/auth-telemetry-policy-config.md index c3a6f285f..7336fd0ae 100644 --- a/context/plans/auth-telemetry-policy-config.md +++ b/context/plans/auth-telemetry-policy-config.md @@ -187,7 +187,7 @@ Repository binding, credential identity (`sub`, `workspace_id`), expiry checks, - `logout` keeps interactive access in every mode, so one Keychain dialog per explicit logout remains possible. This is intended. - Non-interactive Keychain semantics stay unchanged. - **Startup cost on hook paths:** the policy comes from the config resolution `build_startup_context` already performs. No additional file reads. -- **cwd-based local discovery:** Claude hooks and the headers helper resolve `/.sce/config.json`. A launch from a subdirectory misses the repository layer, which can only *restrict*, so the failure mode is fail-open toward the user's global consent. This matches the existing config contract and is listed as an open question. +- **cwd-based local discovery:** Claude hooks and the headers helper resolve `/.sce/config.json`. A launch from a subdirectory misses the repository layer, which can only *restrict*, so the failure mode is fail-open toward the user's global consent. This matches the existing config contract and is listed as an open question. *Resolved after T08:* repository discovery is now Git-root relative, and an explicit config file no longer replaces the global layer (see the amended [ADR](../decisions/2026-10-20-consent-gated-access-policy-precedence.md)). - **Mixed versions:** older binaries reject configs that carry the new keys (see Migration). ### Out of scope, with future interfaces @@ -457,7 +457,7 @@ Persist this field in every plan; this is durable plan state, not chat state: - Existing logged-in users silently lose managed SCE export on upgrade, because a missing `telemetry.enabled` means disabled. Doctor and login now say so, but nothing prompts the user. Is that acceptable, or should the release ship with the future setup consent question? Inferring consent from an existing `telemetry-ready.json` was rejected because it makes hidden state decide consent. - `mandatory` changes very little today. Cloud commands already require credentials, and hooks must never block, so the only enforced difference is a nonzero unauthenticated `whoami`. It is kept so the future setup and auto-login work has a stable mode to build on. If no near-term consumer exists, shipping only `disabled | optional` would be the smaller version. - Telemetry opt-out does not stop Claude-native export from settings written by earlier setups, and those settings are user-level, shared across repositories. Should a follow-up plan for SCE-owned Claude settings reconciliation be scheduled now, so the opt-out can eventually be described as complete? -- Repository-layer discovery uses `/.sce/config.json`. A Claude hook or headers helper launched from a subdirectory sees only the user layer, so a repository opt-out can be missed there. Fixing this means Git-root-relative discovery for every config consumer, which is broader than this plan. +- ~~Repository-layer discovery uses `/.sce/config.json`.~~ Resolved: the shared resolver now discovers `.sce/config.json` at the enclosing Git worktree root for every consumer, and `--config` / `SCE_CONFIG_FILE` are loaded on top of the global and repository layers instead of replacing them, so neither path can bypass a global or repository opt-out. See [access policy](../cli/access-policy.md). ## Validation Report @@ -501,4 +501,4 @@ Persist this field in every plan; this is durable plan state, not chat state: - The manual macOS check (locked login Keychain, no Keychain dialog, no `sce.hook` spans, at most one logout prompt) was not run; macOS Keychain behavior is unverified on real hardware. - Flake checks ran only for x86_64-linux; darwin and aarch64-linux systems were omitted. -- Open questions in this plan (silent loss of managed export on upgrade, minimal `mandatory` semantics, legacy Claude-native settings, ``-relative repository discovery) remain unresolved product decisions. +- Open questions in this plan (silent loss of managed export on upgrade, minimal `mandatory` semantics, legacy Claude-native settings) remain unresolved product decisions. The ``-relative repository discovery question is resolved: discovery is now Git-root relative. diff --git a/context/sce/telemetry-credential.md b/context/sce/telemetry-credential.md index e125e7582..9981cd3f8 100644 --- a/context/sce/telemetry-credential.md +++ b/context/sce/telemetry-credential.md @@ -71,7 +71,7 @@ flowchart LR - Launch context (verified against Claude Code 2.1.284 with a real `claude -p` run): Claude runs the helper with no arguments, with its working directory set to the directory Claude was launched from (possibly a subdirectory), and without `CLAUDE_PROJECT_DIR`. Claude's documentation states that it does not pass `OTEL_*` variables to subprocesses. The helper therefore uses only the working directory, ignores `CLAUDE_PROJECT_DIR` (a value inherited from a parent session could name another project), and never requires an `OTEL_*` variable to be present. - Authorization: the helper walks up to the enclosing Git root, resolves the repository ID with the same precedence as Agent Trace storage, and prints headers only when that repository is bound to the identity of a valid credential that the current WorkOS session owns (see Repository bindings). An unbound repository, a repository bound to another user or workspace, a directory outside Git, or a repository without a resolvable identity gets no token. `.claude/settings.json`, SCE hook markers, and remote names are never treated as proof of ownership. - Destination tripwire: if `OTEL_EXPORTER_OTLP_ENDPOINT`, a per-signal `OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_ENDPOINT`, or `BETA_TRACING_ENDPOINT` is visible to the helper with a non-canonical value, the helper refuses. This catches visible misconfiguration only. It is not endpoint pinning (see Security boundaries). -- Policy gate: the helper first resolves the effective access policy from its working directory ([access-policy.md](../cli/access-policy.md)). When telemetry is not `Enabled` (including `auth.mode: disabled`, a skipped invalid discovered config, or an unresolvable config), it fails closed before the destination tripwire, the readiness hint, repository resolution, or the auth DB. Because discovery is ``-relative, a launch from a subdirectory sees only the user layer. +- Policy gate: the helper first resolves the effective access policy from its working directory ([access-policy.md](../cli/access-policy.md)). When telemetry is not `Enabled` (including `auth.mode: disabled`, a skipped invalid discovered config, or an unresolvable config), it fails closed before the destination tripwire, the readiness hint, repository resolution, or the auth DB. Repository discovery is Git-root relative, so a launch from a subdirectory applies the same repository policy as a launch from the root. `repository_id_for` uses the same `.git` ancestor walk, so policy and repository identity describe the same root. - Without the readiness hint the helper fails closed before resolving the repository or opening the auth DB. With it, the credential lookup uses the non-interactive credential-store path and never prompts. - Repository resolution and the credential lookup together are bounded by `CREDENTIAL_LOOKUP_DEADLINE`. Resolution spawns one `git config --get` process, which is needed to compute the repository ID; there is no network call and no issuance. Every failure exits nonzero with the fixed stderr diagnostic `Telemetry credential is unavailable.` and empty stdout. That includes a missing `auth.db`, which the helper never creates or migrates, so concurrent helper calls on a never-logged-in machine cannot race to initialize it. The helper never initializes managed exporter telemetry. - It is omitted from `sce --help`, `sce auth --help`, and shell completions.