返回 CodeWhale
mod.rs
根目录 / crates / tui / src / tui / setup / mod.rs
1 //! Progressive setup and repair guide.
2 //!
3 //! Bare `/setup` starts at the first missing decision and otherwise shows a
4 //! compact readiness summary. Optional power tools only join that journey when
5 //! they are already configured or need repair. Named `/setup <target>` routes
6 //! and the versioned Constitution checkpoint remain compatibility entrypoints,
7 //! but ordinary preferences belong to `/settings` and advanced keys belong to
8 //! `/config <key>`.
9
10 use std::borrow::Cow;
11 use std::cell::Cell;
12 use std::path::Path;
13
14 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
15 use ratatui::{
16 buffer::Buffer,
17 layout::Rect,
18 style::{Modifier, Style},
19 text::{Line, Span},
20 widgets::{Paragraph, Widget, Wrap},
21 };
22 use unicode_segmentation::UnicodeSegmentation;
23
24 use crate::tui::app::{App, AppModeUi};
25 use crate::tui::views::{
26 ActionHint, ModalKind, ModalView, ViewAction, ViewEvent, render_modal_footer,
27 render_panel_scroll_rail, render_underwater_surface,
28 };
29 use codewhale_engine::prompts::{
30 BASE_PROMPT_OVERRIDE_OPT_IN_ENV, CONSTITUTION_OVERRIDE_FILE, base_prompt_override_opt_in,
31 };
32 use codewhale_engine::provider_readiness::has_api_key;
33 use codewhale_localization::{Locale, MessageId, tr};
34 use codewhale_palette as palette;
35 use codewhale_runtime::config::Config;
36
37 use codewhale_config::{
38 AutonomyPreference, ConstitutionAuthoring, ConstitutionChoice, ConstitutionSource,
39 ConstitutionValidity, InheritedConfigFacts, RuntimePostureSource, SetupState, SetupStep,
40 StepEntry, StepStatus, UserConstitution, UserConstitutionLoad,
41 user_constitution::MAX_NOTES_LEN,
42 };
43
44 mod fleet_draft;
45 mod model_draft;
46 mod operate;
47 mod persistence;
48 mod provider;
49 mod remote;
50 mod tools_mcp;
51
52 pub(crate) use fleet_draft::{draft_fleet_profile_with_model, workspace_fingerprint};
53 pub(crate) use model_draft::draft_constitution_with_model;
54 use persistence::SetupPersistenceFacts;
55 pub(crate) use provider::record_configured_route;
56 use remote::SetupRemoteFacts;
57
58 use codewhale_engine::prompts::CONSTITUTION_CHECKPOINT_VERSION;
59
60 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
61 pub enum SetupCommitKind {
62 BundledConstitution,
63 DeferredConstitution,
64 }
65
66 pub trait SetupWizardStep {
67 fn id(&self) -> SetupStep;
68 fn title_id(&self) -> MessageId;
69 fn why_id(&self) -> MessageId;
70 fn required(&self) -> bool;
71 }
72
73 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
74 struct StaticSetupStep {
75 id: SetupStep,
76 title_id: MessageId,
77 why_id: MessageId,
78 required: bool,
79 }
80
81 impl SetupWizardStep for StaticSetupStep {
82 fn id(&self) -> SetupStep {
83 self.id
84 }
85
86 fn title_id(&self) -> MessageId {
87 self.title_id
88 }
89
90 fn why_id(&self) -> MessageId {
91 self.why_id
92 }
93
94 fn required(&self) -> bool {
95 self.required
96 }
97 }
98
99 const STEP_SPECS: [StaticSetupStep; 10] = [
100 StaticSetupStep {
101 id: SetupStep::Language,
102 title_id: MessageId::SetupStepLanguageTitle,
103 why_id: MessageId::SetupStepLanguageWhy,
104 required: true,
105 },
106 StaticSetupStep {
107 id: SetupStep::ProviderModel,
108 title_id: MessageId::SetupStepProviderModelTitle,
109 why_id: MessageId::SetupStepProviderModelWhy,
110 required: true,
111 },
112 StaticSetupStep {
113 id: SetupStep::TrustSandbox,
114 title_id: MessageId::SetupStepTrustSandboxTitle,
115 why_id: MessageId::SetupStepTrustSandboxWhy,
116 required: true,
117 },
118 StaticSetupStep {
119 id: SetupStep::Constitution,
120 title_id: MessageId::SetupStepConstitutionTitle,
121 why_id: MessageId::SetupStepConstitutionWhy,
122 required: true,
123 },
124 StaticSetupStep {
125 id: SetupStep::OperateFleet,
126 title_id: MessageId::SetupStepOperateFleetTitle,
127 why_id: MessageId::SetupStepOperateFleetWhy,
128 required: false,
129 },
130 StaticSetupStep {
131 id: SetupStep::Hotbar,
132 title_id: MessageId::SetupStepHotbarTitle,
133 why_id: MessageId::SetupStepHotbarWhy,
134 required: false,
135 },
136 StaticSetupStep {
137 id: SetupStep::ToolsMcp,
138 title_id: MessageId::SetupStepToolsMcpTitle,
139 why_id: MessageId::SetupStepToolsMcpWhy,
140 required: false,
141 },
142 StaticSetupStep {
143 id: SetupStep::RemoteRuntime,
144 title_id: MessageId::SetupStepRemoteRuntimeTitle,
145 why_id: MessageId::SetupStepRemoteRuntimeWhy,
146 required: false,
147 },
148 StaticSetupStep {
149 id: SetupStep::Persistence,
150 title_id: MessageId::SetupStepPersistenceTitle,
151 why_id: MessageId::SetupStepPersistenceWhy,
152 required: false,
153 },
154 StaticSetupStep {
155 id: SetupStep::Verification,
156 title_id: MessageId::SetupStepVerificationTitle,
157 why_id: MessageId::SetupStepVerificationWhy,
158 required: false,
159 },
160 ];
161
162 #[derive(Debug, Clone, PartialEq, Eq)]
163 pub struct SetupWizardView {
164 state: SetupState,
165 selected: usize,
166 locale: Locale,
167 /// Bare `/setup` is a short runtime-derived repair journey. Explicit
168 /// targets remain focused compatibility cards outside that journey.
169 progressive_guide: bool,
170 /// Technical inventory and preset details stay off the first paint.
171 details_expanded: bool,
172 facts: SetupRuntimeFacts,
173 guided_draft: GuidedConstitutionDraft,
174 /// First-run shows one plain-language initiative choice. The six-axis
175 /// editor remains available explicitly, but never competes with the
176 /// recommended path on first paint.
177 constitution_advanced: bool,
178 freeform_note: String,
179 editing_freeform_note: bool,
180 guided_preview_seen: bool,
181 /// The keep-existing path mirrors the guided two-step: the first `K`
182 /// opens the rendered preview of the existing file, the second completes
183 /// the checkpoint without touching it.
184 existing_preview_seen: bool,
185 /// A model-drafted constitution awaiting ratification, installed by the
186 /// host after a successful one-shot draft (already sanitized + bounded).
187 /// Cleared whenever a guided answer changes so a stale draft can never be
188 /// ratified against fresh answers.
189 model_draft: Option<Box<UserConstitution>>,
190 /// Display label of the model that authored `model_draft` (safe metadata,
191 /// e.g. "GLM-5.2"), for provenance copy only.
192 model_draft_label: Option<String>,
193 /// The answers (and free-form note) the in-flight model draft was asked
194 /// to write. A draft lands only while they are still the wizard's
195 /// answers; one requested for answers since changed is stale (U08-06).
196 model_draft_request: Option<(GuidedConstitutionDraft, Option<String>)>,
197 runtime_preset: SetupRuntimePreset,
198 runtime_preset_preview_seen: bool,
199 body_scroll: usize,
200 body_max_scroll: Cell<usize>,
201 }
202
203 #[derive(Debug, Clone, PartialEq, Eq)]
204 struct SetupRuntimeFacts {
205 provider: String,
206 model: String,
207 auth: String,
208 health: String,
209 provider_ready: bool,
210 provider_status: StepStatus,
211 provider_result: String,
212 work_intent: String,
213 approval: String,
214 shell: String,
215 allow_shell_enabled: bool,
216 trust: String,
217 sandbox: String,
218 sandbox_mode_value: String,
219 network: String,
220 network_default_value: String,
221 runtime_result: String,
222 operate_runtime_ready: bool,
223 operate_runtime_result: String,
224 fleet_roster_ready: bool,
225 fleet_roster_result: String,
226 operate_concurrency_result: String,
227 operate_result: String,
228 hotbar_bindings_result: String,
229 hotbar_actions_result: String,
230 hotbar_result: String,
231 tools_mcp_servers_result: String,
232 tools_mcp_skills_result: String,
233 tools_mcp_tools_result: String,
234 tools_mcp_plugins_result: String,
235 tools_mcp_dsh_result: String,
236 tools_mcp_hotbar_result: String,
237 tools_mcp_result: String,
238 tools_mcp_needs_action: bool,
239 tools_mcp_path_display: String,
240 tools_mcp_skills_path_display: String,
241 tools_mcp_plugins_path_display: String,
242 remote_clouds_result: String,
243 remote_bridges_result: String,
244 remote_providers_result: String,
245 remote_mode_result: String,
246 remote_command_provider: String,
247 remote_result: String,
248 remote_control_result: String,
249 /// The four observed remote modes (#3409). Empty only before facts load.
250 remote_modes: Vec<remote::RemoteModeFact>,
251 /// True when a mode is missing a token or config. Recorded as
252 /// `NeedsAction`, which by contract never blocks the ready screen.
253 remote_needs_action: bool,
254 persistence: SetupPersistenceFacts,
255 default_mode: String,
256 approval_policy_value: String,
257 project_override_warning: Option<String>,
258 constitution_autonomy: String,
259 constitution_file: SetupConstitutionFileState,
260 expert_override: SetupExpertOverrideState,
261 }
262
263 impl Default for SetupRuntimeFacts {
264 fn default() -> Self {
265 Self {
266 provider: "not loaded".to_string(),
267 model: "not loaded".to_string(),
268 auth: "not checked".to_string(),
269 health: "not checked".to_string(),
270 provider_ready: false,
271 provider_status: StepStatus::NeedsAction,
272 provider_result: "provider/model not loaded".to_string(),
273 work_intent: "not loaded".to_string(),
274 approval: "not loaded".to_string(),
275 shell: "not loaded".to_string(),
276 allow_shell_enabled: false,
277 trust: "not loaded".to_string(),
278 sandbox: "not configured".to_string(),
279 sandbox_mode_value: "default".to_string(),
280 network: "not configured".to_string(),
281 network_default_value: "prompt".to_string(),
282 runtime_result: "permissions not loaded".to_string(),
283 operate_runtime_ready: false,
284 operate_runtime_result: "agent runtime not loaded".to_string(),
285 fleet_roster_ready: false,
286 fleet_roster_result: "Fleet not loaded".to_string(),
287 operate_concurrency_result: "concurrency not loaded".to_string(),
288 operate_result: "operate readiness not loaded".to_string(),
289 hotbar_bindings_result: "Hotbar config not loaded".to_string(),
290 hotbar_actions_result: "Hotbar actions not loaded".to_string(),
291 hotbar_result: "hotbar not loaded".to_string(),
292 tools_mcp_servers_result: "MCP config not loaded".to_string(),
293 tools_mcp_skills_result: "skills dir not loaded".to_string(),
294 tools_mcp_tools_result: "tools dir not loaded".to_string(),
295 tools_mcp_plugins_result: "plugins dir not loaded".to_string(),
296 tools_mcp_dsh_result: "DeepSeek Harness not probed".to_string(),
297 tools_mcp_hotbar_result: "hotbar source metadata not loaded".to_string(),
298 tools_mcp_result: "tools/MCP not loaded".to_string(),
299 tools_mcp_needs_action: false,
300 tools_mcp_path_display: String::new(),
301 tools_mcp_skills_path_display: String::new(),
302 tools_mcp_plugins_path_display: String::new(),
303 remote_clouds_result: "remote cloud registry not loaded".to_string(),
304 remote_bridges_result: "remote bridge registry not loaded".to_string(),
305 remote_providers_result: "provider registry not loaded".to_string(),
306 remote_mode_result: "remote setup mode not loaded".to_string(),
307 remote_command_provider: "deepseek".to_string(),
308 remote_result: "remote runtime not loaded".to_string(),
309 remote_control_result: "off".to_string(),
310 remote_modes: Vec::new(),
311 remote_needs_action: false,
312 persistence: SetupPersistenceFacts::default(),
313 default_mode: "agent".to_string(),
314 approval_policy_value: "on-request".to_string(),
315 project_override_warning: None,
316 constitution_autonomy: "not loaded".to_string(),
317 constitution_file: SetupConstitutionFileState::NotChecked,
318 expert_override: SetupExpertOverrideState::NotChecked,
319 }
320 }
321 }
322
323 struct SetupDiskProbeInput {
324 config_path: Option<std::path::PathBuf>,
325 locale: Locale,
326 trust_mode: bool,
327 tools_mcp: tools_mcp::ToolsMcpProbeInput,
328 }
329
330 impl SetupDiskProbeInput {
331 fn from_app_config(app: &App, config: &Config) -> Self {
332 let codewhale_home = setup_codewhale_home_dir();
333 Self {
334 config_path: app.config_path.clone(),
335 locale: app.ui_locale,
336 trust_mode: app.trust_mode,
337 tools_mcp: tools_mcp::ToolsMcpProbeInput::from_app_config(app, config, codewhale_home),
338 }
339 }
340 }
341
342 struct SetupDiskProbes {
343 state: SetupState,
344 expert_override: SetupExpertOverrideState,
345 roster: codewhale_engine::fleet::roster::FleetRoster,
346 persistence: SetupPersistenceFacts,
347 tools_mcp: tools_mcp::SetupToolsMcpFacts,
348 project_override_warning: Option<String>,
349 constitution_autonomy: String,
350 constitution_file: SetupConstitutionFileState,
351 }
352
353 impl SetupDiskProbes {
354 fn collect(input: SetupDiskProbeInput) -> Self {
355 let expert_override = SetupExpertOverrideState::load();
356 let user_constitution = UserConstitution::load().ok();
357 let state = match SetupState::load() {
358 Ok(Some(state)) => state,
359 _ => {
360 let user_constitution_validity = user_constitution.as_ref().map_or(
361 ConstitutionValidity::Unknown,
362 UserConstitutionLoad::validity,
363 );
364 let has_user_constitution = user_constitution
365 .as_ref()
366 .is_some_and(|loaded| !matches!(loaded, UserConstitutionLoad::Missing));
367 SetupState::derive_inherited(&InheritedConfigFacts {
368 language: Some(input.locale.tag().to_string()),
369 has_provider_route: !input.tools_mcp.config.default_model().trim().is_empty(),
370 has_credentials_or_local_runtime: has_api_key(&input.tools_mcp.config),
371 trust_chosen: input.trust_mode
372 || !codewhale_runtime::config::needs_trust(&input.tools_mcp.workspace),
373 has_expert_override: expert_override.is_active(),
374 has_user_constitution,
375 user_constitution_validity,
376 })
377 }
378 };
379 let roster = codewhale_engine::fleet::identity::load_effective_roster(
380 &input.tools_mcp.config.fleet_config(),
381 &input.tools_mcp.workspace,
382 Some(input.tools_mcp.plugin_registry.as_ref()),
383 );
384 let persistence = SetupPersistenceFacts::from_paths(
385 input.config_path,
386 &input.tools_mcp.config,
387 &input.tools_mcp.codewhale_home,
388 );
389 let tools_mcp = tools_mcp::SetupToolsMcpFacts::from_probe_input(&input.tools_mcp);
390 let project_override_warning =
391 project_runtime_override_warning(&input.tools_mcp.workspace, input.locale);
392 let constitution_autonomy = user_constitution
393 .as_ref()
394 .and_then(|load| {
395 load.constitution().map(|constitution| {
396 autonomy_label(constitution.autonomy_preference, input.locale).to_string()
397 })
398 })
399 .unwrap_or_else(|| tr(input.locale, MessageId::SetupAutonomyUnspecified).to_string());
400 let constitution_file = SetupConstitutionFileState::load();
401 Self {
402 state,
403 expert_override,
404 roster,
405 persistence,
406 tools_mcp,
407 project_override_warning,
408 constitution_autonomy,
409 constitution_file,
410 }
411 }
412
413 fn fallback(locale: Locale) -> Self {
414 Self {
415 state: SetupState::default(),
416 expert_override: SetupExpertOverrideState::NotChecked,
417 roster: codewhale_engine::fleet::roster::FleetRoster::failed("setup probe task failed"),
418 persistence: SetupPersistenceFacts::default(),
419 tools_mcp: tools_mcp::SetupToolsMcpFacts::default(),
420 project_override_warning: None,
421 constitution_autonomy: tr(locale, MessageId::SetupAutonomyUnspecified).to_string(),
422 constitution_file: SetupConstitutionFileState::NotChecked,
423 }
424 }
425
426 async fn load(app: &App, config: &Config) -> Self {
427 let input = SetupDiskProbeInput::from_app_config(app, config);
428 match tokio::task::spawn_blocking(move || Self::collect(input)).await {
429 Ok(probes) => probes,
430 Err(error) => {
431 tracing::warn!(target: "tui::setup", %error, "setup probe task failed");
432 Self::fallback(app.ui_locale)
433 }
434 }
435 }
436 }
437
438 impl SetupRuntimeFacts {
439 fn from_app_config(app: &App, config: &Config) -> Self {
440 let probes = SetupDiskProbes::collect(SetupDiskProbeInput::from_app_config(app, config));
441 Self::from_app_config_with_probes(app, config, probes).1
442 }
443
444 fn from_app_config_with_probes(
445 app: &App,
446 config: &Config,
447 probes: SetupDiskProbes,
448 ) -> (SetupState, Self) {
449 let SetupDiskProbes {
450 state,
451 expert_override,
452 roster,
453 persistence,
454 tools_mcp,
455 project_override_warning,
456 constitution_autonomy,
457 constitution_file,
458 } = probes;
459 let readiness = app
460 .admitted_provider_identity()
461 .ok()
462 .filter(|identity| config.verify_provider_identity(identity).is_ok())
463 .map_or(
464 codewhale_engine::provider_readiness::ResolvedProviderReadiness::InvalidRoute,
465 |identity| {
466 codewhale_engine::provider_readiness::resolve_for_model(
467 config,
468 identity,
469 if app.auto_model { "auto" } else { &app.model },
470 &app.provider_health,
471 )
472 },
473 );
474 // A failed observed check remains retryable in route pickers, but the
475 // setup receipt must not certify it as healthy. Saved-unchecked and
476 // local-unchecked are honest reviewed configuration states; an actual
477 // session failure is NeedsAction until a later success replaces it.
478 let provider_status = provider::step_status(&readiness);
479 let provider_ready = matches!(
480 provider_status,
481 StepStatus::Configured | StepStatus::Verified
482 );
483 let model = app.model_display_label();
484 let provider_name = app
485 .admitted_provider_identity()
486 .map_or("unavailable", |identity| {
487 identity
488 .compatibility()
489 .map_or(identity.key.as_str(), |row| row.label)
490 })
491 .to_string();
492 let context_window = app.effective_context_window();
493 let context_window_source = app.effective_context_window_source().display_label();
494 let provider =
495 format!("{provider_name} · context {context_window} ({context_window_source})");
496 let auth = readiness.label().into_owned();
497 let health = if provider_ready {
498 format!("{}; route can be attempted", readiness.label())
499 } else if matches!(
500 &readiness,
501 codewhale_engine::provider_readiness::ResolvedProviderReadiness::SavedLastCheckFailed { .. }
502 ) {
503 format!("{}; retry or open /provider", readiness.label())
504 } else if app.api_provider == codewhale_config::ProviderKind::OpenaiCodex {
505 format!(
506 "{}; Sign in with ChatGPT via `codewhale auth chatgpt` or /provider setup openai-codex (subscription billing). Codex CLI import remains an explicit alternative.",
507 readiness.label()
508 )
509 } else if let Some(url) = codewhale_runtime::config::credential_help_for_provider_route(
510 app.api_provider,
511 &config.active_route_base_url(),
512 )
513 .credential_url
514 {
515 format!(
516 "{}; credentials: {url}; open /provider to repair the route",
517 readiness.label()
518 )
519 } else {
520 format!(
521 "{}; {}; open /provider to repair the route",
522 readiness.label(),
523 codewhale_runtime::config::credential_help_for_provider_route(
524 app.api_provider,
525 &config.active_route_base_url(),
526 )
527 .guidance
528 )
529 };
530 let provider_result = format!(
531 "provider={}, model={}, context_window={} ({}) auth={}, health={}",
532 app.provider_identity_for_persistence(),
533 model,
534 context_window,
535 context_window_source,
536 readiness.label(),
537 if provider_ready {
538 "attemptable"
539 } else {
540 "needs action"
541 }
542 );
543 let shell = if app.allow_shell { "enabled" } else { "hidden" }.to_string();
544 let trust = if app.trust_mode {
545 "trusted workspace / writes allowed by permissions"
546 } else {
547 "workspace trust not elevated"
548 }
549 .to_string();
550 let sandbox = config
551 .sandbox_mode
552 .as_deref()
553 .filter(|mode| !mode.trim().is_empty())
554 .unwrap_or("default")
555 .to_string();
556 let sandbox_mode_value = sandbox.clone();
557 let network_default_value = config
558 .network
559 .as_ref()
560 .map_or("prompt".to_string(), |policy| policy.default.clone());
561 let network = config
562 .network
563 .as_ref()
564 .map_or("prompt by default".to_string(), |policy| {
565 format!("default {}", policy.default)
566 });
567 let runtime_result = format!(
568 "intent={}, approval={}, shell={}, trust={}, sandbox={}, network={}",
569 app.mode.as_setting(),
570 app.approval_mode
571 .permission_chip_label()
572 .to_ascii_lowercase(),
573 if app.allow_shell { "enabled" } else { "hidden" },
574 if app.trust_mode {
575 "trusted"
576 } else {
577 "workspace"
578 },
579 sandbox,
580 network
581 );
582 let operate =
583 operate::SetupOperateFacts::from_app_config(app, config, provider_ready, &roster);
584 let known_hotbar_action_ids = app
585 .hotbar_actions
586 .iter()
587 .map(|action| action.id())
588 .collect::<Vec<_>>();
589 let hotbar_resolution = config.resolve_hotbar_bindings(&known_hotbar_action_ids);
590 let configured_hotbar_slots = config.hotbar.as_ref().map_or(0, Vec::len);
591 let hotbar_state = match config.hotbar.as_ref() {
592 None => "hidden",
593 Some(bindings) if bindings.is_empty() => "disabled",
594 Some(_) => "customized",
595 };
596 let active_hotbar_slots = hotbar_resolution.bindings.len();
597 let hotbar_warning_count = hotbar_resolution.warnings.len();
598 let hotbar_bindings_result = format!(
599 "{hotbar_state}; configured_slots={configured_hotbar_slots}; active_slots={active_hotbar_slots}; warnings={hotbar_warning_count}"
600 );
601 let hotbar_actions_result =
602 format!("{} bindable actions registered", app.hotbar_actions.len());
603 let hotbar_result = format!(
604 "state={hotbar_state}, configured_slots={configured_hotbar_slots}, active_slots={active_hotbar_slots}, actions={}, warnings={hotbar_warning_count}",
605 app.hotbar_actions.len()
606 );
607 let tools_mcp_servers_result = tools_mcp.servers_result;
608 let tools_mcp_skills_result = tools_mcp.skills_result;
609 let tools_mcp_tools_result = tools_mcp.tools_result;
610 let tools_mcp_plugins_result = tools_mcp.plugins_result;
611 let tools_mcp_hotbar_result = tools_mcp.hotbar_result;
612 let tools_mcp_dsh_result = tools_mcp.dsh_result;
613 let tools_mcp_result = tools_mcp.result;
614 let tools_mcp_needs_action = tools_mcp.needs_action;
615 let tools_mcp_path_display = tools_mcp.mcp_path_display;
616 let tools_mcp_skills_path_display = tools_mcp.skills_path_display;
617 let tools_mcp_plugins_path_display = tools_mcp.plugins_path_display;
618 let remote = SetupRemoteFacts::from_app(app);
619 let remote_needs_action = remote.needs_action();
620 (
621 state,
622 Self {
623 provider,
624 model,
625 auth,
626 health,
627 provider_ready,
628 provider_status,
629 provider_result,
630 work_intent: app.mode.display_name_localized(app.ui_locale).into_owned(),
631 approval: app
632 .approval_mode
633 .permission_chip_label()
634 .to_ascii_lowercase(),
635 shell,
636 allow_shell_enabled: app.allow_shell,
637 trust,
638 sandbox,
639 sandbox_mode_value,
640 network,
641 network_default_value,
642 runtime_result,
643 operate_runtime_ready: operate.runtime_ready,
644 operate_runtime_result: operate.runtime_result,
645 fleet_roster_ready: operate.roster_ready,
646 fleet_roster_result: operate.roster_result,
647 operate_concurrency_result: operate.concurrency_result,
648 operate_result: operate.result,
649 hotbar_bindings_result,
650 hotbar_actions_result,
651 hotbar_result,
652 tools_mcp_servers_result,
653 tools_mcp_skills_result,
654 tools_mcp_tools_result,
655 tools_mcp_plugins_result,
656 tools_mcp_hotbar_result,
657 tools_mcp_dsh_result,
658 tools_mcp_result,
659 tools_mcp_needs_action,
660 tools_mcp_path_display,
661 tools_mcp_skills_path_display,
662 tools_mcp_plugins_path_display,
663 remote_clouds_result: remote.clouds_result,
664 remote_bridges_result: remote.bridges_result,
665 remote_providers_result: remote.providers_result,
666 remote_mode_result: remote.mode_result,
667 remote_command_provider: remote.command_provider,
668 remote_result: remote.result,
669 remote_control_result: {
670 use codewhale_app_server::remote_control::Status;
671 let message = match app.remote_control.status() {
672 Status::Connected => MessageId::SetupRemoteStatusReady,
673 Status::Connecting | Status::Stopping => MessageId::SetupStatusInProgress,
674 Status::Failed => MessageId::SetupRemoteStatusNeedsAction,
675 Status::Off => MessageId::SetupRemoteStatusDisabled,
676 };
677 tr(app.ui_locale, message).into_owned()
678 },
679 remote_needs_action,
680 remote_modes: remote.modes,
681 persistence,
682 default_mode: app.mode.as_setting().to_string(),
683 approval_policy_value: config
684 .approval_policy
685 .as_deref()
686 .filter(|policy| !policy.trim().is_empty())
687 .unwrap_or("on-request")
688 .to_string(),
689 project_override_warning,
690 constitution_autonomy,
691 constitution_file,
692 expert_override,
693 },
694 )
695 }
696 }
697
698 fn setup_codewhale_home_dir() -> std::path::PathBuf {
699 codewhale_config::codewhale_home().unwrap_or_else(|_| {
700 codewhale_paths::user_home().map_or_else(
701 || std::path::PathBuf::from(".codewhale"),
702 |home| home.join(".codewhale"),
703 )
704 })
705 }
706
707 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
708 pub enum SetupRuntimePreset {
709 AskFirst,
710 #[default]
711 NormalAgent,
712 HighTrustLocal,
713 }
714
715 impl SetupRuntimePreset {
716 const ALL: [Self; 3] = [Self::AskFirst, Self::NormalAgent, Self::HighTrustLocal];
717
718 fn from_key(key: char) -> Option<Self> {
719 match key {
720 '1' => Some(Self::AskFirst),
721 '2' => Some(Self::NormalAgent),
722 '3' => Some(Self::HighTrustLocal),
723 _ => None,
724 }
725 }
726
727 pub fn id(self) -> &'static str {
728 match self {
729 Self::AskFirst => "ask-first",
730 Self::NormalAgent => "normal-agent",
731 Self::HighTrustLocal => "high-trust-local",
732 }
733 }
734
735 fn title_id(self) -> MessageId {
736 match self {
737 Self::AskFirst => MessageId::SetupRuntimePresetAskFirstTitle,
738 Self::NormalAgent => MessageId::SetupRuntimePresetNormalAgentTitle,
739 Self::HighTrustLocal => MessageId::SetupRuntimePresetHighTrustTitle,
740 }
741 }
742
743 fn description_id(self) -> MessageId {
744 match self {
745 Self::AskFirst => MessageId::SetupRuntimePresetAskFirstDescription,
746 Self::NormalAgent => MessageId::SetupRuntimePresetNormalAgentDescription,
747 Self::HighTrustLocal => MessageId::SetupRuntimePresetHighTrustDescription,
748 }
749 }
750
751 pub fn default_mode(self) -> &'static str {
752 match self {
753 Self::AskFirst => "plan",
754 Self::NormalAgent | Self::HighTrustLocal => "agent",
755 }
756 }
757
758 pub fn permission_posture(self) -> &'static str {
759 match self {
760 Self::AskFirst => "ask",
761 Self::NormalAgent => "accept-edits",
762 Self::HighTrustLocal => "full-access",
763 }
764 }
765
766 pub fn approval_policy(self) -> Option<&'static str> {
767 match self {
768 Self::AskFirst => Some("on-request"),
769 Self::NormalAgent => Some("accept-edits"),
770 // Full Access lives in TUI settings; it is intentionally not a
771 // top-level approval_policy value.
772 Self::HighTrustLocal => None,
773 }
774 }
775
776 pub fn allow_shell(self) -> bool {
777 match self {
778 Self::AskFirst => false,
779 Self::NormalAgent | Self::HighTrustLocal => true,
780 }
781 }
782
783 pub fn sandbox_mode(self) -> &'static str {
784 match self {
785 Self::AskFirst => "read-only",
786 Self::NormalAgent => "workspace-write",
787 Self::HighTrustLocal => "danger-full-access",
788 }
789 }
790
791 pub fn result_summary(self) -> String {
792 let approval = self
793 .approval_policy()
794 .unwrap_or("unset (Full Access saved in TUI settings)");
795 format!(
796 "preset={}, default_mode={}, permission_posture={}, approval_policy={}, allow_shell={}, sandbox_mode={}, network=unchanged, trust=unchanged",
797 self.id(),
798 self.display_mode(),
799 self.permission_posture(),
800 approval,
801 self.allow_shell(),
802 self.sandbox_mode()
803 )
804 }
805
806 fn display_mode(self) -> &'static str {
807 match self {
808 Self::AskFirst => "plan",
809 Self::NormalAgent => "act",
810 Self::HighTrustLocal => "act + full-access",
811 }
812 }
813 }
814
815 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
816 enum SetupConstitutionFileState {
817 NotChecked,
818 Missing,
819 Loaded,
820 Empty,
821 Invalid,
822 Unreadable,
823 PathError,
824 }
825
826 impl SetupConstitutionFileState {
827 fn load() -> Self {
828 match UserConstitution::path() {
829 Ok(path) => Self::from_load(&UserConstitution::load_from(&path)),
830 Err(_) => Self::PathError,
831 }
832 }
833
834 fn from_load(load: &UserConstitutionLoad) -> Self {
835 match load {
836 UserConstitutionLoad::Missing => Self::Missing,
837 UserConstitutionLoad::Empty => Self::Empty,
838 UserConstitutionLoad::Invalid(_) => Self::Invalid,
839 UserConstitutionLoad::Unreadable(_) => Self::Unreadable,
840 UserConstitutionLoad::Loaded(_) => Self::Loaded,
841 }
842 }
843
844 fn label(self, choice: ConstitutionChoice, locale: Locale) -> Cow<'static, str> {
845 let id = match self {
846 Self::NotChecked => MessageId::SetupConstitutionFileNotChecked,
847 Self::Missing => MessageId::SetupConstitutionFileMissing,
848 Self::Loaded if choice == ConstitutionChoice::GuidedCustom => {
849 MessageId::SetupConstitutionFileLoadedSelected
850 }
851 Self::Loaded if choice.is_explicit() => MessageId::SetupConstitutionFileLoadedInactive,
852 Self::Loaded => MessageId::SetupConstitutionFileLoadedUnselected,
853 Self::Empty => MessageId::SetupConstitutionFileEmpty,
854 Self::Invalid => MessageId::SetupConstitutionFileInvalid,
855 Self::Unreadable => MessageId::SetupConstitutionFileUnreadable,
856 Self::PathError => MessageId::SetupConstitutionFilePathError,
857 };
858 tr(locale, id)
859 }
860 }
861
862 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
863 enum SetupExpertOverrideState {
864 NotChecked,
865 Missing,
866 Active,
867 Disabled,
868 Empty,
869 Unreadable,
870 PathError,
871 }
872
873 const EXPERT_OVERRIDE_MAX_BYTES: u64 = 1024 * 1024;
874
875 impl SetupExpertOverrideState {
876 fn load() -> Self {
877 let Some(path) = expert_override_path() else {
878 return Self::PathError;
879 };
880 let read = std::fs::File::open(&path).and_then(|file| {
881 use std::io::Read as _;
882 let mut raw = String::new();
883 file.take(EXPERT_OVERRIDE_MAX_BYTES + 1)
884 .read_to_string(&mut raw)?;
885 Ok(raw)
886 });
887 match read {
888 Ok(raw) if raw.len() as u64 > EXPERT_OVERRIDE_MAX_BYTES => Self::Unreadable,
889 Ok(raw) if raw.trim().is_empty() => Self::Empty,
890 Ok(_) if base_prompt_override_opt_in() => Self::Active,
891 Ok(_) => Self::Disabled,
892 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Self::Missing,
893 Err(_) => Self::Unreadable,
894 }
895 }
896
897 fn is_active(self) -> bool {
898 matches!(self, Self::Active)
899 }
900
901 fn label(self, locale: Locale) -> Cow<'static, str> {
902 match self {
903 Self::NotChecked => tr(locale, MessageId::SetupExpertOverrideNotChecked),
904 Self::Missing => tr(locale, MessageId::SetupExpertOverrideMissing),
905 Self::Active => tr(locale, MessageId::SetupExpertOverrideActive),
906 Self::Disabled => tr(locale, MessageId::SetupExpertOverrideDisabled)
907 .replace("{env}", BASE_PROMPT_OVERRIDE_OPT_IN_ENV)
908 .into(),
909 Self::Empty => tr(locale, MessageId::SetupExpertOverrideEmpty),
910 Self::Unreadable => tr(locale, MessageId::SetupExpertOverrideUnreadable),
911 Self::PathError => tr(locale, MessageId::SetupExpertOverridePathError),
912 }
913 }
914 }
915
916 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
917 pub(crate) struct GuidedConstitutionDraft {
918 purpose: GuidedPurpose,
919 autonomy: AutonomyPreference,
920 evidence: GuidedEvidence,
921 communication: GuidedCommunication,
922 privacy: GuidedPrivacy,
923 principles: GuidedPrinciples,
924 }
925
926 impl Default for GuidedConstitutionDraft {
927 fn default() -> Self {
928 Self {
929 purpose: GuidedPurpose::Coding,
930 autonomy: AutonomyPreference::Balanced,
931 evidence: GuidedEvidence::TestsAndReceipts,
932 communication: GuidedCommunication::Concise,
933 privacy: GuidedPrivacy::StandardCare,
934 principles: GuidedPrinciples::ScopedChanges,
935 }
936 }
937 }
938
939 impl GuidedConstitutionDraft {
940 fn cycle(&mut self, key: char) -> bool {
941 match key {
942 '1' => self.purpose = self.purpose.next(),
943 '2' => self.autonomy = next_guided_autonomy(self.autonomy),
944 '3' => self.evidence = self.evidence.next(),
945 '4' => self.communication = self.communication.next(),
946 '5' => self.privacy = self.privacy.next(),
947 '6' => self.principles = self.principles.next(),
948 _ => return false,
949 }
950 true
951 }
952
953 fn to_constitution_with_freeform(
954 self,
955 locale: Locale,
956 freeform_note: Option<&str>,
957 ) -> UserConstitution {
958 let mut notes = self.notes(locale);
959 if let Some(note) = freeform_note.map(str::trim).filter(|note| !note.is_empty()) {
960 let own_words = match locale {
961 Locale::Ja => format!(
962 "\nユーザー自由原則:{}",
963 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
964 ),
965 Locale::ZhHans => format!(
966 "\n用户自定义准则:{}",
967 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
968 ),
969 Locale::ZhHant => format!(
970 "\n使用者自由原則:{}",
971 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
972 ),
973 Locale::PtBr => format!(
974 "\nPrincípio livre do usuário: {}",
975 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
976 ),
977 Locale::Es419 => format!(
978 "\nPrincipio libre del usuario: {}",
979 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
980 ),
981 Locale::Vi => format!(
982 "\nNguyên tắc tự do của người dùng: {}",
983 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
984 ),
985 Locale::Ko => format!(
986 "\n사용자 자유 원칙: {}",
987 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
988 ),
989 Locale::Ca => format!(
990 "\nPrincipi lliure de l'usuari: {}",
991 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
992 ),
993 Locale::De => format!(
994 "\nFreitext-Prinzip des Nutzers: {}",
995 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
996 ),
997 Locale::Fr => format!(
998 "\nPrincipe en texte libre de l'utilisateur : {}",
999 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
1000 ),
1001 Locale::Id => format!(
1002 "\nPrinsip bebas pengguna: {}",
1003 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
1004 ),
1005 Locale::Hi => format!(
1006 "\nउपयोगकर्ता मुक्त-पाठ सिद्धांत: {}",
1007 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
1008 ),
1009 Locale::Ru => format!(
1010 "\nСвободный принцип пользователя: {}",
1011 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
1012 ),
1013 Locale::Uk => format!(
1014 "\nВільний принцип користувача: {}",
1015 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
1016 ),
1017 _ => format!(
1018 "\nUser freeform principle: {}",
1019 bounded_freeform_note(note, FREEFORM_NOTE_MAX)
1020 ),
1021 };
1022 notes.push_str(&own_words);
1023 }
1024 UserConstitution {
1025 language: Some(locale.tag().to_string()),
1026 about: Some(self.purpose.about(locale).to_string()),
1027 working_style: vec![
1028 self.purpose.working_style(locale).to_string(),
1029 self.communication.working_style(locale).to_string(),
1030 self.evidence.working_style(locale).to_string(),
1031 self.privacy.working_style(locale).to_string(),
1032 ],
1033 priorities: vec![
1034 authority_priority(locale).to_string(),
1035 autonomy_priority(self.autonomy, locale).to_string(),
1036 self.privacy.escalation_rule(locale).to_string(),
1037 ],
1038 autonomy_preference: self.autonomy,
1039 notes: Some(notes),
1040 ..UserConstitution::default()
1041 }
1042 }
1043
1044 fn notes(self, locale: Locale) -> String {
1045 let notes = tr(locale, MessageId::SetupGuidedNotes);
1046 notes
1047 .replace("{purpose}", &self.purpose.label(locale))
1048 .replace("{initiative}", autonomy_label(self.autonomy, locale))
1049 .replace("{evidence}", &self.evidence.label(locale))
1050 .replace("{communication}", self.communication.label(locale))
1051 .replace("{privacy}", self.privacy.label(locale))
1052 .replace("{principles}", self.principles.label(locale))
1053 .replace("{notes}", self.principles.note(locale))
1054 .to_string()
1055 }
1056 }
1057
1058 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1059 enum GuidedPurpose {
1060 Coding,
1061 Research,
1062 Operations,
1063 Mixed,
1064 }
1065
1066 impl GuidedPurpose {
1067 fn next(self) -> Self {
1068 match self {
1069 Self::Coding => Self::Research,
1070 Self::Research => Self::Operations,
1071 Self::Operations => Self::Mixed,
1072 Self::Mixed => Self::Coding,
1073 }
1074 }
1075
1076 fn label(self, locale: Locale) -> Cow<'static, str> {
1077 match self {
1078 Self::Coding => tr(locale, MessageId::SetupGuidedPurposeCoding),
1079 Self::Research => tr(locale, MessageId::SetupGuidedPurposeResearch),
1080 Self::Operations => tr(locale, MessageId::SetupGuidedPurposeOperations),
1081 Self::Mixed => tr(locale, MessageId::SetupGuidedPurposeMixed),
1082 }
1083 }
1084
1085 fn about(self, locale: Locale) -> Cow<'static, str> {
1086 match self {
1087 Self::Coding => tr(locale, MessageId::SetupGuidedPurposeAboutCoding),
1088 Self::Research => tr(locale, MessageId::SetupGuidedPurposeAboutResearch),
1089 Self::Operations => tr(locale, MessageId::SetupGuidedPurposeAboutOperations),
1090 Self::Mixed => tr(locale, MessageId::SetupGuidedPurposeAboutMixed),
1091 }
1092 }
1093
1094 fn working_style(self, locale: Locale) -> Cow<'static, str> {
1095 match self {
1096 Self::Coding => tr(locale, MessageId::SetupGuidedStyleCoding),
1097 Self::Research => tr(locale, MessageId::SetupGuidedStyleResearch),
1098 Self::Operations => tr(locale, MessageId::SetupGuidedStyleOperations),
1099 Self::Mixed => tr(locale, MessageId::SetupGuidedStyleMixed),
1100 }
1101 }
1102 }
1103
1104 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1105 enum GuidedEvidence {
1106 Assumptions,
1107 TestsAndReceipts,
1108 ReleaseReceipts,
1109 }
1110
1111 impl GuidedEvidence {
1112 fn next(self) -> Self {
1113 match self {
1114 Self::Assumptions => Self::TestsAndReceipts,
1115 Self::TestsAndReceipts => Self::ReleaseReceipts,
1116 Self::ReleaseReceipts => Self::Assumptions,
1117 }
1118 }
1119
1120 fn label(self, locale: Locale) -> Cow<'static, str> {
1121 match self {
1122 Self::Assumptions => tr(locale, MessageId::SetupGuidedEvidenceAssumptions),
1123 Self::TestsAndReceipts => tr(locale, MessageId::SetupGuidedEvidenceTestsAndReceipts),
1124 Self::ReleaseReceipts => tr(locale, MessageId::SetupGuidedEvidenceReleaseReceipts),
1125 }
1126 }
1127
1128 fn working_style(self, locale: Locale) -> &'static str {
1129 match (locale, self) {
1130 (Locale::Ja, Self::Assumptions) => {
1131 "完了を主張する前に、前提、不明点、残るリスクを要約する。"
1132 }
1133 (Locale::Ja, Self::TestsAndReceipts) => {
1134 "不確実性を減らせるときは、コマンド、テスト、スクリーンショット、引用で具体的に検証する。"
1135 }
1136 (Locale::Ja, Self::ReleaseReceipts) => {
1137 "重要な主張とリリース証拠には、ファイル、コマンド、スクリーンショット、CI、出典を示す。"
1138 }
1139 (Locale::ZhHans, Self::Assumptions) => "在宣称完成前总结假设、未知和剩余风险。",
1140 (Locale::ZhHans, Self::TestsAndReceipts) => {
1141 "在能降低不确定性时,用命令、测试、截图或引用给出具体验证。"
1142 }
1143 (Locale::ZhHans, Self::ReleaseReceipts) => {
1144 "对重要结论和发布证据标注文件、命令、截图、CI 或来源。"
1145 }
1146 (Locale::ZhHant, Self::Assumptions) => "在宣稱完成前總結假設、未知和剩餘風險。",
1147 (Locale::ZhHant, Self::TestsAndReceipts) => {
1148 "在能降低不確定性時,用命令、測試、截圖或引用給出具體驗證。"
1149 }
1150 (Locale::ZhHant, Self::ReleaseReceipts) => {
1151 "對重要結論和發布證據標註檔案、命令、截圖、CI 或來源。"
1152 }
1153 (Locale::PtBr, Self::Assumptions) => {
1154 "Resuma premissas, desconhecidos e risco restante antes de dizer que concluiu."
1155 }
1156 (Locale::PtBr, Self::TestsAndReceipts) => {
1157 "Use comandos, testes, screenshots ou citações quando reduzirem a incerteza."
1158 }
1159 (Locale::PtBr, Self::ReleaseReceipts) => {
1160 "Cite arquivos, comandos, screenshots, CI ou fontes para afirmações materiais e evidência de release."
1161 }
1162 (Locale::Es419, Self::Assumptions) => {
1163 "Resume supuestos, incógnitas y riesgo restante antes de afirmar que terminaste."
1164 }
1165 (Locale::Es419, Self::TestsAndReceipts) => {
1166 "Usa comandos, pruebas, capturas o citas cuando reduzcan materialmente la incertidumbre."
1167 }
1168 (Locale::Es419, Self::ReleaseReceipts) => {
1169 "Cita archivos, comandos, capturas, CI o fuentes para afirmaciones materiales y evidencia de release."
1170 }
1171 (Locale::Vi, Self::Assumptions) => {
1172 "Tóm tắt giả định, điều chưa biết và rủi ro còn lại trước khi tuyên bố hoàn tất."
1173 }
1174 (Locale::Vi, Self::TestsAndReceipts) => {
1175 "Dùng lệnh, kiểm thử, ảnh chụp hoặc trích dẫn khi chúng giảm đáng kể bất định."
1176 }
1177 (Locale::Vi, Self::ReleaseReceipts) => {
1178 "Trích dẫn tệp, lệnh, ảnh chụp, CI hoặc nguồn cho tuyên bố quan trọng và bằng chứng phát hành."
1179 }
1180 (Locale::Ko, Self::Assumptions) => {
1181 "완료를 주장하기 전에 가정, 불확실한 점, 남은 위험을 요약한다."
1182 }
1183 (Locale::Ko, Self::TestsAndReceipts) => {
1184 "불확실성을 실질적으로 줄일 수 있을 때는 명령어, 테스트, 스크린샷, 인용으로 구체적으로 검증한다."
1185 }
1186 (Locale::Ko, Self::ReleaseReceipts) => {
1187 "중요한 주장과 릴리스 근거에는 파일 경로, 명령어, 스크린샷, CI, 출처를 제시한다."
1188 }
1189 (Locale::Ca, Self::Assumptions) => {
1190 "Resumeix supòsits, incògnites i risc pendent abans de dir que has acabat."
1191 }
1192 (Locale::Ca, Self::TestsAndReceipts) => {
1193 "Fes servir ordres, tests, captures de pantalla o citacions quan redueixin materialment la incertesa."
1194 }
1195 (Locale::Ca, Self::ReleaseReceipts) => {
1196 "Cita rutes de fitxers, ordres, captures de pantalla, CI o fonts per a afirmacions materials i evidència de release."
1197 }
1198 (Locale::De, Self::Assumptions) => {
1199 "Fasse Annahmen, Unbekannte und Restrisiken zusammen, bevor du Fertigstellung behauptest."
1200 }
1201 (Locale::De, Self::TestsAndReceipts) => {
1202 "Nutze Befehle, Tests, Screenshots oder Zitate, wenn sie die Unsicherheit wesentlich verringern."
1203 }
1204 (Locale::De, Self::ReleaseReceipts) => {
1205 "Nenne Dateipfade, Befehle, Screenshots, CI oder Quellen für wesentliche Aussagen und Release-Nachweise."
1206 }
1207 (Locale::Fr, Self::Assumptions) => {
1208 "Résumez les hypothèses, les inconnues et le risque restant avant d'annoncer la fin du travail."
1209 }
1210 (Locale::Fr, Self::TestsAndReceipts) => {
1211 "Utilisez commandes, tests, captures d'écran ou citations quand ils réduisent sensiblement l'incertitude."
1212 }
1213 (Locale::Fr, Self::ReleaseReceipts) => {
1214 "Citez chemins de fichiers, commandes, captures d'écran, CI ou sources pour les affirmations importantes et les preuves de release."
1215 }
1216 (Locale::Id, Self::Assumptions) => {
1217 "Ringkas asumsi, hal yang belum diketahui, dan risiko tersisa sebelum mengklaim selesai."
1218 }
1219 (Locale::Id, Self::TestsAndReceipts) => {
1220 "Gunakan perintah, tes, tangkapan layar, atau kutipan bila secara nyata mengurangi ketidakpastian."
1221 }
1222 (Locale::Id, Self::ReleaseReceipts) => {
1223 "Kutip path file, perintah, tangkapan layar, CI, atau sumber untuk klaim material dan bukti rilis."
1224 }
1225 (Locale::Hi, Self::Assumptions) => {
1226 "पूर्णता का दावा करने से पहले धारणाएँ, अज्ञात बातें और शेष जोखिम सारांशित करें।"
1227 }
1228 (Locale::Hi, Self::TestsAndReceipts) => {
1229 "जब वे अनिश्चितता सार्थक रूप से घटाएँ तो कमांड, टेस्ट, स्क्रीनशॉट या उद्धरण उपयोग करें।"
1230 }
1231 (Locale::Hi, Self::ReleaseReceipts) => {
1232 "महत्वपूर्ण दावों और रिलीज़ साक्ष्य के लिए फ़ाइल पथ, कमांड, स्क्रीनशॉट, CI या स्रोत उद्धृत करें।"
1233 }
1234 (Locale::Ru, Self::Assumptions) => {
1235 "Прежде чем заявить о завершении, перечислите предположения, неизвестные и оставшиеся риски."
1236 }
1237 (Locale::Ru, Self::TestsAndReceipts) => {
1238 "Используйте команды, тесты, скриншоты или цитаты, когда они существенно снижают неопределённость."
1239 }
1240 (Locale::Ru, Self::ReleaseReceipts) => {
1241 "Указывайте пути файлов, команды, скриншоты, CI или источники для существенных утверждений и доказательств релиза."
1242 }
1243 (Locale::Uk, Self::Assumptions) => {
1244 "Перш ніж заявити про завершення, підсумуйте припущення, невідомі та залишкові ризики."
1245 }
1246 (Locale::Uk, Self::TestsAndReceipts) => {
1247 "Використовуйте команди, тести, скриншоти або цитати, коли вони суттєво зменшують невизначеність."
1248 }
1249 (Locale::Uk, Self::ReleaseReceipts) => {
1250 "Посилайтеся на шляхи файлів, команди, скриншоти, CI або джерела для суттєвих тверджень і доказів релізу."
1251 }
1252 (_, Self::Assumptions) => {
1253 "Summarize assumptions, unknowns, and remaining risk before claiming completion."
1254 }
1255 (_, Self::TestsAndReceipts) => {
1256 "Use commands, tests, screenshots, or citations when they materially reduce uncertainty."
1257 }
1258 (_, Self::ReleaseReceipts) => {
1259 "Cite file paths, commands, screenshots, CI, or sources for material claims and release evidence."
1260 }
1261 }
1262 }
1263 }
1264
1265 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1266 enum GuidedCommunication {
1267 Concise,
1268 Teaching,
1269 Direct,
1270 }
1271
1272 impl GuidedCommunication {
1273 fn next(self) -> Self {
1274 match self {
1275 Self::Concise => Self::Teaching,
1276 Self::Teaching => Self::Direct,
1277 Self::Direct => Self::Concise,
1278 }
1279 }
1280
1281 fn label(self, locale: Locale) -> &'static str {
1282 match (locale, self) {
1283 (Locale::Ja, Self::Concise) => "簡潔",
1284 (Locale::Ja, Self::Teaching) => "説明重視",
1285 (Locale::Ja, Self::Direct) => "直接的",
1286 (Locale::ZhHans, Self::Concise) => "简洁",
1287 (Locale::ZhHans, Self::Teaching) => "教学式",
1288 (Locale::ZhHans, Self::Direct) => "直接",
1289 (Locale::ZhHant, Self::Concise) => "簡潔",
1290 (Locale::ZhHant, Self::Teaching) => "教學式",
1291 (Locale::ZhHant, Self::Direct) => "直接",
1292 (Locale::PtBr, Self::Concise) => "conciso",
1293 (Locale::PtBr, Self::Teaching) => "didático",
1294 (Locale::PtBr, Self::Direct) => "direto",
1295 (Locale::Es419, Self::Concise) => "conciso",
1296 (Locale::Es419, Self::Teaching) => "didáctico",
1297 (Locale::Es419, Self::Direct) => "directo",
1298 (Locale::Vi, Self::Concise) => "ngắn gọn",
1299 (Locale::Vi, Self::Teaching) => "giảng giải",
1300 (Locale::Vi, Self::Direct) => "trực tiếp",
1301 (Locale::Ko, Self::Concise) => "간결함",
1302 (Locale::Ko, Self::Teaching) => "설명 중심",
1303 (Locale::Ko, Self::Direct) => "직설적",
1304 (Locale::Ca, Self::Concise) => "concís",
1305 (Locale::Ca, Self::Teaching) => "didàctic",
1306 (Locale::Ca, Self::Direct) => "directe",
1307 (Locale::De, Self::Concise) => "prägnant",
1308 (Locale::De, Self::Teaching) => "lehrend",
1309 (Locale::De, Self::Direct) => "direkt",
1310 (Locale::Fr, Self::Concise) => "concis",
1311 (Locale::Fr, Self::Teaching) => "pédagogique",
1312 (Locale::Fr, Self::Direct) => "direct",
1313 (Locale::Id, Self::Concise) => "ringkas",
1314 (Locale::Id, Self::Teaching) => "mengajar",
1315 (Locale::Id, Self::Direct) => "langsung",
1316 (Locale::Hi, Self::Concise) => "संक्षिप्त",
1317 (Locale::Hi, Self::Teaching) => "शिक्षणपरक",
1318 (Locale::Hi, Self::Direct) => "सीधा",
1319 (Locale::Ru, Self::Concise) => "краткий",
1320 (Locale::Ru, Self::Teaching) => "обучающий",
1321 (Locale::Ru, Self::Direct) => "прямой",
1322 (Locale::Uk, Self::Concise) => "стислий",
1323 (Locale::Uk, Self::Teaching) => "навчальний",
1324 (Locale::Uk, Self::Direct) => "прямий",
1325 (_, Self::Concise) => "concise",
1326 (_, Self::Teaching) => "teaching",
1327 (_, Self::Direct) => "direct",
1328 }
1329 }
1330
1331 fn working_style(self, locale: Locale) -> &'static str {
1332 match (locale, self) {
1333 (Locale::Ja, Self::Concise) => "更新は簡潔にし、重要なトレードオフだけ短く説明する。",
1334 (Locale::Ja, Self::Teaching) => {
1335 "重要な推論とトレードオフを、ユーザーが仕組みを理解できる程度に説明する。"
1336 }
1337 (Locale::Ja, Self::Direct) => {
1338 "阻塞、リスク、不確実性を直接述べ、装飾的な文案を避ける。"
1339 }
1340 (Locale::ZhHans, Self::Concise) => "保持更新简洁,并只解释重要取舍。",
1341 (Locale::ZhHans, Self::Teaching) => "解释关键推理和取舍,让用户能理解系统。",
1342 (Locale::ZhHans, Self::Direct) => "直接说明阻塞、风险和不确定性,避免装饰性文案。",
1343 (Locale::ZhHant, Self::Concise) => "保持更新簡潔,並只解釋重要取捨。",
1344 (Locale::ZhHant, Self::Teaching) => "解釋關鍵推理和取捨,讓使用者能理解系統。",
1345 (Locale::ZhHant, Self::Direct) => "直接說明阻塞、風險和不確定性,避免裝飾性文案。",
1346 (Locale::PtBr, Self::Concise) => {
1347 "Mantenha atualizações concisas e explique brevemente só os tradeoffs importantes."
1348 }
1349 (Locale::PtBr, Self::Teaching) => {
1350 "Explique raciocínio e tradeoffs principais o bastante para o usuário entender o sistema."
1351 }
1352 (Locale::PtBr, Self::Direct) => {
1353 "Seja direto sobre bloqueios, risco e incerteza; evite texto ornamental."
1354 }
1355 (Locale::Es419, Self::Concise) => {
1356 "Mantén las actualizaciones concisas y explica brevemente solo los tradeoffs importantes."
1357 }
1358 (Locale::Es419, Self::Teaching) => {
1359 "Explica el razonamiento y los tradeoffs clave lo suficiente para que el usuario entienda el sistema."
1360 }
1361 (Locale::Es419, Self::Direct) => {
1362 "Sé directo sobre bloqueos, riesgo e incertidumbre; evita texto ornamental."
1363 }
1364 (Locale::Vi, Self::Concise) => {
1365 "Giữ cập nhật ngắn gọn và chỉ giải thích ngắn các đánh đổi quan trọng."
1366 }
1367 (Locale::Vi, Self::Teaching) => {
1368 "Giải thích suy luận và đánh đổi chính đủ để người dùng hiểu hệ thống."
1369 }
1370 (Locale::Vi, Self::Direct) => {
1371 "Nói thẳng về điểm chặn, rủi ro và bất định; tránh câu chữ trang trí."
1372 }
1373 (Locale::Ko, Self::Concise) => {
1374 "업데이트는 간결하게 유지하고, 중요한 트레이드오프만 짧게 설명한다."
1375 }
1376 (Locale::Ko, Self::Teaching) => {
1377 "사용자가 시스템을 이해할 수 있을 만큼 핵심 추론과 트레이드오프를 설명한다."
1378 }
1379 (Locale::Ko, Self::Direct) => {
1380 "차단 요인, 위험, 불확실성을 직설적으로 말하고 장식적인 표현은 피한다."
1381 }
1382 (Locale::Ca, Self::Concise) => {
1383 "Mantén les actualitzacions concises i explica breument només els compromisos importants."
1384 }
1385 (Locale::Ca, Self::Teaching) => {
1386 "Explica el raonament i els compromisos clau prou perquè l'usuari pugui entendre el sistema."
1387 }
1388 (Locale::Ca, Self::Direct) => {
1389 "Sigues directe sobre bloquejos, risc i incertesa; evita el text ornamental."
1390 }
1391 (Locale::De, Self::Concise) => {
1392 "Halte Aktualisierungen knapp und erkläre wichtige Trade-offs nur kurz."
1393 }
1394 (Locale::De, Self::Teaching) => {
1395 "Erkläre zentrale Begründungen und Trade-offs so weit, dass der Nutzer das System verstehen kann."
1396 }
1397 (Locale::De, Self::Direct) => {
1398 "Sei direkt bei Blockern, Risiken und Unsicherheit; vermeide dekorative Formulierungen."
1399 }
1400 (Locale::Fr, Self::Concise) => {
1401 "Gardez les mises à jour concises et n'expliquez que brièvement les arbitrages importants."
1402 }
1403 (Locale::Fr, Self::Teaching) => {
1404 "Expliquez le raisonnement et les arbitrages clés assez pour que l'utilisateur comprenne le système."
1405 }
1406 (Locale::Fr, Self::Direct) => {
1407 "Soyez direct sur les blocages, les risques et l'incertitude ; évitez le texte ornemental."
1408 }
1409 (Locale::Id, Self::Concise) => {
1410 "Jaga pembaruan tetap ringkas dan jelaskan tradeoff penting secara singkat."
1411 }
1412 (Locale::Id, Self::Teaching) => {
1413 "Jelaskan penalaran dan tradeoff kunci secukupnya agar pengguna dapat memahami sistem."
1414 }
1415 (Locale::Id, Self::Direct) => {
1416 "Bicara langsung soal penghambat, risiko, dan ketidakpastian; hindari teks hiasan."
1417 }
1418 (Locale::Hi, Self::Concise) => "अपडेट संक्षिप्त रखें और महत्वपूर्ण ट्रेडऑफ़ संक्षेप में समझाएँ।",
1419 (Locale::Hi, Self::Teaching) => {
1420 "मुख्य तर्क और ट्रेडऑफ़ इतना समझाएँ कि उपयोगकर्ता सिस्टम समझ सके।"
1421 }
1422 (Locale::Hi, Self::Direct) => {
1423 "रुकावटों, जोखिम और अनिश्चितता के बारे में सीधे बोलें; सजावटी भाषा से बचें।"
1424 }
1425 (Locale::Ru, Self::Concise) => {
1426 "Держите обновления краткими и лишь коротко поясняйте важные компромиссы."
1427 }
1428 (Locale::Ru, Self::Teaching) => {
1429 "Объясняйте ключевые рассуждения и компромиссы настолько, чтобы пользователь мог понять систему."
1430 }
1431 (Locale::Ru, Self::Direct) => {
1432 "Говорите прямо о блокерах, рисках и неопределённости; избегайте декоративных формулировок."
1433 }
1434 (Locale::Uk, Self::Concise) => {
1435 "Тримайте оновлення стислими й лише коротко пояснюйте важливі компроміси."
1436 }
1437 (Locale::Uk, Self::Teaching) => {
1438 "Пояснюйте ключові міркування та компроміси настільки, щоб користувач міг зрозуміти систему."
1439 }
1440 (Locale::Uk, Self::Direct) => {
1441 "Говоріть прямо про блокери, ризики та невизначеність; уникайте декоративних формулювань."
1442 }
1443 (_, Self::Concise) => "Keep updates concise and explain important tradeoffs briefly.",
1444 (_, Self::Teaching) => {
1445 "Explain key reasoning and tradeoffs enough that the user can learn the system."
1446 }
1447 (_, Self::Direct) => {
1448 "Be direct about blockers, risk, and uncertainty; avoid ornamental copy."
1449 }
1450 }
1451 }
1452 }
1453
1454 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1455 enum GuidedPrivacy {
1456 StandardCare,
1457 StrictBoundaries,
1458 ProjectLocal,
1459 }
1460
1461 impl GuidedPrivacy {
1462 fn next(self) -> Self {
1463 match self {
1464 Self::StandardCare => Self::StrictBoundaries,
1465 Self::StrictBoundaries => Self::ProjectLocal,
1466 Self::ProjectLocal => Self::StandardCare,
1467 }
1468 }
1469
1470 fn label(self, locale: Locale) -> &'static str {
1471 match (locale, self) {
1472 (Locale::Ja, Self::StandardCare) => "標準保護",
1473 (Locale::Ja, Self::StrictBoundaries) => "厳格な境界",
1474 (Locale::Ja, Self::ProjectLocal) => "プロジェクト内メモリ",
1475 (Locale::ZhHans, Self::StandardCare) => "标准保护",
1476 (Locale::ZhHans, Self::StrictBoundaries) => "严格边界",
1477 (Locale::ZhHans, Self::ProjectLocal) => "项目内记忆",
1478 (Locale::ZhHant, Self::StandardCare) => "標準保護",
1479 (Locale::ZhHant, Self::StrictBoundaries) => "嚴格邊界",
1480 (Locale::ZhHant, Self::ProjectLocal) => "專案內記憶",
1481 (Locale::PtBr, Self::StandardCare) => "cuidado padrão",
1482 (Locale::PtBr, Self::StrictBoundaries) => "limites estritos",
1483 (Locale::PtBr, Self::ProjectLocal) => "memória local do projeto",
1484 (Locale::Es419, Self::StandardCare) => "cuidado estándar",
1485 (Locale::Es419, Self::StrictBoundaries) => "límites estrictos",
1486 (Locale::Es419, Self::ProjectLocal) => "memoria local del proyecto",
1487 (Locale::Vi, Self::StandardCare) => "bảo vệ tiêu chuẩn",
1488 (Locale::Vi, Self::StrictBoundaries) => "ranh giới nghiêm ngặt",
1489 (Locale::Vi, Self::ProjectLocal) => "bộ nhớ trong dự án",
1490 (Locale::Ko, Self::StandardCare) => "표준 보호",
1491 (Locale::Ko, Self::StrictBoundaries) => "엄격한 경계",
1492 (Locale::Ko, Self::ProjectLocal) => "프로젝트 내 메모리",
1493 (Locale::Ca, Self::StandardCare) => "cura estàndard",
1494 (Locale::Ca, Self::StrictBoundaries) => "límits estrictes",
1495 (Locale::Ca, Self::ProjectLocal) => "memòria local del projecte",
1496 (Locale::De, Self::StandardCare) => "Standardvorsorge",
1497 (Locale::De, Self::StrictBoundaries) => "strenge Grenzen",
1498 (Locale::De, Self::ProjectLocal) => "projektlokaler Speicher",
1499 (Locale::Fr, Self::StandardCare) => "soin standard",
1500 (Locale::Fr, Self::StrictBoundaries) => "limites strictes",
1501 (Locale::Fr, Self::ProjectLocal) => "mémoire locale au projet",
1502 (Locale::Id, Self::StandardCare) => "perlindungan standar",
1503 (Locale::Id, Self::StrictBoundaries) => "batasan ketat",
1504 (Locale::Id, Self::ProjectLocal) => "memori lokal proyek",
1505 (Locale::Hi, Self::StandardCare) => "मानक सावधानी",
1506 (Locale::Hi, Self::StrictBoundaries) => "सख्त सीमाएँ",
1507 (Locale::Hi, Self::ProjectLocal) => "प्रोजेक्ट-स्थानीय मेमोरी",
1508 (Locale::Ru, Self::StandardCare) => "стандартная осторожность",
1509 (Locale::Ru, Self::StrictBoundaries) => "строгие границы",
1510 (Locale::Ru, Self::ProjectLocal) => "память внутри проекта",
1511 (Locale::Uk, Self::StandardCare) => "стандартна обережність",
1512 (Locale::Uk, Self::StrictBoundaries) => "суворі межі",
1513 (Locale::Uk, Self::ProjectLocal) => "пам'ять у межах проєкту",
1514 (_, Self::StandardCare) => "standard care",
1515 (_, Self::StrictBoundaries) => "strict boundaries",
1516 (_, Self::ProjectLocal) => "project-local memory",
1517 }
1518 }
1519
1520 fn working_style(self, locale: Locale) -> &'static str {
1521 match (locale, self) {
1522 (Locale::Ja, Self::StandardCare) => {
1523 "秘密情報、ユーザーファイル、Git 履歴、本番システム、コスト、プライバシー、時間を保護する。"
1524 }
1525 (Locale::Ja, Self::StrictBoundaries) => {
1526 "秘密、個人データ、認証情報、本番状態、資金、公開操作は、先に確認する境界として扱う。"
1527 }
1528 (Locale::Ja, Self::ProjectLocal) => {
1529 "プロジェクト固有の文脈はプロジェクト内に留め、明示要求がない限りメモリへ書かない。"
1530 }
1531 (Locale::ZhHans, Self::StandardCare) => {
1532 "保护密钥、用户文件、Git 历史、生产系统、成本、隐私和时间。"
1533 }
1534 (Locale::ZhHans, Self::StrictBoundaries) => {
1535 "把密钥、个人数据、凭据、生产状态、资金和发布动作视为先确认边界。"
1536 }
1537 (Locale::ZhHans, Self::ProjectLocal) => {
1538 "项目特定上下文留在项目内,除非明确要求,否则不要写入记忆。"
1539 }
1540 (Locale::ZhHant, Self::StandardCare) => {
1541 "保護密鑰、使用者檔案、Git 歷史、生產系統、成本、隱私和時間。"
1542 }
1543 (Locale::ZhHant, Self::StrictBoundaries) => {
1544 "把密鑰、個人資料、憑據、生產狀態、資金和發布動作視為先確認邊界。"
1545 }
1546 (Locale::ZhHant, Self::ProjectLocal) => {
1547 "專案特定上下文留在專案內,除非明確要求,否則不要寫入記憶。"
1548 }
1549 (Locale::PtBr, Self::StandardCare) => {
1550 "Proteja segredos, arquivos do usuário, histórico git, produção, custo, privacidade e tempo."
1551 }
1552 (Locale::PtBr, Self::StrictBoundaries) => {
1553 "Trate segredos, dados pessoais, credenciais, estado de produção, dinheiro e publicações como limites de confirmação."
1554 }
1555 (Locale::PtBr, Self::ProjectLocal) => {
1556 "Mantenha contexto específico do projeto no projeto; evite gravar na memória sem pedido explícito."
1557 }
1558 (Locale::Es419, Self::StandardCare) => {
1559 "Protege secretos, archivos del usuario, historial git, producción, costo, privacidad y tiempo."
1560 }
1561 (Locale::Es419, Self::StrictBoundaries) => {
1562 "Trata secretos, datos personales, credenciales, estado de producción, dinero y publicaciones como límites de confirmación."
1563 }
1564 (Locale::Es419, Self::ProjectLocal) => {
1565 "Mantén el contexto específico del proyecto en el proyecto; evita llevarlo a memoria sin pedido explícito."
1566 }
1567 (Locale::Vi, Self::StandardCare) => {
1568 "Bảo vệ bí mật, tệp người dùng, lịch sử git, hệ thống sản xuất, chi phí, riêng tư và thời gian."
1569 }
1570 (Locale::Vi, Self::StrictBoundaries) => {
1571 "Xem bí mật, dữ liệu cá nhân, thông tin xác thực, trạng thái sản xuất, tiền và xuất bản là ranh giới cần xác nhận."
1572 }
1573 (Locale::Vi, Self::ProjectLocal) => {
1574 "Giữ ngữ cảnh riêng của dự án trong dự án; tránh ghi vào bộ nhớ nếu không được yêu cầu rõ."
1575 }
1576 (Locale::Ko, Self::StandardCare) => {
1577 "비밀 정보, 사용자 파일, Git 이력, 프로덕션 시스템, 비용, 프라이버시, 시간을 보호한다."
1578 }
1579 (Locale::Ko, Self::StrictBoundaries) => {
1580 "비밀 정보, 개인 데이터, 자격 증명, 프로덕션 상태, 자금, 게시 작업은 먼저 확인하는 경계로 취급한다."
1581 }
1582 (Locale::Ko, Self::ProjectLocal) => {
1583 "프로젝트 고유 맥락은 프로젝트 안에 두고, 명시적으로 요청받지 않는 한 메모리에 쓰지 않는다."
1584 }
1585 (Locale::Ca, Self::StandardCare) => {
1586 "Protegeix secrets, fitxers de l'usuari, historial de git, sistemes de producció, cost, privacitat i temps."
1587 }
1588 (Locale::Ca, Self::StrictBoundaries) => {
1589 "Tracta secrets, dades personals, credencials, estat de producció, diners i accions de publicació com a límits que cal confirmar primer."
1590 }
1591 (Locale::Ca, Self::ProjectLocal) => {
1592 "Mantén el context específic del projecte dins del projecte; evita portar-lo a la memòria si no se't demana explícitament."
1593 }
1594 (Locale::De, Self::StandardCare) => {
1595 "Schütze Geheimnisse, Nutzerdateien, Git-Verlauf, Produktionssysteme, Kosten, Privatsphäre und Zeit."
1596 }
1597 (Locale::De, Self::StrictBoundaries) => {
1598 "Behandle Geheimnisse, persönliche Daten, Zugangsdaten, Produktionszustand, Geld und Veröffentlichungen als Grenzen, die erst bestätigt werden."
1599 }
1600 (Locale::De, Self::ProjectLocal) => {
1601 "Halte projektspezifischen Kontext im Projekt; vermeide es, sensible Details ohne ausdrückliche Bitte in den Speicher zu übernehmen."
1602 }
1603 (Locale::Fr, Self::StandardCare) => {
1604 "Protégez secrets, fichiers utilisateur, historique git, systèmes de production, coût, vie privée et temps."
1605 }
1606 (Locale::Fr, Self::StrictBoundaries) => {
1607 "Traitez secrets, données personnelles, identifiants, état de production, argent et publications comme des limites exigeant confirmation."
1608 }
1609 (Locale::Fr, Self::ProjectLocal) => {
1610 "Gardez le contexte propre au projet dans le projet ; évitez de l'écrire en mémoire sans demande explicite."
1611 }
1612 (Locale::Id, Self::StandardCare) => {
1613 "Lindungi rahasia, file pengguna, riwayat git, sistem produksi, biaya, privasi, dan waktu."
1614 }
1615 (Locale::Id, Self::StrictBoundaries) => {
1616 "Perlakukan rahasia, data pribadi, kredensial, status produksi, uang, dan tindakan publikasi sebagai batas yang harus dikonfirmasi dulu."
1617 }
1618 (Locale::Id, Self::ProjectLocal) => {
1619 "Simpan konteks khusus proyek di dalam proyek; hindari membawanya ke memori kecuali diminta secara eksplisit."
1620 }
1621 (Locale::Hi, Self::StandardCare) => {
1622 "रहस्यों, उपयोगकर्ता फ़ाइलों, git इतिहास, प्रोडक्शन सिस्टम, लागत, गोपनीयता और समय की रक्षा करें।"
1623 }
1624 (Locale::Hi, Self::StrictBoundaries) => {
1625 "रहस्यों, व्यक्तिगत डेटा, क्रेडेंशियल, प्रोडक्शन स्थिति, धन और प्रकाशन क्रियाओं को पहले-पुष्टि सीमाओं की तरह मानें।"
1626 }
1627 (Locale::Hi, Self::ProjectLocal) => {
1628 "प्रोजेक्ट-विशिष्ट संदर्भ प्रोजेक्ट के भीतर रखें; स्पष्ट अनुरोध के बिना संवेदनशील विवरण मेमोरी में न ले जाएँ।"
1629 }
1630 (Locale::Ru, Self::StandardCare) => {
1631 "Защищайте секреты, файлы пользователя, историю git, production-системы, затраты, приватность и время."
1632 }
1633 (Locale::Ru, Self::StrictBoundaries) => {
1634 "Считайте секреты, персональные данные, учётные данные, production-состояние, деньги и публикации границами, требующими подтверждения."
1635 }
1636 (Locale::Ru, Self::ProjectLocal) => {
1637 "Держите контекст, специфичный для проекта, внутри проекта; не переносите чувствительные детали в память без явного запроса."
1638 }
1639 (Locale::Uk, Self::StandardCare) => {
1640 "Захищайте секрети, файли користувача, історію git, production-системи, витрати, приватність і час."
1641 }
1642 (Locale::Uk, Self::StrictBoundaries) => {
1643 "Вважайте секрети, персональні дані, облікові дані, production-стан, гроші та публікації межами, що потребують підтвердження."
1644 }
1645 (Locale::Uk, Self::ProjectLocal) => {
1646 "Тримайте контекст, специфічний для проєкту, всередині проєкту; не переносьте чутливі деталі в пам'ять без явного запиту."
1647 }
1648 (_, Self::StandardCare) => {
1649 "Protect secrets, user files, git history, production systems, cost, privacy, and time."
1650 }
1651 (_, Self::StrictBoundaries) => {
1652 "Treat secrets, personal data, credentials, production state, money, and publish actions as stop-and-confirm boundaries."
1653 }
1654 (_, Self::ProjectLocal) => {
1655 "Keep project-specific context local; avoid carrying sensitive details into memory unless explicitly asked."
1656 }
1657 }
1658 }
1659
1660 fn escalation_rule(self, locale: Locale) -> &'static str {
1661 match (locale, self) {
1662 (Locale::Ja, Self::StandardCare) => {
1663 "破壊的、高コスト、認証情報、公開、法務、セキュリティリスクのある操作の前に尋ねる。"
1664 }
1665 (Locale::Ja, Self::StrictBoundaries) => {
1666 "機微情報の読み取りや拡散、本番システム操作、支出、公開の前に停止して尋ねる。"
1667 }
1668 (Locale::Ja, Self::ProjectLocal) => {
1669 "プロジェクト詳細をメモリ、ワークスペース、古い引き継ぎへ持ち出す前に確認する。"
1670 }
1671 (Locale::ZhHans, Self::StandardCare) => {
1672 "遇到破坏性、高成本、凭据、发布、法律或安全风险操作时先询问。"
1673 }
1674 (Locale::ZhHans, Self::StrictBoundaries) => {
1675 "在读取或传播敏感信息、触碰生产系统、花费资金或发布内容前停止并询问。"
1676 }
1677 (Locale::ZhHans, Self::ProjectLocal) => {
1678 "需要跨项目记忆、复制项目细节或引用旧交接时,先确认这些上下文仍适用。"
1679 }
1680 (Locale::ZhHant, Self::StandardCare) => {
1681 "遇到破壞性、高成本、憑據、發布、法律或安全風險操作時先詢問。"
1682 }
1683 (Locale::ZhHant, Self::StrictBoundaries) => {
1684 "在讀取或傳播敏感資訊、觸碰生產系統、花費資金或發布內容前停止並詢問。"
1685 }
1686 (Locale::ZhHant, Self::ProjectLocal) => {
1687 "需要跨專案記憶、複製專案細節或引用舊交接時,先確認這些上下文仍適用。"
1688 }
1689 (Locale::PtBr, Self::StandardCare) => {
1690 "Pergunte antes de ações destrutivas, caras, com credenciais, publicação, risco legal ou de segurança."
1691 }
1692 (Locale::PtBr, Self::StrictBoundaries) => {
1693 "Pare e pergunte antes de ler ou espalhar dados sensíveis, tocar produção, gastar dinheiro ou publicar."
1694 }
1695 (Locale::PtBr, Self::ProjectLocal) => {
1696 "Confirme antes de levar detalhes do projeto para memória, workspaces ou handoffs antigos."
1697 }
1698 (Locale::Es419, Self::StandardCare) => {
1699 "Pregunta antes de acciones destructivas, costosas, con credenciales, publicación o riesgo legal/de seguridad."
1700 }
1701 (Locale::Es419, Self::StrictBoundaries) => {
1702 "Detente y pregunta antes de leer o difundir datos sensibles, tocar producción, gastar dinero o publicar."
1703 }
1704 (Locale::Es419, Self::ProjectLocal) => {
1705 "Confirma antes de llevar detalles del proyecto a memoria, workspaces o handoffs viejos."
1706 }
1707 (Locale::Vi, Self::StandardCare) => {
1708 "Hỏi trước các thao tác phá hủy, tốn kém, liên quan thông tin xác thực, xuất bản, pháp lý hoặc bảo mật."
1709 }
1710 (Locale::Vi, Self::StrictBoundaries) => {
1711 "Dừng và hỏi trước khi đọc/phát tán dữ liệu nhạy cảm, chạm sản xuất, chi tiền hoặc xuất bản."
1712 }
1713 (Locale::Vi, Self::ProjectLocal) => {
1714 "Xác nhận trước khi mang chi tiết dự án sang bộ nhớ, workspace khác hoặc handoff cũ."
1715 }
1716 (Locale::Ko, Self::StandardCare) => {
1717 "파괴적이거나, 비용이 크거나, 자격 증명, 게시, 법적, 보안 위험이 있는 작업 전에 먼저 물어본다."
1718 }
1719 (Locale::Ko, Self::StrictBoundaries) => {
1720 "민감 정보를 읽거나 퍼뜨리기 전, 프로덕션 시스템을 건드리기 전, 자금을 쓰거나 게시하기 전에 멈추고 물어본다."
1721 }
1722 (Locale::Ko, Self::ProjectLocal) => {
1723 "프로젝트 세부 정보를 메모리, 다른 워크스페이스, 오래된 인계 자료로 옮기기 전에 확인한다."
1724 }
1725 (Locale::Ca, Self::StandardCare) => {
1726 "Pregunta abans d'accions destructives, costoses, amb credencials, de publicació o amb risc legal o de seguretat."
1727 }
1728 (Locale::Ca, Self::StrictBoundaries) => {
1729 "Atura't i pregunta abans de llegir o difondre dades sensibles, tocar sistemes de producció, gastar diners o publicar."
1730 }
1731 (Locale::Ca, Self::ProjectLocal) => {
1732 "Confirma abans de portar detalls del projecte a la memòria, a altres espais de treball o a traspasos antics."
1733 }
1734 (Locale::De, Self::StandardCare) => {
1735 "Frage vor destruktiven, kostspieligen, zugangsdatenbezogenen, veröffentlichenden, rechtlichen oder sicherheitskritischen Aktionen."
1736 }
1737 (Locale::De, Self::StrictBoundaries) => {
1738 "Halte an und frage, bevor du sensible Daten liest oder verbreitest, Produktionssysteme anfasst, Geld ausgibst oder veröffentlichst."
1739 }
1740 (Locale::De, Self::ProjectLocal) => {
1741 "Bestätige, bevor du Projektdetails in Speicher, Workspaces oder veraltete Übergaben überträgst."
1742 }
1743 (Locale::Fr, Self::StandardCare) => {
1744 "Demandez avant toute action destructive, coûteuse, impliquant des identifiants, une publication, ou un risque juridique ou de sécurité."
1745 }
1746 (Locale::Fr, Self::StrictBoundaries) => {
1747 "Arrêtez et demandez avant de lire ou diffuser des données sensibles, de toucher aux systèmes de production, de dépenser de l'argent ou de publier."
1748 }
1749 (Locale::Fr, Self::ProjectLocal) => {
1750 "Confirmez avant de transporter des détails du projet vers la mémoire, d'autres espaces de travail ou d'anciens transferts."
1751 }
1752 (Locale::Id, Self::StandardCare) => {
1753 "Tanya sebelum tindakan destruktif, mahal, terkait kredensial, publikasi, hukum, atau berisiko keamanan."
1754 }
1755 (Locale::Id, Self::StrictBoundaries) => {
1756 "Berhenti dan tanya sebelum membaca atau menyebarkan data sensitif, menyentuh sistem produksi, membelanjakan uang, atau mempublikasikan."
1757 }
1758 (Locale::Id, Self::ProjectLocal) => {
1759 "Konfirmasi sebelum membawa detail proyek ke memori, workspace lain, atau handoff lama."
1760 }
1761 (Locale::Hi, Self::StandardCare) => {
1762 "विनाशकारी, उच्च-लागत, क्रेडेंशियल, प्रकाशन, कानूनी या सुरक्षा-जोखिम कार्यों से पहले पूछें।"
1763 }
1764 (Locale::Hi, Self::StrictBoundaries) => {
1765 "संवेदनशील डेटा पढ़ने या फैलाने, प्रोडक्शन सिस्टम छूने, धन खर्च करने या प्रकाशित करने से पहले रुककर पूछें।"
1766 }
1767 (Locale::Hi, Self::ProjectLocal) => {
1768 "प्रोजेक्ट विवरण मेमोरी, अन्य कार्यक्षेत्रों या पुराने हैंडऑफ़ में ले जाने से पहले पुष्टि करें।"
1769 }
1770 (Locale::Ru, Self::StandardCare) => {
1771 "Спрашивайте перед деструктивными, дорогими, связанными с учётными данными, публикацией, юридическими или угрожающими безопасности действиями."
1772 }
1773 (Locale::Ru, Self::StrictBoundaries) => {
1774 "Остановитесь и спросите, прежде чем читать или распространять чувствительные данные, трогать production-системы, тратить деньги или публиковать."
1775 }
1776 (Locale::Ru, Self::ProjectLocal) => {
1777 "Подтвердите, прежде чем переносить детали проекта в память, другие рабочие области или устаревшие передаточные заметки."
1778 }
1779 (Locale::Uk, Self::StandardCare) => {
1780 "Питайте перед руйнівними, дорогими, пов'язаними з обліковими даними, публікацією, юридичними чи небезпечними для безпеки діями."
1781 }
1782 (Locale::Uk, Self::StrictBoundaries) => {
1783 "Зупиніться й запитайте, перш ніж читати чи поширювати чутливі дані, чіпати production-системи, витрачати гроші або публікувати."
1784 }
1785 (Locale::Uk, Self::ProjectLocal) => {
1786 "Підтвердьте, перш ніж переносити деталі проєкту в пам'ять, інші робочі простори чи застарілі передаточні нотатки."
1787 }
1788 (_, Self::StandardCare) => {
1789 "Ask before destructive, high-cost, credential, publishing, legal, or security-risk actions."
1790 }
1791 (_, Self::StrictBoundaries) => {
1792 "Stop and ask before reading or spreading sensitive data, touching production systems, spending money, or publishing."
1793 }
1794 (_, Self::ProjectLocal) => {
1795 "Confirm before carrying project details across memory, workspaces, or stale handoffs."
1796 }
1797 }
1798 }
1799 }
1800
1801 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1802 enum GuidedPrinciples {
1803 ScopedChanges,
1804 UserVoice,
1805 ReversibleOps,
1806 }
1807
1808 impl GuidedPrinciples {
1809 fn next(self) -> Self {
1810 match self {
1811 Self::ScopedChanges => Self::UserVoice,
1812 Self::UserVoice => Self::ReversibleOps,
1813 Self::ReversibleOps => Self::ScopedChanges,
1814 }
1815 }
1816
1817 fn label(self, locale: Locale) -> &'static str {
1818 match (locale, self) {
1819 (Locale::Ja, Self::ScopedChanges) => "小さく絞った変更",
1820 (Locale::Ja, Self::UserVoice) => "ユーザーの声を保つ",
1821 (Locale::Ja, Self::ReversibleOps) => "可逆手順",
1822 (Locale::ZhHans, Self::ScopedChanges) => "小范围改动",
1823 (Locale::ZhHans, Self::UserVoice) => "保留用户语气",
1824 (Locale::ZhHans, Self::ReversibleOps) => "可逆步骤",
1825 (Locale::ZhHant, Self::ScopedChanges) => "小範圍改動",
1826 (Locale::ZhHant, Self::UserVoice) => "保留使用者語氣",
1827 (Locale::ZhHant, Self::ReversibleOps) => "可逆步驟",
1828 (Locale::PtBr, Self::ScopedChanges) => "mudanças focadas",
1829 (Locale::PtBr, Self::UserVoice) => "preservar voz do usuário",
1830 (Locale::PtBr, Self::ReversibleOps) => "passos reversíveis",
1831 (Locale::Es419, Self::ScopedChanges) => "cambios acotados",
1832 (Locale::Es419, Self::UserVoice) => "preservar voz del usuario",
1833 (Locale::Es419, Self::ReversibleOps) => "pasos reversibles",
1834 (Locale::Vi, Self::ScopedChanges) => "thay đổi có phạm vi",
1835 (Locale::Vi, Self::UserVoice) => "giữ giọng người dùng",
1836 (Locale::Vi, Self::ReversibleOps) => "bước có thể đảo ngược",
1837 (Locale::Ko, Self::ScopedChanges) => "범위가 명확한 변경",
1838 (Locale::Ko, Self::UserVoice) => "사용자의 어조 유지",
1839 (Locale::Ko, Self::ReversibleOps) => "되돌릴 수 있는 단계",
1840 (Locale::Ca, Self::ScopedChanges) => "canvis acotats",
1841 (Locale::Ca, Self::UserVoice) => "veu de l'usuari",
1842 (Locale::Ca, Self::ReversibleOps) => "passos reversibles",
1843 (Locale::De, Self::ScopedChanges) => "begrenzte Änderungen",
1844 (Locale::De, Self::UserVoice) => "Stimme des Nutzers",
1845 (Locale::De, Self::ReversibleOps) => "reversible Schritte",
1846 (Locale::Fr, Self::ScopedChanges) => "changements ciblés",
1847 (Locale::Fr, Self::UserVoice) => "voix de l'utilisateur",
1848 (Locale::Fr, Self::ReversibleOps) => "étapes réversibles",
1849 (Locale::Id, Self::ScopedChanges) => "perubahan terbatas",
1850 (Locale::Id, Self::UserVoice) => "suara pengguna",
1851 (Locale::Id, Self::ReversibleOps) => "langkah reversibel",
1852 (Locale::Hi, Self::ScopedChanges) => "सीमित बदलाव",
1853 (Locale::Hi, Self::UserVoice) => "उपयोगकर्ता की आवाज़",
1854 (Locale::Hi, Self::ReversibleOps) => "उत्क्रमणीय चरण",
1855 (Locale::Ru, Self::ScopedChanges) => "ограниченные изменения",
1856 (Locale::Ru, Self::UserVoice) => "голос пользователя",
1857 (Locale::Ru, Self::ReversibleOps) => "обратимые шаги",
1858 (Locale::Uk, Self::ScopedChanges) => "обмежені зміни",
1859 (Locale::Uk, Self::UserVoice) => "голос користувача",
1860 (Locale::Uk, Self::ReversibleOps) => "оборотні кроки",
1861 (_, Self::ScopedChanges) => "scoped changes",
1862 (_, Self::UserVoice) => "user voice",
1863 (_, Self::ReversibleOps) => "reversible steps",
1864 }
1865 }
1866
1867 fn note(self, locale: Locale) -> &'static str {
1868 match (locale, self) {
1869 (Locale::Ja, Self::ScopedChanges) => {
1870 "自由原則:小さくレビューしやすい変更を優先し、明示要求がない限り無関係なリファクタを避ける。"
1871 }
1872 (Locale::Ja, Self::UserVoice) => {
1873 "自由原則:ユーザーの語調、ブランド、制約を保ち、好みを権限拡大として扱わない。"
1874 }
1875 (Locale::Ja, Self::ReversibleOps) => {
1876 "自由原則:影響の大きい操作の前に、可逆手順、チェックポイント、ロールバック説明を選ぶ。"
1877 }
1878 (Locale::ZhHans, Self::ScopedChanges) => {
1879 "自定义准则:优先采用小范围、可审查的改动;除非明确要求,不做无关重构。"
1880 }
1881 (Locale::ZhHans, Self::UserVoice) => {
1882 "自定义准则:保留用户的语气、品牌和约束;不把偏好推断成权限扩大。"
1883 }
1884 (Locale::ZhHans, Self::ReversibleOps) => {
1885 "自定义准则:先选择可逆步骤、检查点和回滚说明,再进行高影响操作。"
1886 }
1887 (Locale::ZhHant, Self::ScopedChanges) => {
1888 "自由原則:優先採用小範圍、可審查的改動;除非明確要求,不做無關重構。"
1889 }
1890 (Locale::ZhHant, Self::UserVoice) => {
1891 "自由原則:保留使用者的語氣、品牌和約束;不把偏好推斷成權限擴大。"
1892 }
1893 (Locale::ZhHant, Self::ReversibleOps) => {
1894 "自由原則:先選擇可逆步驟、檢查點和回復說明,再進行高影響操作。"
1895 }
1896 (Locale::PtBr, Self::ScopedChanges) => {
1897 "Princípio livre: prefira mudanças pequenas e revisáveis; evite refactors não relacionados sem pedido explícito."
1898 }
1899 (Locale::PtBr, Self::UserVoice) => {
1900 "Princípio livre: preserve a voz, marca e restrições do usuário sem tratar preferências como expansão de permissão."
1901 }
1902 (Locale::PtBr, Self::ReversibleOps) => {
1903 "Princípio livre: favoreça passos reversíveis, checkpoints e notas de rollback antes de ações de alto impacto."
1904 }
1905 (Locale::Es419, Self::ScopedChanges) => {
1906 "Principio libre: prefiere cambios pequeños y revisables; evita refactors no relacionados sin pedido explícito."
1907 }
1908 (Locale::Es419, Self::UserVoice) => {
1909 "Principio libre: preserva la voz, marca y restricciones del usuario sin tratar preferencias como expansión de permisos."
1910 }
1911 (Locale::Es419, Self::ReversibleOps) => {
1912 "Principio libre: favorece pasos reversibles, checkpoints y notas de rollback antes de acciones de alto impacto."
1913 }
1914 (Locale::Vi, Self::ScopedChanges) => {
1915 "Nguyên tắc tự do: ưu tiên thay đổi nhỏ, dễ review; tránh refactor không liên quan nếu không được yêu cầu rõ."
1916 }
1917 (Locale::Vi, Self::UserVoice) => {
1918 "Nguyên tắc tự do: giữ giọng, thương hiệu và ràng buộc của người dùng, không xem sở thích là mở rộng quyền."
1919 }
1920 (Locale::Vi, Self::ReversibleOps) => {
1921 "Nguyên tắc tự do: ưu tiên bước có thể đảo ngược, checkpoint và ghi chú rollback trước thao tác tác động cao."
1922 }
1923 (Locale::Ko, Self::ScopedChanges) => {
1924 "자유 원칙: 작고 리뷰하기 쉬운 변경을 우선하고, 명시적으로 요청받지 않는 한 관련 없는 리팩터링은 하지 않는다."
1925 }
1926 (Locale::Ko, Self::UserVoice) => {
1927 "자유 원칙: 사용자의 어조, 브랜드, 제약을 유지하고 선호를 권한 확대로 취급하지 않는다."
1928 }
1929 (Locale::Ko, Self::ReversibleOps) => {
1930 "자유 원칙: 영향이 큰 작업 전에 되돌릴 수 있는 단계, 체크포인트, 롤백 메모를 우선한다."
1931 }
1932 (Locale::Ca, Self::ScopedChanges) => {
1933 "Principi lliure: prefereix canvis petits i revisables i evita refactors no relacionats si no es demanen explícitament."
1934 }
1935 (Locale::Ca, Self::UserVoice) => {
1936 "Principi lliure: preserva la veu, la marca i les restriccions de l'usuari sense tractar les preferències com una ampliació de permisos."
1937 }
1938 (Locale::Ca, Self::ReversibleOps) => {
1939 "Principi lliure: priorita passos reversibles, punts de control i notes de marxa enrere abans d'operacions d'alt impacte."
1940 }
1941 (Locale::De, Self::ScopedChanges) => {
1942 "Freitext-Prinzip: Bevorzuge kleine, überprüfbare Änderungen und vermeide unzusammenhängende Refactorings, sofern nicht ausdrücklich gewünscht."
1943 }
1944 (Locale::De, Self::UserVoice) => {
1945 "Freitext-Prinzip: Bewahre Stimme, Marke und Vorgaben des Nutzers, ohne Präferenzen als Rechteausweitung zu behandeln."
1946 }
1947 (Locale::De, Self::ReversibleOps) => {
1948 "Freitext-Prinzip: Bevorzuge reversible Schritte, Checkpoints und Rollback-Notizen vor einschneidenden Operationen."
1949 }
1950 (Locale::Fr, Self::ScopedChanges) => {
1951 "Principe libre : préférez des changements petits et révisables et évitez les refactors sans rapport, sauf demande explicite."
1952 }
1953 (Locale::Fr, Self::UserVoice) => {
1954 "Principe libre : préservez la voix, la marque et les contraintes de l'utilisateur sans traiter ses préférences comme une extension de permissions."
1955 }
1956 (Locale::Fr, Self::ReversibleOps) => {
1957 "Principe libre : privilégiez étapes réversibles, points de contrôle et notes de rollback avant les opérations à fort impact."
1958 }
1959 (Locale::Id, Self::ScopedChanges) => {
1960 "Prinsip bebas: utamakan perubahan kecil yang mudah ditinjau dan hindari refactor tak terkait kecuali diminta secara eksplisit."
1961 }
1962 (Locale::Id, Self::UserVoice) => {
1963 "Prinsip bebas: jaga suara, merek, dan batasan pengguna tanpa memperlakukan preferensi sebagai perluasan izin."
1964 }
1965 (Locale::Id, Self::ReversibleOps) => {
1966 "Prinsip bebas: utamakan langkah reversibel, checkpoint, dan catatan rollback sebelum operasi berdampak besar."
1967 }
1968 (Locale::Hi, Self::ScopedChanges) => {
1969 "मुक्त-पाठ सिद्धांत: छोटे, समीक्षायोग्य बदलावों को प्राथमिकता दें और स्पष्ट अनुरोध के बिना असंबंधित रिफैक्टर से बचें।"
1970 }
1971 (Locale::Hi, Self::UserVoice) => {
1972 "मुक्त-पाठ सिद्धांत: उपयोगकर्ता की आवाज़, ब्रांड और बाधाएँ सुरक्षित रखें; प्राथमिकताओं को अनुमति-विस्तार न मानें।"
1973 }
1974 (Locale::Hi, Self::ReversibleOps) => {
1975 "मुक्त-पाठ सिद्धांत: उच्च-प्रभाव कार्यों से पहले उत्क्रमणीय चरणों, चेकपॉइंट और रोलबैक नोट्स को प्राथमिकता दें।"
1976 }
1977 (Locale::Ru, Self::ScopedChanges) => {
1978 "Свободный принцип: предпочитайте небольшие, проверяемые изменения и избегайте несвязанных рефакторингов без явного запроса."
1979 }
1980 (Locale::Ru, Self::UserVoice) => {
1981 "Свободный принцип: сохраняйте голос, бренд и ограничения пользователя, не трактуя предпочтения как расширение полномочий."
1982 }
1983 (Locale::Ru, Self::ReversibleOps) => {
1984 "Свободный принцип: отдавайте предпочтение обратимым шагам, контрольным точкам и заметкам об откате перед высокорисковыми операциями."
1985 }
1986 (Locale::Uk, Self::ScopedChanges) => {
1987 "Вільний принцип: надавайте перевагу невеликим, перевірюваним змінам і уникайте непов'язаних рефакторингів без явного запиту."
1988 }
1989 (Locale::Uk, Self::UserVoice) => {
1990 "Вільний принцип: зберігайте голос, бренд і обмеження користувача, не трактуючи вподобання як розширення повноважень."
1991 }
1992 (Locale::Uk, Self::ReversibleOps) => {
1993 "Вільний принцип: надавайте перевагу оборотним крокам, контрольним точкам і нотаткам про відкат перед високоризиковими операціями."
1994 }
1995 (_, Self::ScopedChanges) => {
1996 "Freeform principle: prefer small, reviewable changes and avoid unrelated refactors unless explicitly requested."
1997 }
1998 (_, Self::UserVoice) => {
1999 "Freeform principle: preserve the user's voice, brand, and constraints without treating preferences as permission expansion."
2000 }
2001 (_, Self::ReversibleOps) => {
2002 "Freeform principle: favor reversible steps, checkpoints, and rollback notes before high-impact operations."
2003 }
2004 }
2005 }
2006 }
2007
2008 fn next_guided_autonomy(preference: AutonomyPreference) -> AutonomyPreference {
2009 match preference {
2010 AutonomyPreference::Unspecified | AutonomyPreference::Cautious => {
2011 AutonomyPreference::Balanced
2012 }
2013 AutonomyPreference::Balanced => AutonomyPreference::Autonomous,
2014 AutonomyPreference::Autonomous => AutonomyPreference::Cautious,
2015 }
2016 }
2017
2018 fn autonomy_label(preference: AutonomyPreference, locale: Locale) -> &'static str {
2019 match (locale, preference) {
2020 (Locale::Ja, AutonomyPreference::Cautious) => "慎重",
2021 (Locale::Ja, AutonomyPreference::Balanced) => "バランス",
2022 (Locale::Ja, AutonomyPreference::Autonomous) => "積極的",
2023 (Locale::ZhHans, AutonomyPreference::Cautious) => "谨慎",
2024 (Locale::ZhHans, AutonomyPreference::Balanced) => "平衡",
2025 (Locale::ZhHans, AutonomyPreference::Autonomous) => "积极主动",
2026 (Locale::ZhHant, AutonomyPreference::Cautious) => "謹慎",
2027 (Locale::ZhHant, AutonomyPreference::Balanced) => "平衡",
2028 (Locale::ZhHant, AutonomyPreference::Autonomous) => "積極主動",
2029 (Locale::PtBr, AutonomyPreference::Cautious) => "cauteloso",
2030 (Locale::PtBr, AutonomyPreference::Balanced) => "equilibrado",
2031 (Locale::PtBr, AutonomyPreference::Autonomous) => "ambicioso",
2032 (Locale::Es419, AutonomyPreference::Cautious) => "cauteloso",
2033 (Locale::Es419, AutonomyPreference::Balanced) => "equilibrado",
2034 (Locale::Es419, AutonomyPreference::Autonomous) => "ambicioso",
2035 (Locale::Vi, AutonomyPreference::Cautious) => "thận trọng",
2036 (Locale::Vi, AutonomyPreference::Balanced) => "cân bằng",
2037 (Locale::Vi, AutonomyPreference::Autonomous) => "chủ động",
2038 (Locale::Ko, AutonomyPreference::Cautious) => "신중함",
2039 (Locale::Ko, AutonomyPreference::Balanced) => "균형",
2040 (Locale::Ko, AutonomyPreference::Autonomous) => "적극적",
2041 (Locale::Ca, AutonomyPreference::Cautious) => "cautelós",
2042 (Locale::Ca, AutonomyPreference::Balanced) => "equilibrat",
2043 (Locale::Ca, AutonomyPreference::Autonomous) => "ambiciós",
2044 (Locale::De, AutonomyPreference::Cautious) => "vorsichtig",
2045 (Locale::De, AutonomyPreference::Balanced) => "ausgewogen",
2046 (Locale::De, AutonomyPreference::Autonomous) => "ambitioniert",
2047 (Locale::Fr, AutonomyPreference::Cautious) => "prudent",
2048 (Locale::Fr, AutonomyPreference::Balanced) => "équilibré",
2049 (Locale::Fr, AutonomyPreference::Autonomous) => "ambitieux",
2050 (Locale::Id, AutonomyPreference::Cautious) => "hati-hati",
2051 (Locale::Id, AutonomyPreference::Balanced) => "seimbang",
2052 (Locale::Id, AutonomyPreference::Autonomous) => "ambisius",
2053 (Locale::Hi, AutonomyPreference::Cautious) => "सावधान",
2054 (Locale::Hi, AutonomyPreference::Balanced) => "संतुलित",
2055 (Locale::Hi, AutonomyPreference::Autonomous) => "महत्वाकांक्षी",
2056 (Locale::Ru, AutonomyPreference::Cautious) => "осторожный",
2057 (Locale::Ru, AutonomyPreference::Balanced) => "сбалансированный",
2058 (Locale::Ru, AutonomyPreference::Autonomous) => "самостоятельный",
2059 (Locale::Uk, AutonomyPreference::Cautious) => "обережний",
2060 (Locale::Uk, AutonomyPreference::Balanced) => "збалансований",
2061 (Locale::Uk, AutonomyPreference::Autonomous) => "самостійний",
2062 (_, AutonomyPreference::Cautious) => "cautious",
2063 (_, AutonomyPreference::Balanced) => "balanced",
2064 (_, AutonomyPreference::Autonomous) => "ambitious",
2065 (_, AutonomyPreference::Unspecified) => "unspecified",
2066 }
2067 }
2068
2069 fn autonomy_priority(preference: AutonomyPreference, locale: Locale) -> &'static str {
2070 match (locale, preference) {
2071 (Locale::Ja, AutonomyPreference::Cautious) => {
2072 "ファイル編集、コマンド実行、あいまいな製品判断の前に停止して尋ねる。"
2073 }
2074 (Locale::Ja, AutonomyPreference::Balanced) => {
2075 "明確で低リスクな作業は直接進め、危険、破壊的、あいまいな操作では先に確認する。"
2076 }
2077 (Locale::Ja, AutonomyPreference::Autonomous) => {
2078 "安全な定型作業はまとめて進めるが、破壊的、認証情報、公開、高コスト、法務、セキュリティリスクでは停止して尋ねる。"
2079 }
2080 (Locale::ZhHans, AutonomyPreference::Cautious) => {
2081 "在编辑文件、运行命令或产品选择不明确前,倾向先停下询问。"
2082 }
2083 (Locale::ZhHans, AutonomyPreference::Balanced) => {
2084 "清晰低风险任务可直接行动;遇到风险、破坏性或歧义时先确认。"
2085 }
2086 (Locale::ZhHans, AutonomyPreference::Autonomous) => {
2087 "可批量处理安全的常规工作,但遇到破坏性、凭据、发布、高成本、法律或安全风险时停止询问。"
2088 }
2089 (Locale::ZhHant, AutonomyPreference::Cautious) => {
2090 "在編輯檔案、執行命令或產品選擇不明確前,傾向先停下詢問。"
2091 }
2092 (Locale::ZhHant, AutonomyPreference::Balanced) => {
2093 "清晰低風險任務可直接行動;遇到風險、破壞性或歧義時先確認。"
2094 }
2095 (Locale::ZhHant, AutonomyPreference::Autonomous) => {
2096 "可批量處理安全的常規工作,但遇到破壞性、憑據、發布、高成本、法律或安全風險時停止詢問。"
2097 }
2098 (Locale::PtBr, AutonomyPreference::Cautious) => {
2099 "Pare e pergunte antes de editar arquivos, rodar comandos ou escolher entre caminhos ambíguos de produto."
2100 }
2101 (Locale::PtBr, AutonomyPreference::Balanced) => {
2102 "Aja diretamente em tarefas claras e de baixo risco; confirme antes de ações arriscadas, destrutivas ou ambíguas."
2103 }
2104 (Locale::PtBr, AutonomyPreference::Autonomous) => {
2105 "Agrupe trabalho seguro de rotina, mas pare para ações destrutivas, credenciais, publicação, alto custo, legais ou de segurança."
2106 }
2107 (Locale::Es419, AutonomyPreference::Cautious) => {
2108 "Detente y pregunta antes de editar archivos, ejecutar comandos o elegir entre caminos ambiguos de producto."
2109 }
2110 (Locale::Es419, AutonomyPreference::Balanced) => {
2111 "Actúa directamente en tareas claras y de bajo riesgo; confirma antes de acciones riesgosas, destructivas o ambiguas."
2112 }
2113 (Locale::Es419, AutonomyPreference::Autonomous) => {
2114 "Agrupa trabajo seguro de rutina, pero detente ante acciones destructivas, credenciales, publicación, alto costo, legales o de seguridad."
2115 }
2116 (Locale::Vi, AutonomyPreference::Cautious) => {
2117 "Dừng và hỏi trước khi sửa tệp, chạy lệnh hoặc chọn giữa đường sản phẩm mơ hồ."
2118 }
2119 (Locale::Vi, AutonomyPreference::Balanced) => {
2120 "Hành động trực tiếp với việc rõ, rủi ro thấp; xác nhận trước việc rủi ro, phá hủy hoặc mơ hồ."
2121 }
2122 (Locale::Vi, AutonomyPreference::Autonomous) => {
2123 "Gộp việc thường lệ an toàn, nhưng dừng với thao tác phá hủy, thông tin xác thực, xuất bản, chi phí cao, pháp lý hoặc bảo mật."
2124 }
2125 (Locale::Ko, AutonomyPreference::Cautious) => {
2126 "파일 수정, 명령어 실행, 애매한 제품 선택 전에 멈추고 물어본다."
2127 }
2128 (Locale::Ko, AutonomyPreference::Balanced) => {
2129 "명확하고 위험이 낮은 작업은 바로 진행하고, 위험하거나 파괴적이거나 애매한 작업은 먼저 확인한다."
2130 }
2131 (Locale::Ko, AutonomyPreference::Autonomous) => {
2132 "안전한 정형 작업은 모아서 진행하되, 파괴적이거나 자격 증명, 게시, 고비용, 법적, 보안 위험이 있는 작업에서는 멈추고 물어본다."
2133 }
2134 (Locale::Ca, AutonomyPreference::Cautious) => {
2135 "Atura't i pregunta abans d'editar fitxers, executar ordres o triar entre camins de producte ambigus."
2136 }
2137 (Locale::Ca, AutonomyPreference::Balanced) => {
2138 "Actua directament en tasques clares i de baix risc; confirma abans d'accions arriscades, destructives o ambigües."
2139 }
2140 (Locale::Ca, AutonomyPreference::Autonomous) => {
2141 "Agrupa la feina rutinària segura, però atura't davant accions destructives, amb credencials, de publicació, d'alt cost o amb risc legal o de seguretat."
2142 }
2143 (Locale::De, AutonomyPreference::Cautious) => {
2144 "Halte an und frage, bevor du Dateien bearbeitest, Befehle ausführst oder zwischen mehrdeutigen Produktwegen wählst."
2145 }
2146 (Locale::De, AutonomyPreference::Balanced) => {
2147 "Handle direkt bei klaren, risikoarmen Aufgaben; bestätige vor riskanten, destruktiven oder mehrdeutigen Aktionen."
2148 }
2149 (Locale::De, AutonomyPreference::Autonomous) => {
2150 "Bündle sichere Routinearbeit, aber halte an bei destruktiven, zugangsdatenbezogenen, veröffentlichenden, kostspieligen, rechtlichen oder sicherheitskritischen Aktionen."
2151 }
2152 (Locale::Fr, AutonomyPreference::Cautious) => {
2153 "Arrêtez et demandez avant de modifier des fichiers, d'exécuter des commandes ou de choisir entre des voies produit ambiguës."
2154 }
2155 (Locale::Fr, AutonomyPreference::Balanced) => {
2156 "Agissez directement sur les tâches claires et à faible risque ; confirmez avant les actions risquées, destructives ou ambiguës."
2157 }
2158 (Locale::Fr, AutonomyPreference::Autonomous) => {
2159 "Regroupez le travail de routine sûr, mais arrêtez devant les actions destructives, impliquant des identifiants, des publications, coûteuses, juridiques ou à risque de sécurité."
2160 }
2161 (Locale::Id, AutonomyPreference::Cautious) => {
2162 "Berhenti dan tanya sebelum mengedit file, menjalankan perintah, atau memilih di antara jalur produk yang ambigu."
2163 }
2164 (Locale::Id, AutonomyPreference::Balanced) => {
2165 "Bertindak langsung pada tugas yang jelas dan berisiko rendah; konfirmasi sebelum tindakan berisiko, destruktif, atau ambigu."
2166 }
2167 (Locale::Id, AutonomyPreference::Autonomous) => {
2168 "Kelompokkan pekerjaan rutin yang aman, tetapi berhenti untuk tindakan destruktif, terkait kredensial, publikasi, mahal, hukum, atau berisiko keamanan."
2169 }
2170 (Locale::Hi, AutonomyPreference::Cautious) => {
2171 "फ़ाइलें संपादित करने, कमांड चलाने या अस्पष्ट उत्पाद मार्गों में चुनने से पहले रुककर पूछें।"
2172 }
2173 (Locale::Hi, AutonomyPreference::Balanced) => {
2174 "स्पष्ट, कम-जोखिम वाले कार्यों पर सीधे कार्य करें; जोखिमपूर्ण, विनाशकारी या अस्पष्ट कार्यों से पहले पुष्टि करें।"
2175 }
2176 (Locale::Hi, AutonomyPreference::Autonomous) => {
2177 "सुरक्षित नियमित काम एक साथ करें, लेकिन विनाशकारी, क्रेडेंशियल, प्रकाशन, उच्च-लागत, कानूनी या सुरक्षा-जोखिम कार्यों पर रुककर पूछें।"
2178 }
2179 (Locale::Ru, AutonomyPreference::Cautious) => {
2180 "Остановитесь и спросите перед редактированием файлов, запуском команд или выбором между неоднозначными продуктовыми путями."
2181 }
2182 (Locale::Ru, AutonomyPreference::Balanced) => {
2183 "Действуйте напрямую в ясных низкорисковых задачах; подтверждайте перед рискованными, деструктивными или неоднозначными действиями."
2184 }
2185 (Locale::Ru, AutonomyPreference::Autonomous) => {
2186 "Группируйте безопасную рутинную работу, но останавливайтесь перед деструктивными действиями, действиями с учётными данными, публикациями, дорогими, юридическими или угрожающими безопасности операциями."
2187 }
2188 (Locale::Uk, AutonomyPreference::Cautious) => {
2189 "Зупиніться й запитайте перед редагуванням файлів, запуском команд або вибором між неоднозначними продуктовими шляхами."
2190 }
2191 (Locale::Uk, AutonomyPreference::Balanced) => {
2192 "Дійте безпосередньо в чітких низькоризикових завданнях; підтверджуйте перед ризикованими, руйнівними чи неоднозначними діями."
2193 }
2194 (Locale::Uk, AutonomyPreference::Autonomous) => {
2195 "Групуйте безпечну рутинну роботу, але зупиняйтеся перед руйнівними діями, діями з обліковими даними, публікаціями, дорогими, юридичними чи небезпечними для безпеки операціями."
2196 }
2197 (_, AutonomyPreference::Cautious) => {
2198 "Stop and ask before editing files, running commands, or choosing between ambiguous product paths."
2199 }
2200 (_, AutonomyPreference::Balanced) => {
2201 "Do clear, low-risk work; ask before risky, destructive, or unclear work."
2202 }
2203 (_, AutonomyPreference::Autonomous) => {
2204 "Batch routine safe work, then stop for destructive, credential, publishing, high-cost, legal, or security-risk actions."
2205 }
2206 (_, AutonomyPreference::Unspecified) => "No standing initiative preference was selected.",
2207 }
2208 }
2209
2210 fn authority_priority(locale: Locale) -> &'static str {
2211 match locale {
2212 Locale::Ja => {
2213 "現在のユーザー要求とライブツール証拠は、メモリ、古い引き継ぎ、推測より優先される。"
2214 }
2215 Locale::ZhHans => "当前用户请求和实时工具证据优先于记忆、陈旧交接和猜测。",
2216 Locale::ZhHant => "目前使用者請求和即時工具證據優先於記憶、陳舊交接和猜測。",
2217 Locale::PtBr => {
2218 "Pedidos atuais do usuário e evidência viva das ferramentas superam memória, handoffs antigos e palpites."
2219 }
2220 Locale::Es419 => {
2221 "Las solicitudes actuales del usuario y la evidencia viva de herramientas superan memoria, handoffs viejos y suposiciones."
2222 }
2223 Locale::Vi => {
2224 "Yêu cầu hiện tại của người dùng và bằng chứng trực tiếp từ công cụ ưu tiên hơn bộ nhớ, handoff cũ và phỏng đoán."
2225 }
2226 Locale::Ko => {
2227 "현재 사용자 요청과 실시간 도구 근거는 메모리, 오래된 인계 자료, 추측보다 우선한다."
2228 }
2229 Locale::Ca => {
2230 "Les peticions actuals de l'usuari i l'evidència en directe de les eines prevalen sobre la memòria, els traspasos antics i les conjectures."
2231 }
2232 Locale::De => {
2233 "Aktuelle Nutzeranfragen und Live-Werkzeugnachweise haben Vorrang vor Speicher, veralteten Übergaben und Vermutungen."
2234 }
2235 Locale::Fr => {
2236 "Les demandes actuelles de l'utilisateur et les preuves directes des outils priment sur la mémoire, les anciens transferts et les suppositions."
2237 }
2238 Locale::Id => {
2239 "Permintaan pengguna saat ini dan bukti langsung dari alat mengalahkan memori, handoff lama, dan tebakan."
2240 }
2241 Locale::Hi => "वर्तमान उपयोगकर्ता अनुरोध और लाइव टूल साक्ष्य मेमोरी, पुराने हैंडऑफ़ और अनुमानों से ऊपर हैं।",
2242 Locale::Ru => {
2243 "Текущие запросы пользователя и живые свидетельства инструментов важнее памяти, устаревших передаточных заметок и догадок."
2244 }
2245 Locale::Uk => {
2246 "Поточні запити користувача та живі свідчення інструментів важливіші за пам'ять, застарілі передаточні нотатки й здогадки."
2247 }
2248 _ => {
2249 "Current user requests and live tool evidence outrank memory, stale handoffs, and guesses."
2250 }
2251 }
2252 }
2253
2254 const FREEFORM_NOTE_MAX: usize = MAX_NOTES_LEN - 1_000;
2255
2256 fn sanitize_freeform_note(input: &str, max_chars: usize) -> String {
2257 input
2258 .replace("\r\n", "\n")
2259 .replace('\r', "\n")
2260 .chars()
2261 .filter_map(|ch| {
2262 if ch == '\t' {
2263 Some(' ')
2264 } else if ch == '\n' || !ch.is_control() {
2265 Some(ch)
2266 } else {
2267 None
2268 }
2269 })
2270 .take(max_chars)
2271 .collect()
2272 }
2273
2274 fn bounded_freeform_note(input: &str, max_chars: usize) -> String {
2275 sanitize_freeform_note(input, max_chars).trim().to_string()
2276 }
2277
2278 fn compact_freeform_preview(note: &str) -> String {
2279 let compact = note.split_whitespace().collect::<Vec<_>>().join(" ");
2280 let mut graphemes = UnicodeSegmentation::graphemes(compact.as_str(), true);
2281 let mut preview: String = graphemes.by_ref().take(96).collect();
2282 if graphemes.next().is_some() {
2283 preview.push_str("...");
2284 }
2285 preview
2286 }
2287
2288 fn freeform_note_line(locale: Locale, note: &str, editing: bool) -> Line<'static> {
2289 let preview = compact_freeform_preview(note);
2290 let text = match (locale, editing, preview.is_empty()) {
2291 (Locale::Ja, true, true) => {
2292 "F 自由原則:編集中 - 有界の原則を入力または貼り付け、Enter で完了".to_string()
2293 }
2294 (Locale::Ja, true, false) => format!("F 自由原則:編集中 - {preview}"),
2295 (Locale::Ja, false, true) => "F 自由原則:F で有界の原則を入力または貼り付け".to_string(),
2296 (Locale::Ja, false, false) => format!("F 自由原則:{preview}"),
2297 (Locale::ZhHans, true, true) => {
2298 "F 自定义准则:正在编辑 - 输入或粘贴明确的准则,Enter 完成".to_string()
2299 }
2300 (Locale::ZhHans, true, false) => format!("F 自定义准则:正在编辑 - {preview}"),
2301 (Locale::ZhHans, false, true) => {
2302 "F 自定义准则:按 F 输入或粘贴自己的明确准则".to_string()
2303 }
2304 (Locale::ZhHans, false, false) => format!("F 自定义准则:{preview}"),
2305 (Locale::ZhHant, true, true) => {
2306 "F 自由原則:正在編輯 - 輸入或貼上有界原則,Enter 完成".to_string()
2307 }
2308 (Locale::ZhHant, true, false) => format!("F 自由原則:正在編輯 - {preview}"),
2309 (Locale::ZhHant, false, true) => "F 自由原則:按 F 輸入或貼上自己的有界原則".to_string(),
2310 (Locale::ZhHant, false, false) => format!("F 自由原則:{preview}"),
2311 (Locale::PtBr, true, true) => {
2312 "F Princípio livre: editando - digite ou cole um princípio limitado, Enter para concluir".to_string()
2313 }
2314 (Locale::PtBr, true, false) => format!("F Princípio livre: editando - {preview}"),
2315 (Locale::PtBr, false, true) => {
2316 "F Princípio livre: pressione F para digitar ou colar um princípio limitado".to_string()
2317 }
2318 (Locale::PtBr, false, false) => format!("F Princípio livre: {preview}"),
2319 (Locale::Es419, true, true) => {
2320 "F Principio libre: editando - escribe o pega un principio acotado, Enter para terminar".to_string()
2321 }
2322 (Locale::Es419, true, false) => format!("F Principio libre: editando - {preview}"),
2323 (Locale::Es419, false, true) => {
2324 "F Principio libre: presiona F para escribir o pegar un principio acotado".to_string()
2325 }
2326 (Locale::Es419, false, false) => format!("F Principio libre: {preview}"),
2327 (Locale::Vi, true, true) => {
2328 "F Nguyên tắc tự do: đang sửa - nhập hoặc dán nguyên tắc có giới hạn, Enter để xong".to_string()
2329 }
2330 (Locale::Vi, true, false) => format!("F Nguyên tắc tự do: đang sửa - {preview}"),
2331 (Locale::Vi, false, true) => {
2332 "F Nguyên tắc tự do: nhấn F để nhập hoặc dán nguyên tắc có giới hạn".to_string()
2333 }
2334 (Locale::Vi, false, false) => format!("F Nguyên tắc tự do: {preview}"),
2335 (Locale::Ko, true, true) => {
2336 "F 자유 원칙: 편집 중 - 제한된 원칙을 입력하거나 붙여넣고 Enter로 완료".to_string()
2337 }
2338 (Locale::Ko, true, false) => format!("F 자유 원칙: 편집 중 - {preview}"),
2339 (Locale::Ko, false, true) => "F 자유 원칙: F를 눌러 제한된 원칙을 입력하거나 붙여넣기".to_string(),
2340 (Locale::Ko, false, false) => format!("F 자유 원칙: {preview}"),
2341 (Locale::Ca, true, true) => {
2342 "F Paraules pròpies: editant - escriu o enganxa un principi acotat, Enter per acabar".to_string()
2343 }
2344 (Locale::Ca, true, false) => format!("F Paraules pròpies: editant - {preview}"),
2345 (Locale::Ca, false, true) => {
2346 "F Paraules pròpies: prem F per escriure o enganxar un principi acotat".to_string()
2347 }
2348 (Locale::Ca, false, false) => format!("F Paraules pròpies: {preview}"),
2349 (Locale::De, true, true) => {
2350 "F Eigene Worte: Bearbeitung - tippe oder füge ein begrenztes Prinzip ein, Enter zum Abschluss".to_string()
2351 }
2352 (Locale::De, true, false) => format!("F Eigene Worte: Bearbeitung - {preview}"),
2353 (Locale::De, false, true) => {
2354 "F Eigene Worte: F drücken, um ein begrenztes Prinzip zu tippen oder einzufügen".to_string()
2355 }
2356 (Locale::De, false, false) => format!("F Eigene Worte: {preview}"),
2357 (Locale::Fr, true, true) => {
2358 "F Vos mots : édition - tapez ou collez un principe borné, Entrée pour terminer".to_string()
2359 }
2360 (Locale::Fr, true, false) => format!("F Vos mots : édition - {preview}"),
2361 (Locale::Fr, false, true) => {
2362 "F Vos mots : appuyez sur F pour taper ou coller un principe borné".to_string()
2363 }
2364 (Locale::Fr, false, false) => format!("F Vos mots : {preview}"),
2365 (Locale::Id, true, true) => {
2366 "F Kata sendiri: mengedit - ketik atau tempel prinsip terbatas, Enter untuk selesai".to_string()
2367 }
2368 (Locale::Id, true, false) => format!("F Kata sendiri: mengedit - {preview}"),
2369 (Locale::Id, false, true) => {
2370 "F Kata sendiri: tekan F untuk mengetik atau menempel prinsip terbatas".to_string()
2371 }
2372 (Locale::Id, false, false) => format!("F Kata sendiri: {preview}"),
2373 (Locale::Hi, true, true) => {
2374 "F अपने शब्द: संपादन जारी - सीमित सिद्धांत टाइप या पेस्ट करें, Enter से समाप्त करें".to_string()
2375 }
2376 (Locale::Hi, true, false) => format!("F अपने शब्द: संपादन जारी - {preview}"),
2377 (Locale::Hi, false, true) => {
2378 "F अपने शब्द: सीमित सिद्धांत टाइप या पेस्ट करने के लिए F दबाएँ".to_string()
2379 }
2380 (Locale::Hi, false, false) => format!("F अपने शब्द: {preview}"),
2381 (Locale::Ru, true, true) => {
2382 "F Свои слова: редактирование - введите или вставьте ограниченный принцип, Enter для завершения".to_string()
2383 }
2384 (Locale::Ru, true, false) => format!("F Свои слова: редактирование - {preview}"),
2385 (Locale::Ru, false, true) => {
2386 "F Свои слова: нажмите F, чтобы ввести или вставить ограниченный принцип".to_string()
2387 }
2388 (Locale::Ru, false, false) => format!("F Свои слова: {preview}"),
2389 (Locale::Uk, true, true) => {
2390 "F Свої слова: редагування - введіть або вставте обмежений принцип, Enter для завершення".to_string()
2391 }
2392 (Locale::Uk, true, false) => format!("F Свої слова: редагування - {preview}"),
2393 (Locale::Uk, false, true) => {
2394 "F Свої слова: натисніть F, щоб ввести або вставити обмежений принцип".to_string()
2395 }
2396 (Locale::Uk, false, false) => format!("F Свої слова: {preview}"),
2397 (_, true, true) => {
2398 "F Own words: editing - type or paste a bounded principle, Enter to finish".to_string()
2399 }
2400 (_, true, false) => format!("F Own words: editing - {preview}"),
2401 (_, false, true) => "F Own words: press F to type or paste a bounded principle".to_string(),
2402 (_, false, false) => format!("F Own words: {preview}"),
2403 };
2404 let style = if editing || !preview.is_empty() {
2405 Style::default().fg(palette::WHALE_HUMAN)
2406 } else {
2407 Style::default().fg(palette::TEXT_MUTED)
2408 };
2409 Line::from(Span::styled(text, style))
2410 }
2411
2412 impl SetupWizardView {
2413 #[must_use]
2414 pub async fn load_for_app(app: &App, config: &Config) -> Self {
2415 let probes = SetupDiskProbes::load(app, config).await;
2416 let (state, facts) = SetupRuntimeFacts::from_app_config_with_probes(app, config, probes);
2417 Self::new_with_facts(state, app.ui_locale, facts)
2418 }
2419
2420 #[must_use]
2421 pub fn new_checkpoint_for_app(app: &App, config: &Config) -> Self {
2422 let probes = SetupDiskProbes::collect(SetupDiskProbeInput::from_app_config(app, config));
2423 let (state, facts) = SetupRuntimeFacts::from_app_config_with_probes(app, config, probes);
2424 Self::new_checkpoint_with_facts(state, app.ui_locale, facts)
2425 }
2426
2427 #[must_use]
2428 pub async fn load_for_app_at(app: &App, config: &Config, step: SetupStep) -> Self {
2429 let probes = SetupDiskProbes::load(app, config).await;
2430 let (state, facts) = SetupRuntimeFacts::from_app_config_with_probes(app, config, probes);
2431 Self::new_at_with_facts(state, app.ui_locale, step, facts)
2432 }
2433
2434 #[must_use]
2435 pub fn selected_step(&self) -> SetupStep {
2436 STEP_SPECS[self.selected].id()
2437 }
2438
2439 fn selected_spec(&self) -> &'static dyn SetupWizardStep {
2440 &STEP_SPECS[self.selected]
2441 }
2442
2443 fn new_with_facts(state: SetupState, locale: Locale, facts: SetupRuntimeFacts) -> Self {
2444 let selected = progressive_initial_step_index(&state, &facts);
2445 Self {
2446 state,
2447 selected,
2448 locale,
2449 progressive_guide: true,
2450 details_expanded: false,
2451 facts,
2452 guided_draft: GuidedConstitutionDraft::default(),
2453 constitution_advanced: false,
2454 freeform_note: String::new(),
2455 editing_freeform_note: false,
2456 guided_preview_seen: false,
2457 existing_preview_seen: false,
2458 model_draft: None,
2459 model_draft_label: None,
2460 model_draft_request: None,
2461 runtime_preset: SetupRuntimePreset::default(),
2462 runtime_preset_preview_seen: false,
2463 body_scroll: 0,
2464 body_max_scroll: Cell::new(usize::MAX),
2465 }
2466 }
2467
2468 fn new_at_with_facts(
2469 state: SetupState,
2470 locale: Locale,
2471 step: SetupStep,
2472 facts: SetupRuntimeFacts,
2473 ) -> Self {
2474 Self {
2475 state,
2476 selected: visible_step_index(step),
2477 locale,
2478 progressive_guide: false,
2479 details_expanded: false,
2480 facts,
2481 guided_draft: GuidedConstitutionDraft::default(),
2482 constitution_advanced: false,
2483 freeform_note: String::new(),
2484 editing_freeform_note: false,
2485 guided_preview_seen: false,
2486 existing_preview_seen: false,
2487 model_draft: None,
2488 model_draft_label: None,
2489 model_draft_request: None,
2490 runtime_preset: SetupRuntimePreset::default(),
2491 runtime_preset_preview_seen: false,
2492 body_scroll: 0,
2493 body_max_scroll: Cell::new(usize::MAX),
2494 }
2495 }
2496
2497 fn new_checkpoint_with_facts(
2498 state: SetupState,
2499 locale: Locale,
2500 facts: SetupRuntimeFacts,
2501 ) -> Self {
2502 Self::new_at_with_facts(state, locale, SetupStep::Constitution, facts)
2503 }
2504
2505 fn surface_title(&self) -> String {
2506 tr(self.locale, MessageId::SetupWizardTitle).into_owned()
2507 }
2508
2509 fn tools_relevant(&self) -> bool {
2510 self.facts.tools_mcp_needs_action || !self.facts.tools_mcp_result.contains("overall=off")
2511 }
2512
2513 fn progressive_steps(&self) -> Vec<SetupStep> {
2514 let mut steps = vec![
2515 SetupStep::ProviderModel,
2516 SetupStep::TrustSandbox,
2517 SetupStep::RemoteRuntime,
2518 ];
2519 if self.tools_relevant() {
2520 steps.push(SetupStep::ToolsMcp);
2521 }
2522 steps.push(SetupStep::Verification);
2523 steps
2524 }
2525
2526 fn move_next(&mut self) {
2527 if self.progressive_guide {
2528 let steps = self.progressive_steps();
2529 let position = steps
2530 .iter()
2531 .position(|step| *step == self.selected_step())
2532 .unwrap_or(0);
2533 let next = steps[(position + 1).min(steps.len().saturating_sub(1))];
2534 self.selected = visible_step_index(next);
2535 } else {
2536 self.selected = (self.selected + 1).min(STEP_SPECS.len().saturating_sub(1));
2537 }
2538 self.constitution_advanced = false;
2539 self.details_expanded = false;
2540 self.body_scroll = 0;
2541 }
2542
2543 fn move_back(&mut self) {
2544 if self.progressive_guide {
2545 let steps = self.progressive_steps();
2546 let position = steps
2547 .iter()
2548 .position(|step| *step == self.selected_step())
2549 .unwrap_or(0);
2550 let previous = steps[position.saturating_sub(1)];
2551 self.selected = visible_step_index(previous);
2552 } else {
2553 self.selected = self.selected.saturating_sub(1);
2554 }
2555 self.constitution_advanced = false;
2556 self.details_expanded = false;
2557 self.body_scroll = 0;
2558 }
2559
2560 fn commit_selected_status(
2561 &mut self,
2562 status: StepStatus,
2563 message_id: MessageId,
2564 advance: bool,
2565 ) -> ViewAction {
2566 let spec = self.selected_spec();
2567 let result = match status {
2568 StepStatus::Skipped => Some("skipped by user"),
2569 StepStatus::NeedsAction => Some("retry requested; needs action"),
2570 _ => None,
2571 };
2572 let mut entry = StepEntry::new(status, spec.required(), CONSTITUTION_CHECKPOINT_VERSION);
2573 if let Some(result) = result {
2574 entry = entry.with_result(result);
2575 }
2576 let mut state = self.state.clone();
2577 state.set_step(spec.id(), entry);
2578 if spec.id() == SetupStep::Constitution && status == StepStatus::Skipped {
2579 // `S` is a durable response to the versioned checkpoint, just like
2580 // choosing the explicit defer action. It only skips this setup
2581 // checkpoint, though; it must not replace an already active
2582 // bundled or custom Constitution choice. A fresh state has no
2583 // active choice, so keep the bundled floor by recording Deferred.
2584 let choice = if state.constitution_choice.is_explicit() {
2585 state.constitution_choice
2586 } else {
2587 ConstitutionChoice::Deferred
2588 };
2589 state.complete_constitution_checkpoint(CONSTITUTION_CHECKPOINT_VERSION, choice);
2590 }
2591 self.state = state.clone();
2592 if advance {
2593 self.move_next();
2594 }
2595 ViewAction::Emit(ViewEvent::SetupStateCommitRequested {
2596 state,
2597 message: tr(self.locale, message_id).to_string(),
2598 })
2599 }
2600
2601 fn commit_language_review(&mut self) -> ViewAction {
2602 let mut state = self.state.clone();
2603 state.constitution_language = Some(self.locale.tag().to_string());
2604 state.set_step(
2605 SetupStep::Language,
2606 StepEntry::new(StepStatus::Verified, true, CONSTITUTION_CHECKPOINT_VERSION)
2607 .with_result(format!("setup locale {}", self.locale.tag())),
2608 );
2609 self.state = state.clone();
2610 self.move_next();
2611 ViewAction::Emit(ViewEvent::SetupStateCommitRequested {
2612 state,
2613 message: tr(self.locale, MessageId::SetupLanguageReviewed).to_string(),
2614 })
2615 }
2616
2617 fn commit_provider_model_review(&mut self) -> ViewAction {
2618 let status = self.facts.provider_status;
2619 let mut state = self.state.clone();
2620 state.set_step(
2621 SetupStep::ProviderModel,
2622 provider::step_entry(
2623 status,
2624 CONSTITUTION_CHECKPOINT_VERSION,
2625 self.facts.provider_result.clone(),
2626 ),
2627 );
2628 self.state = state.clone();
2629 self.move_next();
2630 let message_id = if self.facts.provider_ready {
2631 MessageId::SetupProviderModelReviewed
2632 } else {
2633 MessageId::SetupProviderModelNeedsActionSaved
2634 };
2635 ViewAction::Emit(ViewEvent::SetupStateCommitRequested {
2636 state,
2637 message: tr(self.locale, message_id).to_string(),
2638 })
2639 }
2640
2641 fn commit_runtime_posture_review(&mut self) -> ViewAction {
2642 let mut state = self.state.clone();
2643 state.runtime_posture_source = RuntimePostureSource::Confirmed;
2644 state.set_step(
2645 SetupStep::TrustSandbox,
2646 StepEntry::new(StepStatus::Verified, true, CONSTITUTION_CHECKPOINT_VERSION)
2647 .with_result(self.facts.runtime_result.clone()),
2648 );
2649 self.state = state.clone();
2650 self.move_next();
2651 ViewAction::Emit(ViewEvent::SetupStateCommitRequested {
2652 state,
2653 message: tr(self.locale, MessageId::SetupRuntimePostureReviewed).to_string(),
2654 })
2655 }
2656
2657 fn operate_fleet_facts_ready(&self) -> bool {
2658 // Provider, capacity, and roster facts are configuration snapshots,
2659 // not proof of dispatch and terminal receipts. This release must never
2660 // persist an Operate-ready claim from those facts alone.
2661 false
2662 }
2663
2664 fn commit_operate_fleet_review(&mut self) -> ViewAction {
2665 let status = if self.operate_fleet_facts_ready() {
2666 StepStatus::Verified
2667 } else {
2668 StepStatus::NeedsAction
2669 };
2670 let mut state = self.state.clone();
2671 state.set_step(
2672 SetupStep::OperateFleet,
2673 StepEntry::new(status, false, CONSTITUTION_CHECKPOINT_VERSION)
2674 .with_result(self.facts.operate_result.clone()),
2675 );
2676 self.state = state.clone();
2677 self.move_next();
2678 let message_id = if status == StepStatus::Verified {
2679 MessageId::SetupOperateReviewed
2680 } else {
2681 MessageId::SetupOperateNeedsActionSaved
2682 };
2683 ViewAction::Emit(ViewEvent::SetupStateCommitRequested {
2684 state,
2685 message: tr(self.locale, message_id).to_string(),
2686 })
2687 }
2688
2689 fn commit_hotbar_review(&mut self) -> ViewAction {
2690 let mut state = self.state.clone();
2691 state.set_step(
2692 SetupStep::Hotbar,
2693 StepEntry::new(StepStatus::Verified, false, CONSTITUTION_CHECKPOINT_VERSION)
2694 .with_result(self.facts.hotbar_result.clone()),
2695 );
2696 self.state = state.clone();
2697 self.move_next();
2698 ViewAction::Emit(ViewEvent::SetupStateCommitRequested {
2699 state,
2700 message: tr(self.locale, MessageId::SetupHotbarReviewed).to_string(),
2701 })
2702 }
2703
2704 fn commit_tools_mcp_review(&mut self) -> ViewAction {
2705 // Optional step: empty/off inventories settle as Optional; broken
2706 // configured tools record NeedsAction without blocking first-run.
2707 let status = if self.facts.tools_mcp_needs_action {
2708 StepStatus::NeedsAction
2709 } else if self.facts.tools_mcp_result.contains("overall=off") {
2710 StepStatus::Optional
2711 } else {
2712 StepStatus::Verified
2713 };
2714 let mut state = self.state.clone();
2715 state.set_step(
2716 SetupStep::ToolsMcp,
2717 StepEntry::new(status, false, CONSTITUTION_CHECKPOINT_VERSION)
2718 .with_result(self.facts.tools_mcp_result.clone()),
2719 );
2720 self.state = state.clone();
2721 self.move_next();
2722 let message_id = if status == StepStatus::NeedsAction {
2723 MessageId::SetupToolsMcpNeedsActionSaved
2724 } else {
2725 MessageId::SetupToolsMcpReviewed
2726 };
2727 ViewAction::Emit(ViewEvent::SetupStateCommitRequested {
2728 state,
2729 message: tr(self.locale, message_id).to_string(),
2730 })
2731 }
2732
2733 fn preview_tools_mcp_on_ramp(&self) -> ViewAction {
2734 ViewAction::Emit(ViewEvent::OpenTextPager {
2735 title: tr(self.locale, MessageId::SetupToolsMcpPreviewTitle).to_string(),
2736 content: tools_mcp_on_ramp_text(self.locale, &self.facts),
2737 })
2738 }
2739
2740 fn preview_remote_runtime_on_ramp(&self) -> ViewAction {
2741 ViewAction::Emit(ViewEvent::OpenTextPager {
2742 title: tr(self.locale, MessageId::SetupRemotePreviewTitle).to_string(),
2743 content: remote_runtime_on_ramp_text(self.locale, &self.facts),
2744 })
2745 }
2746
2747 /// Record the remote step honestly (#3409).
2748 ///
2749 /// Local-only always works, so Enter alone settles the step — a user who
2750 /// never wants remote access is finished in one key. When a *reachable*
2751 /// mode is missing a token or config the entry is `NeedsAction`, which the
2752 /// setup report and doctor inherit verbatim and which never blocks ready.
2753 fn commit_remote_runtime_review(&mut self) -> ViewAction {
2754 let mut state = self.state.clone();
2755 let status = if self.facts.remote_needs_action {
2756 StepStatus::NeedsAction
2757 } else {
2758 StepStatus::Verified
2759 };
2760 state.set_step(
2761 SetupStep::RemoteRuntime,
2762 StepEntry::new(status, false, CONSTITUTION_CHECKPOINT_VERSION)
2763 .with_result(self.facts.remote_result.clone()),
2764 );
2765 self.state = state.clone();
2766 self.move_next();
2767 ViewAction::Emit(ViewEvent::SetupStateCommitRequested {
2768 state,
2769 message: tr(self.locale, MessageId::SetupRemoteReviewed).to_string(),
2770 })
2771 }
2772
2773 fn commit_persistence_review(&mut self) -> ViewAction {
2774 let mut state = self.state.clone();
2775 state.set_step(
2776 SetupStep::Persistence,
2777 StepEntry::new(StepStatus::Verified, false, CONSTITUTION_CHECKPOINT_VERSION)
2778 .with_result(self.facts.persistence.result.clone()),
2779 );
2780 self.state = state.clone();
2781 self.move_next();
2782 ViewAction::Emit(ViewEvent::SetupStateCommitRequested {
2783 state,
2784 message: tr(self.locale, MessageId::SetupPersistenceReviewed).to_string(),
2785 })
2786 }
2787
2788 fn select_runtime_preset(&mut self, key: char) -> ViewAction {
2789 if let Some(preset) = SetupRuntimePreset::from_key(key)
2790 && preset != self.runtime_preset
2791 {
2792 self.runtime_preset = preset;
2793 self.runtime_preset_preview_seen = false;
2794 }
2795 ViewAction::None
2796 }
2797
2798 fn preview_runtime_preset(&mut self) -> ViewAction {
2799 self.runtime_preset_preview_seen = true;
2800 ViewAction::Emit(ViewEvent::OpenTextPager {
2801 title: tr(self.locale, MessageId::SetupRuntimePresetPreviewTitle).to_string(),
2802 content: runtime_preset_preview_text(self.locale, self.runtime_preset, &self.facts),
2803 })
2804 }
2805
2806 fn commit_runtime_preset(&mut self) -> ViewAction {
2807 if !self.runtime_preset_preview_seen {
2808 return self.preview_runtime_preset();
2809 }
2810
2811 let mut state = self.state.clone();
2812 state.runtime_posture_source = RuntimePostureSource::Confirmed;
2813 state.set_step(
2814 SetupStep::TrustSandbox,
2815 StepEntry::new(StepStatus::Verified, true, CONSTITUTION_CHECKPOINT_VERSION)
2816 .with_result(self.runtime_preset.result_summary()),
2817 );
2818 self.state = state.clone();
2819 self.move_next();
2820 ViewAction::Emit(ViewEvent::SetupRuntimePresetApplyRequested {
2821 preset: self.runtime_preset,
2822 state,
2823 message: tr(self.locale, MessageId::SetupRuntimePresetApplied).to_string(),
2824 })
2825 }
2826
2827 fn commit_setup_report(&mut self) -> ViewAction {
2828 let mut state = self.state.clone();
2829 let status = if setup_report_ready(&state) {
2830 StepStatus::Verified
2831 } else {
2832 StepStatus::NeedsAction
2833 };
2834 state.set_step(
2835 SetupStep::Verification,
2836 StepEntry::new(status, false, CONSTITUTION_CHECKPOINT_VERSION)
2837 .with_result(setup_report_result(&state, &self.facts)),
2838 );
2839 self.state = state.clone();
2840 let event = ViewEvent::SetupStateCommitRequested {
2841 state,
2842 message: tr(self.locale, MessageId::SetupReportRecorded).to_string(),
2843 };
2844 if self.progressive_guide {
2845 ViewAction::EmitAndClose(event)
2846 } else {
2847 ViewAction::Emit(event)
2848 }
2849 }
2850
2851 fn open_constitution_advanced(&mut self) -> ViewAction {
2852 self.constitution_advanced = true;
2853 self.body_scroll = 0;
2854 ViewAction::None
2855 }
2856
2857 fn close_constitution_advanced(&mut self) -> ViewAction {
2858 self.constitution_advanced = false;
2859 self.editing_freeform_note = false;
2860 self.body_scroll = 0;
2861 ViewAction::None
2862 }
2863
2864 /// The first-run path is intentionally one decision: how much initiative
2865 /// Codewhale should take. This saves guidance only. Runtime approval,
2866 /// sandbox, shell, network, trust, and MCP policy remain untouched.
2867 fn commit_simple_constitution(&mut self) -> ViewAction {
2868 match self.facts.constitution_file {
2869 // Existing law is the safest default on an update checkpoint.
2870 // Keep it byte-for-byte and only advance setup state.
2871 SetupConstitutionFileState::Loaded => {
2872 return self.commit_existing_constitution_unchanged();
2873 }
2874 // Do not overwrite a file the user attempted to provide when it
2875 // cannot be parsed or read. The bundled floor remains active and
2876 // Advanced exposes the explicit repair/regenerate choices.
2877 SetupConstitutionFileState::Empty
2878 | SetupConstitutionFileState::Invalid
2879 | SetupConstitutionFileState::Unreadable
2880 | SetupConstitutionFileState::PathError => {
2881 return self.commit_constitution(SetupCommitKind::BundledConstitution);
2882 }
2883 SetupConstitutionFileState::NotChecked | SetupConstitutionFileState::Missing => {}
2884 }
2885
2886 // The compiled constitution already embodies the balanced posture:
2887 // act on clear reversible work without asking, ask with options when a
2888 // choice is the user's, and require express authorization for
2889 // irreversible or external effects.
2890 // Accepting the recommendation therefore records Bundled rather than
2891 // pinning a generated user-global fork that would miss future bundled
2892 // law improvements. Only Customize writes a GuidedCustom file.
2893 self.commit_constitution(SetupCommitKind::BundledConstitution)
2894 }
2895
2896 fn commit_custom_constitution(
2897 &mut self,
2898 constitution: UserConstitution,
2899 authoring: ConstitutionAuthoring,
2900 result_prefix: &str,
2901 ) -> ViewAction {
2902 let mut state = self.state.clone();
2903 state.complete_constitution_checkpoint(
2904 CONSTITUTION_CHECKPOINT_VERSION,
2905 ConstitutionChoice::GuidedCustom,
2906 );
2907 state.constitution_language = constitution.language.clone();
2908 state.constitution_source = ConstitutionSource::UserGlobal;
2909 state.constitution_validity = ConstitutionValidity::Valid;
2910 state.constitution_authoring = Some(authoring);
2911 state.constitution_preview_hash = Some(constitution.preview_hash());
2912 state.constitution_preview_version =
2913 state.constitution_preview_version.saturating_add(1).max(1);
2914 let hash = state
2915 .constitution_preview_hash
2916 .as_deref()
2917 .unwrap_or("unknown");
2918 state.set_step(
2919 SetupStep::Constitution,
2920 StepEntry::new(StepStatus::Verified, true, CONSTITUTION_CHECKPOINT_VERSION)
2921 .with_result(format!("{result_prefix} preview_hash={hash}")),
2922 );
2923 self.state = state.clone();
2924 ViewAction::EmitAndClose(ViewEvent::SetupConstitutionCommitRequested {
2925 constitution,
2926 state,
2927 message: tr(self.locale, MessageId::SetupCheckpointDoneGuided).to_string(),
2928 })
2929 }
2930
2931 fn commit_guided_constitution(&mut self) -> ViewAction {
2932 if !self.guided_preview_seen {
2933 return self.preview_guided_constitution();
2934 }
2935
2936 let (constitution, authoring) = match self.model_draft.as_deref() {
2937 // Model drafts arrive sanitized + bounded from the untrusted-JSON
2938 // gate; ratify exactly what was previewed.
2939 Some(draft) => (draft.clone(), ConstitutionAuthoring::ModelDrafted),
2940 None => (
2941 self.guided_draft
2942 .to_constitution_with_freeform(self.locale, self.freeform_note_for_draft()),
2943 ConstitutionAuthoring::Guided,
2944 ),
2945 };
2946 let result_prefix = match authoring {
2947 ConstitutionAuthoring::ModelDrafted => format!(
2948 "model-drafted constitution ratified ({})",
2949 self.model_draft_label.as_deref().unwrap_or("model")
2950 ),
2951 ConstitutionAuthoring::Guided => "guided custom constitution".to_string(),
2952 };
2953 self.commit_custom_constitution(constitution, authoring, &result_prefix)
2954 }
2955
2956 fn preview_guided_constitution(&mut self) -> ViewAction {
2957 self.guided_preview_seen = true;
2958 let (constitution, provenance) = match self.model_draft.as_deref() {
2959 Some(draft) => (
2960 draft.clone(),
2961 DraftProvenance::Model(
2962 self.model_draft_label
2963 .clone()
2964 .unwrap_or_else(|| "model".to_string()),
2965 ),
2966 ),
2967 None => (
2968 self.guided_draft
2969 .to_constitution_with_freeform(self.locale, self.freeform_note_for_draft()),
2970 DraftProvenance::Guided,
2971 ),
2972 };
2973 ViewAction::Emit(ViewEvent::OpenTextPager {
2974 title: ratification_preview_title(self.locale).to_string(),
2975 content: constitution_ratification_text(self.locale, &constitution, &provenance),
2976 })
2977 }
2978
2979 fn cycle_guided_answer(&mut self, key: char) -> ViewAction {
2980 if self.guided_draft.cycle(key) {
2981 self.guided_preview_seen = false;
2982 // Answers changed under the draft: the model draft is stale law
2983 // and must be re-drafted or replaced by the guided rendering.
2984 self.model_draft = None;
2985 self.model_draft_label = None;
2986 }
2987 ViewAction::None
2988 }
2989
2990 /// `A` on the constitution step: ask the first configured model to draft.
2991 /// Requires a ready provider route; otherwise the key is inert and the
2992 /// deterministic guided flow stands untouched.
2993 fn request_model_draft(&mut self) -> ViewAction {
2994 if !self.facts.provider_ready {
2995 return ViewAction::None;
2996 }
2997 self.model_draft_request = Some(self.current_model_draft_request());
2998 ViewAction::Emit(ViewEvent::SetupConstitutionModelDraftRequested {
2999 draft: self.guided_draft,
3000 freeform_note: self.freeform_note_for_draft().map(str::to_string),
3001 locale: self.locale,
3002 })
3003 }
3004
3005 fn toggle_freeform_edit(&mut self) -> ViewAction {
3006 if self.selected_step() == SetupStep::Constitution {
3007 self.editing_freeform_note = !self.editing_freeform_note;
3008 }
3009 ViewAction::None
3010 }
3011
3012 fn current_model_draft_request(&self) -> (GuidedConstitutionDraft, Option<String>) {
3013 (
3014 self.guided_draft,
3015 self.freeform_note_for_draft().map(str::to_string),
3016 )
3017 }
3018
3019 fn freeform_note_for_draft(&self) -> Option<&str> {
3020 let note = self.freeform_note.trim();
3021 (!note.is_empty()).then_some(note)
3022 }
3023
3024 fn append_freeform_note_text(&mut self, text: &str) {
3025 let mut next = self.freeform_note.clone();
3026 next.push_str(text);
3027 self.freeform_note = sanitize_freeform_note(&next, FREEFORM_NOTE_MAX);
3028 self.guided_preview_seen = false;
3029 self.model_draft = None;
3030 self.model_draft_label = None;
3031 }
3032
3033 fn handle_freeform_note_key(&mut self, key: KeyEvent) -> Option<ViewAction> {
3034 if self.selected_step() != SetupStep::Constitution || !self.editing_freeform_note {
3035 return None;
3036 }
3037 match key.code {
3038 KeyCode::Esc | KeyCode::Enter => {
3039 self.editing_freeform_note = false;
3040 Some(ViewAction::None)
3041 }
3042 KeyCode::Backspace => {
3043 self.freeform_note.pop();
3044 self.guided_preview_seen = false;
3045 self.model_draft = None;
3046 self.model_draft_label = None;
3047 Some(ViewAction::None)
3048 }
3049 KeyCode::Char(c)
3050 if crate::tui::widgets::key_hint::is_altgr(key.modifiers)
3051 || !key
3052 .modifiers
3053 .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
3054 {
3055 let mut buf = [0; 4];
3056 self.append_freeform_note_text(c.encode_utf8(&mut buf));
3057 Some(ViewAction::None)
3058 }
3059 _ => Some(ViewAction::None),
3060 }
3061 }
3062
3063 /// Install a model-drafted constitution (already sanitized + bounded by
3064 /// the untrusted-JSON gate) and return the `(title, content)` of the
3065 /// ratification preview the host must open in the same breath — that is
3066 /// what satisfies the preview gate. Ratifying still takes the explicit
3067 /// `G` keypress afterwards.
3068 ///
3069 /// Returns `None`, installing nothing, when the answers or note changed
3070 /// after the draft was requested: that draft is law for answers the
3071 /// person no longer holds (U08-06).
3072 #[must_use]
3073 pub(crate) fn install_model_draft(
3074 &mut self,
3075 constitution: Box<UserConstitution>,
3076 model_label: String,
3077 ) -> Option<(String, String)> {
3078 if self.model_draft_request.as_ref() != Some(&self.current_model_draft_request()) {
3079 return None;
3080 }
3081 self.model_draft_request = None;
3082 let content = constitution_ratification_text(
3083 self.locale,
3084 &constitution,
3085 &DraftProvenance::Model(model_label.clone()),
3086 );
3087 self.model_draft = Some(constitution);
3088 self.model_draft_label = Some(model_label);
3089 self.guided_preview_seen = true;
3090 Some((ratification_preview_title(self.locale).to_string(), content))
3091 }
3092
3093 fn commit_constitution(&self, kind: SetupCommitKind) -> ViewAction {
3094 let choice = match kind {
3095 SetupCommitKind::BundledConstitution => ConstitutionChoice::Bundled,
3096 SetupCommitKind::DeferredConstitution => ConstitutionChoice::Deferred,
3097 };
3098 let mut state = self.state.clone();
3099 state.complete_constitution_checkpoint(CONSTITUTION_CHECKPOINT_VERSION, choice);
3100 state.constitution_source = ConstitutionSource::Bundled;
3101 state.constitution_validity = ConstitutionValidity::Unknown;
3102 state.constitution_authoring = None;
3103 state.constitution_preview_hash = None;
3104 state.set_step(
3105 SetupStep::Constitution,
3106 StepEntry::new(StepStatus::Verified, true, CONSTITUTION_CHECKPOINT_VERSION)
3107 .with_result(match kind {
3108 SetupCommitKind::BundledConstitution => "bundled/default constitution",
3109 SetupCommitKind::DeferredConstitution => "checkpoint deferred; bundled applies",
3110 }),
3111 );
3112 let message_id = match kind {
3113 SetupCommitKind::BundledConstitution => MessageId::SetupCheckpointDoneBundled,
3114 SetupCommitKind::DeferredConstitution => MessageId::SetupCheckpointDeferred,
3115 };
3116 ViewAction::EmitAndClose(ViewEvent::SetupStateCommitRequested {
3117 state,
3118 message: tr(self.locale, message_id).to_string(),
3119 })
3120 }
3121
3122 fn load_existing_constitution(&self) -> Option<UserConstitution> {
3123 if self.facts.constitution_file != SetupConstitutionFileState::Loaded {
3124 return None;
3125 }
3126 // Re-read the live file so a stale card cannot ratify a file that
3127 // has since become invalid; any non-loaded state leaves the key inert.
3128 UserConstitution::load().ok()?.constitution().cloned()
3129 }
3130
3131 fn commit_existing_constitution_unchanged(&mut self) -> ViewAction {
3132 let Some(constitution) = self.load_existing_constitution() else {
3133 return ViewAction::None;
3134 };
3135 let mut state = self.state.clone();
3136 state.complete_constitution_checkpoint(
3137 CONSTITUTION_CHECKPOINT_VERSION,
3138 ConstitutionChoice::GuidedCustom,
3139 );
3140 state.constitution_source = ConstitutionSource::UserGlobal;
3141 state.constitution_validity = ConstitutionValidity::Valid;
3142 state.constitution_preview_hash = Some(constitution.preview_hash());
3143 state.set_step(
3144 SetupStep::Constitution,
3145 StepEntry::new(StepStatus::Verified, true, CONSTITUTION_CHECKPOINT_VERSION)
3146 .with_result("existing constitution kept unchanged"),
3147 );
3148 self.state = state.clone();
3149 ViewAction::EmitAndClose(ViewEvent::SetupStateCommitRequested {
3150 state,
3151 message: tr(self.locale, MessageId::SetupCheckpointDoneKept).to_string(),
3152 })
3153 }
3154
3155 /// Complete the checkpoint by keeping the existing valid
3156 /// `constitution.json` exactly as it stands (#3794). First `K` previews
3157 /// the rendered law; second `K` records the choice. The file is never
3158 /// rewritten — only `setup_state.json` changes, through the same commit
3159 /// event as every other completion.
3160 fn commit_keep_existing_constitution(&mut self) -> ViewAction {
3161 let Some(constitution) = self.load_existing_constitution() else {
3162 return ViewAction::None;
3163 };
3164 if !self.existing_preview_seen {
3165 self.existing_preview_seen = true;
3166 let content = constitution_ratification_text(
3167 self.locale,
3168 &constitution,
3169 &DraftProvenance::Existing,
3170 );
3171 return ViewAction::Emit(ViewEvent::OpenTextPager {
3172 title: ratification_preview_title(self.locale).to_string(),
3173 content,
3174 });
3175 }
3176 self.commit_existing_constitution_unchanged()
3177 }
3178
3179 fn status_label(&self, status: StepStatus) -> Cow<'static, str> {
3180 tr(
3181 self.locale,
3182 match status {
3183 StepStatus::NotStarted => MessageId::SetupStatusNotStarted,
3184 StepStatus::Recommended => MessageId::SetupStatusRecommended,
3185 StepStatus::Optional => MessageId::SetupStatusOptional,
3186 StepStatus::Deferred => MessageId::SetupStatusDeferred,
3187 StepStatus::InProgress => MessageId::SetupStatusInProgress,
3188 StepStatus::Configured => MessageId::PickerActionConfigured,
3189 StepStatus::NeedsAction => MessageId::SetupStatusNeedsAction,
3190 StepStatus::Verified => MessageId::SetupStatusVerified,
3191 StepStatus::Skipped => MessageId::SetupStatusSkipped,
3192 StepStatus::Failed => MessageId::SetupStatusFailed,
3193 },
3194 )
3195 }
3196 }
3197
3198 impl ModalView for SetupWizardView {
3199 fn kind(&self) -> ModalKind {
3200 ModalKind::SetupWizard
3201 }
3202
3203 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
3204 if let Some(action) = self.handle_freeform_note_key(key) {
3205 return action;
3206 }
3207 if self.selected_step() == SetupStep::Constitution && !self.constitution_advanced {
3208 return match key.code {
3209 KeyCode::Esc | KeyCode::Char('q') => ViewAction::Close,
3210 KeyCode::Left | KeyCode::Char('b') => {
3211 self.move_back();
3212 ViewAction::None
3213 }
3214 KeyCode::Char('c') => self.open_constitution_advanced(),
3215 KeyCode::Enter => self.commit_simple_constitution(),
3216 _ => ViewAction::None,
3217 };
3218 }
3219 if self.selected_step() == SetupStep::Constitution
3220 && self.constitution_advanced
3221 && key.code == KeyCode::Esc
3222 {
3223 return self.close_constitution_advanced();
3224 }
3225 match key.code {
3226 KeyCode::Esc | KeyCode::Char('q') => ViewAction::Close,
3227 KeyCode::Char('i') | KeyCode::Char('?') if self.progressive_guide => {
3228 self.details_expanded = !self.details_expanded;
3229 self.body_scroll = 0;
3230 ViewAction::None
3231 }
3232 KeyCode::Left | KeyCode::Char('b') => {
3233 self.move_back();
3234 ViewAction::None
3235 }
3236 KeyCode::Right | KeyCode::Char('n') => {
3237 self.move_next();
3238 ViewAction::None
3239 }
3240 KeyCode::PageUp => {
3241 self.body_scroll = self.body_scroll.saturating_sub(8);
3242 ViewAction::None
3243 }
3244 KeyCode::PageDown => {
3245 self.body_scroll = self
3246 .body_scroll
3247 .saturating_add(8)
3248 .min(self.body_max_scroll.get());
3249 ViewAction::None
3250 }
3251 KeyCode::Up if self.progressive_guide => {
3252 self.body_scroll = self.body_scroll.saturating_sub(1);
3253 ViewAction::None
3254 }
3255 KeyCode::Down if self.progressive_guide => {
3256 self.body_scroll = self
3257 .body_scroll
3258 .saturating_add(1)
3259 .min(self.body_max_scroll.get());
3260 ViewAction::None
3261 }
3262 KeyCode::Up => {
3263 self.move_back();
3264 ViewAction::None
3265 }
3266 KeyCode::Down => {
3267 self.move_next();
3268 ViewAction::None
3269 }
3270 KeyCode::Char('s') if self.progressive_guide => {
3271 if self.selected_step() == SetupStep::Verification {
3272 ViewAction::Close
3273 } else {
3274 self.move_next();
3275 ViewAction::None
3276 }
3277 }
3278 KeyCode::Char('s') => {
3279 self.commit_selected_status(StepStatus::Skipped, MessageId::SetupStepSkipped, true)
3280 }
3281 KeyCode::Char('r')
3282 if self.progressive_guide
3283 && matches!(
3284 self.selected_step(),
3285 SetupStep::RemoteRuntime | SetupStep::Verification
3286 ) =>
3287 {
3288 ViewAction::EmitAndClose(ViewEvent::SetupOpenRemoteControlRequested)
3289 }
3290 KeyCode::Char('p')
3291 if self.progressive_guide && self.selected_step() == SetupStep::Verification =>
3292 {
3293 ViewAction::EmitAndClose(ViewEvent::SetupOpenProviderRequested)
3294 }
3295 KeyCode::Char('c')
3296 if self.progressive_guide && self.selected_step() == SetupStep::Verification =>
3297 {
3298 self.selected = visible_step_index(SetupStep::TrustSandbox);
3299 self.details_expanded = false;
3300 self.body_scroll = 0;
3301 ViewAction::None
3302 }
3303 KeyCode::Char('r')
3304 if !self.progressive_guide && self.selected_step() == SetupStep::ToolsMcp =>
3305 {
3306 self.preview_tools_mcp_on_ramp()
3307 }
3308 KeyCode::Char('r') if self.selected_step() == SetupStep::RemoteRuntime => {
3309 self.preview_remote_runtime_on_ramp()
3310 }
3311 KeyCode::Char('r') => self.commit_selected_status(
3312 StepStatus::NeedsAction,
3313 MessageId::SetupStepRetryRecorded,
3314 false,
3315 ),
3316 KeyCode::Char('g') if self.selected_step() == SetupStep::Constitution => {
3317 self.commit_guided_constitution()
3318 }
3319 KeyCode::Char('p') if self.selected_step() == SetupStep::ProviderModel => {
3320 ViewAction::EmitAndClose(ViewEvent::SetupOpenProviderRequested)
3321 }
3322 KeyCode::Char('m') if self.selected_step() == SetupStep::ProviderModel => {
3323 ViewAction::EmitAndClose(ViewEvent::SetupOpenModelRequested)
3324 }
3325 KeyCode::Char('p') if self.selected_step() == SetupStep::OperateFleet => {
3326 ViewAction::EmitAndClose(ViewEvent::SetupOpenProviderRequested)
3327 }
3328 KeyCode::Char('f') if self.selected_step() == SetupStep::OperateFleet => {
3329 ViewAction::EmitAndClose(ViewEvent::SetupOpenFleetRequested)
3330 }
3331 KeyCode::Char('h') if self.selected_step() == SetupStep::Hotbar => {
3332 ViewAction::EmitAndClose(ViewEvent::SetupOpenHotbarRequested)
3333 }
3334 KeyCode::Char('m') if self.selected_step() == SetupStep::TrustSandbox => {
3335 ViewAction::EmitAndClose(ViewEvent::SetupOpenModeRequested)
3336 }
3337 KeyCode::Char('c') if self.selected_step() == SetupStep::TrustSandbox => {
3338 ViewAction::EmitAndClose(ViewEvent::SetupOpenConfigRequested)
3339 }
3340 KeyCode::Char(key @ ('1' | '2' | '3'))
3341 if self.selected_step() == SetupStep::TrustSandbox =>
3342 {
3343 self.select_runtime_preset(key)
3344 }
3345 KeyCode::Char('a') if self.selected_step() == SetupStep::TrustSandbox => {
3346 self.commit_runtime_preset()
3347 }
3348 KeyCode::Char(key @ ('1' | '2' | '3' | '4' | '5' | '6'))
3349 if self.selected_step() == SetupStep::Constitution =>
3350 {
3351 self.cycle_guided_answer(key)
3352 }
3353 KeyCode::Char('a') if self.selected_step() == SetupStep::Constitution => {
3354 self.request_model_draft()
3355 }
3356 KeyCode::Char('f') if self.selected_step() == SetupStep::Constitution => {
3357 self.toggle_freeform_edit()
3358 }
3359 KeyCode::Char('k') if self.selected_step() == SetupStep::Constitution => {
3360 self.commit_keep_existing_constitution()
3361 }
3362 KeyCode::Char('u') if self.selected_step() == SetupStep::Constitution => {
3363 self.commit_constitution(SetupCommitKind::BundledConstitution)
3364 }
3365 KeyCode::Char('d') if self.selected_step() == SetupStep::Constitution => {
3366 self.commit_constitution(SetupCommitKind::DeferredConstitution)
3367 }
3368 KeyCode::Enter if self.selected_step() == SetupStep::Constitution => {
3369 self.commit_constitution(SetupCommitKind::BundledConstitution)
3370 }
3371 KeyCode::Enter if self.selected_step() == SetupStep::Language => {
3372 self.commit_language_review()
3373 }
3374 KeyCode::Enter if self.selected_step() == SetupStep::ProviderModel => {
3375 if self.progressive_guide && !self.facts.provider_ready {
3376 ViewAction::EmitAndClose(ViewEvent::SetupOpenProviderRequested)
3377 } else {
3378 self.commit_provider_model_review()
3379 }
3380 }
3381 KeyCode::Enter if self.selected_step() == SetupStep::TrustSandbox => {
3382 self.commit_runtime_posture_review()
3383 }
3384 KeyCode::Enter if self.selected_step() == SetupStep::OperateFleet => {
3385 self.commit_operate_fleet_review()
3386 }
3387 KeyCode::Enter if self.selected_step() == SetupStep::Hotbar => {
3388 self.commit_hotbar_review()
3389 }
3390 KeyCode::Enter if self.selected_step() == SetupStep::ToolsMcp => {
3391 self.commit_tools_mcp_review()
3392 }
3393 KeyCode::Enter if self.selected_step() == SetupStep::RemoteRuntime => {
3394 self.commit_remote_runtime_review()
3395 }
3396 KeyCode::Enter if self.selected_step() == SetupStep::Persistence => {
3397 self.commit_persistence_review()
3398 }
3399 KeyCode::Enter if self.selected_step() == SetupStep::Verification => {
3400 self.commit_setup_report()
3401 }
3402 KeyCode::Enter => {
3403 self.move_next();
3404 ViewAction::None
3405 }
3406 _ => ViewAction::None,
3407 }
3408 }
3409
3410 fn handle_paste(&mut self, text: &str) -> bool {
3411 if self.selected_step() != SetupStep::Constitution || !self.constitution_advanced {
3412 return false;
3413 }
3414 self.append_freeform_note_text(text);
3415 true
3416 }
3417
3418 fn render(&self, area: Rect, buf: &mut Buffer) {
3419 let inner = render_underwater_surface(area, buf, self.surface_title());
3420 let simple_constitution =
3421 self.selected_step() == SetupStep::Constitution && !self.constitution_advanced;
3422 let hints = if self.progressive_guide {
3423 self.progressive_action_hints()
3424 } else if simple_constitution {
3425 vec![
3426 ActionHint::new(
3427 "Enter",
3428 tr(
3429 self.locale,
3430 if self.facts.constitution_file == SetupConstitutionFileState::Loaded {
3431 MessageId::SetupActionKeepExisting
3432 } else {
3433 MessageId::SetupActionUseRecommended
3434 },
3435 )
3436 .to_string(),
3437 ),
3438 ActionHint::new(
3439 "C",
3440 tr(self.locale, MessageId::SetupActionCustomize).to_string(),
3441 ),
3442 ActionHint::new("B", tr(self.locale, MessageId::SetupActionBack).to_string()),
3443 ActionHint::new(
3444 "Esc",
3445 tr(self.locale, MessageId::SetupActionCancel).to_string(),
3446 ),
3447 ]
3448 } else {
3449 let mut hints = vec![
3450 ActionHint::new(
3451 "Enter",
3452 tr(self.locale, MessageId::SetupActionContinue).to_string(),
3453 ),
3454 ActionHint::new("B", tr(self.locale, MessageId::SetupActionBack).to_string()),
3455 ActionHint::new("S", tr(self.locale, MessageId::SetupActionSkip).to_string()),
3456 ];
3457 self.extend_focused_action_hints(&mut hints);
3458 hints.push(ActionHint::new(
3459 "Esc",
3460 tr(self.locale, MessageId::SetupActionCancel).to_string(),
3461 ));
3462 hints
3463 };
3464 let content_area = render_modal_footer(inner, buf, &hints);
3465 let spec = self.selected_spec();
3466 let (title_text, question_text) = if self.progressive_guide {
3467 match self.selected_step() {
3468 SetupStep::Verification if self.facts.provider_ready => (
3469 tr(self.locale, MessageId::OnboardReadyTitle).into_owned(),
3470 tr(self.locale, MessageId::OnboardReadyLead).into_owned(),
3471 ),
3472 SetupStep::ProviderModel | SetupStep::Verification => (
3473 tr(self.locale, MessageId::OnboardProviderTitle).into_owned(),
3474 tr(self.locale, MessageId::OnboardProviderBlurb).into_owned(),
3475 ),
3476 SetupStep::TrustSandbox => (
3477 tr(self.locale, MessageId::SetupStepTrustSandboxTitle).into_owned(),
3478 tr(self.locale, MessageId::SetupRuntimePostureReviewHint).into_owned(),
3479 ),
3480 SetupStep::RemoteRuntime => (
3481 "/rc".to_string(),
3482 tr(self.locale, MessageId::CmdRemoteControlDescription).into_owned(),
3483 ),
3484 _ => (
3485 tr(self.locale, spec.title_id()).into_owned(),
3486 tr(self.locale, spec.why_id()).into_owned(),
3487 ),
3488 }
3489 } else {
3490 (
3491 tr(self.locale, spec.title_id()).into_owned(),
3492 tr(self.locale, spec.why_id()).into_owned(),
3493 )
3494 };
3495 let title = Line::from(Span::styled(
3496 title_text,
3497 Style::default()
3498 .fg(palette::WHALE_ACTION)
3499 .add_modifier(Modifier::BOLD),
3500 ));
3501 let why = Line::from(Span::raw(question_text));
3502 let mut lines = vec![title, why, Line::from("")];
3503 lines.extend(self.selected_step_detail_lines());
3504 let wrap_width = usize::from(content_area.width).max(1);
3505 let visual_rows: usize = lines
3506 .iter()
3507 .map(|line| line.width().div_ceil(wrap_width).max(1))
3508 .sum();
3509 let visible_rows = usize::from(content_area.height).max(1);
3510 let max_scroll = visual_rows.saturating_sub(visible_rows);
3511 self.body_max_scroll.set(max_scroll);
3512 let scroll = self.body_scroll.min(max_scroll);
3513 let content_area =
3514 render_panel_scroll_rail(content_area, buf, visual_rows, scroll, visible_rows, true);
3515 // Explicit base ink: same black-on-black hazard as the pager body;
3516 // value spans below carry no fg of their own.
3517 Paragraph::new(lines)
3518 .wrap(Wrap { trim: false })
3519 .scroll((u16::try_from(scroll).unwrap_or(u16::MAX), 0))
3520 .style(Style::default().fg(palette::TEXT_PRIMARY))
3521 .render(content_area, buf);
3522 }
3523
3524 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
3525 self
3526 }
3527 }
3528
3529 impl SetupWizardView {
3530 fn progressive_action_hints(&self) -> Vec<ActionHint> {
3531 let back = || ActionHint::new("B", tr(self.locale, MessageId::SetupActionBack).to_string());
3532 let exit = || {
3533 ActionHint::new(
3534 "Esc",
3535 tr(self.locale, MessageId::SetupActionCancel).to_string(),
3536 )
3537 };
3538 let details = || {
3539 ActionHint::new(
3540 "I",
3541 tr(self.locale, MessageId::CtxMenuOpenDetails).to_string(),
3542 )
3543 };
3544 let skip = || ActionHint::new("S", tr(self.locale, MessageId::SetupActionSkip).to_string());
3545 let mut hints = match self.selected_step() {
3546 SetupStep::ProviderModel => vec![
3547 ActionHint::new(
3548 "Enter",
3549 tr(
3550 self.locale,
3551 if self.facts.provider_ready {
3552 MessageId::SetupActionContinue
3553 } else {
3554 MessageId::SetupActionProvider
3555 },
3556 )
3557 .to_string(),
3558 ),
3559 skip(),
3560 details(),
3561 exit(),
3562 ],
3563 SetupStep::TrustSandbox => vec![
3564 ActionHint::new(
3565 "Enter",
3566 tr(self.locale, MessageId::SetupActionKeepExisting).to_string(),
3567 ),
3568 skip(),
3569 details(),
3570 exit(),
3571 ],
3572 SetupStep::RemoteRuntime => vec![
3573 ActionHint::new(
3574 "R",
3575 tr(self.locale, MessageId::CmdRemoteControlDescription).to_string(),
3576 ),
3577 skip(),
3578 details(),
3579 exit(),
3580 ],
3581 SetupStep::ToolsMcp => vec![
3582 ActionHint::new(
3583 "Enter",
3584 tr(self.locale, MessageId::SetupActionContinue).to_string(),
3585 ),
3586 skip(),
3587 details(),
3588 exit(),
3589 ],
3590 SetupStep::Verification => {
3591 let mut hints = vec![
3592 ActionHint::new(
3593 "Enter",
3594 tr(self.locale, MessageId::OnboardReadyStart).to_string(),
3595 ),
3596 ActionHint::new(
3597 "C",
3598 tr(self.locale, MessageId::SetupActionCustomize).to_string(),
3599 ),
3600 details(),
3601 exit(),
3602 ];
3603 if !self.facts.provider_ready {
3604 hints.insert(
3605 0,
3606 ActionHint::new(
3607 "P",
3608 tr(self.locale, MessageId::SetupActionProvider).to_string(),
3609 ),
3610 );
3611 }
3612 hints
3613 }
3614 _ => vec![exit()],
3615 };
3616 let position = self
3617 .progressive_steps()
3618 .iter()
3619 .position(|step| *step == self.selected_step())
3620 .unwrap_or(0);
3621 if position > 0 {
3622 hints.insert(hints.len().saturating_sub(1), back());
3623 }
3624 hints
3625 }
3626
3627 fn extend_focused_action_hints(&self, hints: &mut Vec<ActionHint>) {
3628 match self.selected_step() {
3629 SetupStep::Constitution if self.constitution_advanced => {
3630 hints.push(ActionHint::new(
3631 "1-6",
3632 tr(self.locale, MessageId::SetupActionTuneGuided).to_string(),
3633 ));
3634 hints.push(ActionHint::new(
3635 "G",
3636 tr(self.locale, MessageId::SetupActionGuided).to_string(),
3637 ));
3638 hints.push(ActionHint::new(
3639 "F",
3640 tr(self.locale, MessageId::SetupActionFreeform).to_string(),
3641 ));
3642 }
3643 SetupStep::ProviderModel => {
3644 hints.push(ActionHint::new(
3645 "P",
3646 tr(self.locale, MessageId::SetupActionProvider).to_string(),
3647 ));
3648 hints.push(ActionHint::new(
3649 "M",
3650 tr(self.locale, MessageId::SetupActionModel).to_string(),
3651 ));
3652 }
3653 SetupStep::OperateFleet => hints.push(ActionHint::new(
3654 "F",
3655 tr(self.locale, MessageId::SetupActionFleet).to_string(),
3656 )),
3657 SetupStep::Hotbar => hints.push(ActionHint::new(
3658 "H",
3659 tr(self.locale, MessageId::SetupActionHotbar).to_string(),
3660 )),
3661 SetupStep::ToolsMcp | SetupStep::RemoteRuntime => hints.push(ActionHint::new(
3662 "R",
3663 tr(self.locale, MessageId::SetupActionRetry).to_string(),
3664 )),
3665 SetupStep::TrustSandbox => hints.push(ActionHint::new(
3666 "C",
3667 tr(self.locale, MessageId::SetupActionConfig).to_string(),
3668 )),
3669 _ => {}
3670 }
3671 }
3672
3673 fn selected_step_detail_lines(&self) -> Vec<Line<'static>> {
3674 if self.progressive_guide {
3675 return if self.details_expanded {
3676 self.progressive_expanded_lines()
3677 } else {
3678 self.progressive_detail_lines()
3679 };
3680 }
3681 match self.selected_step() {
3682 SetupStep::ProviderModel => self.provider_model_detail_lines(),
3683 SetupStep::TrustSandbox => self.runtime_posture_detail_lines(),
3684 SetupStep::Constitution if self.constitution_advanced => {
3685 self.constitution_detail_lines()
3686 }
3687 SetupStep::Constitution => self.constitution_simple_lines(),
3688 SetupStep::OperateFleet => self.operate_fleet_detail_lines(),
3689 SetupStep::Hotbar => self.hotbar_detail_lines(),
3690 SetupStep::ToolsMcp => self.tools_mcp_detail_lines(),
3691 SetupStep::RemoteRuntime => self.remote_runtime_detail_lines(),
3692 SetupStep::Persistence => self.persistence_detail_lines(),
3693 SetupStep::Verification => self.verification_detail_lines(),
3694 _ => Vec::new(),
3695 }
3696 }
3697
3698 fn progressive_detail_lines(&self) -> Vec<Line<'static>> {
3699 match self.selected_step() {
3700 SetupStep::ProviderModel => {
3701 let answer = format!(
3702 "{} · {} · {}",
3703 self.facts.provider, self.facts.model, self.facts.auth
3704 );
3705 vec![self.detail_row(MessageId::SetupCardRouteLabel, &answer)]
3706 }
3707 SetupStep::TrustSandbox => {
3708 let answer = format!(
3709 "{} · {} · {}",
3710 self.facts.approval, self.facts.trust, self.facts.sandbox
3711 );
3712 let mut lines = vec![self.detail_row(MessageId::SetupCardApprovalLabel, &answer)];
3713 if let Some(warning) = &self.facts.project_override_warning {
3714 lines.push(
3715 self.detail_row(MessageId::SetupRuntimeProjectOverrideLabel, warning),
3716 );
3717 }
3718 lines
3719 }
3720 SetupStep::RemoteRuntime => vec![self.detail_row(
3721 MessageId::SetupRemoteModeLabel,
3722 &self.facts.remote_control_result,
3723 )],
3724 SetupStep::ToolsMcp => {
3725 let status = tr(
3726 self.locale,
3727 if self.facts.tools_mcp_needs_action {
3728 MessageId::SetupStatusNeedsAction
3729 } else {
3730 MessageId::SetupStatusVerified
3731 },
3732 )
3733 .into_owned();
3734 vec![self.detail_row(MessageId::SetupStepToolsMcpTitle, &status)]
3735 }
3736 SetupStep::Verification => self.progressive_summary_lines(),
3737 _ => self.selected_step_detail_lines_expanded(),
3738 }
3739 }
3740
3741 fn selected_step_detail_lines_expanded(&self) -> Vec<Line<'static>> {
3742 match self.selected_step() {
3743 SetupStep::ProviderModel => self.provider_model_detail_lines(),
3744 SetupStep::TrustSandbox => self.runtime_posture_detail_lines(),
3745 SetupStep::ToolsMcp => self.tools_mcp_detail_lines(),
3746 SetupStep::RemoteRuntime => self.remote_runtime_detail_lines(),
3747 SetupStep::Verification => self.verification_detail_lines(),
3748 _ => Vec::new(),
3749 }
3750 }
3751
3752 fn progressive_expanded_lines(&self) -> Vec<Line<'static>> {
3753 if self.selected_step() != SetupStep::Verification {
3754 return self.selected_step_detail_lines_expanded();
3755 }
3756 let mut lines = self.progressive_summary_lines();
3757 lines.push(Line::from(""));
3758 lines.push(Line::from(vec![
3759 Span::styled(
3760 "/settings ",
3761 Style::default()
3762 .fg(palette::WHALE_ACTION)
3763 .add_modifier(Modifier::BOLD),
3764 ),
3765 Span::raw(tr(self.locale, MessageId::CmdSettingsDescription).to_string()),
3766 ]));
3767 lines.push(Line::from(vec![
3768 Span::styled(
3769 "/config <key> ",
3770 Style::default()
3771 .fg(palette::TEXT_MUTED)
3772 .add_modifier(Modifier::BOLD),
3773 ),
3774 Span::raw(tr(self.locale, MessageId::SetupActionConfig).to_string()),
3775 ]));
3776 lines
3777 }
3778
3779 fn progressive_summary_lines(&self) -> Vec<Line<'static>> {
3780 let route = format!("{} · {}", self.facts.provider, self.facts.model);
3781 let permissions = format!(
3782 "{} · {} · {}",
3783 self.facts.approval, self.facts.trust, self.facts.sandbox
3784 );
3785 let mut lines = vec![
3786 self.detail_row(MessageId::SetupStepProviderModelTitle, &route),
3787 self.detail_row(MessageId::SetupStepTrustSandboxTitle, &permissions),
3788 self.detail_row(
3789 MessageId::SetupStepRemoteRuntimeTitle,
3790 &self.facts.remote_control_result,
3791 ),
3792 ];
3793 if self.tools_relevant() {
3794 let tools_status = tr(
3795 self.locale,
3796 if self.facts.tools_mcp_needs_action {
3797 MessageId::SetupStatusNeedsAction
3798 } else {
3799 MessageId::SetupStatusVerified
3800 },
3801 )
3802 .into_owned();
3803 lines.push(self.detail_row(MessageId::SetupStepToolsMcpTitle, &tools_status));
3804 }
3805 lines
3806 }
3807
3808 fn constitution_simple_lines(&self) -> Vec<Line<'static>> {
3809 if self.facts.constitution_file == SetupConstitutionFileState::Loaded {
3810 return vec![
3811 self.detail_row(
3812 MessageId::SetupConstitutionExistingLabel,
3813 &self
3814 .facts
3815 .constitution_file
3816 .label(self.state.constitution_choice, self.locale),
3817 ),
3818 Line::from(Span::styled(
3819 tr(
3820 self.locale,
3821 MessageId::SetupConstitutionExistingDefaultDetail,
3822 )
3823 .to_string(),
3824 Style::default().fg(palette::TEXT_MUTED),
3825 )),
3826 ];
3827 }
3828 if !matches!(
3829 self.facts.constitution_file,
3830 SetupConstitutionFileState::NotChecked | SetupConstitutionFileState::Missing
3831 ) {
3832 return vec![
3833 self.detail_row(
3834 MessageId::SetupConstitutionExistingLabel,
3835 &self
3836 .facts
3837 .constitution_file
3838 .label(self.state.constitution_choice, self.locale),
3839 ),
3840 Line::from(Span::styled(
3841 tr(self.locale, MessageId::SetupConstitutionRepairDefaultDetail).to_string(),
3842 Style::default().fg(palette::TEXT_MUTED),
3843 )),
3844 ];
3845 }
3846
3847 let recommendation = format!(
3848 "{} · {}",
3849 tr(self.locale, MessageId::SetupStatusRecommended),
3850 autonomy_label(AutonomyPreference::Balanced, self.locale)
3851 );
3852 vec![
3853 Line::from(Span::styled(
3854 recommendation,
3855 Style::default()
3856 .fg(palette::TEXT_PRIMARY)
3857 .add_modifier(Modifier::BOLD),
3858 )),
3859 Line::from(Span::styled(
3860 autonomy_priority(AutonomyPreference::Balanced, self.locale).to_string(),
3861 Style::default().fg(palette::TEXT_MUTED),
3862 )),
3863 ]
3864 }
3865
3866 fn provider_model_detail_lines(&self) -> Vec<Line<'static>> {
3867 vec![
3868 self.detail_row(MessageId::SetupCardRouteLabel, &self.facts.provider),
3869 self.detail_row(MessageId::SetupCardModelLabel, &self.facts.model),
3870 self.detail_row(MessageId::SetupCardAuthLabel, &self.facts.auth),
3871 self.detail_row(MessageId::SetupCardHealthLabel, &self.facts.health),
3872 Line::from(Span::styled(
3873 tr(
3874 self.locale,
3875 if self.facts.provider_ready {
3876 MessageId::SetupProviderModelReadyHint
3877 } else {
3878 MessageId::SetupProviderModelNeedsActionHint
3879 },
3880 )
3881 .to_string(),
3882 Style::default().fg(palette::TEXT_MUTED),
3883 )),
3884 ]
3885 }
3886
3887 fn constitution_detail_lines(&self) -> Vec<Line<'static>> {
3888 let choice = constitution_choice_label(self.state.constitution_choice);
3889 let source = constitution_source_label(self.state.constitution_source);
3890 let validity = constitution_validity_label(self.state.constitution_validity);
3891 let source_state = format!("{source}; validity {validity}");
3892 let existing_file = self
3893 .facts
3894 .constitution_file
3895 .label(self.state.constitution_choice, self.locale);
3896 let expert_override = self.facts.expert_override.label(self.locale);
3897 let preview = self
3898 .state
3899 .constitution_preview_hash
3900 .as_deref()
3901 .unwrap_or("not accepted yet")
3902 .to_string();
3903 let mut lines = vec![
3904 self.detail_row(MessageId::SetupConstitutionChoiceLabel, choice),
3905 self.detail_row(MessageId::SetupConstitutionSourceLabel, &source_state),
3906 self.detail_row(MessageId::SetupConstitutionPreviewLabel, &preview),
3907 self.detail_row(MessageId::SetupConstitutionExistingLabel, &existing_file),
3908 self.detail_row(
3909 MessageId::SetupConstitutionExpertOverrideLabel,
3910 &expert_override,
3911 ),
3912 Line::from(Span::styled(
3913 tr(self.locale, MessageId::SetupConstitutionGuidedAnswersHint).to_string(),
3914 Style::default().fg(palette::TEXT_MUTED),
3915 )),
3916 self.guided_answer_pair(
3917 (
3918 "1",
3919 MessageId::SetupConstitutionPurposeLabel,
3920 &self.guided_draft.purpose.label(self.locale),
3921 ),
3922 (
3923 "2",
3924 MessageId::SetupConstitutionAutonomyLabel,
3925 autonomy_label(self.guided_draft.autonomy, self.locale),
3926 ),
3927 ),
3928 self.guided_answer_pair(
3929 (
3930 "3",
3931 MessageId::SetupConstitutionEvidenceLabel,
3932 &self.guided_draft.evidence.label(self.locale),
3933 ),
3934 (
3935 "4",
3936 MessageId::SetupConstitutionCommunicationLabel,
3937 self.guided_draft.communication.label(self.locale),
3938 ),
3939 ),
3940 self.guided_answer_single(
3941 "5",
3942 MessageId::SetupConstitutionPrivacyLabel,
3943 self.guided_draft.privacy.label(self.locale),
3944 ),
3945 self.guided_answer_single(
3946 "6",
3947 MessageId::SetupConstitutionPrinciplesLabel,
3948 self.guided_draft.principles.label(self.locale),
3949 ),
3950 freeform_note_line(self.locale, &self.freeform_note, self.editing_freeform_note),
3951 ];
3952 if self.facts.constitution_file == SetupConstitutionFileState::Loaded {
3953 lines.push(Line::from(Span::styled(
3954 keep_existing_invitation_line(self.locale),
3955 Style::default().fg(palette::WHALE_HUMAN),
3956 )));
3957 }
3958 if let Some(label) = self
3959 .model_draft_label
3960 .as_deref()
3961 .filter(|_| self.model_draft.is_some())
3962 {
3963 lines.push(Line::from(Span::styled(
3964 model_draft_ready_line(self.locale, label),
3965 Style::default().fg(palette::STATUS_SUCCESS),
3966 )));
3967 } else if self.facts.provider_ready {
3968 lines.push(Line::from(Span::styled(
3969 model_draft_invitation_line(self.locale, &self.facts.model),
3970 Style::default().fg(palette::WHALE_HUMAN),
3971 )));
3972 }
3973 lines.push(Line::from(Span::styled(
3974 tr(self.locale, MessageId::SetupConstitutionGuidedHint).to_string(),
3975 Style::default().fg(palette::TEXT_MUTED),
3976 )));
3977 lines
3978 }
3979
3980 fn runtime_posture_detail_lines(&self) -> Vec<Line<'static>> {
3981 let project_override = self
3982 .facts
3983 .project_override_warning
3984 .clone()
3985 .unwrap_or_else(|| {
3986 tr(self.locale, MessageId::SetupRuntimeProjectOverrideNone).to_string()
3987 });
3988 let mut lines = vec![
3989 self.detail_row(MessageId::SetupCardIntentLabel, &self.facts.work_intent),
3990 self.detail_row(MessageId::SetupCardApprovalLabel, &self.facts.approval),
3991 self.detail_row(MessageId::SetupCardShellLabel, &self.facts.shell),
3992 self.detail_row(MessageId::SetupCardTrustLabel, &self.facts.trust),
3993 self.detail_row(MessageId::SetupCardSandboxLabel, &self.facts.sandbox),
3994 self.detail_row(MessageId::SetupCardNetworkLabel, &self.facts.network),
3995 self.detail_row(
3996 MessageId::SetupRuntimePresetSelectedLabel,
3997 &runtime_preset_summary(self.locale, self.runtime_preset),
3998 ),
3999 self.detail_row(
4000 MessageId::SetupRuntimePresetDiffLabel,
4001 &runtime_preset_inline_diff(self.runtime_preset, &self.facts),
4002 ),
4003 self.detail_row(
4004 MessageId::SetupRuntimeProjectOverrideLabel,
4005 &project_override,
4006 ),
4007 Line::from(Span::styled(
4008 tr(self.locale, MessageId::SetupRuntimePostureBoundary).to_string(),
4009 Style::default().fg(palette::TEXT_MUTED),
4010 )),
4011 Line::from(Span::styled(
4012 tr(self.locale, MessageId::SetupRuntimePresetSafetyFloor).to_string(),
4013 Style::default().fg(palette::TEXT_MUTED),
4014 )),
4015 self.setup_review_hint_line(
4016 MessageId::SetupRuntimePostureReviewHint,
4017 Some("Press M for work mode or C for config."),
4018 ),
4019 Line::from(Span::styled(
4020 tr(self.locale, MessageId::SetupRuntimePresetApplyHint).to_string(),
4021 Style::default().fg(palette::TEXT_MUTED),
4022 )),
4023 ];
4024 for (idx, preset) in SetupRuntimePreset::ALL.iter().enumerate() {
4025 let marker = if *preset == self.runtime_preset {
4026 ">"
4027 } else {
4028 " "
4029 };
4030 lines.push(Line::from(Span::styled(
4031 format!(
4032 "{marker} {}. {}",
4033 idx + 1,
4034 runtime_preset_summary(self.locale, *preset)
4035 ),
4036 Style::default().fg(if *preset == self.runtime_preset {
4037 palette::TEXT_PRIMARY
4038 } else {
4039 palette::TEXT_MUTED
4040 }),
4041 )));
4042 }
4043 lines
4044 }
4045
4046 fn operate_fleet_detail_lines(&self) -> Vec<Line<'static>> {
4047 let route = format!("{} / {}", self.facts.provider, self.facts.model);
4048 let readiness = self.ready_label(self.operate_fleet_facts_ready());
4049 vec![
4050 self.detail_row(MessageId::SetupCardRouteLabel, &route),
4051 self.detail_row(MessageId::SetupCardAuthLabel, &self.facts.auth),
4052 self.detail_row(
4053 MessageId::SetupOperateRuntimeLabel,
4054 &self.facts.operate_runtime_result,
4055 ),
4056 self.detail_row(
4057 MessageId::SetupOperateRosterLabel,
4058 &self.facts.fleet_roster_result,
4059 ),
4060 self.detail_row(
4061 MessageId::SetupOperateConcurrencyLabel,
4062 &self.facts.operate_concurrency_result,
4063 ),
4064 self.detail_row(MessageId::SetupOperateReadinessLabel, &readiness),
4065 self.setup_review_hint_line(MessageId::SetupOperateReviewHint, None),
4066 ]
4067 }
4068
4069 fn hotbar_detail_lines(&self) -> Vec<Line<'static>> {
4070 vec![
4071 self.detail_row(
4072 MessageId::SetupHotbarBindingsLabel,
4073 &self.facts.hotbar_bindings_result,
4074 ),
4075 self.detail_row(
4076 MessageId::SetupHotbarActionsLabel,
4077 &self.facts.hotbar_actions_result,
4078 ),
4079 self.setup_review_hint_line(
4080 MessageId::SetupHotbarReviewHint,
4081 Some("Press H to customize slots."),
4082 ),
4083 ]
4084 }
4085
4086 fn tools_mcp_detail_lines(&self) -> Vec<Line<'static>> {
4087 vec![
4088 self.detail_row(
4089 MessageId::SetupToolsMcpServersLabel,
4090 &self.facts.tools_mcp_servers_result,
4091 ),
4092 self.detail_row(
4093 MessageId::SetupToolsMcpSkillsLabel,
4094 &self.facts.tools_mcp_skills_result,
4095 ),
4096 self.detail_row(
4097 MessageId::SetupToolsMcpToolsLabel,
4098 &self.facts.tools_mcp_tools_result,
4099 ),
4100 self.detail_row(
4101 MessageId::SetupToolsMcpPluginsLabel,
4102 &self.facts.tools_mcp_plugins_result,
4103 ),
4104 self.detail_row(
4105 MessageId::SetupToolsMcpHotbarLabel,
4106 &self.facts.tools_mcp_hotbar_result,
4107 ),
4108 self.detail_row(
4109 MessageId::SetupToolsMcpDshLabel,
4110 &self.facts.tools_mcp_dsh_result,
4111 ),
4112 self.setup_review_hint_line(
4113 MessageId::SetupToolsMcpReviewHint,
4114 Some("Press R for safe on-ramps (no auto-run)."),
4115 ),
4116 ]
4117 }
4118
4119 /// #3409: one row per mode, each carrying its own observed status. The
4120 /// registry counts stay available in the preview; the card itself answers
4121 /// "where can this be reached from?" in four plain lines.
4122 fn remote_runtime_detail_lines(&self) -> Vec<Line<'static>> {
4123 let mut lines = Vec::new();
4124 for fact in &self.facts.remote_modes {
4125 lines.push(self.detail_row(
4126 fact.mode.label_id(),
4127 &format!(
4128 "{} · {}",
4129 tr(self.locale, fact.status.label_id()),
4130 fact.detail
4131 ),
4132 ));
4133 }
4134 if lines.is_empty() {
4135 lines.push(self.detail_row(
4136 MessageId::SetupRemoteModeLabel,
4137 &self.facts.remote_mode_result,
4138 ));
4139 }
4140 lines.push(self.detail_row(
4141 MessageId::SetupRemoteProvidersLabel,
4142 &self.facts.remote_providers_result,
4143 ));
4144 lines.push(self.setup_review_hint_line(
4145 MessageId::SetupRemoteReviewHint,
4146 Some("Press R to preview (nothing is written). Enter keeps local-only."),
4147 ));
4148 lines
4149 }
4150
4151 fn persistence_detail_lines(&self) -> Vec<Line<'static>> {
4152 vec![
4153 self.detail_row(
4154 MessageId::SetupPersistenceHomeLabel,
4155 &self.facts.persistence.home_result,
4156 ),
4157 self.detail_row(
4158 MessageId::SetupPersistenceConfigLabel,
4159 &self.facts.persistence.config_result,
4160 ),
4161 self.detail_row(
4162 MessageId::SetupPersistenceStateLabel,
4163 &self.facts.persistence.state_result,
4164 ),
4165 self.detail_row(
4166 MessageId::SetupPersistenceConstitutionLabel,
4167 &self.facts.persistence.constitution_result,
4168 ),
4169 self.detail_row(
4170 MessageId::SetupPersistenceMemoryLabel,
4171 &self.facts.persistence.memory_result,
4172 ),
4173 self.setup_review_hint_line(MessageId::SetupPersistenceReviewHint, None),
4174 ]
4175 }
4176
4177 fn verification_detail_lines(&self) -> Vec<Line<'static>> {
4178 let mut lines = vec![
4179 self.detail_row(
4180 MessageId::SetupReportFirstRunLabel,
4181 &self.ready_label(self.state.first_run_ready()),
4182 ),
4183 self.detail_row(
4184 MessageId::SetupReportUpdateLabel,
4185 &self.ready_label(self.state.update_ready(CONSTITUTION_CHECKPOINT_VERSION)),
4186 ),
4187 self.detail_row(
4188 MessageId::SetupReportOperateLabel,
4189 &self.ready_label(self.state.operate_ready()),
4190 ),
4191 self.detail_row(
4192 MessageId::SetupReportSourceLabel,
4193 &self.state_source_label(),
4194 ),
4195 self.detail_row(
4196 MessageId::SetupReportAutonomyLabel,
4197 &self.facts.constitution_autonomy,
4198 ),
4199 self.detail_row(
4200 MessageId::SetupReportRuntimePostureLabel,
4201 &self.facts.runtime_result,
4202 ),
4203 Line::from(""),
4204 Line::from(Span::styled(
4205 tr(self.locale, MessageId::SetupReportRowsLabel).to_string(),
4206 Style::default()
4207 .fg(palette::TEXT_MUTED)
4208 .add_modifier(Modifier::BOLD),
4209 )),
4210 ];
4211
4212 for spec in STEP_SPECS {
4213 let step = spec.id();
4214 let entry = self.state.steps.get(&step);
4215 let required = entry.map_or(spec.required(), |entry| entry.required);
4216 let required_label = if required {
4217 tr(self.locale, MessageId::SetupReportRequired)
4218 } else {
4219 tr(self.locale, MessageId::SetupReportOptional)
4220 };
4221 let mut value = format!(
4222 "{} ({})",
4223 self.status_label(self.state.status(step)),
4224 required_label
4225 );
4226 if let Some(version) = entry.and_then(|entry| entry.version.as_deref()) {
4227 value.push_str(&format!(" · {version}"));
4228 }
4229 if let Some(result) = entry.and_then(|entry| entry.result.as_deref()) {
4230 value.push_str(&format!(" · {result}"));
4231 }
4232 lines.push(self.detail_row(spec.title_id(), &value));
4233 }
4234
4235 lines.push(Line::from(""));
4236 let next_action = tr(self.locale, self.next_action_id()).to_string();
4237 lines.push(self.detail_row(MessageId::SetupReportNextActionLabel, &next_action));
4238 lines
4239 }
4240
4241 fn setup_review_hint_line(
4242 &self,
4243 hint_id: MessageId,
4244 english_action: Option<&'static str>,
4245 ) -> Line<'static> {
4246 let hint = if self.locale == Locale::En {
4247 let mut hint = "Enter records this setup snapshot.".to_string();
4248 if let Some(action) = english_action {
4249 hint.push(' ');
4250 hint.push_str(action);
4251 }
4252 hint
4253 } else {
4254 tr(self.locale, hint_id).to_string()
4255 };
4256 Line::from(Span::styled(hint, Style::default().fg(palette::TEXT_MUTED)))
4257 }
4258
4259 fn ready_label(&self, ready: bool) -> String {
4260 if ready {
4261 tr(self.locale, MessageId::SetupReportReady).to_string()
4262 } else {
4263 tr(self.locale, MessageId::SetupStatusNeedsAction).to_string()
4264 }
4265 }
4266
4267 fn state_source_label(&self) -> String {
4268 if self.state.inherited {
4269 tr(self.locale, MessageId::SetupReportInherited).to_string()
4270 } else {
4271 tr(self.locale, MessageId::SetupReportPersisted).to_string()
4272 }
4273 }
4274
4275 fn next_action_id(&self) -> MessageId {
4276 if !self.state.update_ready(CONSTITUTION_CHECKPOINT_VERSION) {
4277 return MessageId::SetupReportNextActionConstitution;
4278 }
4279 if !matches!(
4280 self.state.status(SetupStep::ProviderModel),
4281 StepStatus::Configured | StepStatus::Verified | StepStatus::NeedsAction
4282 ) {
4283 return MessageId::SetupReportNextActionProvider;
4284 }
4285 if !self.state.runtime_posture_source.is_reviewed() {
4286 return MessageId::SetupReportNextActionRuntime;
4287 }
4288 if !self.state.first_run_ready() {
4289 return MessageId::SetupReportNextActionRequired;
4290 }
4291 if !self.state.operate_ready() {
4292 return MessageId::SetupReportNextActionOperate;
4293 }
4294 MessageId::SetupReportNextActionNone
4295 }
4296
4297 fn detail_row(&self, label: MessageId, value: &str) -> Line<'static> {
4298 Line::from(vec![
4299 Span::styled(
4300 format!("{} ", tr(self.locale, label)),
4301 Style::default()
4302 .fg(palette::TEXT_MUTED)
4303 .add_modifier(Modifier::BOLD),
4304 ),
4305 Span::raw(value.to_string()),
4306 ])
4307 }
4308
4309 fn guided_answer_pair(
4310 &self,
4311 left: (&str, MessageId, &str),
4312 right: (&str, MessageId, &str),
4313 ) -> Line<'static> {
4314 let label_style = Style::default()
4315 .fg(palette::TEXT_MUTED)
4316 .add_modifier(Modifier::BOLD);
4317 Line::from(vec![
4318 Span::styled(
4319 format!("{} {} ", left.0, tr(self.locale, left.1)),
4320 label_style,
4321 ),
4322 Span::raw(left.2.to_string()),
4323 Span::styled(" · ", Style::default().fg(palette::TEXT_MUTED)),
4324 Span::styled(
4325 format!("{} {} ", right.0, tr(self.locale, right.1)),
4326 label_style,
4327 ),
4328 Span::raw(right.2.to_string()),
4329 ])
4330 }
4331
4332 fn guided_answer_single(&self, key: &str, label: MessageId, value: &str) -> Line<'static> {
4333 Line::from(vec![
4334 Span::styled(
4335 format!("{key} {} ", tr(self.locale, label)),
4336 Style::default()
4337 .fg(palette::TEXT_MUTED)
4338 .add_modifier(Modifier::BOLD),
4339 ),
4340 Span::raw(value.to_string()),
4341 ])
4342 }
4343 }
4344
4345 fn setup_report_ready(state: &SetupState) -> bool {
4346 state.first_run_ready() || state.update_ready(CONSTITUTION_CHECKPOINT_VERSION)
4347 }
4348
4349 fn runtime_preset_summary(locale: Locale, preset: SetupRuntimePreset) -> String {
4350 format!(
4351 "{} - {}",
4352 tr(locale, preset.title_id()),
4353 tr(locale, preset.description_id())
4354 )
4355 }
4356
4357 fn runtime_preset_inline_diff(preset: SetupRuntimePreset, facts: &SetupRuntimeFacts) -> String {
4358 runtime_preset_diff_rows(preset, facts).join("; ")
4359 }
4360
4361 fn runtime_preset_preview_text(
4362 locale: Locale,
4363 preset: SetupRuntimePreset,
4364 facts: &SetupRuntimeFacts,
4365 ) -> String {
4366 let mut lines = vec![
4367 tr(locale, MessageId::SetupRuntimePresetPreviewTitle).to_string(),
4368 runtime_preset_summary(locale, preset),
4369 String::new(),
4370 tr(locale, MessageId::SetupRuntimePresetDiffLabel).to_string(),
4371 ];
4372 lines.extend(
4373 runtime_preset_diff_rows(preset, facts)
4374 .into_iter()
4375 .map(|row| format!("- {row}")),
4376 );
4377 lines.extend([
4378 String::new(),
4379 tr(locale, MessageId::SetupRuntimePostureBoundary).to_string(),
4380 tr(locale, MessageId::SetupRuntimePresetSafetyFloor).to_string(),
4381 tr(locale, MessageId::SetupRuntimePresetApplyHint).to_string(),
4382 ]);
4383 lines.join("\n")
4384 }
4385
4386 fn runtime_preset_diff_rows(preset: SetupRuntimePreset, facts: &SetupRuntimeFacts) -> Vec<String> {
4387 let approval_target = preset.approval_policy().map_or_else(
4388 || "removed; Full Access comes from settings.permission_posture".to_string(),
4389 ToString::to_string,
4390 );
4391 let mut rows = vec![
4392 format!(
4393 "settings.default_mode: {} -> {}",
4394 facts.default_mode,
4395 preset.display_mode()
4396 ),
4397 format!(
4398 "settings.permission_posture: -> {}",
4399 preset.permission_posture()
4400 ),
4401 format!(
4402 "config.approval_policy: {} -> {}",
4403 facts.approval_policy_value, approval_target
4404 ),
4405 format!(
4406 "config.allow_shell: {} -> {}",
4407 facts.allow_shell_enabled,
4408 preset.allow_shell()
4409 ),
4410 format!(
4411 "config.sandbox_mode: {} -> {}",
4412 facts.sandbox_mode_value,
4413 preset.sandbox_mode()
4414 ),
4415 format!(
4416 "config.network.default: {} -> unchanged",
4417 facts.network_default_value
4418 ),
4419 format!("workspace trust: {} -> unchanged", facts.trust),
4420 ];
4421 if let Some(warning) = facts.project_override_warning.as_deref() {
4422 rows.push(format!("project override warning: {warning}"));
4423 }
4424 rows
4425 }
4426
4427 fn project_runtime_override_warning(workspace: &Path, locale: Locale) -> Option<String> {
4428 let outcome = codewhale_config::load_project_config_outcome(workspace);
4429 // A project config that exists but can't be parsed is not the same as no
4430 // project config: its restrictions are silently not in effect, and the
4431 // workspace falls back to the user's baseline. Say so here rather than
4432 // only in a log line the TUI never shows.
4433 if let Some((path, reason)) = outcome.invalid() {
4434 return Some(
4435 tr(locale, MessageId::SetupProjectPermissionsInvalid)
4436 .replace("{path}", &path.display().to_string())
4437 .replace("{reason}", reason),
4438 );
4439 }
4440 let project = outcome.into_config()?;
4441 let mut fields = Vec::new();
4442 if let Some(policy) = project.approval_policy.as_deref() {
4443 fields.push(format!("approval_policy={policy}"));
4444 }
4445 if let Some(mode) = project.sandbox_mode.as_deref() {
4446 fields.push(format!("sandbox_mode={mode}"));
4447 }
4448 if fields.is_empty() {
4449 return None;
4450 }
4451 Some(
4452 tr(locale, MessageId::SetupProjectPermissionsOverride)
4453 .replace("{fields}", &fields.join(", ")),
4454 )
4455 }
4456
4457 fn setup_report_result(state: &SetupState, facts: &SetupRuntimeFacts) -> String {
4458 format!(
4459 "first_run={}, update={}, operate={}, constitution={:?}, autonomy={}, posture={:?}, runtime={}, operate_fleet={}",
4460 if state.first_run_ready() {
4461 "ready"
4462 } else {
4463 "needs_action"
4464 },
4465 if state.update_ready(CONSTITUTION_CHECKPOINT_VERSION) {
4466 "ready"
4467 } else {
4468 "needs_action"
4469 },
4470 if state.operate_ready() {
4471 "ready"
4472 } else {
4473 "needs_action"
4474 },
4475 state.constitution_choice,
4476 facts.constitution_autonomy,
4477 state.runtime_posture_source,
4478 facts.runtime_result,
4479 facts.operate_result
4480 )
4481 }
4482
4483 fn remote_runtime_on_ramp_text(locale: Locale, facts: &SetupRuntimeFacts) -> String {
4484 remote::on_ramp_text(
4485 locale,
4486 &facts.remote_clouds_result,
4487 &facts.remote_bridges_result,
4488 &facts.remote_providers_result,
4489 &facts.remote_mode_result,
4490 &facts.remote_command_provider,
4491 )
4492 }
4493
4494 fn tools_mcp_on_ramp_text(locale: Locale, facts: &SetupRuntimeFacts) -> String {
4495 let tools_facts = tools_mcp::SetupToolsMcpFacts {
4496 servers_result: facts.tools_mcp_servers_result.clone(),
4497 skills_result: facts.tools_mcp_skills_result.clone(),
4498 tools_result: facts.tools_mcp_tools_result.clone(),
4499 plugins_result: facts.tools_mcp_plugins_result.clone(),
4500 hotbar_result: facts.tools_mcp_hotbar_result.clone(),
4501 dsh_result: facts.tools_mcp_dsh_result.clone(),
4502 result: facts.tools_mcp_result.clone(),
4503 overall_status: if facts.tools_mcp_needs_action {
4504 tools_mcp::InventoryStatus::NeedsConfig
4505 } else if facts.tools_mcp_result.contains("overall=off") {
4506 tools_mcp::InventoryStatus::Off
4507 } else {
4508 tools_mcp::InventoryStatus::Healthy
4509 },
4510 needs_action: facts.tools_mcp_needs_action,
4511 mcp_path_display: facts.tools_mcp_path_display.clone(),
4512 skills_path_display: facts.tools_mcp_skills_path_display.clone(),
4513 plugins_path_display: facts.tools_mcp_plugins_path_display.clone(),
4514 };
4515 tools_mcp::on_ramp_text(locale, &tools_facts)
4516 }
4517
4518 /// Who authored the draft being previewed for ratification.
4519 #[derive(Debug, Clone, PartialEq, Eq)]
4520 enum DraftProvenance {
4521 /// Rendered deterministically from the guided answers.
4522 Guided,
4523 /// Drafted by the named model, then sanitized and bounded by Codewhale.
4524 Model(String),
4525 /// The user's existing `constitution.json`, shown unchanged for the
4526 /// keep-existing checkpoint completion (#3794).
4527 Existing,
4528 }
4529
4530 fn ratification_preview_title(locale: Locale) -> &'static str {
4531 match locale {
4532 Locale::Ja => "ユーザー憲法 - 批准前の草案",
4533 Locale::ZhHans => "用户宪章 — 确认前草案",
4534 Locale::ZhHant => "使用者憲法 - 批准前草案",
4535 Locale::PtBr => "Constituição do Usuário - Rascunho para Ratificação",
4536 Locale::Es419 => "Constitución del Usuario - Borrador para Ratificación",
4537 Locale::Vi => "Hiến pháp Người dùng - Bản nháp để phê chuẩn",
4538 Locale::Ko => "사용자 헌법 - 승인 전 초안",
4539 Locale::Ca => "Constitució de l'Usuari - Esborrany per a Ratificació",
4540 Locale::De => "Nutzerverfassung - Entwurf zur Ratifizierung",
4541 Locale::Fr => "Constitution de l'Utilisateur - Brouillon pour Ratification",
4542 Locale::Id => "Konstitusi Pengguna - Draf untuk Ratifikasi",
4543 Locale::Hi => "उपयोगकर्ता संविधान - अंगीकार हेतु मसौदा",
4544 Locale::Ru => "Конституция пользователя - Проект для ратификации",
4545 Locale::Uk => "Конституція користувача - Проєкт для ратифікації",
4546 _ => "User Constitution — Draft for Ratification",
4547 }
4548 }
4549
4550 /// The ratification artifact shown in the pager: provenance, what a
4551 /// constitution is, the exact block that will be injected (byte-identical to
4552 /// prompt assembly's rendering), its authority boundaries, and how to ratify
4553 /// or amend. Only the scaffold differs between guided and model drafts — the
4554 /// law itself always comes from the same renderer.
4555 fn constitution_ratification_text(
4556 locale: Locale,
4557 constitution: &UserConstitution,
4558 provenance: &DraftProvenance,
4559 ) -> String {
4560 const RULE: &str = "──────────────────────────────────────────────────────";
4561 let rendered = constitution
4562 .render_block(None)
4563 .unwrap_or_else(|| match locale {
4564 Locale::Ja => "構造化された憲法は空です。".to_string(),
4565 Locale::ZhHans => "结构化宪章为空。".to_string(),
4566 Locale::ZhHant => "結構化憲法為空。".to_string(),
4567 Locale::PtBr => "A constituição estruturada está vazia.".to_string(),
4568 Locale::Es419 => "La constitución estructurada está vacía.".to_string(),
4569 Locale::Vi => "Hiến pháp có cấu trúc đang trống.".to_string(),
4570 Locale::Ko => "구조화된 헌법이 비어 있습니다.".to_string(),
4571 Locale::Ca => "La constitució estructurada és buida.".to_string(),
4572 Locale::De => "Die strukturierte Verfassung ist leer.".to_string(),
4573 Locale::Fr => "La constitution structurée est vide.".to_string(),
4574 Locale::Id => "Konstitusi terstruktur kosong.".to_string(),
4575 Locale::Hi => "संरचित संविधान खाली है।".to_string(),
4576 Locale::Ru => "Структурированная конституция пуста.".to_string(),
4577 Locale::Uk => "Структурована конституція порожня.".to_string(),
4578 _ => "The structured constitution is empty.".to_string(),
4579 });
4580
4581 match locale {
4582 Locale::Ja => {
4583 let drafted_by = match provenance {
4584 DraftProvenance::Model(label) => format!(
4585 "{label} があなたのガイド回答から起草し、Codewhale が構造検証と境界制限を適用しました。"
4586 ),
4587 DraftProvenance::Guided => {
4588 "あなたのガイド回答から決定的に生成されました。".to_string()
4589 }
4590 DraftProvenance::Existing => {
4591 "既存の憲法を constitution.json から読み込み、変更せずに表示しています。"
4592 .to_string()
4593 }
4594 };
4595 let ratify_how = match provenance {
4596 DraftProvenance::Existing => {
4597 "これはすでに有効な基準です。プレビューを閉じて K を押すと、このまま保持してチェックポイントを完了します。\
4598 ファイルは変更されません。/constitution または /setup でいつでも修正できます。"
4599 }
4600 _ => {
4601 "確認するまで、どの内容も基準にはなりません。プレビューを閉じて G を押すと批准して保存します。\
4602 /constitution または /setup でいつでも修正できます。"
4603 }
4604 };
4605 format!(
4606 "CODEWHALE · ユーザー憲法\n{RULE}\n\n{drafted_by}\n\n\
4607 これは Codewhale があなたと協働するための常設の基準です。優れた憲法のように、使えるほど短く、\
4608 網羅的な規則ではなく持続する原則で構成され、あなたの変化に合わせて修正できます。\
4609 すべての個別判断を裁くのではなく権限と境界を定め、セッションを越えて協働を継続させます。\
4610 ただしこれは記憶ではありません。履歴ではなく原則を保持します。\n\n\
4611 {rendered}\n\n\
4612 権限の階層\nあなたの直接の指示は常にこの文書より優先されます。\n\n\
4613 これができないこと\n\
4614 これは行動を導くものです。承認ポリシー、サンドボックス、Shell、ネットワーク、信頼、MCP 権限、\
4615 既定モード、公開、支出の権限を付与または変更することはできません。これらは実行時にあなたが管理します。\n\n\
4616 縮小コアと任意モジュール\n\
4617 組み込みのコアは引き続き有効です。この草案はユーザーグローバルの長期設定だけを保存します。\
4618 実行とオーケストレーションの機能は、ランタイムポリシー、現在のツールカタログ、または将来の任意モジュールから提供されます。このプレビューはモジュールを有効化せず、設定も変更しません。\n\n\
4619 批准\n{ratify_how}"
4620 )
4621 }
4622 Locale::ZhHans => {
4623 let drafted_by = match provenance {
4624 DraftProvenance::Model(label) => format!(
4625 "由 {label} 根据你的引导式答案起草,并已由 Codewhale 完成结构校验与边界限制。"
4626 ),
4627 DraftProvenance::Guided => "由你的引导式答案确定性生成。".to_string(),
4628 DraftProvenance::Existing => {
4629 "你现有的宪章,读取自 constitution.json——原样展示,未做任何修改。".to_string()
4630 }
4631 };
4632 let ratify_how = match provenance {
4633 DraftProvenance::Existing => {
4634 "这已是你当前使用的宪章。关闭此预览后按 K 保留并完成检查点——文件不会被修改。\
4635 之后可随时用 /constitution 或 /setup 修改。"
4636 }
4637 _ => {
4638 "未经你确认,任何内容都不会成为宪章。关闭此预览后按 G 确认并保存;\
4639 之后可随时用 /constitution 或 /setup 修改。"
4640 }
4641 };
4642 format!(
4643 "CODEWHALE · 用户宪章\n{RULE}\n\n{drafted_by}\n\n\
4644 这是 Codewhale 与你协作时长期遵循的偏好和规则。内容应保持简短、便于执行,以持久原则为主,并可随时调整。\
4645 它界定协作方式与行为边界,而不是替你决定每一种情况;它让协作跨会话延续——但它不是记忆,只保留原则,不保留历史。\n\n\
4646 {rendered}\n\n\
4647 权限层级\n你的直接指令始终高于本文件。\n\n\
4648 它不能做什么\n\
4649 它只提供行为指导,不能授予或更改审批策略、沙箱、Shell、网络、信任、MCP 权限、默认模式、发布或支出权限——这些始终由你在运行时掌控。\n\n\
4650 精简核心与可选策略\n\
4651 内置核心始终生效。本草案只保存你的用户全局长期偏好。执行与编排能力来自运行时策略、当前工具目录或未来的可选规则包;此预览不会启用任何策略或更改配置。\n\n\
4652 确认\n{ratify_how}"
4653 )
4654 }
4655 Locale::ZhHant => {
4656 let drafted_by = match provenance {
4657 DraftProvenance::Model(label) => format!(
4658 "由 {label} 根據你的引導式答案起草,並已由 Codewhale 完成結構驗證與邊界限制。"
4659 ),
4660 DraftProvenance::Guided => "由你的引導式答案確定性生成。".to_string(),
4661 DraftProvenance::Existing => {
4662 "你現有的憲法,讀取自 constitution.json;原樣展示,未做任何修改。".to_string()
4663 }
4664 };
4665 let ratify_how = match provenance {
4666 DraftProvenance::Existing => {
4667 "這已是你現行的準則。關閉此預覽後按 K 保留並完成檢查點;\
4668 檔案不會被修改。之後可隨時用 /constitution 或 /setup 修訂。"
4669 }
4670 _ => {
4671 "未經你確認,任何內容都不會成為準則。關閉此預覽後按 G 批准並保存;\
4672 之後可隨時用 /constitution 或 /setup 修訂。"
4673 }
4674 };
4675 format!(
4676 "CODEWHALE · 使用者憲法\n{RULE}\n\n{drafted_by}\n\n\
4677 這是 Codewhale 與你協作的長期準則。像優秀的憲法一樣:足夠簡短因而可用,由持久原則而非詳盡規則構成,並且可以隨你修訂。\
4678 它界定權力與邊界,而非裁決每個具體決定;它讓協作跨會話延續,但它不是記憶,它承載的是原則,而非歷史。\n\n\
4679 {rendered}\n\n\
4680 權限層級\n你的直接指令始終高於本文件。\n\n\
4681 它不能做什麼\n\
4682 它只提供行為指導,不能授予或更改審批策略、沙箱、Shell、網路、信任、MCP 權限、預設模式、發布或支出權限;這些始終由你在執行時掌控。\n\n\
4683 精簡核心與可選模組\n\
4684 內建核心始終生效。本草案只保存你的使用者全域長期偏好。執行與編排能力由執行時政策、即時工具目錄或未來的可選模組提供;此預覽不會啟用模組或更改其配置。\n\n\
4685 批准\n{ratify_how}"
4686 )
4687 }
4688 Locale::PtBr => {
4689 let drafted_by = match provenance {
4690 DraftProvenance::Model(label) => format!(
4691 "Rascunhado por {label} a partir das suas respostas guiadas, depois validado por schema e limitado pelo Codewhale."
4692 ),
4693 DraftProvenance::Guided => {
4694 "Renderizado deterministicamente a partir das suas respostas guiadas.".to_string()
4695 }
4696 DraftProvenance::Existing => {
4697 "Sua constituição existente, carregada de constitution.json, é exibida sem alterações."
4698 .to_string()
4699 }
4700 };
4701 let ratify_how = match provenance {
4702 DraftProvenance::Existing => {
4703 "Esta já é sua regra vigente. Feche a prévia e pressione K para mantê-la e concluir o checkpoint; \
4704 o arquivo não será modificado. Edite quando quiser com /constitution ou /setup."
4705 }
4706 _ => {
4707 "Nada vira regra até você confirmar. Feche a prévia e pressione G para ratificar e salvar. \
4708 Edite quando quiser com /constitution ou /setup."
4709 }
4710 };
4711 format!(
4712 "CODEWHALE · CONSTITUIÇÃO DO USUÁRIO\n{RULE}\n\n{drafted_by}\n\n\
4713 Esta é a regra permanente de como o Codewhale trabalha com você. Como boas constituições, \
4714 ela é curta o bastante para ser usada, formada por princípios duráveis em vez de regras exaustivas, \
4715 e pode ser emendada conforme você muda. Ela define poderes e limites em vez de decidir cada caso, \
4716 e dá continuidade à colaboração entre sessões. Mas ela não é memória: carrega princípios, não histórico.\n\n\
4717 {rendered}\n\n\
4718 HIERARQUIA DE AUTORIDADE\nSeus pedidos diretos sempre superam este documento.\n\n\
4719 O QUE ISTO NÃO PODE FAZER\n\
4720 Isto orienta comportamento. Não pode conceder nem alterar política de aprovação, sandbox, shell, rede, \
4721 confiança, permissões MCP, modo padrão, publicação ou autoridade para gastos; isso continua sob seu controle em tempo de execução.\n\n\
4722 NÚCLEO REDUZIDO E MÓDULOS OPT-IN\n\
4723 O núcleo embutido continua ativo. Este rascunho só salva suas preferências permanentes globais de usuário. \
4724 Capacidades de execução e orquestração vêm da política de execução, do catálogo de ferramentas ativo ou de módulos opt-in futuros; esta prévia não ativa módulos nem muda sua configuração.\n\n\
4725 RATIFICAÇÃO\n{ratify_how}"
4726 )
4727 }
4728 Locale::Es419 => {
4729 let drafted_by = match provenance {
4730 DraftProvenance::Model(label) => format!(
4731 "Redactado por {label} desde tus respuestas guiadas, luego validado por schema y acotado por Codewhale."
4732 ),
4733 DraftProvenance::Guided => {
4734 "Renderizado de forma determinística desde tus respuestas guiadas.".to_string()
4735 }
4736 DraftProvenance::Existing => {
4737 "Tu constitución existente, cargada desde constitution.json, se muestra sin cambios."
4738 .to_string()
4739 }
4740 };
4741 let ratify_how = match provenance {
4742 DraftProvenance::Existing => {
4743 "Esta ya es tu regla vigente. Cierra la vista previa y presiona K para conservarla y completar el checkpoint; \
4744 el archivo no se modifica. Puedes enmendarla cuando quieras con /constitution o /setup."
4745 }
4746 _ => {
4747 "Nada se vuelve regla hasta que confirmes. Cierra la vista previa y presiona G para ratificar y guardar. \
4748 Puedes enmendarla cuando quieras con /constitution o /setup."
4749 }
4750 };
4751 format!(
4752 "CODEWHALE · CONSTITUCIÓN DEL USUARIO\n{RULE}\n\n{drafted_by}\n\n\
4753 Esta es la regla permanente de cómo Codewhale trabaja contigo. Como las buenas constituciones, \
4754 es lo bastante breve para usarse, hecha de principios duraderos en vez de reglas exhaustivas, \
4755 y enmendable a medida que cambias. Define poderes y límites en vez de decidir cada caso, \
4756 y da continuidad a la colaboración entre sesiones. Pero no es memoria: lleva principios, no historial.\n\n\
4757 {rendered}\n\n\
4758 JERARQUÍA DE AUTORIDAD\nTus pedidos directos siempre superan este documento.\n\n\
4759 LO QUE ESTO NO PUEDE HACER\n\
4760 Orienta comportamiento. No puede conceder ni cambiar política de aprobación, sandbox, shell, red, \
4761 confianza, permisos MCP, modo predeterminado, publicación o autoridad de gasto; eso sigue bajo tu control en tiempo de ejecución.\n\n\
4762 NÚCLEO REDUCIDO Y MÓDULOS OPT-IN\n\
4763 El núcleo integrado sigue activo. Este borrador solo guarda tus preferencias permanentes globales de usuario. \
4764 Las capacidades de ejecución y orquestación provienen de la política de ejecución, el catálogo activo de herramientas o módulos opt-in futuros; esta vista previa no activa módulos ni cambia su configuración.\n\n\
4765 RATIFICACIÓN\n{ratify_how}"
4766 )
4767 }
4768 Locale::Vi => {
4769 let drafted_by = match provenance {
4770 DraftProvenance::Model(label) => format!(
4771 "Được {label} soạn từ câu trả lời hướng dẫn của bạn, rồi được Codewhale kiểm tra schema và giới hạn biên."
4772 ),
4773 DraftProvenance::Guided => {
4774 "Được kết xuất xác định từ câu trả lời hướng dẫn của bạn.".to_string()
4775 }
4776 DraftProvenance::Existing => {
4777 "Hiến pháp hiện có của bạn, tải từ constitution.json, được hiển thị nguyên trạng."
4778 .to_string()
4779 }
4780 };
4781 let ratify_how = match provenance {
4782 DraftProvenance::Existing => {
4783 "Đây đã là luật hiện hành của bạn. Đóng bản xem trước rồi nhấn K để giữ nguyên và hoàn tất checkpoint; \
4784 tệp không bị sửa. Có thể chỉnh bất cứ lúc nào bằng /constitution hoặc /setup."
4785 }
4786 _ => {
4787 "Không có gì trở thành luật cho đến khi bạn xác nhận. Đóng bản xem trước rồi nhấn G để phê chuẩn và lưu. \
4788 Có thể chỉnh bất cứ lúc nào bằng /constitution hoặc /setup."
4789 }
4790 };
4791 format!(
4792 "CODEWHALE · HIẾN PHÁP NGƯỜI DÙNG\n{RULE}\n\n{drafted_by}\n\n\
4793 Đây là luật thường trực cho cách Codewhale làm việc với bạn. Giống các hiến pháp tốt, \
4794 nó đủ ngắn để dùng, gồm các nguyên tắc bền vững thay vì luật lệ cạn kiệt, \
4795 và có thể sửa khi bạn thay đổi. Nó định khung quyền hạn và giới hạn thay vì quyết định từng trường hợp, \
4796 đồng thời giữ sự liên tục giữa các phiên. Nhưng nó không phải bộ nhớ: nó mang nguyên tắc, không mang lịch sử.\n\n\
4797 {rendered}\n\n\
4798 THỨ BẬC THẨM QUYỀN\nYêu cầu trực tiếp của bạn luôn cao hơn tài liệu này.\n\n\
4799 ĐIỀU NÀY KHÔNG THỂ LÀM\n\
4800 Nó hướng dẫn hành vi. Nó không thể cấp hoặc đổi chính sách phê duyệt, sandbox, shell, mạng, \
4801 độ tin cậy, quyền MCP, chế độ mặc định, xuất bản hoặc quyền chi tiêu; những thứ đó vẫn do bạn kiểm soát lúc chạy.\n\n\
4802 LÕI RÚT GỌN VÀ MÔ-ĐUN OPT-IN\n\
4803 Lõi tích hợp vẫn hoạt động. Bản nháp này chỉ lưu tùy chọn thường trực toàn cục của người dùng. \
4804 Khả năng thực thi và điều phối đến từ chính sách thời gian chạy, danh mục công cụ đang hoạt động hoặc mô-đun opt-in trong tương lai; bản xem trước này không bật mô-đun hoặc đổi cấu hình của chúng.\n\n\
4805 PHÊ CHUẨN\n{ratify_how}"
4806 )
4807 }
4808 Locale::Ko => {
4809 let drafted_by = match provenance {
4810 DraftProvenance::Model(label) => format!(
4811 "{label}이(가) 당신의 가이드 답변을 바탕으로 초안을 작성했고, Codewhale이 구조를 검증하고 범위를 제한했습니다."
4812 ),
4813 DraftProvenance::Guided => {
4814 "당신의 가이드 답변으로부터 결정적으로 생성되었습니다.".to_string()
4815 }
4816 DraftProvenance::Existing => {
4817 "constitution.json에서 불러온 기존 헌법이며, 변경 없이 그대로 표시됩니다."
4818 .to_string()
4819 }
4820 };
4821 let ratify_how = match provenance {
4822 DraftProvenance::Existing => {
4823 "이것은 이미 당신의 상시 규칙입니다. 미리보기를 닫고 K를 눌러 그대로 유지하며 체크포인트를 완료하세요; \
4824 파일은 수정되지 않습니다. /constitution 또는 /setup으로 언제든지 수정할 수 있습니다."
4825 }
4826 _ => {
4827 "확인하기 전까지는 아무것도 규칙이 되지 않습니다. 미리보기를 닫고 G를 눌러 승인하고 저장하세요. \
4828 /constitution 또는 /setup으로 언제든지 수정할 수 있습니다."
4829 }
4830 };
4831 format!(
4832 "CODEWHALE · 사용자 헌법\n{RULE}\n\n{drafted_by}\n\n\
4833 이것은 Codewhale이 당신과 함께 일하는 방식에 대한 상시 규칙입니다. 훌륭한 헌법이 그렇듯, \
4834 사용할 수 있을 만큼 짧고, 소모적인 규칙이 아닌 지속적인 원칙으로 이루어져 있으며, 당신이 변화함에 따라 수정할 수 있습니다. \
4835 이는 모든 개별 사례를 판단하는 대신 권한과 한계를 규정하며, 세션을 넘어 협업의 연속성을 부여합니다. \
4836 다만 이것은 기억이 아닙니다: 이력이 아니라 원칙을 담습니다.\n\n\
4837 {rendered}\n\n\
4838 권한 계층\n당신의 직접적인 요청은 언제나 이 문서보다 우선합니다.\n\n\
4839 이것이 할 수 없는 일\n\
4840 이것은 행동을 안내할 뿐입니다. 승인 정책, 샌드박스, 셸, 네트워크, 신뢰, MCP 권한, 기본 모드, 게시, 지출 권한을 \
4841 부여하거나 바꿀 수 없습니다; 이는 여전히 런타임에서 당신이 직접 관리합니다.\n\n\
4842 축소된 코어와 옵트인 모듈\n\
4843 내장된 코어는 계속 활성 상태입니다. 이 초안은 사용자 전역의 상시 선호만 저장합니다. \
4844 실행 및 오케스트레이션 기능은 런타임 정책, 현재 도구 카탈로그 또는 향후 옵트인 모듈에서 제공됩니다. 이 미리보기는 모듈을 활성화하지 않으며 그 설정도 바꾸지 않습니다.\n\n\
4845 승인\n{ratify_how}"
4846 )
4847 }
4848 Locale::Ca => {
4849 let drafted_by = match provenance {
4850 DraftProvenance::Model(label) => format!(
4851 "Redactat per {label} a partir de les teves respostes guiades, després validat per esquema i acotat per Codewhale."
4852 ),
4853 DraftProvenance::Guided => {
4854 "Generat determinísticament a partir de les teves respostes guiades.".to_string()
4855 }
4856 DraftProvenance::Existing => {
4857 "La teva constitució existent, carregada de constitution.json, es mostra sense canvis."
4858 .to_string()
4859 }
4860 };
4861 let ratify_how = match provenance {
4862 DraftProvenance::Existing => {
4863 "Aquesta ja és la teva llei vigent. Tanca la previsualització i prem K per conservar-la i completar el punt de control; \
4864 el fitxer no es modifica. Esmena-la en qualsevol moment amb /constitution o /setup."
4865 }
4866 _ => {
4867 "Res no esdevé llei fins que ho confirmis. Tanca la previsualització i prem G per ratificar i desar. \
4868 Esmena-la en qualsevol moment amb /constitution o /setup."
4869 }
4870 };
4871 format!(
4872 "CODEWHALE · CONSTITUCIÓ DE L'USUARI\n{RULE}\n\n{drafted_by}\n\n\
4873 Aquesta és la llei permanent de com Codewhale treballa amb tu. Com les bones constitucions, \
4874 és prou curta per usar-se, feta de principis duradors en lloc de regles exhaustives, \
4875 i esmenable a mesura que canvies. Defineix poders i límits en lloc de decidir cada cas, \
4876 i dona continuïtat a la col·laboració entre sessions — però no és memòria: porta principis, no història.\n\n\
4877 {rendered}\n\n\
4878 JERARQUIA D'AUTORITAT\nLes teves peticions directes sempre prevalen sobre aquest document.\n\n\
4879 EL QUE AIXÒ NO POT FER\n\
4880 Orienta el comportament. No pot concedir ni canviar la política d'aprovació, sandbox, shell, xarxa, \
4881 confiança, permisos MCP, mode per defecte, publicació o autoritat de despesa; això queda sota el teu control en temps d'execució.\n\n\
4882 NUCLI REDUÏT I MÒDULS OPT-IN\n\
4883 El nucli inclòs continua actiu. Aquest esborrany només desa les teves preferències permanents globals d'usuari. \
4884 Les capacitats d'execució i orquestració provenen de la política d'execució, el catàleg d'eines actiu o futurs mòduls opt-in; aquesta previsualització no activa mòduls ni canvia la seva configuració.\n\n\
4885 RATIFICACIÓ\n{ratify_how}"
4886 )
4887 }
4888 Locale::De => {
4889 let drafted_by = match provenance {
4890 DraftProvenance::Model(label) => format!(
4891 "Entworfen von {label} aus deinen geführten Antworten, dann schema-geprüft und begrenzt durch Codewhale."
4892 ),
4893 DraftProvenance::Guided => {
4894 "Deterministisch aus deinen geführten Antworten erzeugt.".to_string()
4895 }
4896 DraftProvenance::Existing => {
4897 "Deine bestehende Verfassung, geladen aus constitution.json — unverändert gezeigt."
4898 .to_string()
4899 }
4900 };
4901 let ratify_how = match provenance {
4902 DraftProvenance::Existing => {
4903 "Dies ist bereits dein geltendes Recht. Schließe die Vorschau und drücke K, um sie zu behalten und den Checkpoint abzuschließen — \
4904 die Datei wird nicht verändert. Jederzeit mit /constitution oder /setup änderbar."
4905 }
4906 _ => {
4907 "Nichts wird Recht, bevor du bestätigst. Schließe die Vorschau und drücke G, um zu ratifizieren und zu speichern. \
4908 Jederzeit mit /constitution oder /setup änderbar."
4909 }
4910 };
4911 format!(
4912 "CODEWHALE · NUTZERVERFASSUNG\n{RULE}\n\n{drafted_by}\n\n\
4913 Dies ist das geltende Gesetz dafür, wie Codewhale mit dir arbeitet. Wie die besten Verfassungen \
4914 ist sie kurz genug, um genutzt zu werden, besteht aus dauerhaften Prinzipien statt erschöpfender Regeln \
4915 und lässt sich ändern, wenn du dich änderst. Sie rahmt Befugnisse und Grenzen, statt jeden Einzelfall zu entscheiden, \
4916 und gibt deiner Zusammenarbeit Kontinuität über Sitzungen hinweg — aber sie ist kein Gedächtnis: Sie trägt Prinzipien, nicht Geschichte.\n\n\
4917 {rendered}\n\n\
4918 HIERARCHIE DER AUTORITÄT\nDeine direkten Anweisungen stehen immer über diesem Dokument.\n\n\
4919 WAS DIES NICHT KANN\n\
4920 Sie leitet Verhalten. Sie kann keine Freigaberichtlinie, Sandbox, Shell, Netzwerk, \
4921 Vertrauen, MCP-Berechtigungen, Standardmodus, Veröffentlichung oder Ausgabenbefugnis gewähren oder ändern — die bleiben zur Laufzeit in deiner Hand.\n\n\
4922 REDUZIERTER KERN UND OPT-IN-MODULE\n\
4923 Der mitgelieferte Kern bleibt aktiv. Dieser Entwurf speichert nur deine benutzer-globalen Dauerpräferenzen. \
4924 Ausführungs- und Orchestrierungsfähigkeiten kommen aus der Laufzeitrichtlinie, dem aktuellen Werkzeugkatalog oder künftigen Opt-in-Modulen; diese Vorschau aktiviert keine Module und ändert nicht ihre Konfiguration.\n\n\
4925 RATIFIZIERUNG\n{ratify_how}"
4926 )
4927 }
4928 Locale::Fr => {
4929 let drafted_by = match provenance {
4930 DraftProvenance::Model(label) => format!(
4931 "Rédigé par {label} à partir de vos réponses guidées, puis validé par schéma et borné par Codewhale."
4932 ),
4933 DraftProvenance::Guided => {
4934 "Généré de façon déterministe à partir de vos réponses guidées.".to_string()
4935 }
4936 DraftProvenance::Existing => {
4937 "Votre constitution existante, chargée depuis constitution.json — affichée sans modification."
4938 .to_string()
4939 }
4940 };
4941 let ratify_how = match provenance {
4942 DraftProvenance::Existing => {
4943 "C'est déjà votre loi permanente. Fermez cet aperçu, puis appuyez sur K pour la conserver et terminer le point de contrôle — \
4944 le fichier n'est pas modifié. Amendez-la à tout moment avec /constitution ou /setup."
4945 }
4946 _ => {
4947 "Rien ne devient loi avant votre confirmation. Fermez cet aperçu, puis appuyez sur G pour ratifier et enregistrer. \
4948 Amendez-la à tout moment avec /constitution ou /setup."
4949 }
4950 };
4951 format!(
4952 "CODEWHALE · CONSTITUTION DE L'UTILISATEUR\n{RULE}\n\n{drafted_by}\n\n\
4953 Voici la loi permanente qui régit la façon dont Codewhale travaille avec vous. Comme les meilleures constitutions, \
4954 elle est assez courte pour être utilisée, faite de principes durables plutôt que de règles exhaustives, \
4955 et amendable à mesure que vous changez. Elle encadre les pouvoirs et les limites plutôt que de trancher chaque cas, \
4956 et donne à votre collaboration une continuité entre les sessions — mais elle n'est pas une mémoire : elle porte des principes, pas un historique.\n\n\
4957 {rendered}\n\n\
4958 HIÉRARCHIE D'AUTORITÉ\nVos demandes directes priment toujours sur ce document.\n\n\
4959 CE QU'ELLE NE PEUT PAS FAIRE\n\
4960 Elle guide le comportement. Elle ne peut ni accorder ni modifier la politique d'approbation, le sandbox, le shell, le réseau, \
4961 la confiance, les permissions MCP, le mode par défaut, la publication ou le pouvoir de dépense — ceux-ci restent entre vos mains à l'exécution.\n\n\
4962 NOYAU RÉDUIT ET MODULES OPT-IN\n\
4963 Le noyau intégré reste actif. Ce brouillon n'enregistre que vos préférences permanentes globales. \
4964 Les capacités d'exécution et d'orchestration proviennent de la politique d'exécution, du catalogue d'outils actif ou de futurs modules opt-in ; cet aperçu n'active pas de modules et ne change pas leur configuration.\n\n\
4965 RATIFICATION\n{ratify_how}"
4966 )
4967 }
4968 Locale::Id => {
4969 let drafted_by = match provenance {
4970 DraftProvenance::Model(label) => format!(
4971 "Disusun oleh {label} dari jawaban terpandu Anda, lalu diperiksa skemanya dan dibatasi oleh Codewhale."
4972 ),
4973 DraftProvenance::Guided => {
4974 "Dihasilkan secara deterministik dari jawaban terpandu Anda.".to_string()
4975 }
4976 DraftProvenance::Existing => {
4977 "Konstitusi Anda yang ada, dimuat dari constitution.json — ditampilkan tanpa perubahan."
4978 .to_string()
4979 }
4980 };
4981 let ratify_how = match provenance {
4982 DraftProvenance::Existing => {
4983 "Ini sudah menjadi hukum tetap Anda. Tutup pratinjau ini, lalu tekan K untuk mempertahankannya dan menyelesaikan checkpoint — \
4984 file tidak diubah. Amendemen kapan saja dengan /constitution atau /setup."
4985 }
4986 _ => {
4987 "Tidak ada yang menjadi hukum sampai Anda mengonfirmasi. Tutup pratinjau ini, lalu tekan G untuk meratifikasi dan menyimpan. \
4988 Amendemen kapan saja dengan /constitution atau /setup."
4989 }
4990 };
4991 format!(
4992 "CODEWHALE · KONSTITUSI PENGGUNA\n{RULE}\n\n{drafted_by}\n\n\
4993 Ini adalah hukum tetap tentang cara Codewhale bekerja dengan Anda. Seperti konstitusi terbaik, \
4994 ia cukup singkat untuk dipakai, tersusun dari prinsip yang awet alih-alih aturan yang menyeluruh, \
4995 dan dapat diamendemen seiring Anda berubah. Ia membingkai wewenang dan batasan alih-alih memutuskan setiap kasus, \
4996 dan memberi kolaborasi Anda kesinambungan lintas sesi — tetapi ia bukan memori: ia membawa prinsip, bukan riwayat.\n\n\
4997 {rendered}\n\n\
4998 HIERARKI OTORITAS\nPermintaan langsung Anda selalu mengungguli dokumen ini.\n\n\
4999 APA YANG TIDAK BISA DILAKUKANNYA\n\
5000 Ia memandu perilaku. Ia tidak dapat memberi atau mengubah kebijakan persetujuan, sandbox, shell, jaringan, \
5001 kepercayaan, izin MCP, mode default, publikasi, atau wewenang belanja — semua itu tetap di tangan Anda saat runtime.\n\n\
5002 INTI RINGKAS DAN MODUL OPT-IN\n\
5003 Inti bawaan tetap aktif. Draf ini hanya menyimpan preferensi tetap global pengguna Anda. \
5004 Kemampuan eksekusi dan orkestrasi berasal dari kebijakan runtime, katalog alat aktif, atau modul opt-in mendatang; pratinjau ini tidak mengaktifkan modul atau mengubah konfigurasinya.\n\n\
5005 RATIFIKASI\n{ratify_how}"
5006 )
5007 }
5008 Locale::Hi => {
5009 let drafted_by = match provenance {
5010 DraftProvenance::Model(label) => format!(
5011 "{label} द्वारा आपके गाइडेड उत्तरों से तैयार, फिर Codewhale द्वारा स्कीमा-जाँचा और सीमित किया गया।"
5012 ),
5013 DraftProvenance::Guided => "आपके गाइडेड उत्तरों से नियत रूप से तैयार किया गया।".to_string(),
5014 DraftProvenance::Existing => {
5015 "आपका मौजूदा संविधान, constitution.json से लोड किया गया — अपरिवर्तित दिखाया गया।"
5016 .to_string()
5017 }
5018 };
5019 let ratify_how = match provenance {
5020 DraftProvenance::Existing => {
5021 "यह पहले से ही आपका स्थायी कानून है। यह पूर्वावलोकन बंद करें, फिर इसे बनाए रखने और चेकपॉइंट पूरा करने के लिए K दबाएँ — \
5022 फ़ाइल संशोधित नहीं होती। /constitution या /setup से कभी भी संशोधित करें।"
5023 }
5024 _ => {
5025 "जब तक आप पुष्टि नहीं करते, कुछ भी कानून नहीं बनता। यह पूर्वावलोकन बंद करें, फिर अंगीकार और सहेजने के लिए G दबाएँ। \
5026 /constitution या /setup से कभी भी संशोधित करें।"
5027 }
5028 };
5029 format!(
5030 "CODEWHALE · उपयोगकर्ता संविधान\n{RULE}\n\n{drafted_by}\n\n\
5031 यह Codewhale आपके साथ कैसे काम करे, इसका स्थायी कानून है। सर्वोत्तम संविधानों की तरह, \
5032 यह उपयोग के लिए पर्याप्त छोटा है, संपूर्ण नियमों के बजाय टिकाऊ सिद्धांतों से बना है, \
5033 और आपके बदलने के साथ संशोधनीय है। यह हर मामले का फ़ैसला करने के बजाय शक्तियों और सीमाओं का ढाँचा देता है, \
5034 और आपके सहयोग को सत्रों के पार निरंतरता देता है — लेकिन यह मेमोरी नहीं है: यह इतिहास नहीं, सिद्धांत रखता है।\n\n\
5035 {rendered}\n\n\
5036 अधिकार पदानुक्रम\nआपके प्रत्यक्ष अनुरोध हमेशा इस दस्तावेज़ से ऊपर हैं।\n\n\
5037 यह क्या नहीं कर सकता\n\
5038 यह व्यवहार का मार्गदर्शन करता है। यह अनुमति नीति, सैंडबॉक्स, शेल, नेटवर्क, \
5039 ट्रस्ट, MCP अनुमतियाँ, डिफ़ॉल्ट मोड, प्रकाशन या खर्च का अधिकार प्रदान या परिवर्तित नहीं कर सकता — वे रनटाइम पर आपके हाथ में रहते हैं।\n\n\
5040 संक्षिप्त कोर और ऑप्ट-इन मॉड्यूल\n\
5041 Bundled कोर सक्रिय रहता है। यह मसौदा केवल आपकी उपयोगकर्ता-वैश्विक स्थायी प्राथमिकताएँ सहेजता है। \
5042 भारी निष्पादन या ऑर्केस्ट्रेशन सिद्धांत मोड प्रॉम्प्ट या भविष्य के ऑप्ट-इन मॉड्यूल में रहते हैं; यह पूर्वावलोकन मॉड्यूल सक्षम नहीं करता और न ही उनकी कॉन्फ़िगरेशन बदलता है।\n\n\
5043 अंगीकार\n{ratify_how}"
5044 )
5045 }
5046 Locale::Ru => {
5047 let drafted_by = match provenance {
5048 DraftProvenance::Model(label) => format!(
5049 "Подготовлено {label} на основе ваших ответов на наводящие вопросы, затем проверено по схеме и ограничено Codewhale."
5050 ),
5051 DraftProvenance::Guided => {
5052 "Детерминированно построено из ваших ответов на наводящие вопросы.".to_string()
5053 }
5054 DraftProvenance::Existing => {
5055 "Ваша существующая конституция, загруженная из constitution.json, — показана без изменений."
5056 .to_string()
5057 }
5058 };
5059 let ratify_how = match provenance {
5060 DraftProvenance::Existing => {
5061 "Это уже ваш действующий закон. Закройте это превью, затем нажмите K, чтобы сохранить её и завершить контрольную точку — \
5062 файл не изменяется. Изменить можно в любое время через /constitution или /setup."
5063 }
5064 _ => {
5065 "Ничто не становится законом, пока вы не подтвердите. Закройте это превью, затем нажмите G, чтобы ратифицировать и сохранить. \
5066 Изменить можно в любое время через /constitution или /setup."
5067 }
5068 };
5069 format!(
5070 "CODEWHALE · КОНСТИТУЦИЯ ПОЛЬЗОВАТЕЛЯ\n{RULE}\n\n{drafted_by}\n\n\
5071 Это постоянный закон о том, как Codewhale работает с вами. Как лучшие конституции, \
5072 она достаточно коротка, чтобы ей пользоваться, состоит из долговечных принципов, а не исчерпывающих правил, \
5073 и может изменяться вместе с вами. Она очерчивает полномочия и границы, а не решает каждый случай, \
5074 и придаёт вашему сотрудничеству непрерывность между сессиями — но она не память: она хранит принципы, а не историю.\n\n\
5075 {rendered}\n\n\
5076 ИЕРАРХИЯ ПОЛНОМОЧИЙ\nВаши прямые указания всегда важнее этого документа.\n\n\
5077 ЧЕГО ОНА НЕ МОЖЕТ\n\
5078 Она направляет поведение. Она не может предоставить или изменить политику одобрения, sandbox, shell, сеть, \
5079 доверие, разрешения MCP, режим по умолчанию, публикацию или право тратить — они остаются в ваших руках во время выполнения.\n\n\
5080 СОКРАЩЁННОЕ ЯДРО И ОПЦИОНАЛЬНЫЕ МОДУЛИ\n\
5081 Встроенное ядро остаётся активным. Этот проект сохраняет только ваши глобальные постоянные предпочтения. \
5082 Тяжёлая доктрина исполнения или оркестрации принадлежит промптам режимов или будущим опциональным модулям; это превью не включает модули и не меняет их конфигурацию.\n\n\
5083 РАТИФИКАЦИЯ\n{ratify_how}"
5084 )
5085 }
5086 Locale::Uk => {
5087 let drafted_by = match provenance {
5088 DraftProvenance::Model(label) => format!(
5089 "Підготовлено {label} на основі ваших відповідей на навідні запитання, потім перевірено за схемою та обмежено Codewhale."
5090 ),
5091 DraftProvenance::Guided => {
5092 "Детерміновано побудовано з ваших відповідей на навідні запитання.".to_string()
5093 }
5094 DraftProvenance::Existing => {
5095 "Ваша чинна конституція, завантажена з constitution.json, — показана без змін."
5096 .to_string()
5097 }
5098 };
5099 let ratify_how = match provenance {
5100 DraftProvenance::Existing => {
5101 "Це вже ваш чинний закон. Закрийте це прев'ю, потім натисніть K, щоб зберегти її та завершити контрольну точку — \
5102 файл не змінюється. Змінити можна будь-коли через /constitution або /setup."
5103 }
5104 _ => {
5105 "Ніщо не стає законом, доки ви не підтвердите. Закрийте це прев'ю, потім натисніть G, щоб ратифікувати та зберегти. \
5106 Змінити можна будь-коли через /constitution або /setup."
5107 }
5108 };
5109 format!(
5110 "CODEWHALE · КОНСТИТУЦІЯ КОРИСТУВАЧА\n{RULE}\n\n{drafted_by}\n\n\
5111 Це постійний закон про те, як Codewhale працює з вами. Як найкращі конституції, \
5112 вона достатньо коротка, щоб нею користуватися, складається з довговічних принципів, а не вичерпних правил, \
5113 і може змінюватися разом із вами. Вона окреслює повноваження та межі, а не вирішує кожен випадок, \
5114 і надає вашій співпраці неперервність між сесіями — але вона не пам'ять: вона зберігає принципи, а не історію.\n\n\
5115 {rendered}\n\n\
5116 ІЄРАРХІЯ ПОВНОВАЖЕНЬ\nВаші прямі вказівки завжди важливіші за цей документ.\n\n\
5117 ЧОГО ВОНА НЕ МОЖЕ\n\
5118 Вона спрямовує поведінку. Вона не може надати або змінити політику схвалення, sandbox, shell, мережу, \
5119 довіру, дозволи MCP, режим за замовчуванням, публікацію чи право витрачати — вони залишаються у ваших руках під час виконання.\n\n\
5120 СКОРОЧЕНЕ ЯДРО Й ОПЦІЙНІ МОДУЛІ\n\
5121 Вбудоване ядро залишається активним. Цей проєкт зберігає лише ваші глобальні постійні вподобання. \
5122 Важка доктрина виконання чи оркестрації належить промптам режимів або майбутнім опційним модулям; це прев'ю не вмикає модулі й не змінює їхню конфігурацію.\n\n\
5123 РАТИФІКАЦІЯ\n{ratify_how}"
5124 )
5125 }
5126 _ => {
5127 let drafted_by = match provenance {
5128 DraftProvenance::Model(label) => format!(
5129 "Drafted by {label} from your guided answers, then schema-checked and bounded by Codewhale."
5130 ),
5131 DraftProvenance::Guided => {
5132 "Rendered deterministically from your guided answers.".to_string()
5133 }
5134 DraftProvenance::Existing => {
5135 "Your existing constitution, loaded from constitution.json — shown unchanged."
5136 .to_string()
5137 }
5138 };
5139 let ratify_how = match provenance {
5140 DraftProvenance::Existing => {
5141 "This is already your standing law. Close this preview, then press K to \
5142 keep it and complete the checkpoint — the file is not modified. Amend \
5143 anytime with /constitution or /setup."
5144 }
5145 _ => {
5146 "Nothing becomes law until you confirm. Close this preview, then press G to \
5147 ratify and save. Amend anytime with /constitution or /setup."
5148 }
5149 };
5150 format!(
5151 "CODEWHALE · USER CONSTITUTION\n{RULE}\n\n{drafted_by}\n\n\
5152 This is the standing law for how Codewhale works with you. Like the best \
5153 constitutions, it is short enough to use, made of durable principles rather \
5154 than exhaustive rules, and amendable as you change. It frames powers and \
5155 limits rather than deciding every case, and it gives your collaboration \
5156 continuity across sessions — but it is not memory: it carries principles, \
5157 not history.\n\n\
5158 {rendered}\n\n\
5159 HIERARCHY OF AUTHORITY\nYour direct requests always outrank this document.\n\n\
5160 WHAT THIS CANNOT DO\n\
5161 It guides behavior. It cannot grant or change approval policy, sandbox, shell, \
5162 network, trust, MCP permissions, default mode, publishing, or spending \
5163 authority — those stay under your hand at runtime.\n\n\
5164 REDUCED CORE AND OPT-IN MODULES\n\
5165 The bundled core stays active. This draft only saves your user-global \
5166 standing preferences. Execution and orchestration capabilities come from runtime \
5167 policy, the live tool catalog, or future opt-in modules; this preview does not enable modules or change \
5168 their configuration.\n\n\
5169 RATIFICATION\n{ratify_how}"
5170 )
5171 }
5172 }
5173 }
5174
5175 /// Card line inviting the user to let their configured model draft the law.
5176 fn model_draft_invitation_line(locale: Locale, model_label: &str) -> String {
5177 match locale {
5178 Locale::Ja => {
5179 format!("A {model_label} が起草し、あなたが批准します。確認するまで保存しません。")
5180 }
5181 Locale::ZhHans => {
5182 format!("A {model_label} 生成草案,由你确认。未经确认不会保存。")
5183 }
5184 Locale::ZhHant => {
5185 format!("A {model_label} 起草,你批准。未經確認不會保存。")
5186 }
5187 Locale::PtBr => {
5188 format!("A {model_label} pode rascunhar. Você ratifica. Nada salva sem você.")
5189 }
5190 Locale::Es419 => {
5191 format!("A {model_label} puede redactarla. Tú ratificas. Nada se guarda sin ti.")
5192 }
5193 Locale::Vi => {
5194 format!("A {model_label} có thể soạn. Bạn phê chuẩn. Không lưu gì nếu chưa có bạn.")
5195 }
5196 Locale::Ko => {
5197 format!(
5198 "A {model_label}이(가) 초안을 작성할 수 있습니다. 승인은 당신이 합니다. 당신 없이는 아무것도 저장되지 않습니다."
5199 )
5200 }
5201 Locale::Ca => {
5202 format!("A {model_label} la pot redactar. Tu la ratifiques. Res no es desa sense tu.")
5203 }
5204 Locale::De => {
5205 format!(
5206 "A {model_label} kann sie entwerfen. Du ratifizierst sie. Ohne dich wird nichts gespeichert."
5207 )
5208 }
5209 Locale::Fr => {
5210 format!(
5211 "A {model_label} peut la rédiger. Vous la ratifiez. Rien ne s'enregistre sans vous."
5212 )
5213 }
5214 Locale::Id => {
5215 format!(
5216 "A {model_label} dapat menyusunnya. Anda yang meratifikasi. Tidak ada yang tersimpan tanpa Anda."
5217 )
5218 }
5219 Locale::Hi => {
5220 format!(
5221 "A {model_label} इसका मसौदा बना सकता है। अंगीकार आप करते हैं। आपके बिना कुछ भी सहेजा नहीं जाता।"
5222 )
5223 }
5224 Locale::Ru => {
5225 format!(
5226 "A {model_label} может подготовить проект. Ратифицируете вы. Без вас ничего не сохраняется."
5227 )
5228 }
5229 Locale::Uk => {
5230 format!(
5231 "A {model_label} може підготувати проєкт. Ратифікуєте ви. Без вас нічого не зберігається."
5232 )
5233 }
5234 _ => format!("A {model_label} can draft it. You ratify it. Nothing saves without you."),
5235 }
5236 }
5237
5238 /// Card line offering to keep an existing valid constitution unchanged.
5239 fn keep_existing_invitation_line(locale: Locale) -> &'static str {
5240 match locale {
5241 Locale::Ja => "K 既存の憲法を保持 - 確認して保持、ファイルは変更しません。",
5242 Locale::ZhHans => "K 保留现有宪章——先查看,再保留,文件不变。",
5243 Locale::ZhHant => "K 保留現有憲法 - 先查看,再保留,檔案不變。",
5244 Locale::PtBr => "K Manter constituição existente - revise, mantenha, arquivo inalterado.",
5245 Locale::Es419 => {
5246 "K Conservar constitución existente - revisa, conserva, archivo sin cambios."
5247 }
5248 Locale::Vi => "K Giữ hiến pháp hiện có - xem lại, giữ nguyên, tệp không đổi.",
5249 Locale::Ko => "K 기존 헌법 유지 - 검토 후 유지, 파일은 변경되지 않음.",
5250 Locale::Ca => {
5251 "K Mantén la constitució existent - revisa-la, conserva-la, fitxer sense canvis."
5252 }
5253 Locale::De => "K Bestehende Verfassung behalten - prüfen, behalten, Datei unverändert.",
5254 Locale::Fr => {
5255 "K Garder votre constitution existante - révisez-la, gardez-la, fichier inchangé."
5256 }
5257 Locale::Id => {
5258 "K Pertahankan konstitusi Anda yang ada - tinjau, pertahankan, file tidak berubah."
5259 }
5260 Locale::Hi => "K अपना मौजूदा संविधान रखें - समीक्षा करें, बनाए रखें, फ़ाइल अपरिवर्तित।",
5261 Locale::Ru => {
5262 "K Сохранить существующую конституцию - просмотрите, сохраните, файл не изменяется."
5263 }
5264 Locale::Uk => "K Зберегти чинну конституцію - перегляньте, збережіть, файл без змін.",
5265 _ => "K Keep your existing constitution — review it, keep it, file unchanged.",
5266 }
5267 }
5268
5269 /// Card line shown while a model draft awaits ratification.
5270 fn model_draft_ready_line(locale: Locale, model_label: &str) -> String {
5271 match locale {
5272 Locale::Ja => {
5273 format!(
5274 "{model_label} の草案が批准待ちです - G で確認して批准、1-6 で草案を破棄します。"
5275 )
5276 }
5277 Locale::ZhHans => {
5278 format!("{model_label} 的草案待确认——按 G 查看并确认;按 1-6 会丢弃草案。")
5279 }
5280 Locale::ZhHant => {
5281 format!("{model_label} 的草案待批准 - 按 G 查看並批准;按 1-6 會丟棄草案。")
5282 }
5283 Locale::PtBr => {
5284 format!(
5285 "Rascunho de {model_label} aguarda ratificação - G para revisar e ratificar; 1-6 descarta."
5286 )
5287 }
5288 Locale::Es419 => {
5289 format!(
5290 "El borrador de {model_label} espera ratificación - G para revisar y ratificar; 1-6 lo descarta."
5291 )
5292 }
5293 Locale::Vi => {
5294 format!(
5295 "Bản nháp của {model_label} chờ phê chuẩn - G để xem và phê chuẩn; 1-6 sẽ bỏ bản nháp."
5296 )
5297 }
5298 Locale::Ko => {
5299 format!(
5300 "{model_label}의 초안이 승인을 기다리고 있습니다 - G로 확인하고 승인, 1-6은 초안을 버립니다."
5301 )
5302 }
5303 Locale::Ca => {
5304 format!(
5305 "L'esborrany de {model_label} espera ratificació - G per revisar i ratificar; 1-6 el descarta."
5306 )
5307 }
5308 Locale::De => {
5309 format!(
5310 "Entwurf von {model_label} wartet auf Ratifizierung - G zum Prüfen und Ratifizieren; 1-6 verwirft ihn."
5311 )
5312 }
5313 Locale::Fr => {
5314 format!(
5315 "Le brouillon de {model_label} attend ratification - G pour réviser et ratifier ; 1-6 l'écarte."
5316 )
5317 }
5318 Locale::Id => {
5319 format!(
5320 "Draf oleh {model_label} menunggu ratifikasi - G untuk meninjau dan meratifikasi; 1-6 membuangnya."
5321 )
5322 }
5323 Locale::Hi => {
5324 format!(
5325 "{model_label} का मसौदा अंगीकार की प्रतीक्षा में है - समीक्षा और अंगीकार के लिए G; 1-6 उसे खारिज करता है।"
5326 )
5327 }
5328 Locale::Ru => {
5329 format!(
5330 "Проект от {model_label} ожидает ратификации - G для просмотра и ратификации; 1-6 отклоняет его."
5331 )
5332 }
5333 Locale::Uk => {
5334 format!(
5335 "Проєкт від {model_label} очікує ратифікації - G для перегляду та ратифікації; 1-6 відхиляє його."
5336 )
5337 }
5338 _ => format!(
5339 "Draft by {model_label} awaits ratification — G to review and ratify; 1-6 discards it."
5340 ),
5341 }
5342 }
5343
5344 /// Host-facing status line after a successful model draft.
5345 pub(crate) fn model_draft_ready_message(locale: Locale, model_label: &str) -> String {
5346 match locale {
5347 Locale::Ja => format!(
5348 "{model_label} があなたの憲法を起草しました。プレビューを確認してから G で批准してください。"
5349 ),
5350 Locale::ZhHans => {
5351 format!("{model_label} 已生成你的宪章草案。请查看预览,然后按 G 确认。")
5352 }
5353 Locale::ZhHant => format!("{model_label} 已起草你的憲法。請查看預覽,然後按 G 批准。"),
5354 Locale::PtBr => format!(
5355 "{model_label} rascunhou sua constituição. Revise a prévia e pressione G para ratificar."
5356 ),
5357 Locale::Es419 => format!(
5358 "{model_label} redactó tu constitución. Revisa la vista previa y presiona G para ratificar."
5359 ),
5360 Locale::Vi => format!(
5361 "{model_label} đã soạn hiến pháp của bạn. Xem bản xem trước rồi nhấn G để phê chuẩn."
5362 ),
5363 Locale::Ko => format!(
5364 "{model_label}이(가) 당신의 헌법 초안을 작성했습니다. 미리보기를 확인한 뒤 G를 눌러 승인하세요."
5365 ),
5366 Locale::Ca => format!(
5367 "{model_label} ha redactat la teva constitució. Revisa la previsualització i prem G per ratificar."
5368 ),
5369 Locale::De => format!(
5370 "{model_label} hat deine Verfassung entworfen. Prüfe die Vorschau und drücke G zum Ratifizieren."
5371 ),
5372 Locale::Fr => format!(
5373 "{model_label} a rédigé votre constitution. Révisez l'aperçu, puis appuyez sur G pour ratifier."
5374 ),
5375 Locale::Id => format!(
5376 "{model_label} menyusun konstitusi Anda. Tinjau pratinjaunya, lalu tekan G untuk meratifikasi."
5377 ),
5378 Locale::Hi => format!(
5379 "{model_label} ने आपके संविधान का मसौदा तैयार किया। पूर्वावलोकन देखें, फिर अंगीकार के लिए G दबाएँ।"
5380 ),
5381 Locale::Ru => format!(
5382 "{model_label} подготовил проект вашей конституции. Просмотрите превью, затем нажмите G для ратификации."
5383 ),
5384 Locale::Uk => format!(
5385 "{model_label} підготував проєкт вашої конституції. Перегляньте прев'ю, потім натисніть G для ратифікації."
5386 ),
5387 _ => format!(
5388 "{model_label} drafted your constitution. Review the preview, then press G to ratify."
5389 ),
5390 }
5391 }
5392
5393 /// Host-facing status line when model drafting fails or is unavailable. The
5394 /// guided deterministic draft always remains the standing fallback.
5395 pub(crate) fn model_draft_failed_message(
5396 locale: Locale,
5397 model_label: &str,
5398 reason: &str,
5399 ) -> String {
5400 match locale {
5401 Locale::Ja => {
5402 format!(
5403 "{model_label} は起草を完了できませんでした({reason})。ガイド草案は有効です。G でプレビューして批准できます。"
5404 )
5405 }
5406 Locale::ZhHans => {
5407 format!("{model_label} 未能生成草案({reason})。引导式草案仍可使用——按 G 预览并确认。")
5408 }
5409 Locale::ZhHant => {
5410 format!("{model_label} 未能完成起草({reason})。引導式草案仍然有效;按 G 預覽並批准。")
5411 }
5412 Locale::PtBr => {
5413 format!(
5414 "{model_label} não conseguiu rascunhar sua constituição ({reason}). O rascunho guiado continua válido; pressione G para pré-visualizar e ratificar."
5415 )
5416 }
5417 Locale::Es419 => {
5418 format!(
5419 "{model_label} no pudo redactar tu constitución ({reason}). El borrador guiado sigue válido; presiona G para previsualizar y ratificar."
5420 )
5421 }
5422 Locale::Vi => {
5423 format!(
5424 "{model_label} không thể soạn hiến pháp của bạn ({reason}). Bản nháp hướng dẫn vẫn hợp lệ; nhấn G để xem trước và phê chuẩn."
5425 )
5426 }
5427 Locale::Ko => {
5428 format!(
5429 "{model_label}이(가) 당신의 헌법 초안을 작성하지 못했습니다 ({reason}). 가이드 초안은 여전히 유효합니다. G를 눌러 미리보고 승인하세요."
5430 )
5431 }
5432 Locale::Ca => {
5433 format!(
5434 "{model_label} no ha pogut redactar la teva constitució ({reason}). L'esborrany guiat continua vigent; prem G per previsualitzar i ratificar."
5435 )
5436 }
5437 Locale::De => {
5438 format!(
5439 "{model_label} konnte deine Verfassung nicht entwerfen ({reason}). Dein geführter Entwurf bleibt gültig; drücke G für Vorschau und Ratifizierung."
5440 )
5441 }
5442 Locale::Fr => {
5443 format!(
5444 "{model_label} n'a pas pu rédiger votre constitution ({reason}). Votre brouillon guidé reste valide ; appuyez sur G pour l'aperçu et la ratification."
5445 )
5446 }
5447 Locale::Id => {
5448 format!(
5449 "{model_label} tidak dapat menyusun konstitusi Anda ({reason}). Draf terpandu Anda tetap berlaku; tekan G untuk pratinjau dan ratifikasi."
5450 )
5451 }
5452 Locale::Hi => {
5453 format!(
5454 "{model_label} आपके संविधान का मसौदा नहीं बना सका ({reason})। आपका गाइडेड मसौदा अब भी मान्य है; पूर्वावलोकन और अंगीकार के लिए G दबाएँ।"
5455 )
5456 }
5457 Locale::Ru => {
5458 format!(
5459 "{model_label} не смог подготовить вашу конституцию ({reason}). Ваш управляемый проект остаётся в силе — нажмите G для просмотра и ратификации."
5460 )
5461 }
5462 Locale::Uk => {
5463 format!(
5464 "{model_label} не зміг підготувати вашу конституцію ({reason}). Ваш керований проєкт залишається чинним — натисніть G для перегляду та ратифікації."
5465 )
5466 }
5467 _ => format!(
5468 "{model_label} could not draft your constitution ({reason}). Your guided draft still \
5469 stands — press G to preview and ratify."
5470 ),
5471 }
5472 }
5473
5474 fn constitution_choice_label(choice: ConstitutionChoice) -> &'static str {
5475 match choice {
5476 ConstitutionChoice::Unset => "unset",
5477 ConstitutionChoice::Bundled => "bundled/default",
5478 ConstitutionChoice::GuidedCustom => "guided custom",
5479 ConstitutionChoice::ExpertOverride => "expert override",
5480 ConstitutionChoice::Deferred => "deferred",
5481 }
5482 }
5483
5484 fn constitution_source_label(source: ConstitutionSource) -> &'static str {
5485 match source {
5486 ConstitutionSource::Bundled => "bundled",
5487 ConstitutionSource::UserGlobal => "user-global constitution.json",
5488 ConstitutionSource::ExpertOverride => "expert full Markdown override",
5489 }
5490 }
5491
5492 fn constitution_validity_label(validity: ConstitutionValidity) -> &'static str {
5493 match validity {
5494 ConstitutionValidity::Unknown => "unknown",
5495 ConstitutionValidity::Valid => "valid",
5496 ConstitutionValidity::Invalid => "invalid",
5497 ConstitutionValidity::Empty => "empty",
5498 ConstitutionValidity::Unreadable => "unreadable",
5499 }
5500 }
5501
5502 pub fn persist_user_constitution_choice(
5503 constitution: &UserConstitution,
5504 state: &SetupState,
5505 ) -> anyhow::Result<()> {
5506 let constitution_path = UserConstitution::path()?;
5507 let setup_state_path = SetupState::path()?;
5508 let mut transaction = codewhale_config::persistence::SetupTransaction::new();
5509 transaction.stage_json(constitution_path, &constitution.bounded())?;
5510 transaction.stage_json(setup_state_path, state)?;
5511 transaction.commit()
5512 }
5513
5514 #[must_use]
5515 pub fn should_open_update_checkpoint(app: &App, config: &Config) -> bool {
5516 let state = load_setup_state_for_app(app, config);
5517 state.needs_constitution_checkpoint(CONSTITUTION_CHECKPOINT_VERSION)
5518 }
5519
5520 pub fn defer_update_checkpoint_for_app(app: &App, config: &Config) -> anyhow::Result<SetupState> {
5521 let mut state = load_setup_state_for_app(app, config);
5522 if !state.needs_constitution_checkpoint(CONSTITUTION_CHECKPOINT_VERSION) {
5523 return Ok(state);
5524 }
5525 state.complete_constitution_checkpoint(
5526 CONSTITUTION_CHECKPOINT_VERSION,
5527 ConstitutionChoice::Deferred,
5528 );
5529 state.constitution_source = ConstitutionSource::Bundled;
5530 state.constitution_validity = ConstitutionValidity::Unknown;
5531 state.constitution_authoring = None;
5532 state.constitution_preview_hash = None;
5533 state.set_step(
5534 SetupStep::Constitution,
5535 StepEntry::new(StepStatus::Deferred, true, CONSTITUTION_CHECKPOINT_VERSION)
5536 .with_result("checkpoint deferred; bundled applies"),
5537 );
5538 state.save()?;
5539 Ok(state)
5540 }
5541
5542 #[must_use]
5543 pub fn load_setup_state_for_app(app: &App, config: &Config) -> SetupState {
5544 if let Ok(Some(state)) = SetupState::load() {
5545 return state;
5546 }
5547 SetupState::derive_inherited(&inherited_facts_for_app(app, config))
5548 }
5549
5550 pub(crate) fn record_provider_model_setup_state_for_app(
5551 app: &App,
5552 config: &Config,
5553 ) -> anyhow::Result<SetupState> {
5554 let facts = SetupRuntimeFacts::from_app_config(app, config);
5555 let mut state = load_setup_state_for_app(app, config);
5556 state.set_step(
5557 SetupStep::ProviderModel,
5558 provider::step_entry(
5559 facts.provider_status,
5560 CONSTITUTION_CHECKPOINT_VERSION,
5561 facts.provider_result,
5562 ),
5563 );
5564 state.save()?;
5565 Ok(state)
5566 }
5567
5568 #[must_use]
5569 fn inherited_facts_for_app(app: &App, config: &Config) -> InheritedConfigFacts {
5570 let user_constitution = UserConstitution::load().ok();
5571 let user_constitution_validity = user_constitution.as_ref().map_or(
5572 ConstitutionValidity::Unknown,
5573 UserConstitutionLoad::validity,
5574 );
5575 let has_user_constitution = user_constitution
5576 .as_ref()
5577 .is_some_and(|loaded| !matches!(loaded, UserConstitutionLoad::Missing));
5578 let expert_override = SetupExpertOverrideState::load();
5579 InheritedConfigFacts {
5580 language: Some(app.ui_locale.tag().to_string()),
5581 has_provider_route: !config.default_model().trim().is_empty(),
5582 has_credentials_or_local_runtime: has_api_key(config),
5583 trust_chosen: app.trust_mode || !codewhale_runtime::config::needs_trust(&app.workspace),
5584 has_expert_override: expert_override.is_active(),
5585 has_user_constitution,
5586 user_constitution_validity,
5587 }
5588 }
5589
5590 fn expert_override_path() -> Option<std::path::PathBuf> {
5591 codewhale_config::codewhale_home()
5592 .ok()
5593 .map(|home| home.join(Path::new(CONSTITUTION_OVERRIDE_FILE)))
5594 }
5595
5596 #[must_use]
5597 fn progressive_initial_step_index(state: &SetupState, facts: &SetupRuntimeFacts) -> usize {
5598 if !facts.provider_ready {
5599 return step_index(SetupStep::ProviderModel);
5600 }
5601 let runtime_current = if state.inherited {
5602 matches!(state.status(SetupStep::TrustSandbox), StepStatus::Verified)
5603 && state.runtime_posture_source.is_reviewed()
5604 } else {
5605 state
5606 .steps
5607 .get(&SetupStep::TrustSandbox)
5608 .is_some_and(|entry| {
5609 entry.status == StepStatus::Verified
5610 && entry.result.as_deref() == Some(facts.runtime_result.as_str())
5611 })
5612 && state.runtime_posture_source.is_reviewed()
5613 };
5614 if !runtime_current {
5615 return step_index(SetupStep::TrustSandbox);
5616 }
5617 if facts.tools_mcp_needs_action {
5618 return step_index(SetupStep::ToolsMcp);
5619 }
5620 step_index(SetupStep::Verification)
5621 }
5622
5623 #[must_use]
5624 fn step_index(step: SetupStep) -> usize {
5625 STEP_SPECS
5626 .iter()
5627 .position(|spec| spec.id() == step)
5628 .expect("all setup-state steps should have wizard specs")
5629 }
5630
5631 fn visible_step_index(step: SetupStep) -> usize {
5632 STEP_SPECS
5633 .iter()
5634 .position(|spec| spec.id() == step)
5635 .unwrap_or_else(|| step_index(SetupStep::Constitution))
5636 }
5637
5638 #[cfg(test)]
5639 mod progressive_tests {
5640 use super::*;
5641 use crossterm::event::KeyModifiers;
5642
5643 fn facts(provider_ready: bool) -> SetupRuntimeFacts {
5644 SetupRuntimeFacts {
5645 provider: "local".to_string(),
5646 model: "stub-model".to_string(),
5647 auth: if provider_ready { "ready" } else { "missing" }.to_string(),
5648 provider_ready,
5649 provider_status: if provider_ready {
5650 StepStatus::Configured
5651 } else {
5652 StepStatus::NeedsAction
5653 },
5654 runtime_result: "approval=ask; sandbox=workspace; network=prompt".to_string(),
5655 tools_mcp_result: "mcp=off, skills=off, tools=off, plugins=off, overall=off"
5656 .to_string(),
5657 remote_control_result: tr(Locale::En, MessageId::SetupRemoteStatusDisabled)
5658 .into_owned(),
5659 ..SetupRuntimeFacts::default()
5660 }
5661 }
5662
5663 fn complete_state(runtime_result: &str) -> SetupState {
5664 let mut state = SetupState {
5665 runtime_posture_source: RuntimePostureSource::Confirmed,
5666 ..SetupState::default()
5667 };
5668 state.set_step(
5669 SetupStep::TrustSandbox,
5670 StepEntry::new(StepStatus::Verified, true, CONSTITUTION_CHECKPOINT_VERSION)
5671 .with_result(runtime_result),
5672 );
5673 state
5674 }
5675
5676 fn render_text(view: &SetupWizardView, width: u16, height: u16) -> String {
5677 let area = Rect::new(0, 0, width, height);
5678 let mut buffer = Buffer::empty(area);
5679 ModalView::render(view, area, &mut buffer);
5680 (0..height)
5681 .map(|y| {
5682 (0..width)
5683 .map(|x| buffer[(x, y)].symbol())
5684 .collect::<String>()
5685 })
5686 .collect::<Vec<_>>()
5687 .join("\n")
5688 }
5689
5690 #[test]
5691 fn wizard_body_cells_carry_explicit_ink_on_the_dark_surface() {
5692 // The setup surface paints WHALE_BG while the blurb span carries no
5693 // fg of its own, so without the base paragraph style it inherits the
5694 // terminal default: black-on-black on light-profile terminals. Every
5695 // blurb cell must pin to the body ink; the explicitly styled title
5696 // must patch over the base unchanged.
5697 let view = SetupWizardView::new_with_facts(SetupState::default(), Locale::En, facts(false));
5698 let blurb_head: String = tr(Locale::En, MessageId::OnboardProviderBlurb)
5699 .chars()
5700 .take(16)
5701 .collect();
5702 let title_head: String = tr(Locale::En, MessageId::OnboardProviderTitle)
5703 .chars()
5704 .take(16)
5705 .collect();
5706 assert!(
5707 !blurb_head.is_empty() && !title_head.is_empty(),
5708 "test needs non-empty title and blurb heads to locate rows"
5709 );
5710 let area = Rect::new(0, 0, 100, 24);
5711 let mut buffer = Buffer::empty(area);
5712 ModalView::render(&view, area, &mut buffer);
5713 let mut blurb_hit = false;
5714 let mut title_hit = false;
5715 let mut checked = 0;
5716 for y in 0..area.height {
5717 let row: String = (0..area.width).map(|x| buffer[(x, y)].symbol()).collect();
5718 let expected = if row.contains(blurb_head.as_str()) {
5719 blurb_hit = true;
5720 Some(palette::TEXT_PRIMARY)
5721 } else if row.contains(title_head.as_str()) {
5722 title_hit = true;
5723 Some(palette::WHALE_ACTION)
5724 } else {
5725 None
5726 };
5727 let Some(fg) = expected else {
5728 continue;
5729 };
5730 for x in 0..area.width {
5731 let cell = &buffer[(x, y)];
5732 if cell.symbol().trim().is_empty() || matches!(cell.symbol(), "│" | "|") {
5733 continue;
5734 }
5735 assert_eq!(
5736 cell.style().fg,
5737 Some(fg),
5738 "setup body cell ({x}, {y}) must carry explicit ink"
5739 );
5740 checked += 1;
5741 }
5742 }
5743 assert!(
5744 blurb_hit && title_hit && checked > 0,
5745 "expected title and blurb rows in the rendered wizard"
5746 );
5747 }
5748
5749 #[test]
5750 fn fresh_setup_starts_at_the_missing_provider_decision() {
5751 let view = SetupWizardView::new_with_facts(SetupState::default(), Locale::En, facts(false));
5752
5753 assert_eq!(view.selected_step(), SetupStep::ProviderModel);
5754 assert!(matches!(
5755 ModalView::handle_key(
5756 &mut view.clone(),
5757 KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)
5758 ),
5759 ViewAction::EmitAndClose(ViewEvent::SetupOpenProviderRequested)
5760 ));
5761 }
5762
5763 #[test]
5764 fn partial_setup_skips_the_ready_provider_and_asks_for_permissions() {
5765 let mut view =
5766 SetupWizardView::new_with_facts(SetupState::default(), Locale::En, facts(true));
5767
5768 assert_eq!(view.selected_step(), SetupStep::TrustSandbox);
5769 let action =
5770 ModalView::handle_key(&mut view, KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
5771 let ViewAction::Emit(ViewEvent::SetupStateCommitRequested { state, message, .. }) = action
5772 else {
5773 panic!("reviewing the current permissions posture should persist a receipt");
5774 };
5775 assert_eq!(
5776 state.runtime_posture_source,
5777 RuntimePostureSource::Confirmed
5778 );
5779 assert_eq!(state.status(SetupStep::TrustSandbox), StepStatus::Verified);
5780 assert!(!message.is_empty());
5781 assert_eq!(view.selected_step(), SetupStep::RemoteRuntime);
5782 }
5783
5784 #[test]
5785 fn fully_configured_setup_opens_the_compact_summary() {
5786 let facts = facts(true);
5787 let state = complete_state(&facts.runtime_result);
5788 let mut view = SetupWizardView::new_with_facts(state, Locale::En, facts);
5789
5790 assert_eq!(view.selected_step(), SetupStep::Verification);
5791 let action =
5792 ModalView::handle_key(&mut view, KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
5793 let ViewAction::EmitAndClose(ViewEvent::SetupStateCommitRequested { state, .. }) = action
5794 else {
5795 panic!("starting from Ready should persist the report before closing");
5796 };
5797 assert!(state.steps.contains_key(&SetupStep::Verification));
5798 }
5799
5800 #[test]
5801 fn stale_complete_receipts_reopen_the_real_broken_surface() {
5802 let mut provider_broken = facts(false);
5803 provider_broken.runtime_result = "current".to_string();
5804 let state = complete_state("old");
5805 assert_eq!(
5806 SetupWizardView::new_with_facts(state, Locale::En, provider_broken).selected_step(),
5807 SetupStep::ProviderModel
5808 );
5809
5810 let runtime_current = facts(true);
5811 let stale_state = complete_state("old runtime snapshot");
5812 assert_eq!(
5813 SetupWizardView::new_with_facts(stale_state, Locale::En, runtime_current)
5814 .selected_step(),
5815 SetupStep::TrustSandbox
5816 );
5817 }
5818
5819 #[test]
5820 fn configured_broken_tools_join_the_journey_but_empty_tools_do_not() {
5821 let mut broken = facts(true);
5822 let state = complete_state(&broken.runtime_result);
5823 broken.tools_mcp_needs_action = true;
5824 broken.tools_mcp_result = "overall=needs_config".to_string();
5825 let mut broken_view = SetupWizardView::new_with_facts(state.clone(), Locale::En, broken);
5826 assert_eq!(broken_view.selected_step(), SetupStep::ToolsMcp);
5827 let action = ModalView::handle_key(
5828 &mut broken_view,
5829 KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
5830 );
5831 let ViewAction::Emit(ViewEvent::SetupStateCommitRequested { state, .. }) = action else {
5832 panic!("continuing past a broken optional tool should save its visible issue");
5833 };
5834 assert_eq!(state.status(SetupStep::ToolsMcp), StepStatus::NeedsAction);
5835 assert_eq!(broken_view.selected_step(), SetupStep::Verification);
5836
5837 let empty = facts(true);
5838 assert_eq!(
5839 SetupWizardView::new_with_facts(state, Locale::En, empty).selected_step(),
5840 SetupStep::Verification
5841 );
5842 }
5843
5844 #[test]
5845 fn account_action_uses_the_real_remote_control_handoff() {
5846 let facts = facts(true);
5847 let state = complete_state(&facts.runtime_result);
5848 let mut view = SetupWizardView::new_with_facts(state, Locale::En, facts);
5849 view.selected = visible_step_index(SetupStep::RemoteRuntime);
5850
5851 assert!(matches!(
5852 ModalView::handle_key(
5853 &mut view,
5854 KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE)
5855 ),
5856 ViewAction::EmitAndClose(ViewEvent::SetupOpenRemoteControlRequested)
5857 ));
5858 }
5859
5860 #[test]
5861 fn progressive_arrow_keys_scroll_details_without_changing_the_decision() {
5862 let mut view =
5863 SetupWizardView::new_with_facts(SetupState::default(), Locale::En, facts(false));
5864 view.details_expanded = true;
5865 view.body_scroll = 4;
5866 let step = view.selected_step();
5867
5868 assert!(matches!(
5869 ModalView::handle_key(&mut view, KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)),
5870 ViewAction::None
5871 ));
5872 assert_eq!(view.selected_step(), step);
5873 assert_eq!(view.body_scroll, 3);
5874
5875 assert!(matches!(
5876 ModalView::handle_key(&mut view, KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)),
5877 ViewAction::None
5878 ));
5879 assert_eq!(view.selected_step(), step);
5880 assert_eq!(view.body_scroll, 4);
5881 }
5882
5883 #[test]
5884 fn fresh_and_complete_guides_remain_reachable_at_compact_and_normal_sizes() {
5885 let fresh =
5886 SetupWizardView::new_with_facts(SetupState::default(), Locale::En, facts(false));
5887 let fresh_text = render_text(&fresh, 40, 12);
5888 assert!(fresh_text.contains(tr(Locale::En, MessageId::OnboardProviderTitle).as_ref()));
5889 let normal_text = render_text(&fresh, 100, 28);
5890 assert!(normal_text.contains(tr(Locale::En, MessageId::OnboardProviderTitle).as_ref()));
5891 assert!(normal_text.contains("local · stub-model"));
5892
5893 let facts = facts(true);
5894 let complete = SetupWizardView::new_with_facts(
5895 complete_state(&facts.runtime_result),
5896 Locale::En,
5897 facts,
5898 );
5899 let complete_text = render_text(&complete, 40, 12);
5900 assert!(complete_text.contains(tr(Locale::En, MessageId::OnboardReadyTitle).as_ref()));
5901 }
5902
5903 #[tokio::test(flavor = "current_thread")]
5904 async fn load_for_app_at_populates_tools_mcp_facts_off_runtime_thread() {
5905 let tmp = tempfile::TempDir::new().expect("tempdir");
5906 let skills_dir = tmp.path().join("skills");
5907 std::fs::create_dir_all(skills_dir.join("beta")).expect("skill dir");
5908 std::fs::write(
5909 skills_dir.join("beta").join("SKILL.md"),
5910 "---\nname: beta\n---\nbody\n",
5911 )
5912 .expect("skill file");
5913
5914 let options = crate::tui::app::TuiOptions {
5915 config_path: None,
5916 skills_dir: skills_dir.clone(),
5917 memory_path: tmp.path().join("memory.md"),
5918 mcp_config_path: tmp.path().join("mcp.json"),
5919 ..crate::tui::test_support::test_tui_options(tmp.path())
5920 };
5921 let config = Config::default();
5922 let mut app = App::new(options, &config);
5923 app.ui_locale = Locale::En;
5924 app.skills_dir = skills_dir;
5925 app.cached_skills.clear();
5926
5927 let view = SetupWizardView::load_for_app_at(&app, &config, SetupStep::ToolsMcp).await;
5928 assert_eq!(view.selected_step(), SetupStep::ToolsMcp);
5929 assert!(
5930 view.facts.tools_mcp_skills_result.contains("1 on disk"),
5931 "unexpected skills result: {}",
5932 view.facts.tools_mcp_skills_result
5933 );
5934 }
5935
5936 #[test]
5937 fn freeform_note_preserves_typed_spaces_shifted_chars_and_paste() {
5938 let mut view = SetupWizardView::new_at_with_facts(
5939 SetupState::default(),
5940 Locale::En,
5941 SetupStep::Constitution,
5942 facts(false),
5943 );
5944 view.constitution_advanced = true;
5945 view.editing_freeform_note = true;
5946
5947 ModalView::handle_key(
5948 &mut view,
5949 KeyEvent::new(KeyCode::Char('N'), KeyModifiers::SHIFT),
5950 );
5951 for ch in ['o', ' ', 'p', 'r', 'o', 'd'] {
5952 ModalView::handle_key(
5953 &mut view,
5954 KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE),
5955 );
5956 }
5957 assert_eq!(view.freeform_note, "No prod");
5958 assert!(ModalView::handle_paste(&mut view, "\r\nEver!\rAlways"));
5959 assert_eq!(view.freeform_note, "No prod\nEver!\nAlways");
5960 assert_eq!(
5961 view.freeform_note_for_draft(),
5962 Some("No prod\nEver!\nAlways")
5963 );
5964 }
5965
5966 #[test]
5967 fn compact_freeform_preview_truncates_by_grapheme_cluster() {
5968 let family = "👨‍👩‍👧‍👦";
5969 let note = family.repeat(100);
5970 assert_eq!(
5971 compact_freeform_preview(&note),
5972 format!("{}...", family.repeat(96))
5973 );
5974 }
5975
5976 #[test]
5977 fn body_scroll_clamps_to_rendered_ceiling() {
5978 let mut view =
5979 SetupWizardView::new_with_facts(SetupState::default(), Locale::En, facts(false));
5980 view.details_expanded = true;
5981 let _ = render_text(&view, 60, 12);
5982 let ceiling = view.body_max_scroll.get();
5983 assert!(ceiling < usize::MAX);
5984 for _ in 0..30 {
5985 ModalView::handle_key(
5986 &mut view,
5987 KeyEvent::new(KeyCode::PageDown, KeyModifiers::NONE),
5988 );
5989 }
5990 assert_eq!(view.body_scroll, ceiling);
5991 ModalView::handle_key(&mut view, KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
5992 assert_eq!(view.body_scroll, ceiling);
5993 }
5994 }
5995
5995 lines RUST