1use std::path::PathBuf;
2
3use crate::core::editor_registry::{ConfigType, EditorTarget, WriteAction, WriteOptions};
4use crate::core::portable_binary::resolve_portable_binary;
5use crate::core::setup_report::{PlatformInfo, SetupItem, SetupReport, SetupStepReport};
6use crate::hooks::{HookMode, recommend_hook_mode};
7use chrono::Utc;
8use std::ffi::OsString;
9mod mcp;
10pub use mcp::*;
11mod helpers;
12pub use helpers::*;
13
14pub fn claude_config_json_path(home: &std::path::Path) -> PathBuf {
15 crate::core::editor_registry::claude_mcp_json_path(home)
16}
17
18pub fn claude_config_dir(home: &std::path::Path) -> PathBuf {
19 crate::core::editor_registry::claude_state_dir(home)
20}
21
22pub(crate) struct EnvVarGuard {
23 key: &'static str,
24 previous: Option<OsString>,
25}
26
27impl EnvVarGuard {
28 pub(crate) fn set(key: &'static str, value: &str) -> Self {
29 let previous = std::env::var_os(key);
30 unsafe { std::env::set_var(key, value) };
34 Self { key, previous }
35 }
36}
37
38impl Drop for EnvVarGuard {
39 fn drop(&mut self) {
40 if let Some(previous) = &self.previous {
41 unsafe { std::env::set_var(self.key, previous) };
44 } else {
45 unsafe { std::env::remove_var(self.key) };
48 }
49 }
50}
51
52fn first_run_setup_level() -> (bool, bool) {
55 use std::io::Write;
56
57 let cfg = crate::core::config::Config::load();
58 if cfg.setup.auto_inject_rules.is_some() {
59 return (
60 cfg.setup.should_inject_rules(),
61 cfg.setup.should_inject_skills(),
62 );
63 }
64
65 println!();
66 println!(" \x1b[1mWelcome to lean-ctx!\x1b[0m");
67 println!();
68 println!(" lean-ctx compresses AI context by 60-99%, saving tokens and money.");
69 println!();
70 println!(" Choose your setup level:");
71 println!(
72 " \x1b[36m[1]\x1b[0m Minimal \x1b[2m— Just MCP tools, no config file changes (recommended)\x1b[0m"
73 );
74 println!(
75 " \x1b[36m[2]\x1b[0m Standard \x1b[2m— MCP tools + agent instructions for optimal mode selection\x1b[0m"
76 );
77 println!(
78 " \x1b[36m[3]\x1b[0m Full \x1b[2m— Everything (tools + rules + skills + shell hooks)\x1b[0m"
79 );
80 println!();
81 print!(" Your choice \x1b[1m[1]\x1b[0m: ");
82 std::io::stdout().flush().ok();
83
84 let mut input = String::new();
85 let choice = if std::io::stdin().read_line(&mut input).is_ok() {
86 input.trim().parse::<u8>().unwrap_or(1)
87 } else {
88 1
89 };
90
91 match choice {
92 3 => (true, true),
93 2 => (true, false),
94 _ => (false, false),
95 }
96}
97
98fn persist_setup_choice(inject_rules: bool, inject_skills: bool) {
100 if let Err(e) = crate::core::config::Config::update_global(|cfg| {
101 cfg.setup.auto_inject_rules = Some(inject_rules);
102 cfg.setup.auto_inject_skills = Some(inject_skills);
103 }) {
104 tracing::warn!("could not persist setup choice: {e}");
105 }
106}
107
108pub fn run_setup() {
109 use crate::terminal_ui;
110
111 if crate::shell::is_non_interactive() {
112 eprintln!("Non-interactive terminal detected (no TTY on stdin).");
113 eprintln!(
114 "Running in non-interactive mode (equivalent to: lean-ctx setup --non-interactive --yes)"
115 );
116 eprintln!();
117 let opts = SetupOptions {
118 non_interactive: true,
119 yes: true,
120 ..Default::default()
121 };
122 match run_setup_with_options(opts) {
123 Ok(report) => {
124 for w in &report.warnings {
125 tracing::warn!("{w}");
126 }
127 }
128 Err(e) => tracing::error!("Setup error: {e}"),
129 }
130 return;
131 }
132
133 let Some(home) = dirs::home_dir() else {
134 tracing::error!("Cannot determine home directory");
135 std::process::exit(1);
136 };
137
138 let binary = resolve_portable_binary();
139
140 let home_str = home.to_string_lossy().to_string();
141
142 terminal_ui::print_setup_header();
143
144 let (inject_rules, inject_skills) = first_run_setup_level();
145 persist_setup_choice(inject_rules, inject_skills);
146
147 terminal_ui::print_step_header(1, 13, "Shell Hook");
148 crate::cli::cmd_init(&["--global".to_string()]);
149 crate::shell_hook::install_all(false);
150
151 terminal_ui::print_step_header(2, 13, "Daemon");
152 if crate::daemon::is_daemon_running() {
153 terminal_ui::print_status_ok("Daemon running — restarting with current binary…");
154 let _ = crate::daemon::stop_daemon();
155 std::thread::sleep(std::time::Duration::from_millis(500));
156 if let Err(e) = crate::daemon::start_daemon(&[]) {
157 terminal_ui::print_status_warn(&format!("Daemon restart failed: {e}"));
158 }
159 } else if let Err(e) = crate::daemon::start_daemon(&[]) {
160 terminal_ui::print_status_warn(&format!("Daemon start failed: {e}"));
161 }
162
163 terminal_ui::print_step_header(3, 13, "AI Tool Detection");
164
165 let targets = crate::core::editor_registry::build_targets(&home);
166 let update_mcp = crate::core::config::Config::load()
170 .setup
171 .should_update_mcp();
172 let mut newly_configured: Vec<&str> = Vec::new();
173 let mut already_configured: Vec<&str> = Vec::new();
174 let mut not_installed: Vec<&str> = Vec::new();
175 let mut mcp_skipped: Vec<&str> = Vec::new();
176 let mut errors: Vec<&str> = Vec::new();
177
178 for target in &targets {
179 let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
180
181 if !target.detect_path.exists() {
182 not_installed.push(target.name);
183 continue;
184 }
185
186 if !update_mcp {
187 terminal_ui::print_status_ok(&format!(
188 "{:<20} \x1b[2mMCP registration skipped (auto_update_mcp=false)\x1b[0m",
189 target.name
190 ));
191 mcp_skipped.push(target.name);
192 continue;
193 }
194
195 let mode = if target.agent_key.is_empty() {
196 HookMode::Mcp
197 } else {
198 recommend_hook_mode(&target.agent_key)
199 };
200
201 match crate::core::editor_registry::write_config_with_options(
202 target,
203 &binary,
204 WriteOptions {
205 overwrite_invalid: false,
206 },
207 ) {
208 Ok(res) if res.action == WriteAction::Already => {
209 terminal_ui::print_status_ok(&format!(
210 "{:<20} \x1b[36m{mode}\x1b[0m \x1b[2m{short_path}\x1b[0m",
211 target.name
212 ));
213 already_configured.push(target.name);
214 }
215 Ok(_) => {
216 terminal_ui::print_status_new(&format!(
217 "{:<20} \x1b[36m{mode}\x1b[0m \x1b[2m{short_path}\x1b[0m",
218 target.name
219 ));
220 newly_configured.push(target.name);
221 }
222 Err(e) => {
223 terminal_ui::print_status_warn(&format!("{}: {e}", target.name));
224 errors.push(target.name);
225 }
226 }
227 }
228
229 let total_ok = newly_configured.len() + already_configured.len();
230 if total_ok == 0 && errors.is_empty() && mcp_skipped.is_empty() {
231 terminal_ui::print_status_warn(
232 "No AI tools detected. Install one and re-run: lean-ctx setup",
233 );
234 }
235
236 if !not_installed.is_empty() {
237 println!(
238 " \x1b[2m○ {} not detected: {}\x1b[0m",
239 not_installed.len(),
240 not_installed.join(", ")
241 );
242 }
243
244 configure_plan_mode_settings(&newly_configured, &already_configured);
245
246 terminal_ui::print_step_header(4, 13, "Agent Rules");
247 let rules_result = if inject_rules {
248 let r = crate::rules_inject::inject_all_rules(&home);
249 for name in &r.injected {
250 terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules injected\x1b[0m"));
251 }
252 for name in &r.updated {
253 terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules updated\x1b[0m"));
254 }
255 for name in &r.already {
256 terminal_ui::print_status_ok(&format!("{name:<20} \x1b[2mrules up-to-date\x1b[0m"));
257 }
258 for err in &r.errors {
259 terminal_ui::print_status_warn(err);
260 }
261 if !r.backed_up.is_empty() {
262 for bak in &r.backed_up {
263 println!(" \x1b[2m ↳ backup: {bak}\x1b[0m");
264 }
265 }
266 if r.injected.is_empty()
267 && r.updated.is_empty()
268 && r.already.is_empty()
269 && r.errors.is_empty()
270 {
271 terminal_ui::print_status_skip("No agent rules needed");
272 }
273 r
274 } else {
275 terminal_ui::print_status_skip("Skipped (run `lean-ctx setup --inject-rules` to enable)");
276 crate::rules_inject::InjectResult::default()
277 };
278
279 for target in &targets {
280 if !target.detect_path.exists() || target.agent_key.is_empty() {
281 continue;
282 }
283 let mode = recommend_hook_mode(&target.agent_key);
284 crate::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
285 }
286
287 terminal_ui::print_step_header(5, 13, "API Proxy (optional)");
288 {
289 let cfg = crate::core::config::Config::load();
290 let proxy_port = crate::proxy_setup::default_port();
291
292 match cfg.proxy_enabled {
293 Some(true) => {
294 crate::proxy_autostart::install(proxy_port, false);
295 std::thread::sleep(std::time::Duration::from_millis(500));
296 crate::proxy_setup::install_proxy_env(&home, proxy_port, false);
297 terminal_ui::print_status_ok("Proxy active (opted in)");
298 }
299 Some(false) => {
300 terminal_ui::print_status_skip(
301 "Proxy disabled (run `lean-ctx proxy enable` to change)",
302 );
303 }
304 None => {
305 println!(
306 " \x1b[2mThe API proxy routes LLM requests through lean-ctx for additional\x1b[0m"
307 );
308 println!(
309 " \x1b[2mtool-result compression and precise token analytics in the dashboard.\x1b[0m"
310 );
311 println!();
312 println!(
313 " \x1b[2mWithout it: MCP tools, shell hooks, gain tracking, and memory\x1b[0m"
314 );
315 println!(
316 " \x1b[2mall work normally. The proxy adds ~5-15% extra savings on top.\x1b[0m"
317 );
318 println!();
319 print!(" Enable the API proxy? [y/N] ");
320 let _ = std::io::Write::flush(&mut std::io::stdout());
321 let mut input = String::new();
322 let _ = std::io::stdin().read_line(&mut input);
323 let answer = matches!(input.trim().to_lowercase().as_str(), "y" | "yes");
324 if let Err(e) =
325 crate::core::config::Config::update_global(|c| c.proxy_enabled = Some(answer))
326 {
327 tracing::warn!("could not persist proxy choice: {e}");
328 }
329 if answer {
330 crate::proxy_autostart::install(proxy_port, false);
331 std::thread::sleep(std::time::Duration::from_millis(500));
332 crate::proxy_setup::install_proxy_env(&home, proxy_port, false);
333 terminal_ui::print_status_new("Proxy enabled");
334 } else {
335 terminal_ui::print_status_skip(
336 "Proxy skipped (run `lean-ctx proxy enable` anytime)",
337 );
338 }
339 }
340 }
341 }
342
343 terminal_ui::print_step_header(6, 13, "IDE Config Access (optional)");
344 {
345 let cfg = crate::core::config::Config::load();
346 match cfg.allow_ide_config_dirs {
347 Some(true) => {
348 terminal_ui::print_status_ok(
349 "Enabled — the agent can read your editors' config dirs",
350 );
351 }
352 Some(false) => {
353 terminal_ui::print_status_skip(
354 "Off (enable: lean-ctx config set allow_ide_config_dirs true)",
355 );
356 }
357 None => {
358 println!(
359 " \x1b[2mlean-ctx tools are jailed to the current project. Enabling this lets\x1b[0m"
360 );
361 println!(
362 " \x1b[2mthe agent read every supported editor's config dir (~/.cursor, VS Code,\x1b[0m"
363 );
364 println!(
365 " \x1b[2mCline/Roo, JetBrains, …) to manage MCP setup across editors.\x1b[0m"
366 );
367 println!();
368 println!(
369 " \x1b[33mTrade-off:\x1b[0m \x1b[2mthose dirs can hold other agents' sessions & credentials.\x1b[0m"
370 );
371 println!();
372 print!(" Allow the agent to read IDE config dirs? [y/N] ");
373 let _ = std::io::Write::flush(&mut std::io::stdout());
374 let mut input = String::new();
375 let _ = std::io::stdin().read_line(&mut input);
376 let answer = matches!(input.trim().to_lowercase().as_str(), "y" | "yes");
377 if let Err(e) = crate::core::config::Config::update_global(|c| {
378 c.allow_ide_config_dirs = Some(answer);
379 }) {
380 tracing::warn!("could not persist IDE-config-access choice: {e}");
381 }
382 if answer {
383 terminal_ui::print_status_new("IDE config access enabled");
384 } else {
385 terminal_ui::print_status_skip(
386 "Skipped (enable later: lean-ctx config set allow_ide_config_dirs true)",
387 );
388 }
389 }
390 }
391 }
392
393 terminal_ui::print_step_header(7, 13, "Skill Files");
394 if inject_skills {
395 let skill_result = install_skill_files(&home);
396 for (name, installed) in &skill_result {
397 if *installed {
398 terminal_ui::print_status_new(&format!(
399 "{name:<20} \x1b[2mSKILL.md installed\x1b[0m"
400 ));
401 } else {
402 terminal_ui::print_status_ok(&format!(
403 "{name:<20} \x1b[2mSKILL.md up-to-date\x1b[0m"
404 ));
405 }
406 }
407 if skill_result.is_empty() {
408 terminal_ui::print_status_skip("No skill directories to install");
409 }
410 } else {
411 terminal_ui::print_status_skip(
412 "Skipped (skill files install with the rules opt-in; choose Standard/Full in `lean-ctx setup`)",
413 );
414 }
415
416 terminal_ui::print_step_header(8, 13, "Environment Check");
417 let lean_dir = crate::core::data_dir::lean_ctx_data_dir()
418 .unwrap_or_else(|_| home.join(".config/lean-ctx"));
419 if lean_dir.exists() {
420 terminal_ui::print_status_ok(&format!("{} ready", lean_dir.display()));
421 } else {
422 let _ = std::fs::create_dir_all(&lean_dir);
423 terminal_ui::print_status_new(&format!("Created {}", lean_dir.display()));
424 }
425 if let Some(report) = crate::core::data_consolidate::consolidate()
426 && report.files_moved > 0
427 {
428 terminal_ui::print_status_new(&format!(
429 "Consolidated {} file(s) from a split data dir into {}",
430 report.files_moved,
431 report.canonical.display()
432 ));
433 }
434 crate::doctor::run_compact();
435
436 crate::core::layout_pin::heal();
439
440 terminal_ui::print_step_header(9, 13, "Help Improve lean-ctx");
441 println!(" Share anonymous compression stats to make lean-ctx better.");
442 println!(" \x1b[1mNo code, no file names, no personal data — ever.\x1b[0m");
443 println!();
444 print!(" Enable anonymous data sharing? \x1b[1m[y/N]\x1b[0m ");
445 use std::io::Write;
446 std::io::stdout().flush().ok();
447
448 let mut input = String::new();
449 let contribute = if std::io::stdin().read_line(&mut input).is_ok() {
450 let answer = input.trim().to_lowercase();
451 answer == "y" || answer == "yes"
452 } else {
453 false
454 };
455
456 if contribute {
457 let config_path = crate::core::config::Config::path()
458 .unwrap_or_else(|| home.join(".config/lean-ctx").join("config.toml"));
459 if let Some(dir) = config_path.parent() {
460 let _ = std::fs::create_dir_all(dir);
461 }
462 let mut config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
463 if !config_content.contains("[cloud]") {
464 if !config_content.is_empty() && !config_content.ends_with('\n') {
465 config_content.push('\n');
466 }
467 config_content.push_str("\n[cloud]\ncontribute_enabled = true\n");
468 let _ = crate::config_io::write_atomic_with_backup(&config_path, &config_content);
469 }
470 terminal_ui::print_status_ok("Enabled — thank you!");
471 } else {
472 terminal_ui::print_status_skip("Skipped — enable later with: lean-ctx config");
473 }
474
475 terminal_ui::print_step_header(10, 13, "Auto-Updates");
476 println!(" Keep lean-ctx up to date automatically.");
477 println!(" \x1b[1mChecks GitHub every 6h, installs only when a new release exists.\x1b[0m");
478 println!(
479 " \x1b[2mNo restarts mid-session. Change anytime: lean-ctx update --schedule off\x1b[0m"
480 );
481 println!();
482 print!(" Enable automatic updates? \x1b[1m[y/N]\x1b[0m ");
483 std::io::stdout().flush().ok();
484
485 let mut auto_input = String::new();
486 let auto_update = if std::io::stdin().read_line(&mut auto_input).is_ok() {
487 let answer = auto_input.trim().to_lowercase();
488 answer == "y" || answer == "yes"
489 } else {
490 false
491 };
492
493 if auto_update {
494 let cfg = crate::core::config::Config::load();
495 let hours = cfg.updates.check_interval_hours;
496 match crate::core::update_scheduler::install_schedule(hours) {
497 Ok(info) => {
498 crate::core::update_scheduler::set_auto_update(true, false, hours);
499 terminal_ui::print_status_ok(&format!("Enabled — {info}"));
500 }
501 Err(e) => {
502 terminal_ui::print_status_warn(&format!("Scheduler setup failed: {e}"));
503 terminal_ui::print_status_skip("Enable later: lean-ctx update --schedule");
504 }
505 }
506 } else {
507 crate::core::update_scheduler::set_auto_update(false, false, 6);
508 terminal_ui::print_status_skip("Skipped — enable later: lean-ctx update --schedule");
509 }
510
511 terminal_ui::print_step_header(11, 13, "Tool Profile");
512 configure_tool_profile();
513
514 terminal_ui::print_step_header(12, 13, "Advanced Tuning (optional)");
515 configure_premium_features(&home);
516
517 terminal_ui::print_step_header(13, 13, "Code Intelligence");
518 let cwd = std::env::current_dir().ok();
519 let cwd_is_home = cwd
520 .as_ref()
521 .is_some_and(|d| dirs::home_dir().is_some_and(|h| d.as_path() == h.as_path()));
522 if cwd_is_home {
523 terminal_ui::print_status_warn(
524 "Running from $HOME — graph build skipped to avoid scanning your entire home directory.",
525 );
526 println!();
527 println!(" \x1b[1mSet a default project root to avoid this:\x1b[0m");
528 println!(" \x1b[2mEnter your main project path (or press Enter to skip):\x1b[0m");
529 print!(" \x1b[1m>\x1b[0m ");
530 use std::io::Write;
531 std::io::stdout().flush().ok();
532 let mut root_input = String::new();
533 if std::io::stdin().read_line(&mut root_input).is_ok() {
534 let root_trimmed = root_input.trim();
535 if root_trimmed.is_empty() {
536 terminal_ui::print_status_skip(
537 "No project root set. Set later: lean-ctx config set project_root /path/to/project",
538 );
539 } else {
540 let root_path = std::path::Path::new(root_trimmed);
541 if root_path.exists() && root_path.is_dir() {
542 let config_path = crate::core::config::Config::path()
543 .unwrap_or_else(|| home.join(".config/lean-ctx").join("config.toml"));
544 let mut content = std::fs::read_to_string(&config_path).unwrap_or_default();
545 if content.contains("project_root") {
546 if let Ok(re) = regex::Regex::new(r#"(?m)^project_root\s*=\s*"[^"]*""#) {
547 content = re
548 .replace(&content, &format!("project_root = \"{root_trimmed}\""))
549 .to_string();
550 }
551 } else {
552 if !content.is_empty() && !content.ends_with('\n') {
553 content.push('\n');
554 }
555 content.push_str(&format!("project_root = \"{root_trimmed}\"\n"));
556 }
557 let _ = crate::config_io::write_atomic_with_backup(&config_path, &content);
558 terminal_ui::print_status_ok(&format!("Project root set: {root_trimmed}"));
559 if crate::core::pathutil::has_project_marker(root_path) {
560 spawn_index_build_background(root_path);
561 terminal_ui::print_status_ok("Graph build started (background)");
562 }
563 } else {
564 terminal_ui::print_status_warn(&format!(
565 "Path not found: {root_trimmed} — skipped"
566 ));
567 }
568 }
569 }
570 } else {
571 let is_project = cwd
572 .as_ref()
573 .is_some_and(|d| crate::core::pathutil::has_project_marker(d));
574 if is_project {
575 println!(" \x1b[2mBuilding code graph for graph-aware reads, impact analysis,\x1b[0m");
576 println!(" \x1b[2mand smart search fusion in the background...\x1b[0m");
577 if let Some(ref root) = cwd {
578 spawn_index_build_background(root);
579 }
580 terminal_ui::print_status_ok("Graph build started (background)");
581 } else {
582 println!(" \x1b[2mRun `lean-ctx graph build` inside any git project to enable\x1b[0m");
583 println!(
584 " \x1b[2mgraph-aware reads, impact analysis, and smart search fusion.\x1b[0m"
585 );
586 }
587 }
588 println!();
589
590 {
591 let tools = crate::core::editor_registry::writers::auto_approve_tools();
592 println!();
593 println!(
594 " \x1b[33m⚡ Auto-approved tools ({} total):\x1b[0m",
595 tools.len()
596 );
597 for chunk in tools.chunks(6) {
598 let names: Vec<_> = chunk.iter().map(|t| format!("\x1b[2m{t}\x1b[0m")).collect();
599 println!(" {}", names.join(", "));
600 }
601 println!(" \x1b[2mDisable with: lean-ctx setup --no-auto-approve\x1b[0m");
602 }
603
604 println!();
605 println!(
606 " \x1b[1;32m✓ Setup complete!\x1b[0m \x1b[1m{}\x1b[0m configured, \x1b[2m{} already set, {} skipped\x1b[0m",
607 newly_configured.len(),
608 already_configured.len(),
609 not_installed.len()
610 );
611
612 if !errors.is_empty() {
613 println!(
614 " \x1b[33m⚠ {} error{}: {}\x1b[0m",
615 errors.len(),
616 if errors.len() == 1 { "" } else { "s" },
617 errors.join(", ")
618 );
619 }
620
621 let source_cmd = crate::shell_hook::shell_source_command().unwrap_or("Restart your shell");
622
623 let dim = "\x1b[2m";
624 let bold = "\x1b[1m";
625 let cyan = "\x1b[36m";
626 let yellow = "\x1b[33m";
627 let rst = "\x1b[0m";
628
629 println!();
630 println!(" {bold}Next steps:{rst}");
631 println!();
632 println!(" {cyan}1.{rst} Reload your shell:");
633 println!(" {bold}{source_cmd}{rst}");
634 println!();
635
636 let mut tools_to_restart: Vec<String> = newly_configured
637 .iter()
638 .map(std::string::ToString::to_string)
639 .collect();
640 for name in rules_result
641 .injected
642 .iter()
643 .chain(rules_result.updated.iter())
644 {
645 if !tools_to_restart.contains(name) {
646 tools_to_restart.push(name.clone());
647 }
648 }
649
650 if !tools_to_restart.is_empty() {
651 println!(" {cyan}2.{rst} {yellow}{bold}Restart your IDE / AI tool:{rst}");
652 println!(" {bold}{}{rst}", tools_to_restart.join(", "));
653 println!(
654 " {dim}Changes take effect after a full restart (MCP may be enabled or disabled depending on mode).{rst}"
655 );
656 println!(" {dim}Close and re-open the application completely.{rst}");
657 } else if !already_configured.is_empty() {
658 println!(
659 " {cyan}2.{rst} {dim}Your tools are already configured — no restart needed.{rst}"
660 );
661 }
662
663 println!();
664 println!(
665 " {dim}After restart, lean-ctx will automatically optimize every AI interaction.{rst}"
666 );
667 println!(" {dim}Verify with:{rst} {bold}lean-ctx gain{rst}");
668
669 println!();
670 terminal_ui::print_logo_animated();
671 terminal_ui::print_command_box();
672
673 crate::cli::show_first_run_wow();
674}
675
676pub fn run_onboard() {
684 use crate::terminal_ui;
685
686 let dim = "\x1b[2m";
687 let bold = "\x1b[1m";
688 let cyan = "\x1b[36m";
689 let green = "\x1b[1;32m";
690 let yellow = "\x1b[33m";
691 let rst = "\x1b[0m";
692
693 println!();
694 println!(" {bold}Connecting lean-ctx to your AI tools…{rst}");
695 println!(
696 " {dim}No questions — using recommended defaults. Run `lean-ctx setup` for full control.{rst}"
697 );
698 println!();
699
700 let opts = SetupOptions {
701 non_interactive: true,
702 yes: true,
703 fix: true,
704 ..Default::default()
705 };
706
707 let report = match run_setup_with_options(opts) {
708 Ok(r) => r,
709 Err(e) => {
710 eprintln!(" {yellow}Onboarding could not complete: {e}{rst}");
711 eprintln!(" {dim}Try the guided setup instead: lean-ctx setup{rst}");
712 std::process::exit(1);
713 }
714 };
715
716 let connected: Vec<String> = report
717 .steps
718 .iter()
719 .find(|s| s.name == "editors")
720 .map(|s| {
721 s.items
722 .iter()
723 .filter(|i| matches!(i.status.as_str(), "created" | "updated" | "already"))
724 .map(|i| i.name.clone())
725 .collect()
726 })
727 .unwrap_or_default();
728
729 let data_dir = crate::core::data_dir::lean_ctx_data_dir()
730 .map_or_else(|_| "~/.lean-ctx".to_string(), |p| p.display().to_string());
731
732 println!();
733 if connected.is_empty() {
734 println!(" {yellow}No AI tools detected yet.{rst}");
735 println!(
736 " {dim}Install Cursor, Claude Code, VS Code, etc., then re-run: lean-ctx onboard{rst}"
737 );
738 } else {
739 println!(" {green}✓ lean-ctx is connected.{rst}");
740 println!();
741 println!(" {bold}Connected:{rst} {}", connected.join(", "));
742 }
743 println!(" {dim}Data dir:{rst} {data_dir}");
744
745 let source_cmd = crate::shell_hook::shell_source_command().unwrap_or("Restart your shell");
746 println!();
747 println!(" {bold}One last step:{rst}");
748 println!(" {cyan}1.{rst} Reload your shell: {bold}{source_cmd}{rst}");
749 if !connected.is_empty() {
750 println!(
751 " {cyan}2.{rst} {yellow}Fully restart your AI tool{rst} {dim}(so it reconnects to lean-ctx){rst}"
752 );
753 println!(
754 " {cyan}3.{rst} Ask your AI to read a file — lean-ctx optimizes it automatically."
755 );
756 }
757 println!();
758 println!(
759 " {dim}Check anytime:{rst} {bold}lean-ctx doctor{rst} {dim}·{rst} {bold}lean-ctx gain{rst}"
760 );
761 println!();
762 terminal_ui::print_command_box();
763
764 crate::cli::show_first_run_wow();
765}
766
767#[derive(Debug, Clone, Copy, Default)]
768pub struct SetupOptions {
769 pub non_interactive: bool,
770 pub yes: bool,
771 pub fix: bool,
772 pub json: bool,
773 pub no_auto_approve: bool,
774 pub skip_proxy: bool,
775 pub skip_rules: bool,
776 pub force_inject_rules: bool,
778}
779
780pub fn run_setup_with_options(opts: SetupOptions) -> Result<SetupReport, String> {
781 let _quiet_guard = opts.json.then(|| EnvVarGuard::set("LEAN_CTX_QUIET", "1"));
782 let started_at = Utc::now();
783 let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
784 let binary = resolve_portable_binary();
785 let home_str = home.to_string_lossy().to_string();
786
787 crate::core::layout_pin::heal();
790
791 let mut steps: Vec<SetupStepReport> = Vec::new();
792
793 let mut shell_step = SetupStepReport {
795 name: "shell_hook".to_string(),
796 ok: true,
797 items: Vec::new(),
798 warnings: Vec::new(),
799 errors: Vec::new(),
800 };
801 if !opts.non_interactive || opts.yes {
802 if opts.json {
803 crate::cli::cmd_init_quiet(&["--global".to_string()]);
804 } else {
805 crate::cli::cmd_init(&["--global".to_string()]);
806 }
807 crate::shell_hook::install_all(opts.json);
808 #[cfg(not(windows))]
809 {
810 let hook_content = crate::cli::generate_hook_posix(&binary);
811 if crate::shell::is_container() {
812 crate::cli::write_env_sh_for_containers(&hook_content);
813 shell_step.items.push(SetupItem {
814 name: "env_sh".to_string(),
815 status: "created".to_string(),
816 path: Some(crate::core::paths::config_dir().map_or_else(
817 |_| "~/.config/lean-ctx/env.sh".to_string(),
818 |d| d.join("env.sh").to_string_lossy().to_string(),
819 )),
820 note: Some("Docker/CI helper (BASH_ENV / CLAUDE_ENV_FILE)".to_string()),
821 });
822 } else {
823 shell_step.items.push(SetupItem {
824 name: "env_sh".to_string(),
825 status: "skipped".to_string(),
826 path: None,
827 note: Some("not a container environment".to_string()),
828 });
829 }
830 }
831 shell_step.items.push(SetupItem {
832 name: "init --global".to_string(),
833 status: "ran".to_string(),
834 path: None,
835 note: None,
836 });
837 shell_step.items.push(SetupItem {
838 name: "universal_shell_hook".to_string(),
839 status: "installed".to_string(),
840 path: None,
841 note: Some("~/.zshenv, ~/.bashenv, agent aliases".to_string()),
842 });
843 } else {
844 shell_step
845 .warnings
846 .push("non_interactive_without_yes: shell hook not installed (use --yes)".to_string());
847 shell_step.ok = false;
848 shell_step.items.push(SetupItem {
849 name: "init --global".to_string(),
850 status: "skipped".to_string(),
851 path: None,
852 note: Some("requires --yes in --non-interactive mode".to_string()),
853 });
854 }
855 steps.push(shell_step);
856
857 let mut daemon_step = SetupStepReport {
859 name: "daemon".to_string(),
860 ok: true,
861 items: Vec::new(),
862 warnings: Vec::new(),
863 errors: Vec::new(),
864 };
865 {
866 let was_running = crate::daemon::is_daemon_running();
867 if was_running {
868 let _ = crate::daemon::stop_daemon();
869 std::thread::sleep(std::time::Duration::from_millis(500));
870 }
871 match crate::daemon::start_daemon(&[]) {
872 Ok(()) => {
873 let action = if was_running { "restarted" } else { "started" };
874 daemon_step.items.push(SetupItem {
875 name: "serve --daemon".to_string(),
876 status: action.to_string(),
877 path: Some(crate::daemon::daemon_addr().display()),
878 note: Some("CLI commands can route via IPC when running".to_string()),
879 });
880 }
881 Err(e) => {
882 daemon_step
883 .warnings
884 .push(format!("daemon start failed (non-fatal): {e}"));
885 daemon_step.items.push(SetupItem {
886 name: "serve --daemon".to_string(),
887 status: "skipped".to_string(),
888 path: None,
889 note: Some(format!("optional — {e}")),
890 });
891 }
892 }
893 }
894 steps.push(daemon_step);
895
896 let mut editor_step = SetupStepReport {
898 name: "editors".to_string(),
899 ok: true,
900 items: Vec::new(),
901 warnings: Vec::new(),
902 errors: Vec::new(),
903 };
904
905 let targets = crate::core::editor_registry::build_targets(&home);
906 let update_mcp = crate::core::config::Config::load()
909 .setup
910 .should_update_mcp();
911 for target in &targets {
912 let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
913 if !target.detect_path.exists() {
914 editor_step.items.push(SetupItem {
915 name: target.name.to_string(),
916 status: "not_detected".to_string(),
917 path: Some(short_path),
918 note: None,
919 });
920 continue;
921 }
922
923 let mode = if target.agent_key.is_empty() {
924 HookMode::Mcp
925 } else {
926 recommend_hook_mode(&target.agent_key)
927 };
928
929 if !update_mcp {
930 editor_step.items.push(SetupItem {
931 name: target.name.to_string(),
932 status: "skipped".to_string(),
933 path: Some(short_path),
934 note: Some(format!(
935 "mode={mode}; MCP registration skipped (auto_update_mcp=false)"
936 )),
937 });
938 continue;
939 }
940
941 let res = crate::core::editor_registry::write_config_with_options(
942 target,
943 &binary,
944 WriteOptions {
945 overwrite_invalid: opts.fix,
946 },
947 );
948 match res {
949 Ok(w) => {
950 let note_parts: Vec<String> = [Some(format!("mode={mode}")), w.note]
951 .into_iter()
952 .flatten()
953 .collect();
954 editor_step.items.push(SetupItem {
955 name: target.name.to_string(),
956 status: match w.action {
957 WriteAction::Created => "created".to_string(),
958 WriteAction::Updated => "updated".to_string(),
959 WriteAction::Already => "already".to_string(),
960 },
961 path: Some(short_path),
962 note: Some(note_parts.join("; ")),
963 });
964 }
965 Err(e) => {
966 editor_step.ok = false;
967 editor_step.items.push(SetupItem {
968 name: target.name.to_string(),
969 status: "error".to_string(),
970 path: Some(short_path),
971 note: Some(e),
972 });
973 }
974 }
975 }
976 steps.push(editor_step);
977
978 let mut rules_step = SetupStepReport {
980 name: "agent_rules".to_string(),
981 ok: true,
982 items: Vec::new(),
983 warnings: Vec::new(),
984 errors: Vec::new(),
985 };
986 let setup_cfg = crate::core::config::Config::load().setup;
987 let should_inject = if opts.skip_rules {
988 false
989 } else if opts.force_inject_rules {
990 true
991 } else if opts.yes && opts.non_interactive {
992 setup_cfg.should_inject_rules()
993 } else {
994 true
995 };
996
997 if should_inject {
998 let rules_result = crate::rules_inject::inject_all_rules(&home);
999 for n in rules_result.injected {
1000 rules_step.items.push(SetupItem {
1001 name: n,
1002 status: "injected".to_string(),
1003 path: None,
1004 note: None,
1005 });
1006 }
1007 for n in rules_result.updated {
1008 rules_step.items.push(SetupItem {
1009 name: n,
1010 status: "updated".to_string(),
1011 path: None,
1012 note: None,
1013 });
1014 }
1015 for n in rules_result.already {
1016 rules_step.items.push(SetupItem {
1017 name: n,
1018 status: "already".to_string(),
1019 path: None,
1020 note: None,
1021 });
1022 }
1023 if !rules_result.backed_up.is_empty() {
1024 for bak in &rules_result.backed_up {
1025 rules_step.items.push(SetupItem {
1026 name: "backup".to_string(),
1027 status: "created".to_string(),
1028 path: Some(bak.clone()),
1029 note: Some("previous version backed up".to_string()),
1030 });
1031 }
1032 }
1033 for e in rules_result.errors {
1034 rules_step.ok = false;
1035 rules_step.errors.push(e);
1036 }
1037 } else {
1038 let reason = if opts.skip_rules {
1039 "--skip-rules flag set"
1040 } else {
1041 "auto_inject_rules not enabled (run `lean-ctx setup --inject-rules`)"
1042 };
1043 rules_step.items.push(SetupItem {
1044 name: "agent_rules".to_string(),
1045 status: "skipped".to_string(),
1046 path: None,
1047 note: Some(reason.to_string()),
1048 });
1049 }
1050 steps.push(rules_step);
1051
1052 let mut skill_step = SetupStepReport {
1054 name: "skill_files".to_string(),
1055 ok: true,
1056 items: Vec::new(),
1057 warnings: Vec::new(),
1058 errors: Vec::new(),
1059 };
1060 let should_install_skills = if opts.skip_rules {
1061 false
1062 } else if opts.force_inject_rules {
1063 true
1064 } else if opts.yes && opts.non_interactive {
1065 setup_cfg.should_inject_skills()
1066 } else {
1067 true
1068 };
1069 if should_install_skills {
1070 let skill_results = crate::rules_inject::install_all_skills(&home);
1071 for (name, is_new) in &skill_results {
1072 skill_step.items.push(SetupItem {
1073 name: name.clone(),
1074 status: if *is_new { "installed" } else { "already" }.to_string(),
1075 path: None,
1076 note: Some("SKILL.md".to_string()),
1077 });
1078 }
1079 } else {
1080 skill_step.items.push(SetupItem {
1081 name: "skill_files".to_string(),
1082 status: "skipped".to_string(),
1083 path: None,
1084 note: Some("auto_inject_skills not enabled".to_string()),
1085 });
1086 }
1087 if !skill_step.items.is_empty() {
1088 steps.push(skill_step);
1089 }
1090
1091 let mut hooks_step = SetupStepReport {
1093 name: "agent_hooks".to_string(),
1094 ok: true,
1095 items: Vec::new(),
1096 warnings: Vec::new(),
1097 errors: Vec::new(),
1098 };
1099 for target in &targets {
1100 if !target.detect_path.exists() || target.agent_key.is_empty() {
1101 continue;
1102 }
1103 let mode = recommend_hook_mode(&target.agent_key);
1104 crate::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
1105 let mcp_note = if setup_cfg.should_update_mcp() {
1108 match configure_agent_mcp(&target.agent_key) {
1109 Ok(()) => "; MCP config updated".to_string(),
1110 Err(e) => format!("; MCP config skipped: {e}"),
1111 }
1112 } else {
1113 "; MCP registration skipped (auto_update_mcp=false)".to_string()
1114 };
1115 hooks_step.items.push(SetupItem {
1116 name: format!("{} hooks", target.name),
1117 status: "installed".to_string(),
1118 path: Some(target.detect_path.to_string_lossy().to_string()),
1119 note: Some(format!(
1120 "mode={mode}; merge-based install/repair (preserves other hooks/plugins){mcp_note}"
1121 )),
1122 });
1123 }
1124 if !hooks_step.items.is_empty() {
1125 steps.push(hooks_step);
1126 }
1127
1128 let mut tool_profile_step = SetupStepReport {
1134 name: "tool_profile".to_string(),
1135 ok: true,
1136 items: Vec::new(),
1137 warnings: Vec::new(),
1138 errors: Vec::new(),
1139 };
1140 {
1141 let cfg = crate::core::config::Config::load();
1142 if cfg.tool_profile.is_none() && std::env::var("LEAN_CTX_TOOL_PROFILE").is_err() {
1143 let lazy_count = crate::tool_defs::core_tool_names().len();
1144 tool_profile_step.items.push(SetupItem {
1145 name: "tool_profile".to_string(),
1146 status: "lean default".to_string(),
1147 path: None,
1148 note: Some(format!(
1149 "{lazy_count} tools advertised, all reachable via ctx_call \
1150 (pin more with: lean-ctx tools standard|power)"
1151 )),
1152 });
1153 } else {
1154 let profile = cfg.tool_profile_effective();
1155 let overhead_hint = match profile {
1156 crate::core::tool_profiles::ToolProfile::Power => {
1157 "; advertises ALL tool schemas — `lean-ctx tools lean` cuts this to the lazy core"
1158 }
1159 _ => "",
1160 };
1161 tool_profile_step.items.push(SetupItem {
1162 name: "tool_profile".to_string(),
1163 status: "already".to_string(),
1164 path: None,
1165 note: Some(format!("profile={}{overhead_hint}", profile.as_str())),
1166 });
1167 }
1168 }
1169 steps.push(tool_profile_step);
1170
1171 let mut proxy_step = SetupStepReport {
1173 name: "proxy".to_string(),
1174 ok: true,
1175 items: Vec::new(),
1176 warnings: Vec::new(),
1177 errors: Vec::new(),
1178 };
1179 if opts.skip_proxy {
1180 proxy_step.items.push(SetupItem {
1181 name: "proxy".to_string(),
1182 status: "skipped".to_string(),
1183 path: None,
1184 note: Some("Proxy not enabled (run `lean-ctx proxy enable`)".to_string()),
1185 });
1186 } else {
1187 let proxy_cfg = crate::core::config::Config::load();
1188 if proxy_cfg.proxy_enabled == Some(true) {
1189 let proxy_port = crate::proxy_setup::default_port();
1190 crate::proxy_autostart::install(proxy_port, true);
1191 std::thread::sleep(std::time::Duration::from_millis(500));
1192 crate::proxy_setup::install_proxy_env(&home, proxy_port, opts.json);
1193 proxy_step.items.push(SetupItem {
1194 name: "proxy_autostart".to_string(),
1195 status: "installed".to_string(),
1196 path: None,
1197 note: Some("LaunchAgent/systemd auto-start on login".to_string()),
1198 });
1199 proxy_step.items.push(SetupItem {
1200 name: "proxy_env".to_string(),
1201 status: "configured".to_string(),
1202 path: None,
1203 note: Some("ANTHROPIC_BASE_URL, OPENAI_BASE_URL, GEMINI_API_BASE_URL".to_string()),
1204 });
1205 } else {
1206 proxy_step.items.push(SetupItem {
1207 name: "proxy".to_string(),
1208 status: "skipped".to_string(),
1209 path: None,
1210 note: Some(
1211 "Proxy not opted-in (run `lean-ctx proxy enable` to activate)".to_string(),
1212 ),
1213 });
1214 }
1215 }
1216 steps.push(proxy_step);
1217
1218 let mut env_step = SetupStepReport {
1220 name: "doctor_compact".to_string(),
1221 ok: true,
1222 items: Vec::new(),
1223 warnings: Vec::new(),
1224 errors: Vec::new(),
1225 };
1226 let (passed, total) = crate::doctor::compact_score();
1227 env_step.items.push(SetupItem {
1228 name: "doctor".to_string(),
1229 status: format!("{passed}/{total}"),
1230 path: None,
1231 note: None,
1232 });
1233 if passed != total {
1234 env_step.warnings.push(format!(
1235 "doctor compact not fully passing: {passed}/{total}"
1236 ));
1237 }
1238 steps.push(env_step);
1239
1240 {
1242 let has_env_root = std::env::var("LEAN_CTX_PROJECT_ROOT").is_ok_and(|v| !v.is_empty());
1243 let cfg = crate::core::config::Config::load();
1244 let has_cfg_root = cfg.project_root.as_ref().is_some_and(|v| !v.is_empty());
1245 if !has_env_root
1246 && !has_cfg_root
1247 && let Ok(cwd) = std::env::current_dir()
1248 {
1249 let is_home = dirs::home_dir().is_some_and(|h| cwd == h);
1250 if is_home {
1251 let mut root_step = SetupStepReport {
1252 name: "project_root".to_string(),
1253 ok: true,
1254 items: Vec::new(),
1255 warnings: vec![
1256 "No project_root configured. Running from $HOME can cause excessive scanning. \
1257 Set via: lean-ctx config set project_root /path/to/project".to_string()
1258 ],
1259 errors: Vec::new(),
1260 };
1261 root_step.items.push(SetupItem {
1262 name: "project_root".to_string(),
1263 status: "unconfigured".to_string(),
1264 path: None,
1265 note: Some(
1266 "Set LEAN_CTX_PROJECT_ROOT or add project_root to config.toml".to_string(),
1267 ),
1268 });
1269 steps.push(root_step);
1270 }
1271 }
1272 }
1273
1274 if let Ok(cwd) = std::env::current_dir()
1279 && may_autoindex_cwd(&cwd)
1280 && crate::core::pathutil::has_project_marker(&cwd)
1281 {
1282 spawn_index_build_background(&cwd);
1283 }
1284
1285 if opts.yes
1290 && !opts.fix
1291 && crate::core::config::Config::load()
1292 .allow_ide_config_dirs
1293 .is_none()
1294 && let Err(e) =
1295 crate::core::config::Config::update_global(|c| c.allow_ide_config_dirs = Some(true))
1296 {
1297 tracing::warn!("could not enable IDE config access: {e}");
1298 }
1299
1300 let finished_at = Utc::now();
1301 let success = steps.iter().all(|s| s.ok);
1302 let report = SetupReport {
1303 schema_version: 1,
1304 started_at,
1305 finished_at,
1306 success,
1307 platform: PlatformInfo {
1308 os: std::env::consts::OS.to_string(),
1309 arch: std::env::consts::ARCH.to_string(),
1310 },
1311 steps,
1312 warnings: Vec::new(),
1313 errors: Vec::new(),
1314 };
1315
1316 let path = SetupReport::default_path()?;
1317 let mut content =
1318 serde_json::to_string_pretty(&report).map_err(|e| format!("serialize report: {e}"))?;
1319 content.push('\n');
1320 crate::config_io::write_atomic(&path, &content)?;
1321
1322 Ok(report)
1323}
1324
1325fn may_autoindex_cwd(cwd: &std::path::Path) -> bool {
1334 !crate::core::pathutil::is_under_tcc_protected_dir(cwd)
1335}
1336
1337fn spawn_index_build_background(root: &std::path::Path) {
1338 if std::env::var("LEAN_CTX_DISABLED").is_ok()
1339 || matches!(std::env::var("LEAN_CTX_QUIET"), Ok(v) if v.trim() == "1")
1340 {
1341 return;
1342 }
1343 let root_str = crate::core::graph_index::normalize_project_root(&root.to_string_lossy());
1344 if !crate::core::graph_index::is_safe_scan_root_public(&root_str) {
1345 tracing::info!("[setup: skipping background graph build for unsafe root {root_str}]");
1346 return;
1347 }
1348
1349 let binary = resolve_portable_binary();
1350
1351 #[cfg(unix)]
1352 {
1353 let mut cmd = std::process::Command::new("nice");
1354 cmd.args(["-n", "19"]);
1355 if which_ionice_available() {
1356 cmd.arg("ionice").args(["-c", "3"]);
1357 }
1358 cmd.arg(&binary)
1359 .args(["index", "build", "--root"])
1360 .arg(root)
1361 .stdout(std::process::Stdio::null())
1362 .stderr(std::process::Stdio::null())
1363 .stdin(std::process::Stdio::null());
1364 let _ = cmd.spawn();
1365 }
1366
1367 #[cfg(windows)]
1368 {
1369 use std::os::windows::process::CommandExt;
1370 const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
1371 const CREATE_NO_WINDOW: u32 = 0x0800_0000;
1372 let _ = std::process::Command::new(&binary)
1373 .args(["index", "build", "--root"])
1374 .arg(root)
1375 .stdout(std::process::Stdio::null())
1376 .stderr(std::process::Stdio::null())
1377 .stdin(std::process::Stdio::null())
1378 .creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW)
1379 .spawn();
1380 }
1381}
1382
1383#[cfg(unix)]
1384fn which_ionice_available() -> bool {
1385 std::process::Command::new("ionice")
1386 .arg("--version")
1387 .stdout(std::process::Stdio::null())
1388 .stderr(std::process::Stdio::null())
1389 .status()
1390 .is_ok()
1391}
1392
1393#[cfg(all(test, target_os = "macos"))]
1394mod tests {
1395 use super::*;
1396
1397 #[test]
1401 fn may_autoindex_cwd_skips_tcc_protected_dirs() {
1402 let Some(home) = dirs::home_dir() else {
1403 return;
1404 };
1405 assert!(!may_autoindex_cwd(&home.join("Documents/proj")));
1406 assert!(!may_autoindex_cwd(&home.join("Desktop/proj")));
1407 assert!(!may_autoindex_cwd(&home.join("Downloads/proj")));
1408 assert!(may_autoindex_cwd(&home.join("code/proj")));
1409 assert!(may_autoindex_cwd(std::path::Path::new("/tmp/proj")));
1410 }
1411
1412 #[test]
1413 #[cfg(target_os = "macos")]
1414 fn qoder_agent_targets_include_all_macos_mcp_locations() {
1415 let home = std::path::Path::new("/Users/tester");
1416 let targets = agent_mcp_targets("qoder", home).unwrap();
1417 let paths: Vec<_> = targets.iter().map(|t| t.config_path.as_path()).collect();
1418
1419 assert_eq!(
1420 paths,
1421 vec![
1422 home.join(".qoder/mcp.json").as_path(),
1423 home.join("Library/Application Support/Qoder/User/mcp.json")
1424 .as_path(),
1425 home.join("Library/Application Support/Qoder/SharedClientCache/mcp.json")
1426 .as_path(),
1427 ]
1428 );
1429 assert!(
1430 targets
1431 .iter()
1432 .all(|t| t.config_type == ConfigType::QoderSettings)
1433 );
1434 }
1435}