diff --git a/cli/src/app.rs b/cli/src/app.rs index 1384b491a..f6b62be50 100644 --- a/cli/src/app.rs +++ b/cli/src/app.rs @@ -31,7 +31,6 @@ struct AppRuntime { telemetry_enabled: bool, fs: services::capabilities::StdFsOps, git: services::capabilities::ProcessGitOps, - registry: services::command_registry::CommandRegistry, startup_diagnostic: Option, } @@ -377,7 +376,6 @@ fn initialize_runtime(startup: StartupContext) -> Result { .telemetry_enabled(), fs: services::capabilities::StdFsOps, git: services::capabilities::ProcessGitOps, - registry: services::command_registry::build_default_registry(), startup_diagnostic: startup.startup_diagnostic, }) } @@ -396,7 +394,6 @@ where let context = runtime.context(); run_command_lifecycle_with_context( args, - &runtime.registry, &context, runtime.startup_diagnostic.as_deref(), stdout, @@ -407,7 +404,6 @@ where async fn run_command_lifecycle_with_context( args: I, - registry: &services::command_registry::CommandRegistry, context: &AppContext<'_, L, T>, startup_diagnostic: Option<&str>, stdout: &mut StdoutW, @@ -436,7 +432,7 @@ where let Some((command_args, (stdout, stderr))) = command_inputs else { return Err(repeated_dispatch_error()); }; - let result = dispatch_command(command_args, registry, context, stderr).await; + let result = dispatch_command(command_args, context, stderr).await; app_support::render_command_result( result, Some(context.logger()), @@ -456,7 +452,6 @@ fn repeated_dispatch_error() -> CliError { async fn dispatch_command( args: Vec, - registry: &services::command_registry::CommandRegistry, context: &AppContext<'_, L, T>, stderr: &mut StderrW, ) -> Result @@ -465,22 +460,20 @@ where T: TelemetryTrait, StderrW: Write, { - let command = parse_command_phase(args, registry, context)?; + let command = parse_command_phase(args, context)?; services::managed_telemetry::trace_export::record_command_name(&command.name()); app_support::execute_command_phase(&command, context, stderr).await } fn parse_command_phase( args: I, - registry: &services::command_registry::CommandRegistry, context: &impl HasLogger, ) -> Result where I: IntoIterator, { let logger = context.logger(); - let command = - services::parse::command_runtime::parse_runtime_command(args, registry, Some(logger))?; + let command = services::parse::command_runtime::parse_runtime_command(args, Some(logger))?; logger.info( "sce.command.parsed", "Command parsed", @@ -679,7 +672,6 @@ pub(crate) mod tests { let mut stdout = Vec::new(); let result = Box::pin(run_command_lifecycle_with_context( args.into_iter().map(String::from), - &services::command_registry::CommandRegistry::default(), &context, None, &mut stdout, @@ -739,7 +731,6 @@ pub(crate) mod tests { let context = AppContext::new(&logger, &telemetry, &fs, &git, None); let result = Box::pin(run_command_lifecycle_with_context( args.iter().map(|arg| (*arg).to_string()), - &services::command_registry::CommandRegistry::default(), &context, None, stdout, @@ -849,7 +840,6 @@ pub(crate) mod tests { let result = Box::pin(run_command_lifecycle_with_context( ["sce", "help"].map(String::from), - &services::command_registry::CommandRegistry::default(), &context, None, &mut FailingWriter, diff --git a/cli/src/command_surface.rs b/cli/src/command_surface.rs index f47cc52eb..13682865d 100644 --- a/cli/src/command_surface.rs +++ b/cli/src/command_surface.rs @@ -19,12 +19,6 @@ const SCE_BANNER_VISIT_SUFFIX: &str = " to learn more."; const HELP_COMMAND_NAME: &str = "help"; const HELP_COMMAND_PURPOSE: &str = "Show help for the current CLI surface"; -pub fn is_known_command(name: &str) -> bool { - name == HELP_COMMAND_NAME - || cli_schema::TOP_LEVEL_COMMANDS - .iter() - .any(|command| command.name == name) -} enum HelpSectionBodyLine { Text(&'static str), Command { diff --git a/cli/src/services/command_registry.rs b/cli/src/services/command_registry.rs index 1723364a5..c9ff67541 100644 --- a/cli/src/services/command_registry.rs +++ b/cli/src/services/command_registry.rs @@ -5,19 +5,6 @@ use crate::app::{ContextWithRepoRoot, HasLogger}; use crate::services; use crate::services::error::CliError; -const DEFAULT_COMMAND_NAMES: &[&str] = &[ - services::auth_command::NAME, - services::completion::NAME, - services::config::NAME, - services::doctor::NAME, - services::help::NAME, - services::hooks::NAME, - services::bash_policy::NAME, - services::setup::NAME, - services::sync::NAME, - services::version::NAME, -]; - pub enum RuntimeCommand { Help(services::help::command::HelpCommand), HelpText(services::help::command::HelpTextCommand), @@ -73,104 +60,3 @@ impl RuntimeCommand { } } } - -pub struct CommandRegistry { - names: &'static [&'static str], -} - -impl CommandRegistry { - pub fn contains(&self, name: &str) -> bool { - self.names.contains(&name) - } -} - -impl Default for CommandRegistry { - fn default() -> Self { - build_default_registry() - } -} - -pub fn build_default_registry() -> CommandRegistry { - CommandRegistry { - names: DEFAULT_COMMAND_NAMES, - } -} - -pub fn default_runtime_command(name: &str) -> Option { - match name { - services::help::NAME => Some(RuntimeCommand::Help(services::help::command::HelpCommand)), - services::auth_command::NAME => Some(RuntimeCommand::Auth( - services::auth_command::command::AuthCommand { - request: services::auth_command::AuthRequest { - subcommand: services::auth_command::AuthSubcommand::Whoami { - format: services::auth_command::AuthFormat::Text, - }, - }, - }, - )), - services::config::NAME => Some(RuntimeCommand::Config( - services::config::command::ConfigCommand { - subcommand: services::config::ConfigSubcommand::Show( - services::config::ConfigRequest { - report_format: services::config::ReportFormat::Text, - config_path: None, - log_level: None, - }, - ), - }, - )), - services::setup::NAME => Some(RuntimeCommand::Setup( - services::setup::command::SetupCommand { - request: services::setup::SetupRequest { - config_mode: Some(services::setup::SetupMode::Interactive), - install_hooks: true, - hooks_repo_path: None, - context_only: false, - optional_workflows: None, - reconfigure: false, - }, - }, - )), - services::doctor::NAME => Some(RuntimeCommand::Doctor( - services::doctor::command::DoctorCommand { - request: services::doctor::DoctorRequest { - mode: services::doctor::DoctorMode::Diagnose, - format: services::doctor::DoctorFormat::Text, - }, - }, - )), - services::hooks::NAME => Some(RuntimeCommand::Hooks( - services::hooks::command::HooksCommand { - subcommand: services::hooks::HookSubcommand::PreCommit, - }, - )), - services::bash_policy::NAME => Some(RuntimeCommand::Policy( - services::bash_policy::command::PolicyCommand { - request: services::bash_policy::BashPolicyRequest { - input: services::bash_policy::PolicyInputMode::ClaudePreToolUse, - output: services::bash_policy::PolicyOutputMode::ClaudeHook, - }, - }, - )), - services::version::NAME => Some(RuntimeCommand::Version( - services::version::command::VersionCommand { - request: services::version::VersionRequest { - format: services::version::VersionFormat::Text, - }, - }, - )), - services::completion::NAME => Some(RuntimeCommand::Completion( - services::completion::command::CompletionCommand { - request: services::completion::CompletionRequest { - shell: services::completion::CompletionShell::Bash, - }, - }, - )), - services::sync::NAME => Some(RuntimeCommand::Sync(services::sync::command::SyncCommand { - request: services::sync::SyncRequest { - format: services::output_format::OutputFormat::Text, - }, - })), - _ => None, - } -} diff --git a/cli/src/services/parse/command_runtime.rs b/cli/src/services/parse/command_runtime.rs index 3bea38104..929ab295c 100644 --- a/cli/src/services/parse/command_runtime.rs +++ b/cli/src/services/parse/command_runtime.rs @@ -1,12 +1,11 @@ -use crate::{cli_schema, command_surface, services}; +use crate::{cli_schema, services}; use clap::{ArgAction, CommandFactory}; -use services::command_registry::{CommandRegistry, RuntimeCommand}; +use services::command_registry::RuntimeCommand; use services::error::{CliError, FailureClass}; use services::observability::traits::Logger as LoggerTrait; pub fn parse_runtime_command( args: I, - registry: &CommandRegistry, logger: Option<&dyn LoggerTrait>, ) -> Result where @@ -29,26 +28,22 @@ where } if args_vec.len() <= 1 { - return registry_command(registry, services::help::NAME); + return Ok(help_command()); } let cli = match cli_schema::Cli::try_parse_from(&args_vec) { Ok(cli) => cli, - Err(error) => return handle_clap_error(&args_vec, registry, &error), + Err(error) => return handle_clap_error(&args_vec, &error), }; let Some(command) = cli.command else { - return registry_command(registry, services::help::NAME); + return Ok(help_command()); }; convert_clap_command(command) } -fn handle_clap_error( - args: &[String], - registry: &CommandRegistry, - error: &clap::Error, -) -> Result { +fn handle_clap_error(args: &[String], error: &clap::Error) -> Result { if error.kind() == clap::error::ErrorKind::DisplayHelp { if let Some((name, text)) = render_subcommand_help_from_args(args) { return Ok(RuntimeCommand::HelpText( @@ -56,7 +51,7 @@ fn handle_clap_error( )); } - return registry_command(registry, services::help::NAME); + return Ok(help_command()); } if error.kind() == clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand { @@ -76,28 +71,20 @@ fn handle_clap_error( )); } - return registry_command(registry, services::help::NAME); + return Ok(help_command()); } if error.kind() == clap::error::ErrorKind::DisplayVersion { - return registry_command(registry, services::version::NAME); + return convert_clap_command(cli_schema::Commands::Version { + format: services::output_format::OutputFormat::Text, + }); } Err(classify_clap_error(error)) } -fn registry_command(registry: &CommandRegistry, name: &str) -> Result { - if !registry.contains(name) { - return Err(CliError::runtime(anyhow::Error::msg(format!( - "Command '{name}' is not registered. Try: run 'sce --help' to see available commands." - )))); - } - - services::command_registry::default_runtime_command(name).ok_or_else(|| { - CliError::runtime(anyhow::Error::msg(format!( - "Command '{name}' is not registered. Try: run 'sce --help' to see available commands." - ))) - }) +fn help_command() -> RuntimeCommand { + RuntimeCommand::Help(services::help::command::HelpCommand) } fn classify_clap_error(error: &clap::Error) -> CliError { @@ -225,7 +212,11 @@ fn clean_clap_error_message(message: &str, kind: clap::error::ErrorKind) -> Stri match kind { ErrorKind::InvalidSubcommand => { if let Some(subcommand) = extract_quoted_value(message) { - if command_surface::is_known_command(&subcommand) { + if subcommand == services::help::NAME + || cli_schema::Cli::command() + .find_subcommand(&subcommand) + .is_some() + { format!( "Command '{subcommand}' is currently unavailable in this build. Try: run 'sce --help' to see available commands in this build." ) @@ -566,12 +557,8 @@ mod tests { use std::process::ExitCode; fn parse(args: &[&str]) -> RuntimeCommand { - parse_runtime_command( - args.iter().map(|arg| (*arg).to_string()), - &CommandRegistry::default(), - None, - ) - .expect("command should parse") + parse_runtime_command(args.iter().map(|arg| (*arg).to_string()), None) + .expect("command should parse") } fn help_payload(command: RuntimeCommand) -> String { @@ -582,6 +569,18 @@ mod tests { } } + #[test] + fn global_version_flag_uses_version_command() { + let RuntimeCommand::Version(command) = parse(&["sce", "--version"]) else { + panic!("expected version command"); + }; + + assert_eq!( + command.request.format, + services::output_format::OutputFormat::Text + ); + } + #[test] fn sync_parses_to_sync_request_with_default_text_format() { let command = parse(&["sce", "sync"]); @@ -818,7 +817,6 @@ mod tests { let Err(error) = parse_runtime_command( ["sce", "--not-an-option"].into_iter().map(String::from), - &CommandRegistry::default(), None, ) else { panic!("unknown option should remain an error"); diff --git a/context/architecture.md b/context/architecture.md index 26ba801b2..6dc1e606e 100644 --- a/context/architecture.md +++ b/context/architecture.md @@ -48,9 +48,9 @@ The repository includes a new placeholder Rust binary crate at `cli/`. - `cli/src/main.rs` is the executable entrypoint (`sce`) and delegates to `app::run`. - `cli/src/cli_schema.rs` defines the clap-based CLI schema using derive macros for all top-level commands and subcommands, including the top-level `sync` command, and renders command-local help text for the `auth` command tree (`auth`, `auth login`, `auth logout`, `auth whoami`). - `cli/src/app.rs` provides the clap-based argument dispatch loop with deterministic help/setup execution, bare-command help routing for `sce auth` and `sce config`, successful unknown-command fallback to top-level or closest-parent help, centralized stream routing (`stdout` success payloads, `stderr` redacted diagnostics), stable class-based exit-code mapping (`2` parse, `3` validation, `4` runtime, `5` dependency), and stable class-based stderr diagnostic codes (`SCE-ERR-PARSE`, `SCE-ERR-VALIDATION`, `SCE-ERR-RUNTIME`, `SCE-ERR-DEPENDENCY`) with default `Try:` remediation injection when missing. -- The app runtime now moves through explicit startup phases in `cli/src/app.rs`: dependency bootstrapping (`perform_dependency_check`), startup context construction (`build_startup_context`), runtime initialization (`initialize_runtime`), directly awaited command parse/execute inside the telemetry polling scope (`run_command_lifecycle`, `parse_command_phase` plus `services::app_support::execute_command_phase`), and final output rendering through `services::app_support::render_run_outcome`. `AppRuntime` owns the concrete production logger, no-op telemetry runtime, filesystem ops, git ops, static `CommandRegistry`, and startup-diagnostic state across those phases; `RunOutcome` carries final render data with an optional generic logger implementing `services::observability::traits::Logger`, so render support can log classified errors without production-logger type coupling. If a telemetry implementation attempts to invoke the command action more than once, dispatch returns a runtime-classified error instead of panicking or reusing consumed arguments. +- The app runtime now moves through explicit startup phases in `cli/src/app.rs`: dependency bootstrapping (`perform_dependency_check`), startup context construction (`build_startup_context`), runtime initialization (`initialize_runtime`), directly awaited command parse/execute inside the telemetry polling scope (`run_command_lifecycle`, `parse_command_phase` plus `services::app_support::execute_command_phase`), and final output rendering through `services::app_support::render_run_outcome`. `AppRuntime` owns the concrete production logger, no-op telemetry runtime, filesystem ops, git ops, and startup-diagnostic state across those phases; `RunOutcome` carries final render data with an optional generic logger implementing `services::observability::traits::Logger`, so render support can log classified errors without production-logger type coupling. If a telemetry implementation attempts to invoke the command action more than once, dispatch returns a runtime-classified error instead of panicking or reusing consumed arguments. - `AppContext` is the CLI's borrowed dependency view in `cli/src/app.rs`: it is generic over logger, telemetry, filesystem, and git capability implementations and stores references plus an optional `repo_root: Option` instead of owning `Arc` trait objects. Because it borrows from `AppRuntime`, `AppContext` is command-scoped: borrowing across directly awaited execution is safe while the owner lives, but detached work cannot retain that borrowed view. No new `Send`, `Sync`, or `'static` command bounds are required. Startup creates a context view over `AppRuntime`'s concrete production dependencies with `repo_root` set to `None`; command paths can derive repo-root-scoped context views through the `ContextWithRepoRoot` accessor trait / `AppContext::with_repo_root(...)`, which reuses the same borrowed dependencies while attaching the resolved root. Narrow accessor traits expose associated concrete capability types for logger, telemetry, fs, and git (`&Self::...`) plus repo-root access, so call sites can express capability requirements without erasing the borrowed dependencies back to trait objects; lifecycle providers consume the repo-root accessor rather than the full context type. -- Command parse-time conversion and run-time handling are separated by an internal static `RuntimeCommand` seam. `cli/src/services/command_registry.rs` defines the `RuntimeCommand` enum with variants for help/help-text, version, completion, auth, config, setup, doctor, hooks, policy, and sync, plus a deterministic `CommandRegistry` name catalog populated by `build_default_registry()`. `parse_command_phase` in `cli/src/app.rs` delegates clap-output conversion to `cli/src/services/parse/command_runtime.rs`, which owns clap error classification, help rendering bridges, longest-valid-parent traversal for unknown command paths, and parsed-request-to-enum conversion while returning concrete enum values. Service-owned `command.rs` modules define command payload structs and generic execution methods with narrow context requirements: context-free commands accept any context, hooks requires logger access, setup/doctor require repo-root scoping, and central dispatch requires the union of logger plus repo-root-scoping capabilities. `services::app_support::execute_command_phase` emits lifecycle logs around `RuntimeCommand::execute_with_stderr(...)`; the enum performs the only central dispatch match and delegates business behavior to the service-owned command structs, with sync receiving the app-owned stderr writer for format-gated progress. +- Command parse-time conversion and run-time handling are separated by an internal static `RuntimeCommand` seam. `cli/src/services/command_registry.rs` defines the `RuntimeCommand` enum with variants for help/help-text, version, completion, auth, config, setup, doctor, hooks, policy, and sync, with no additional command registry or default-command catalog. `parse_command_phase` in `cli/src/app.rs` delegates clap-output conversion to `cli/src/services/parse/command_runtime.rs`, which owns clap error classification, help rendering bridges, longest-valid-parent traversal for unknown command paths, and parsed-request-to-enum conversion while returning concrete enum values. Service-owned `command.rs` modules define command payload structs and generic execution methods with narrow context requirements: context-free commands accept any context, hooks requires logger access, setup/doctor require repo-root scoping, and central dispatch requires the union of logger plus repo-root-scoping capabilities. `services::app_support::execute_command_phase` emits lifecycle logs around `RuntimeCommand::execute_with_stderr(...)`; the enum performs the only central dispatch match and delegates business behavior to the service-owned command structs, with sync receiving the app-owned stderr writer for format-gated progress. - Startup observability bootstrapping in `cli/src/app.rs` still tolerates invalid default-discovered config files by continuing with degraded defaults plus `sce.config.invalid_config` warn-level logs, but the warning/logging work is now isolated behind the startup-context and runtime-initialization phases rather than one inline startup function. - `cli/src/services/observability.rs` provides deterministic runtime observability controls and rendering for app lifecycle logs, including shared config-resolved threshold/format, explicit config-file/default `log_to_file`, and `log_dir` inputs with precedence `env > config file > defaults` for non-flag observability keys, stable event identifiers, severity filtering, the forced-emission warning path used for invalid discovered config startup diagnostics, error-specific stderr suppression when file logging is enabled while non-error records and file-write diagnostics remain on stderr, redaction-safe emission through the shared security helper, and log-directory writes with bounded retention. Config resolution also carries a positive config-file/default-only `log_file_retention_limit` (`10` by default) into startup observability config and `sce config show`; the concrete logger stores that resolved value and threads it through primary and v2 cleanup. When `log_dir` resolves from `SCE_LOG_DIR`, config, or the `/sce/logs` default, each enabled or forced log operation selects `/sce-.log` or `/sce--.log` using the machine-local date and optional logger session context, with deterministic percent-encoding for unsafe session filename bytes; after successfully writing a newly created selected file, retention keeps the configured number of newest direct regular `*.log` files by mtime plus path/name tie-break and fails open on cleanup errors. Its `observability::traits` submodule exposes the current `Logger` API with `Option<&str>` session context plus the generic async, deliberately non-object-safe `Telemetry` capability and `NoopLogger`; the concrete observability `Logger` and `NoopTelemetry` implement those capability traits; `NoopTelemetry` installs no tracing subscriber. `services::app_support::render_run_outcome` consumes the logger through that trait boundary when logging classified errors and stdout-write failures. - `cli/src/services/managed_telemetry.rs` (+ `managed_telemetry/trace_export.rs`, `managed_telemetry/log_export.rs`) owns hardcoded managed OTLP defaults, credential-backed runtime telemetry selection from the encrypted auth DB, and bounded fail-open OTLP/HTTP protobuf export of `sce.command` spans (or one `sce.hook` span, with `sce.mutation_scope`/`sce.git_snapshot`/`sce.persistence` operation children opened through `trace_export::in_child_span` at the Claude adapter seam and in `mutation_trace::runtime`, for Claude-invoked hooks admitted by `managed_span_kind` in `cli/src/app.rs`) and allowlisted `Logger` events to the pinned canonical collector (metrics endpoint reserved, not exported); see `context/sce/cli-observability-contract.md`. @@ -85,7 +85,7 @@ The repository includes a new placeholder Rust binary crate at `cli/`. - `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. The former `combine_patches`/`intersect_patches` set operations and the suffix-equivalence path helper were removed; attribution-grade file identity lives in `cli/src/services/agent_trace/repository_path.rs`, and `parse_patch` is 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. +- `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 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. - `cli/README.md` is the crate-local onboarding and usage source of truth for placeholder behavior, safety limitations, and roadmap mapping back to service contracts. - `flake.nix` applies `rust-overlay` (`oxalica/rust-overlay`) to nixpkgs, pins `rust-bin.stable.1.95.0.default` with `rustfmt` + `clippy`, and reads package/check version from repo-root `.version`. Its `cliGeneratedInput` derivation invokes the shared generated-input producer from a declarative source containing the producer and canonical inputs, then publishes the producer-validated handoff as its store output. Native, release, test, and Clippy Cargo derivations receive that same store path through `SCE_CLI_GENERATED_INPUT_DIR`; their Cargo environments exclude Pkl and assert that it is unavailable. Repository-mode `cli/build.rs` validates the handoff before copying it into `OUT_DIR`; published crates use the validated packaging-only fallback. The build script stages SQL under `OUT_DIR/static/migrations` and writes `OUT_DIR/generated_migrations.rs` with deterministic migration constants sorted by numeric filename prefix. - Crane dependency-only derivations and `cli-fmt` intentionally do not receive `SCE_CLI_GENERATED_INPUT_DIR`, so canonical generation changes invalidate the producer and compiling derivations while preserving host/musl dependency artifacts and formatting. The root flake runs `cli-tests`, `cli-clippy`, and `cli-fmt` through Crane-backed paths and exposes `cli-generated-input` as the focused payload/inventory integrity check. It also exposes directory-scoped JS validation derivations for `npm/` and `config/lib/`, while `pkl-generated` uses a narrow canonical-input source set plus maybe-missing forbidden paths so reintroduced generated repository artifacts fail the check. diff --git a/context/cli/cli-command-surface.md b/context/cli/cli-command-surface.md index 9a1de8db8..ac439b87c 100644 --- a/context/cli/cli-command-surface.md +++ b/context/cli/cli-command-surface.md @@ -116,7 +116,7 @@ An interactive `setup` run instead resolves the selection through an `inquire` m ## Command loop and error model - Argument parsing is handled by `clap` derive macros in `cli/src/cli_schema.rs` and dispatched from `cli/src/app.rs`. -- `cli/src/app.rs` now runs commands through explicit phases with `StartupContext`, `AppRuntime`, and generic `RunOutcome` carrying startup-derived observability config, logger/telemetry state, registry state, and final render data across the lifecycle without hardcoding render support to the production logger type. +- `cli/src/app.rs` now runs commands through explicit phases with `StartupContext`, `AppRuntime`, and generic `RunOutcome` carrying startup-derived observability config, logger/telemetry state and final render data across the lifecycle without hardcoding render support to the production logger type. - `parse_command_phase` delegates clap output conversion to `cli/src/services/parse/command_runtime.rs`, which returns concrete `RuntimeCommand` enum variants; `services::app_support::execute_command_phase` emits lifecycle logs around directly awaited `RuntimeCommand::execute_with_stderr(...)`, and the enum delegates behavior to service-owned command payload structs. - Top-level failures are classified into stable exit-code classes owned by `cli/src/app.rs`: `2` parse, `3` validation, `4` runtime, and `5` dependency. - User-facing diagnostics are rendered on `stderr` as `Error [SCE-ERR-]: ...` with class-default `Try:` remediation appended only when missing; when stderr color is enabled the heading, error code, and diagnostic body all render through shared stderr styling helpers. diff --git a/context/glossary.md b/context/glossary.md index ec52334c4..4d04de85b 100644 --- a/context/glossary.md +++ b/context/glossary.md @@ -141,7 +141,7 @@ - `SCE_LOG_DIR`: Optional runtime env key for `sce` observability log-directory configuration; when set, it overrides config-file `log_dir` and the `/sce/logs` default and must be non-empty. - `app startup phases`: Current `cli/src/app.rs` execution model that separates dependency checking, startup-context construction, runtime initialization, command parse/execute, and output rendering into named helpers while preserving the CLI's existing exit-code, stderr-diagnostic, and degraded-startup behavior; output rendering and execution-phase logging helpers live in `cli/src/services/app_support.rs`. - `RunOutcome`: Generic final render payload in `cli/src/services/app_support.rs` (`RunOutcome`) carrying a command result, optional startup diagnostic, and optional logger implementing the logger trait boundary. Production construction in `cli/src/app.rs` uses the concrete observability logger, while rendering is not hardcoded to that production type. -- `CommandRegistry`: Static command-name catalog in `cli/src/services/command_registry.rs`; populated by `build_default_registry()` and carried by `AppRuntime` during command dispatch. It exposes deterministic command-name membership for the current top-level command catalog (`help`, `auth`, `config`, `setup`, `doctor`, `hooks`, `policy`, `sync`, `version`, and `completion`) while actual parsed command payloads are represented by the `RuntimeCommand` enum rather than zero-arg boxed constructors. +- `RuntimeCommand`: Static enum in `cli/src/services/command_registry.rs` containing concrete command payloads and their direct execution dispatch. `cli_schema::Commands` owns the Clap command grammar; `parse/command_runtime.rs` converts parsed requests directly into `RuntimeCommand` without a parallel command-name registry or default-constructor catalog. - `ServiceLifecycle`: Compile-safe lifecycle trait seam in `cli/src/services/lifecycle.rs` with default no-op generic `diagnose`, `fix`, and `setup` methods over `C: HasRepoRoot`; it exposes lifecycle-owned health, fix, and setup result types, while doctor/setup adapt those records at orchestration boundaries before rendering command-owned output. The hooks service has `HooksLifecycle` for hook rollout diagnosis/fix/setup, the config service has `ConfigLifecycle` for global/repo-local config validation plus repo-local config bootstrap, local_db has `LocalDbLifecycle` for canonical local DB path health/bootstrap/setup, auth_db has `AuthDbLifecycle` for canonical auth DB path health/bootstrap/setup, and agent_trace_db has `AgentTraceDbLifecycle` for repository identity resolution, setup-time repository-scoped Agent Trace DB initialization, and repository Agent Trace DB path health/bootstrap, returning an actionable "requires a Git repository" diagnostic outside repository context (the former global parent fallback was removed by the `retire-legacy-agent-trace-db` plan). Doctor runtime aggregates the static provider catalog for `diagnose` and `fix`; setup command aggregates providers for `setup` in order (config → local_db → auth_db → agent_trace_db → hooks when requested). - `lifecycle provider catalog`: Shared factory in `cli/src/services/lifecycle.rs` (`lifecycle_providers(include_hooks)`) that returns static `LifecycleProvider` enum values in deterministic config → local_db → auth_db → agent_trace_db → hooks order, used by doctor with hooks included and by setup with hooks included only when requested. The enum owns concrete-provider dispatch for `diagnose`, `fix`, and `setup` without boxed provider trait objects or `&dyn HasRepoRoot` lifecycle context erasure. - `sce config command surface`: Implemented top-level CLI command routed by `cli/src/app.rs` to `cli/src/services/config/mod.rs` (with schema/file-parsing delegated to `cli/src/services/config/schema.rs`, runtime precedence resolution delegated to `cli/src/services/config/resolver.rs`, and text/JSON output construction delegated to `cli/src/services/config/render.rs`), exposing `show`, `validate`, and `--help` for deterministic runtime config inspection and validation; `show` reports resolved flat logging observability values with provenance, while `validate` reports pass/fail plus validation issues and warnings only.