| 1 | //! `/constitution` command surface (#3806). |
| 2 | |
| 3 | use std::fmt::Write as _; |
| 4 | use std::path::PathBuf; |
| 5 | |
| 6 | use super::SharedCommandHost; |
| 7 | use crate::tui::app::{App, AppAction}; |
| 8 | use crate::tui::pager::PagerView; |
| 9 | use codewhale_command_contract::constitution::{ |
| 10 | CommandConstitutionContext, ConstitutionAction, ConstitutionLocale, |
| 11 | }; |
| 12 | use codewhale_config::{ |
| 13 | ConstitutionChoice, ConstitutionSource, ConstitutionValidity, RuntimePostureSource, SetupState, |
| 14 | SetupStep, UserConstitution, UserConstitutionLoad, |
| 15 | }; |
| 16 | use codewhale_localization::{Locale, MessageId}; |
| 17 | |
| 18 | pub(crate) struct ConstitutionAdapter<'a> { |
| 19 | pub(super) host: SharedCommandHost<'a>, |
| 20 | } |
| 21 | |
| 22 | impl TryFrom<ConstitutionAction> for AppAction { |
| 23 | type Error = String; |
| 24 | |
| 25 | fn try_from(action: ConstitutionAction) -> Result<Self, String> { |
| 26 | Ok(match action { |
| 27 | ConstitutionAction::OpenManager { review } => Self::OpenConstitutionManager { review }, |
| 28 | ConstitutionAction::OpenSetupConstitution => Self::OpenSetupWizardAt { |
| 29 | step: SetupStep::Constitution, |
| 30 | }, |
| 31 | ConstitutionAction::OpenSetupPosture => Self::OpenSetupWizardAt { |
| 32 | step: SetupStep::TrustSandbox, |
| 33 | }, |
| 34 | ConstitutionAction::UseBundled => Self::UseBundledConstitution, |
| 35 | ConstitutionAction::PreviewEffectiveBasePrompt => Self::PreviewEffectiveBasePrompt, |
| 36 | }) |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | impl CommandConstitutionContext for ConstitutionAdapter<'_> { |
| 41 | fn locale(&self) -> ConstitutionLocale { |
| 42 | match self.host.app.borrow().ui_locale { |
| 43 | Locale::ZhHans => ConstitutionLocale::ZhHans, |
| 44 | _ => ConstitutionLocale::En, |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | fn open_pager(&mut self, title: &str, body: &str) { |
| 49 | open_pager(&mut self.host.app.borrow_mut(), title, body); |
| 50 | } |
| 51 | |
| 52 | fn preview_text(&self) -> String { |
| 53 | preview_text(self.host.app.borrow().ui_locale) |
| 54 | } |
| 55 | |
| 56 | fn repo_constitution_block(&self) -> Option<String> { |
| 57 | codewhale_engine::project_context::load_repo_constitution_block( |
| 58 | &self.host.app.borrow().workspace, |
| 59 | ) |
| 60 | .0 |
| 61 | } |
| 62 | |
| 63 | fn show_pending_suggestions(&mut self, title: &str) { |
| 64 | let mut app = self.host.app.borrow_mut(); |
| 65 | let (text, reviewed) = suggestions_text(app.ui_locale); |
| 66 | app.constitution_reviewed_digest = reviewed; |
| 67 | open_pager(&mut app, title, &text); |
| 68 | } |
| 69 | |
| 70 | fn ratify_clauses(&mut self, ids: &[&str]) -> String { |
| 71 | let mut app = self.host.app.borrow_mut(); |
| 72 | let owned_ids: Vec<String> = ids.iter().map(|id| (*id).to_string()).collect(); |
| 73 | let (message, ratified) = ratify_text( |
| 74 | app.ui_locale, |
| 75 | app.constitution_reviewed_digest.as_deref(), |
| 76 | &owned_ids, |
| 77 | ); |
| 78 | if ratified.is_some() { |
| 79 | app.constitution_reviewed_digest = ratified; |
| 80 | } |
| 81 | message |
| 82 | } |
| 83 | |
| 84 | fn migrate(&self) -> String { |
| 85 | migrate_text(self.host.app.borrow().ui_locale) |
| 86 | } |
| 87 | |
| 88 | fn rollback(&self) -> String { |
| 89 | rollback_text(self.host.app.borrow().ui_locale) |
| 90 | } |
| 91 | |
| 92 | fn repair_text(&self) -> String { |
| 93 | repair_text(self.host.app.borrow().ui_locale) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | pub(crate) fn open_manager(app: &mut App, review: bool, account: Result<bool, String>) { |
| 98 | let locale = app.ui_locale; |
| 99 | let mut text = format_status(app, locale, &account); |
| 100 | let title = if review { |
| 101 | let _ = write!(text, "\n\n{}", preview_text(locale)); |
| 102 | review_title(locale) |
| 103 | } else { |
| 104 | manager_title(locale) |
| 105 | }; |
| 106 | open_pager(app, title, &text); |
| 107 | } |
| 108 | |
| 109 | fn suggestions_text(locale: Locale) -> (String, Option<String>) { |
| 110 | let UserConstitutionStatus::Loaded { constitution, .. } = load_user_constitution() else { |
| 111 | let text = match locale { |
| 112 | Locale::ZhHans => "没有可供审阅的结构化用户全局宪章。".to_string(), |
| 113 | _ => "No structured user-global constitution is available to review.".to_string(), |
| 114 | }; |
| 115 | return (text, None); |
| 116 | }; |
| 117 | let digest = constitution.cache_projection().digest; |
| 118 | let suggested: Vec<_> = constitution.suggested_clauses().collect(); |
| 119 | let accepted = constitution.accepted_clauses().count(); |
| 120 | |
| 121 | let mut out = String::new(); |
| 122 | match locale { |
| 123 | Locale::ZhHans => { |
| 124 | let _ = writeln!(out, "已生效条款:{accepted}"); |
| 125 | let _ = writeln!(out, "当前基线摘要:{digest}"); |
| 126 | out.push('\n'); |
| 127 | if suggested.is_empty() { |
| 128 | out.push_str("没有待批准的建议条款。模型建议在你明确批准之前不会生效。\n"); |
| 129 | } else { |
| 130 | out.push_str("待批准的建议条款(未注入模型,未计入缓存):\n"); |
| 131 | for clause in &suggested { |
| 132 | let _ = writeln!(out, "- [{}] {}", clause.id, clause.text); |
| 133 | } |
| 134 | out.push_str("\n用 /constitution ratify <id> 明确批准。基线变化后需要重新审阅。\n"); |
| 135 | } |
| 136 | } |
| 137 | _ => { |
| 138 | let _ = writeln!(out, "Ratified clauses in force: {accepted}"); |
| 139 | let _ = writeln!(out, "Current base digest: {digest}"); |
| 140 | out.push('\n'); |
| 141 | if suggested.is_empty() { |
| 142 | out.push_str( |
| 143 | "No suggested clauses are awaiting review. Model advice never applies itself.\n", |
| 144 | ); |
| 145 | } else { |
| 146 | out.push_str( |
| 147 | "Suggested clauses awaiting ratification (not injected, not in the cache digest):\n", |
| 148 | ); |
| 149 | for clause in &suggested { |
| 150 | let _ = writeln!(out, "- [{}] {}", clause.id, clause.text); |
| 151 | } |
| 152 | out.push_str( |
| 153 | "\nRatify explicitly with /constitution ratify <id>. If the base changes first, ratification is refused and you review again.\n", |
| 154 | ); |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | (out, Some(digest)) |
| 159 | } |
| 160 | |
| 161 | /// Explicit ratification (#3930). Fails closed: it hands the digest the user |
| 162 | /// reviewed in `/constitution suggestions` to [`UserConstitution::ratify`], |
| 163 | /// which refuses when the live file has moved since, and persists only when the |
| 164 | /// clause set is exactly what the user named. |
| 165 | fn ratify_text(locale: Locale, reviewed: Option<&str>, ids: &[String]) -> (String, Option<String>) { |
| 166 | if ids.is_empty() { |
| 167 | let text = match locale { |
| 168 | Locale::ZhHans => { |
| 169 | "用法:/constitution ratify <id> [<id>...]。先用 /constitution suggestions 查看待批准条款。" |
| 170 | .to_string() |
| 171 | } |
| 172 | _ => "Usage: /constitution ratify <id> [<id>...]. Run /constitution suggestions first to see what is pending.".to_string(), |
| 173 | }; |
| 174 | return (text, None); |
| 175 | } |
| 176 | |
| 177 | let (path, constitution) = match load_user_constitution() { |
| 178 | UserConstitutionStatus::Loaded { path, constitution } => (path, constitution), |
| 179 | _ => { |
| 180 | let text = match locale { |
| 181 | Locale::ZhHans => "没有可批准的结构化用户全局宪章。".to_string(), |
| 182 | _ => "There is no structured user-global constitution to ratify.".to_string(), |
| 183 | }; |
| 184 | return (text, None); |
| 185 | } |
| 186 | }; |
| 187 | |
| 188 | let Some(reviewed) = reviewed else { |
| 189 | let text = match locale { |
| 190 | Locale::ZhHans => { |
| 191 | "未批准任何条款:请先用 /constitution suggestions 审阅待批准条款。".to_string() |
| 192 | } |
| 193 | _ => "Nothing was ratified: review the pending clauses with /constitution suggestions first.".to_string(), |
| 194 | }; |
| 195 | return (text, None); |
| 196 | }; |
| 197 | match constitution.ratify(reviewed, ids, None) { |
| 198 | Err(err) => ( |
| 199 | match locale { |
| 200 | Locale::ZhHans => format!("未批准任何条款:{err}"), |
| 201 | _ => format!("Nothing was ratified: {err}"), |
| 202 | }, |
| 203 | None, |
| 204 | ), |
| 205 | Ok(ratification) => match ratification.constitution.save_to(&path) { |
| 206 | Err(err) => ( |
| 207 | match locale { |
| 208 | Locale::ZhHans => format!("批准已计算但保存失败,文件未更改:{err:#}"), |
| 209 | _ => format!( |
| 210 | "Ratification was computed but could not be saved; the file is unchanged: {err:#}" |
| 211 | ), |
| 212 | }, |
| 213 | None, |
| 214 | ), |
| 215 | Ok(()) => ( |
| 216 | match locale { |
| 217 | Locale::ZhHans => format!( |
| 218 | "已批准 {} 条:{}\n摘要 {} → {}\n这些条款从下一轮起作为会话记录中的消息发送给模型;提示词缓存前缀不变。", |
| 219 | ratification.accepted_clause_ids.len(), |
| 220 | ratification.accepted_clause_ids.join(", "), |
| 221 | ratification.before_digest, |
| 222 | ratification.after_digest, |
| 223 | ), |
| 224 | _ => format!( |
| 225 | "Ratified {} clause(s): {}\nDigest {} → {}\nThey reach the model from the next turn as a message recorded in the session; the prompt-cache prefix is unchanged.", |
| 226 | ratification.accepted_clause_ids.len(), |
| 227 | ratification.accepted_clause_ids.join(", "), |
| 228 | ratification.before_digest, |
| 229 | ratification.after_digest, |
| 230 | ), |
| 231 | }, |
| 232 | Some(ratification.after_digest.clone()), |
| 233 | ), |
| 234 | }, |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | /// Explicit schema migration with a receipt (#4782). A rejection writes nothing. |
| 239 | fn migrate_text(locale: Locale) -> String { |
| 240 | let path = match codewhale_config::UserConstitution::path() { |
| 241 | Ok(path) => path, |
| 242 | Err(err) => return path_error_preview_text(locale, &err.to_string()), |
| 243 | }; |
| 244 | match codewhale_config::UserConstitution::migrate_file(&path) { |
| 245 | Err(err) => match locale { |
| 246 | Locale::ZhHans => format!("迁移失败,文件未更改:{err:#}"), |
| 247 | _ => format!("Migration failed; the file is unchanged: {err:#}"), |
| 248 | }, |
| 249 | Ok(codewhale_config::MigrationOutcome::AlreadyCurrent { |
| 250 | preserved_unknown_keys, |
| 251 | .. |
| 252 | }) => { |
| 253 | let preserved = format_preserved(&preserved_unknown_keys, locale); |
| 254 | match locale { |
| 255 | Locale::ZhHans => { |
| 256 | format!("已是当前架构版本,未重写文件。\n保留的未知字段:{preserved}") |
| 257 | } |
| 258 | _ => format!( |
| 259 | "Already at the current schema; nothing was rewritten.\nPreserved unknown fields: {preserved}" |
| 260 | ), |
| 261 | } |
| 262 | } |
| 263 | Ok(codewhale_config::MigrationOutcome::Migrated { receipt, .. }) => { |
| 264 | let preserved = format_preserved(&receipt.preserved_unknown_keys, locale); |
| 265 | let backup = receipt |
| 266 | .backup_path |
| 267 | .as_ref() |
| 268 | .map(|p| p.display().to_string()) |
| 269 | .unwrap_or_default(); |
| 270 | match locale { |
| 271 | Locale::ZhHans => format!( |
| 272 | "已从架构 v{} 迁移到 v{}。\n备份:{backup}\n保留的未知字段:{preserved}\n模型可见字节摘要:{} → {}({})\n用 /constitution rollback 撤销。", |
| 273 | receipt.from_version, |
| 274 | receipt.to_version, |
| 275 | receipt.before_digest, |
| 276 | receipt.after_digest, |
| 277 | if receipt.is_cache_stable() { |
| 278 | "未改变,模型下一轮收到相同内容" |
| 279 | } else { |
| 280 | "已改变,下一轮作为新的会话消息发送" |
| 281 | }, |
| 282 | ), |
| 283 | _ => format!( |
| 284 | "Migrated schema v{} → v{}.\nBackup: {backup}\nPreserved unknown fields: {preserved}\nModel-facing digest: {} → {} ({}).\nUndo with /constitution rollback.", |
| 285 | receipt.from_version, |
| 286 | receipt.to_version, |
| 287 | receipt.before_digest, |
| 288 | receipt.after_digest, |
| 289 | if receipt.is_cache_stable() { |
| 290 | "unchanged, so the model receives the same text" |
| 291 | } else { |
| 292 | "changed; the new text is sent as a session message at the next turn" |
| 293 | }, |
| 294 | ), |
| 295 | } |
| 296 | } |
| 297 | Ok(codewhale_config::MigrationOutcome::Rejected(rejection)) => match locale { |
| 298 | Locale::ZhHans => format!( |
| 299 | "未迁移,文件保持原样。\n{}\n请手动修正后重试,或用 /constitution bundled 改用内置准则。", |
| 300 | rejection.receipt() |
| 301 | ), |
| 302 | _ => format!( |
| 303 | "Not migrated; the file is left exactly as it was.\n{}\nFix it by hand and retry, or run /constitution bundled to fall back to bundled law.", |
| 304 | rejection.receipt() |
| 305 | ), |
| 306 | }, |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | fn rollback_text(locale: Locale) -> String { |
| 311 | let path = match codewhale_config::UserConstitution::path() { |
| 312 | Ok(path) => path, |
| 313 | Err(err) => return path_error_preview_text(locale, &err.to_string()), |
| 314 | }; |
| 315 | match codewhale_config::UserConstitution::rollback_file(&path) { |
| 316 | Ok(backup) => match locale { |
| 317 | Locale::ZhHans => format!("已从 {} 恢复迁移前的内容。备份已消耗。", backup.display()), |
| 318 | _ => format!( |
| 319 | "Restored the pre-migration constitution from {}. The backup is consumed.", |
| 320 | backup.display() |
| 321 | ), |
| 322 | }, |
| 323 | Err(err) => match locale { |
| 324 | Locale::ZhHans => format!("未回滚:{err:#}"), |
| 325 | _ => format!("Nothing was rolled back: {err:#}"), |
| 326 | }, |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | fn format_preserved(keys: &[String], locale: Locale) -> String { |
| 331 | if keys.is_empty() { |
| 332 | match locale { |
| 333 | Locale::ZhHans => "无".to_string(), |
| 334 | _ => "none".to_string(), |
| 335 | } |
| 336 | } else { |
| 337 | keys.join(", ") |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | fn open_pager(app: &mut App, title: &str, text: &str) { |
| 342 | let width = app |
| 343 | .viewport |
| 344 | .last_transcript_area |
| 345 | .map(|area| area.width) |
| 346 | .unwrap_or(80); |
| 347 | app.view_stack |
| 348 | .push(PagerView::from_text(title, text, width.saturating_sub(2))); |
| 349 | } |
| 350 | |
| 351 | fn format_status(app: &App, locale: Locale, account: &Result<bool, String>) -> String { |
| 352 | let state = load_setup_state(); |
| 353 | let load = load_user_constitution(); |
| 354 | let (constitution_source_path, source_path, has_instructions, warnings) = |
| 355 | match app.instruction_assembly.as_deref() { |
| 356 | Some(assembly) => ( |
| 357 | assembly.constitution_source_path.clone(), |
| 358 | assembly.source_path.clone(), |
| 359 | assembly.global_tokens + assembly.project_tokens > 0, |
| 360 | assembly.warnings.clone(), |
| 361 | ), |
| 362 | None => { |
| 363 | let context = codewhale_engine::project_context::load_project_context_with_parents( |
| 364 | &app.workspace, |
| 365 | ); |
| 366 | ( |
| 367 | context.constitution_source_path, |
| 368 | context.source_path, |
| 369 | context.instructions.is_some(), |
| 370 | context.warnings, |
| 371 | ) |
| 372 | } |
| 373 | }; |
| 374 | let mut out = String::new(); |
| 375 | |
| 376 | let copy = ConstitutionManagerCopy::for_locale(locale); |
| 377 | |
| 378 | let _ = writeln!(out, "{}", copy.manager_header); |
| 379 | out.push_str(match locale { |
| 380 | Locale::ZhHans => "\n下方为本机宪章设置。已登录账户的宪章(包括默认值)优先于本机设置,由引擎在每轮开始时加载;账户服务响应较慢时,该轮使用上次加载的账户宪章。在应用的设置 → 账户 → 宪章中编辑;更改从下一轮生效。\n", |
| 381 | _ => "\nLocal constitution settings follow. The signed-in profile constitution, including its defaults, takes precedence and is loaded by the Engine at each turn; when the account service is slow, a turn uses the last one it loaded. Edit it in Settings → Accounts → Constitution; changes apply from the next turn.\n", |
| 382 | }); |
| 383 | out.push('\n'); |
| 384 | let _ = writeln!(out, "{}", copy.active_stack_header); |
| 385 | let _ = writeln!(out, "- {}", copy.bundled_active); |
| 386 | let account_status = match account { |
| 387 | Ok(true) => codewhale_localization::tr(locale, MessageId::CmdConstitutionAccountApplies) |
| 388 | .into_owned(), |
| 389 | Ok(false) => codewhale_localization::tr(locale, MessageId::CmdConstitutionAccountSignedOut) |
| 390 | .into_owned(), |
| 391 | Err(error) => { |
| 392 | codewhale_localization::tr(locale, MessageId::CmdConstitutionAccountCheckFailed) |
| 393 | .replace("{error}", error) |
| 394 | } |
| 395 | }; |
| 396 | let _ = writeln!(out, "- {account_status}"); |
| 397 | let _ = writeln!( |
| 398 | out, |
| 399 | "- {}: {}", |
| 400 | copy.user_global_label, |
| 401 | user_constitution_stack_status(state.as_ref(), &load, locale, matches!(account, Ok(true))) |
| 402 | ); |
| 403 | if let Some(path) = constitution_source_path.as_ref() { |
| 404 | let _ = writeln!( |
| 405 | out, |
| 406 | "- {}: {} ({})", |
| 407 | copy.repo_local_label, |
| 408 | copy.present, |
| 409 | path.display() |
| 410 | ); |
| 411 | } else { |
| 412 | let _ = writeln!(out, "- {}: {}", copy.repo_local_label, copy.not_present); |
| 413 | } |
| 414 | if let Some(path) = source_path.as_ref() { |
| 415 | let _ = writeln!( |
| 416 | out, |
| 417 | "- {}: {} ({})", |
| 418 | copy.agents_label, |
| 419 | copy.present, |
| 420 | path.display() |
| 421 | ); |
| 422 | } else if has_instructions { |
| 423 | let _ = writeln!(out, "- {}: {}", copy.agents_label, copy.generated_fallback); |
| 424 | } else { |
| 425 | let _ = writeln!(out, "- {}: {}", copy.agents_label, copy.not_present); |
| 426 | } |
| 427 | let whale_warnings = ignored_whale_warnings(&warnings); |
| 428 | if whale_warnings.is_empty() { |
| 429 | let _ = writeln!(out, "- {}: {}", copy.legacy_whale_label, copy.not_present); |
| 430 | } else { |
| 431 | let _ = writeln!( |
| 432 | out, |
| 433 | "- {}: {} ({} {})", |
| 434 | copy.legacy_whale_label, |
| 435 | copy.whale_ignored, |
| 436 | whale_warnings.len(), |
| 437 | copy.location_count_unit(whale_warnings.len()) |
| 438 | ); |
| 439 | for warning in whale_warnings { |
| 440 | let _ = writeln!(out, " - {warning}"); |
| 441 | } |
| 442 | } |
| 443 | let handoff_path = app |
| 444 | .workspace |
| 445 | .join(codewhale_engine::prompts::HANDOFF_RELATIVE_PATH); |
| 446 | let _ = writeln!( |
| 447 | out, |
| 448 | "- {}: {} {}, {} {}", |
| 449 | copy.memory_handoff_label, |
| 450 | copy.memory_label, |
| 451 | if app.use_memory { |
| 452 | copy.enabled |
| 453 | } else { |
| 454 | copy.disabled |
| 455 | }, |
| 456 | copy.handoff_label, |
| 457 | if handoff_path.exists() { |
| 458 | copy.present |
| 459 | } else { |
| 460 | copy.not_present |
| 461 | } |
| 462 | ); |
| 463 | |
| 464 | out.push('\n'); |
| 465 | let _ = writeln!(out, "{}", copy.user_global_header); |
| 466 | let _ = writeln!( |
| 467 | out, |
| 468 | "- {}: {}", |
| 469 | copy.choice_label, |
| 470 | state.as_ref().map_or(copy.not_recorded, |s| choice_label( |
| 471 | s.constitution_choice, |
| 472 | locale |
| 473 | )) |
| 474 | ); |
| 475 | let _ = writeln!( |
| 476 | out, |
| 477 | "- {}: {}", |
| 478 | copy.source_label, |
| 479 | state.as_ref().map_or(copy.not_recorded, |s| source_label( |
| 480 | s.constitution_source, |
| 481 | locale |
| 482 | )) |
| 483 | ); |
| 484 | let _ = writeln!( |
| 485 | out, |
| 486 | "- {}: {}", |
| 487 | copy.file_label, |
| 488 | user_constitution_file_label(&load, locale) |
| 489 | ); |
| 490 | let _ = writeln!( |
| 491 | out, |
| 492 | "- {}: {}", |
| 493 | copy.validity_label, |
| 494 | manager_validity_label(&load, state.as_ref(), locale) |
| 495 | ); |
| 496 | let _ = writeln!( |
| 497 | out, |
| 498 | "- {}: {}", |
| 499 | copy.language_label, |
| 500 | constitution_language(state.as_ref(), &load, locale) |
| 501 | ); |
| 502 | let _ = writeln!( |
| 503 | out, |
| 504 | "- {}: {}", |
| 505 | copy.last_preview_label, |
| 506 | preview_record_label(state.as_ref(), locale) |
| 507 | ); |
| 508 | let _ = writeln!( |
| 509 | out, |
| 510 | "- {}: {}", |
| 511 | copy.runtime_posture_label, |
| 512 | state.as_ref().map_or(copy.not_reviewed, |s| posture_label( |
| 513 | s.runtime_posture_source, |
| 514 | locale |
| 515 | )) |
| 516 | ); |
| 517 | let _ = writeln!( |
| 518 | out, |
| 519 | "- {}: {}", |
| 520 | copy.checkpoint_label, |
| 521 | state.as_ref().map_or(copy.not_completed.to_string(), |s| { |
| 522 | s.constitution_checkpoint_completed_for |
| 523 | .as_ref() |
| 524 | .map_or_else(|| copy.not_completed.to_string(), |v| copy.completed_for(v)) |
| 525 | }) |
| 526 | ); |
| 527 | |
| 528 | out.push('\n'); |
| 529 | let _ = writeln!(out, "{}", copy.preview_header); |
| 530 | let _ = writeln!(out, "- {}", copy.preview_action); |
| 531 | let _ = writeln!(out, "- {}", copy.repo_action); |
| 532 | |
| 533 | out.push('\n'); |
| 534 | let _ = writeln!(out, "{}", copy.maintenance_header); |
| 535 | for action in copy.maintenance_actions { |
| 536 | let _ = writeln!(out, "- {action}"); |
| 537 | } |
| 538 | out |
| 539 | } |
| 540 | |
| 541 | fn preview_text(locale: Locale) -> String { |
| 542 | let state = load_setup_state(); |
| 543 | let load = load_user_constitution(); |
| 544 | match load { |
| 545 | UserConstitutionStatus::Loaded { constitution, .. } => { |
| 546 | let active = user_constitution_is_active(state.as_ref()); |
| 547 | let mut text = String::new(); |
| 548 | if !active { |
| 549 | text.push_str(inactive_preview_text(locale)); |
| 550 | text.push_str("\n\n"); |
| 551 | } |
| 552 | text.push_str( |
| 553 | &constitution |
| 554 | .render_block(None) |
| 555 | .unwrap_or_else(|| structured_empty_text(locale).to_string()), |
| 556 | ); |
| 557 | text |
| 558 | } |
| 559 | UserConstitutionStatus::Missing { path } => missing_preview_text(locale, &path), |
| 560 | UserConstitutionStatus::Empty { path } => empty_preview_text(locale, &path), |
| 561 | UserConstitutionStatus::Invalid { path, error } => { |
| 562 | invalid_preview_text(locale, &path, &error) |
| 563 | } |
| 564 | UserConstitutionStatus::Unreadable { path, error } => { |
| 565 | unreadable_preview_text(locale, &path, &error) |
| 566 | } |
| 567 | UserConstitutionStatus::PathError { error } => path_error_preview_text(locale, &error), |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | fn load_setup_state() -> Option<SetupState> { |
| 572 | SetupState::load().ok().flatten() |
| 573 | } |
| 574 | |
| 575 | #[derive(Debug)] |
| 576 | enum UserConstitutionStatus { |
| 577 | Missing { |
| 578 | path: PathBuf, |
| 579 | }, |
| 580 | Empty { |
| 581 | path: PathBuf, |
| 582 | }, |
| 583 | Invalid { |
| 584 | path: PathBuf, |
| 585 | error: String, |
| 586 | }, |
| 587 | Unreadable { |
| 588 | path: PathBuf, |
| 589 | error: String, |
| 590 | }, |
| 591 | Loaded { |
| 592 | path: PathBuf, |
| 593 | constitution: Box<codewhale_config::UserConstitution>, |
| 594 | }, |
| 595 | PathError { |
| 596 | error: String, |
| 597 | }, |
| 598 | } |
| 599 | |
| 600 | impl UserConstitutionStatus { |
| 601 | fn validity(&self) -> ConstitutionValidity { |
| 602 | match self { |
| 603 | Self::Missing { .. } | Self::PathError { .. } => ConstitutionValidity::Unknown, |
| 604 | Self::Empty { .. } => ConstitutionValidity::Empty, |
| 605 | Self::Invalid { .. } => ConstitutionValidity::Invalid, |
| 606 | Self::Unreadable { .. } => ConstitutionValidity::Unreadable, |
| 607 | Self::Loaded { constitution, .. } => constitution.validity(), |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | fn validity_for_display(&self, state: Option<&SetupState>) -> ConstitutionValidity { |
| 612 | match self { |
| 613 | Self::Missing { .. } | Self::PathError { .. } => { |
| 614 | state.map_or(ConstitutionValidity::Unknown, |s| s.constitution_validity) |
| 615 | } |
| 616 | _ => self.validity(), |
| 617 | } |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | fn load_user_constitution() -> UserConstitutionStatus { |
| 622 | let path = match UserConstitution::path() { |
| 623 | Ok(path) => path, |
| 624 | Err(error) => { |
| 625 | return UserConstitutionStatus::PathError { |
| 626 | error: error.to_string(), |
| 627 | }; |
| 628 | } |
| 629 | }; |
| 630 | |
| 631 | match UserConstitution::load_from(&path) { |
| 632 | UserConstitutionLoad::Missing => UserConstitutionStatus::Missing { path }, |
| 633 | UserConstitutionLoad::Empty => UserConstitutionStatus::Empty { path }, |
| 634 | UserConstitutionLoad::Invalid(error) => UserConstitutionStatus::Invalid { path, error }, |
| 635 | UserConstitutionLoad::Unreadable(error) => { |
| 636 | UserConstitutionStatus::Unreadable { path, error } |
| 637 | } |
| 638 | UserConstitutionLoad::Loaded(constitution) => { |
| 639 | UserConstitutionStatus::Loaded { path, constitution } |
| 640 | } |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | fn user_constitution_stack_status( |
| 645 | state: Option<&SetupState>, |
| 646 | load: &UserConstitutionStatus, |
| 647 | locale: Locale, |
| 648 | account_applies: bool, |
| 649 | ) -> String { |
| 650 | if account_applies |
| 651 | && user_constitution_is_active(state) |
| 652 | && matches!(load, UserConstitutionStatus::Loaded { .. }) |
| 653 | { |
| 654 | return codewhale_localization::tr(locale, MessageId::CmdConstitutionLocalStandby) |
| 655 | .into_owned(); |
| 656 | } |
| 657 | let text = match load { |
| 658 | UserConstitutionStatus::Loaded { .. } if user_constitution_is_active(state) => match locale |
| 659 | { |
| 660 | Locale::ZhHans => "结构化用户全局准则已生效", |
| 661 | _ => "active structured user-global law", |
| 662 | }, |
| 663 | UserConstitutionStatus::Loaded { .. } => match locale { |
| 664 | Locale::ZhHans => "有效但未生效(已选择内置/默认或专家覆盖)", |
| 665 | _ => "valid but inactive (bundled/default or expert override selected)", |
| 666 | }, |
| 667 | UserConstitutionStatus::Missing { .. } => match locale { |
| 668 | Locale::ZhHans => "未配置;使用内置/默认准则", |
| 669 | _ => "not configured; bundled/default applies", |
| 670 | }, |
| 671 | UserConstitutionStatus::Empty { .. } => match locale { |
| 672 | Locale::ZhHans => "为空;建议修复", |
| 673 | _ => "empty; repair recommended", |
| 674 | }, |
| 675 | UserConstitutionStatus::Invalid { .. } => match locale { |
| 676 | Locale::ZhHans => "无效;建议修复", |
| 677 | _ => "invalid; repair recommended", |
| 678 | }, |
| 679 | UserConstitutionStatus::Unreadable { .. } => match locale { |
| 680 | Locale::ZhHans => "无法读取;建议修复", |
| 681 | _ => "unreadable; repair recommended", |
| 682 | }, |
| 683 | UserConstitutionStatus::PathError { .. } => match locale { |
| 684 | Locale::ZhHans => "不可用;CODEWHALE_HOME 错误", |
| 685 | _ => "unavailable; CODEWHALE_HOME error", |
| 686 | }, |
| 687 | }; |
| 688 | text.to_string() |
| 689 | } |
| 690 | |
| 691 | fn user_constitution_is_active(state: Option<&SetupState>) -> bool { |
| 692 | state.is_none_or(|state| state.constitution_choice.applies_user_global()) |
| 693 | } |
| 694 | |
| 695 | fn user_constitution_file_label(load: &UserConstitutionStatus, locale: Locale) -> String { |
| 696 | match load { |
| 697 | UserConstitutionStatus::Missing { path } |
| 698 | | UserConstitutionStatus::Empty { path } |
| 699 | | UserConstitutionStatus::Invalid { path, .. } |
| 700 | | UserConstitutionStatus::Unreadable { path, .. } |
| 701 | | UserConstitutionStatus::Loaded { path, .. } => path.display().to_string(), |
| 702 | UserConstitutionStatus::PathError { .. } => match locale { |
| 703 | Locale::ZhHans => "无法解析", |
| 704 | _ => "unresolved", |
| 705 | } |
| 706 | .to_string(), |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | fn constitution_language( |
| 711 | state: Option<&SetupState>, |
| 712 | load: &UserConstitutionStatus, |
| 713 | locale: Locale, |
| 714 | ) -> String { |
| 715 | if let UserConstitutionStatus::Loaded { constitution, .. } = load |
| 716 | && let Some(language) = constitution.language.as_deref() |
| 717 | { |
| 718 | return language.to_string(); |
| 719 | } |
| 720 | state |
| 721 | .and_then(|s| s.constitution_language.as_deref()) |
| 722 | .unwrap_or(match locale { |
| 723 | Locale::ZhHans => "未记录", |
| 724 | _ => "not recorded", |
| 725 | }) |
| 726 | .to_string() |
| 727 | } |
| 728 | |
| 729 | fn preview_record_label(state: Option<&SetupState>, locale: Locale) -> String { |
| 730 | let Some(state) = state else { |
| 731 | return match locale { |
| 732 | Locale::ZhHans => "未记录", |
| 733 | _ => "not recorded", |
| 734 | } |
| 735 | .to_string(); |
| 736 | }; |
| 737 | match state.constitution_preview_hash.as_deref() { |
| 738 | Some(hash) => format!("v{} ({hash})", state.constitution_preview_version), |
| 739 | None => match locale { |
| 740 | Locale::ZhHans => "未记录", |
| 741 | _ => "not recorded", |
| 742 | } |
| 743 | .to_string(), |
| 744 | } |
| 745 | } |
| 746 | |
| 747 | fn choice_label(choice: ConstitutionChoice, locale: Locale) -> &'static str { |
| 748 | match (locale, choice) { |
| 749 | (Locale::ZhHans, ConstitutionChoice::Unset) => "未设置", |
| 750 | (Locale::ZhHans, ConstitutionChoice::Bundled) => "内置/默认", |
| 751 | (Locale::ZhHans, ConstitutionChoice::GuidedCustom) => "引导式自定义", |
| 752 | (Locale::ZhHans, ConstitutionChoice::ExpertOverride) => "专家覆盖", |
| 753 | (Locale::ZhHans, ConstitutionChoice::Deferred) => "已暂缓;使用内置", |
| 754 | (_, ConstitutionChoice::Unset) => "not set", |
| 755 | (_, ConstitutionChoice::Bundled) => "bundled/default", |
| 756 | (_, ConstitutionChoice::GuidedCustom) => "guided custom", |
| 757 | (_, ConstitutionChoice::ExpertOverride) => "expert override", |
| 758 | (_, ConstitutionChoice::Deferred) => "deferred; bundled applies", |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | fn source_label(source: ConstitutionSource, locale: Locale) -> &'static str { |
| 763 | match (locale, source) { |
| 764 | (Locale::ZhHans, ConstitutionSource::Bundled) => "内置", |
| 765 | (Locale::ZhHans, ConstitutionSource::UserGlobal) => "用户全局 constitution.json", |
| 766 | (Locale::ZhHans, ConstitutionSource::ExpertOverride) => "专家提示词覆盖", |
| 767 | (_, ConstitutionSource::Bundled) => "bundled", |
| 768 | (_, ConstitutionSource::UserGlobal) => "user-global constitution.json", |
| 769 | (_, ConstitutionSource::ExpertOverride) => "expert prompt override", |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | fn validity_label(validity: ConstitutionValidity, locale: Locale) -> &'static str { |
| 774 | match (locale, validity) { |
| 775 | (Locale::ZhHans, ConstitutionValidity::Unknown) => "未知或非自定义", |
| 776 | (Locale::ZhHans, ConstitutionValidity::Valid) => "有效", |
| 777 | (Locale::ZhHans, ConstitutionValidity::Invalid) => "无效", |
| 778 | (Locale::ZhHans, ConstitutionValidity::Empty) => "为空", |
| 779 | (Locale::ZhHans, ConstitutionValidity::Unreadable) => "无法读取", |
| 780 | (_, ConstitutionValidity::Unknown) => "unknown or not custom", |
| 781 | (_, ConstitutionValidity::Valid) => "valid", |
| 782 | (_, ConstitutionValidity::Invalid) => "invalid", |
| 783 | (_, ConstitutionValidity::Empty) => "empty", |
| 784 | (_, ConstitutionValidity::Unreadable) => "unreadable", |
| 785 | } |
| 786 | } |
| 787 | |
| 788 | fn manager_validity_label( |
| 789 | load: &UserConstitutionStatus, |
| 790 | state: Option<&SetupState>, |
| 791 | locale: Locale, |
| 792 | ) -> String { |
| 793 | if matches!(load, UserConstitutionStatus::Missing { .. }) |
| 794 | && state.is_some_and(|state| state.constitution_choice == ConstitutionChoice::Bundled) |
| 795 | { |
| 796 | return match locale { |
| 797 | Locale::ZhHans => "不适用(已选择内置/默认;没有自定义文件)".to_string(), |
| 798 | _ => "not applicable (bundled/default selected; no custom file)".to_string(), |
| 799 | }; |
| 800 | } |
| 801 | validity_label(load.validity_for_display(state), locale).to_string() |
| 802 | } |
| 803 | |
| 804 | fn posture_label(source: RuntimePostureSource, locale: Locale) -> &'static str { |
| 805 | match (locale, source) { |
| 806 | (Locale::ZhHans, RuntimePostureSource::Unset) => "未查看", |
| 807 | (Locale::ZhHans, RuntimePostureSource::Inherited) => "继承自现有配置", |
| 808 | (Locale::ZhHans, RuntimePostureSource::Confirmed) => "已在设置中确认", |
| 809 | (_, RuntimePostureSource::Unset) => "not reviewed", |
| 810 | (_, RuntimePostureSource::Inherited) => "inherited from existing config", |
| 811 | (_, RuntimePostureSource::Confirmed) => "confirmed in setup", |
| 812 | } |
| 813 | } |
| 814 | |
| 815 | fn ignored_whale_warnings(warnings: &[String]) -> Vec<&str> { |
| 816 | warnings |
| 817 | .iter() |
| 818 | .map(String::as_str) |
| 819 | .filter(|warning| warning.contains("WHALE.md is ignored")) |
| 820 | .collect() |
| 821 | } |
| 822 | |
| 823 | fn repair_text(locale: Locale) -> String { |
| 824 | let state = load_setup_state(); |
| 825 | let load = load_user_constitution(); |
| 826 | let file = user_constitution_file_label(&load, locale); |
| 827 | let choice = state.as_ref().map_or( |
| 828 | match locale { |
| 829 | Locale::ZhHans => "未记录", |
| 830 | _ => "not recorded", |
| 831 | }, |
| 832 | |s| choice_label(s.constitution_choice, locale), |
| 833 | ); |
| 834 | let validity = validity_label(load.validity_for_display(state.as_ref()), locale); |
| 835 | let status = user_constitution_stack_status(state.as_ref(), &load, locale, false); |
| 836 | |
| 837 | match locale { |
| 838 | Locale::ZhHans => format!( |
| 839 | "\ |
| 840 | 用户全局宪章修复 |
| 841 | |
| 842 | 当前文件:{file} |
| 843 | 当前状态:{status} |
| 844 | 记录选择:{choice} |
| 845 | 有效性:{validity} |
| 846 | |
| 847 | 接下来将打开 /setup 的宪章步骤。安全修复路径: |
| 848 | - 用 1-6 调整引导式草稿,按 G 预览,再按 G 保存新的结构化 constitution.json。 |
| 849 | - 按 U 或运行 /constitution bundled 记录使用内置/默认准则;现有无效/空/不可读文件不会被注入。 |
| 850 | - 用 /constitution preview 查看当前错误或渲染结果。 |
| 851 | |
| 852 | 这只处理用户全局 constitution.json。运行时批准、沙盒、Shell、网络、信任、默认模式和 MCP 权限仍由运行时姿态/配置控制。" |
| 853 | ), |
| 854 | _ => format!( |
| 855 | "\ |
| 856 | User-global constitution repair |
| 857 | |
| 858 | Current file: {file} |
| 859 | Current state: {status} |
| 860 | Recorded choice: {choice} |
| 861 | Validity: {validity} |
| 862 | |
| 863 | Opening the /setup Constitution step next. Safe repair paths: |
| 864 | - Tune the guided draft with 1-6, press G to preview, then G again to save a fresh structured constitution.json. |
| 865 | - Press U or run /constitution bundled to record bundled/default law; the existing invalid/empty/unreadable file will not be injected. |
| 866 | - Use /constitution preview to inspect the current error or rendered result. |
| 867 | |
| 868 | This only repairs the user-global constitution.json. Runtime approval, sandbox, shell, network, trust, default mode, and MCP authority still belong to runtime posture/config." |
| 869 | ), |
| 870 | } |
| 871 | } |
| 872 | |
| 873 | fn manager_title(locale: Locale) -> &'static str { |
| 874 | match locale { |
| 875 | Locale::ZhHans => "宪章", |
| 876 | _ => "Constitution", |
| 877 | } |
| 878 | } |
| 879 | |
| 880 | fn review_title(locale: Locale) -> &'static str { |
| 881 | match locale { |
| 882 | Locale::ZhHans => "宪章检查", |
| 883 | _ => "Constitution Review", |
| 884 | } |
| 885 | } |
| 886 | |
| 887 | fn inactive_preview_text(locale: Locale) -> &'static str { |
| 888 | match locale { |
| 889 | Locale::ZhHans => "非活动预览:当前选择了内置/默认或专家覆盖。", |
| 890 | _ => "Inactive preview: bundled/default or expert override is selected.", |
| 891 | } |
| 892 | } |
| 893 | |
| 894 | fn structured_empty_text(locale: Locale) -> &'static str { |
| 895 | match locale { |
| 896 | Locale::ZhHans => "结构化宪章为空。", |
| 897 | _ => "The structured constitution is empty.", |
| 898 | } |
| 899 | } |
| 900 | |
| 901 | fn missing_preview_text(locale: Locale, path: &std::path::Path) -> String { |
| 902 | match locale { |
| 903 | Locale::ZhHans => format!( |
| 904 | "未在 {} 找到结构化用户全局宪章。\n\n当前使用内置准则。使用 /constitution edit 创建引导式长期偏好,或使用 /constitution bundled 明确记录内置/默认。", |
| 905 | path.display() |
| 906 | ), |
| 907 | _ => format!( |
| 908 | "No structured user-global constitution found at {}.\n\nBundled law applies. Use /constitution edit to create guided standing preferences, or /constitution bundled to record bundled/default explicitly.", |
| 909 | path.display() |
| 910 | ), |
| 911 | } |
| 912 | } |
| 913 | |
| 914 | fn empty_preview_text(locale: Locale, path: &std::path::Path) -> String { |
| 915 | match locale { |
| 916 | Locale::ZhHans => format!( |
| 917 | "{} 的结构化用户全局宪章为空。使用 /constitution repair 返回引导式宪章步骤。", |
| 918 | path.display() |
| 919 | ), |
| 920 | _ => format!( |
| 921 | "The structured user-global constitution at {} is empty. Use /constitution repair to return to the guided constitution step.", |
| 922 | path.display() |
| 923 | ), |
| 924 | } |
| 925 | } |
| 926 | |
| 927 | fn invalid_preview_text(locale: Locale, path: &std::path::Path, error: &str) -> String { |
| 928 | match locale { |
| 929 | Locale::ZhHans => format!( |
| 930 | "{} 的结构化用户全局宪章无效,且不会注入。\n\n{error}\n\n使用 /constitution repair 返回引导式宪章步骤。", |
| 931 | path.display() |
| 932 | ), |
| 933 | _ => format!( |
| 934 | "The structured user-global constitution at {} is invalid and is not injected.\n\n{error}\n\nUse /constitution repair to return to the guided constitution step.", |
| 935 | path.display() |
| 936 | ), |
| 937 | } |
| 938 | } |
| 939 | |
| 940 | fn unreadable_preview_text(locale: Locale, path: &std::path::Path, error: &str) -> String { |
| 941 | match locale { |
| 942 | Locale::ZhHans => format!( |
| 943 | "无法读取 {} 的结构化用户全局宪章,且不会注入。\n\n{error}\n\n使用 /constitution repair 返回引导式宪章步骤。", |
| 944 | path.display() |
| 945 | ), |
| 946 | _ => format!( |
| 947 | "The structured user-global constitution at {} could not be read and is not injected.\n\n{error}\n\nUse /constitution repair to return to the guided constitution step.", |
| 948 | path.display() |
| 949 | ), |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | fn path_error_preview_text(locale: Locale, error: &str) -> String { |
| 954 | match locale { |
| 955 | Locale::ZhHans => format!("无法为用户全局宪章解析 CODEWHALE_HOME:\n\n{error}"), |
| 956 | _ => { |
| 957 | format!("Could not resolve CODEWHALE_HOME for the user-global constitution:\n\n{error}") |
| 958 | } |
| 959 | } |
| 960 | } |
| 961 | |
| 962 | struct ConstitutionManagerCopy { |
| 963 | manager_header: &'static str, |
| 964 | active_stack_header: &'static str, |
| 965 | bundled_active: &'static str, |
| 966 | user_global_label: &'static str, |
| 967 | repo_local_label: &'static str, |
| 968 | agents_label: &'static str, |
| 969 | legacy_whale_label: &'static str, |
| 970 | memory_handoff_label: &'static str, |
| 971 | memory_label: &'static str, |
| 972 | handoff_label: &'static str, |
| 973 | user_global_header: &'static str, |
| 974 | choice_label: &'static str, |
| 975 | source_label: &'static str, |
| 976 | file_label: &'static str, |
| 977 | validity_label: &'static str, |
| 978 | language_label: &'static str, |
| 979 | last_preview_label: &'static str, |
| 980 | runtime_posture_label: &'static str, |
| 981 | checkpoint_label: &'static str, |
| 982 | preview_header: &'static str, |
| 983 | preview_action: &'static str, |
| 984 | repo_action: &'static str, |
| 985 | maintenance_header: &'static str, |
| 986 | maintenance_actions: &'static [&'static str], |
| 987 | present: &'static str, |
| 988 | not_present: &'static str, |
| 989 | generated_fallback: &'static str, |
| 990 | whale_ignored: &'static str, |
| 991 | enabled: &'static str, |
| 992 | disabled: &'static str, |
| 993 | not_recorded: &'static str, |
| 994 | not_reviewed: &'static str, |
| 995 | not_completed: &'static str, |
| 996 | } |
| 997 | |
| 998 | impl ConstitutionManagerCopy { |
| 999 | fn for_locale(locale: Locale) -> Self { |
| 1000 | match locale { |
| 1001 | Locale::ZhHans => Self { |
| 1002 | manager_header: "宪章管理器", |
| 1003 | active_stack_header: "生效层级", |
| 1004 | bundled_active: "内置基础准则:始终生效", |
| 1005 | user_global_label: "用户全局宪章", |
| 1006 | repo_local_label: "仓库本地宪章", |
| 1007 | agents_label: "AGENTS/项目说明", |
| 1008 | legacy_whale_label: "旧版 WHALE.md", |
| 1009 | memory_handoff_label: "记忆/交接", |
| 1010 | memory_label: "记忆", |
| 1011 | handoff_label: "交接", |
| 1012 | user_global_header: "用户全局宪章", |
| 1013 | choice_label: "选择", |
| 1014 | source_label: "来源", |
| 1015 | file_label: "文件", |
| 1016 | validity_label: "有效性", |
| 1017 | language_label: "语言", |
| 1018 | last_preview_label: "上次接受的预览", |
| 1019 | runtime_posture_label: "运行时姿态", |
| 1020 | checkpoint_label: "准则检查点代次", |
| 1021 | preview_header: "预览", |
| 1022 | preview_action: "/constitution preview 会在存在时打开精确渲染的用户全局块。", |
| 1023 | repo_action: "/constitution repo 会在存在时显示 .codewhale/constitution.json 本地准则。", |
| 1024 | maintenance_header: "维护", |
| 1025 | maintenance_actions: &[ |
| 1026 | "编辑引导式宪章:/constitution edit", |
| 1027 | "预览渲染后的宪章:/constitution preview", |
| 1028 | "查看下一轮的确切基础提示词:/constitution base", |
| 1029 | "审阅待批准的建议条款:/constitution suggestions", |
| 1030 | "批准某条建议条款:/constitution ratify <id>", |
| 1031 | "迁移到当前架构版本:/constitution migrate", |
| 1032 | "使用内置/默认:/constitution bundled", |
| 1033 | "查看现有内容:/constitution review", |
| 1034 | "修复无效/空/不可读文件:/constitution repair", |
| 1035 | "显示仓库本地准则:/constitution repo", |
| 1036 | "解释 AGENTS.md 与宪章:/constitution explain", |
| 1037 | "打开运行时姿态:/constitution posture", |
| 1038 | ], |
| 1039 | present: "存在", |
| 1040 | not_present: "不存在", |
| 1041 | generated_fallback: "生成的后备内容", |
| 1042 | whale_ignored: "已忽略;需要迁移", |
| 1043 | enabled: "启用", |
| 1044 | disabled: "停用", |
| 1045 | not_recorded: "未记录", |
| 1046 | not_reviewed: "未查看", |
| 1047 | not_completed: "未完成", |
| 1048 | }, |
| 1049 | _ => Self { |
| 1050 | manager_header: "Constitution Manager", |
| 1051 | active_stack_header: "Active stack", |
| 1052 | bundled_active: "Bundled Constitution: active base law (always on)", |
| 1053 | user_global_label: "User-global constitution", |
| 1054 | repo_local_label: "Repo-local constitution", |
| 1055 | agents_label: "AGENTS/project instructions", |
| 1056 | legacy_whale_label: "Legacy WHALE.md", |
| 1057 | memory_handoff_label: "Memory/handoff", |
| 1058 | memory_label: "memory", |
| 1059 | handoff_label: "handoff", |
| 1060 | user_global_header: "User-global constitution", |
| 1061 | choice_label: "Choice", |
| 1062 | source_label: "Source", |
| 1063 | file_label: "File", |
| 1064 | validity_label: "Validity", |
| 1065 | language_label: "Language", |
| 1066 | last_preview_label: "Last accepted preview", |
| 1067 | runtime_posture_label: "Runtime posture", |
| 1068 | checkpoint_label: "Constitution checkpoint generation", |
| 1069 | preview_header: "Preview", |
| 1070 | preview_action: "/constitution preview opens the exact rendered user-global block when present.", |
| 1071 | repo_action: "/constitution repo shows .codewhale/constitution.json local law when present.", |
| 1072 | maintenance_header: "Maintenance", |
| 1073 | maintenance_actions: &[ |
| 1074 | "Edit guided constitution: /constitution edit", |
| 1075 | "Preview rendered constitution: /constitution preview", |
| 1076 | "Show the next turn's exact base prompt: /constitution base", |
| 1077 | "Review suggested clauses: /constitution suggestions", |
| 1078 | "Ratify a suggested clause: /constitution ratify <id>", |
| 1079 | "Migrate to the current schema: /constitution migrate", |
| 1080 | "Use bundled/default: /constitution bundled", |
| 1081 | "Review existing: /constitution review", |
| 1082 | "Repair invalid/empty/unreadable: /constitution repair", |
| 1083 | "Show repo-local law: /constitution repo", |
| 1084 | "Explain AGENTS.md vs constitution: /constitution explain", |
| 1085 | "Open runtime posture: /constitution posture", |
| 1086 | ], |
| 1087 | present: "present", |
| 1088 | not_present: "not present", |
| 1089 | generated_fallback: "generated fallback", |
| 1090 | whale_ignored: "ignored; migration needed", |
| 1091 | enabled: "enabled", |
| 1092 | disabled: "disabled", |
| 1093 | not_recorded: "not recorded", |
| 1094 | not_reviewed: "not reviewed", |
| 1095 | not_completed: "not completed", |
| 1096 | }, |
| 1097 | } |
| 1098 | } |
| 1099 | |
| 1100 | fn location_count_unit(&self, count: usize) -> &'static str { |
| 1101 | if self.manager_header == "宪章管理器" { |
| 1102 | "处" |
| 1103 | } else if count == 1 { |
| 1104 | "location" |
| 1105 | } else { |
| 1106 | "locations" |
| 1107 | } |
| 1108 | } |
| 1109 | |
| 1110 | fn completed_for(&self, version: &str) -> String { |
| 1111 | if self.manager_header == "宪章管理器" { |
| 1112 | format!("当前(自 {version} 引入)") |
| 1113 | } else { |
| 1114 | format!("current (introduced in {version})") |
| 1115 | } |
| 1116 | } |
| 1117 | } |
| 1118 | |
| 1119 | #[cfg(test)] |
| 1120 | mod tests { |
| 1121 | use super::*; |
| 1122 | use crate::tui::app::{App, AppAction, TuiOptions}; |
| 1123 | use crate::tui::pager::PagerView; |
| 1124 | use crate::tui::views::ModalKind; |
| 1125 | use codewhale_config::SetupStep; |
| 1126 | use codewhale_runtime::config::Config; |
| 1127 | use std::path::PathBuf; |
| 1128 | use tempfile::tempdir; |
| 1129 | |
| 1130 | fn test_app() -> App { |
| 1131 | test_app_with_workspace(PathBuf::from(".")) |
| 1132 | } |
| 1133 | |
| 1134 | fn test_app_with_workspace(workspace: PathBuf) -> App { |
| 1135 | let options = TuiOptions { |
| 1136 | ..crate::tui::test_support::test_tui_options(workspace) |
| 1137 | }; |
| 1138 | App::new(options, &Config::default()) |
| 1139 | } |
| 1140 | |
| 1141 | fn pop_pager_body(app: &mut App) -> String { |
| 1142 | let mut view = app.view_stack.pop().expect("pager view"); |
| 1143 | let pager = view |
| 1144 | .as_any_mut() |
| 1145 | .downcast_mut::<PagerView>() |
| 1146 | .expect("top view should be pager"); |
| 1147 | pager.body_text() |
| 1148 | } |
| 1149 | |
| 1150 | #[test] |
| 1151 | fn constitution_default_opens_manager_pager() { |
| 1152 | let mut app = test_app(); |
| 1153 | app.ui_locale = Locale::En; |
| 1154 | |
| 1155 | let result = crate::commands::execute("/constitution", &mut app); |
| 1156 | assert_eq!( |
| 1157 | result.action, |
| 1158 | Some(AppAction::OpenConstitutionManager { review: false }) |
| 1159 | ); |
| 1160 | assert!(result.message.is_none()); |
| 1161 | open_manager(&mut app, false, Ok(false)); |
| 1162 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::Pager)); |
| 1163 | assert!(pop_pager_body(&mut app).contains("Constitution Manager")); |
| 1164 | } |
| 1165 | |
| 1166 | #[test] |
| 1167 | fn constitution_manager_marks_whale_md_ignored() { |
| 1168 | let tmp = tempdir().expect("tempdir"); |
| 1169 | std::fs::write(tmp.path().join("WHALE.md"), "legacy instructions").expect("write whale"); |
| 1170 | let mut app = test_app_with_workspace(tmp.path().to_path_buf()); |
| 1171 | app.ui_locale = Locale::En; |
| 1172 | |
| 1173 | open_manager(&mut app, false, Ok(false)); |
| 1174 | let body = pop_pager_body(&mut app); |
| 1175 | assert!(body.contains("Legacy WHALE.md: ignored")); |
| 1176 | assert!(body.contains("WHALE.md is ignored")); |
| 1177 | assert!(!body.contains("legacy instructions")); |
| 1178 | } |
| 1179 | |
| 1180 | #[test] |
| 1181 | fn constitution_bundled_emits_action() { |
| 1182 | let mut app = test_app(); |
| 1183 | |
| 1184 | let result = crate::commands::execute("/constitution bundled", &mut app); |
| 1185 | |
| 1186 | assert_eq!(result.action, Some(AppAction::UseBundledConstitution)); |
| 1187 | } |
| 1188 | |
| 1189 | #[test] |
| 1190 | fn constitution_edit_opens_setup_at_constitution() { |
| 1191 | let mut app = test_app(); |
| 1192 | |
| 1193 | let result = crate::commands::execute("/constitution edit", &mut app); |
| 1194 | |
| 1195 | assert_eq!( |
| 1196 | result.action, |
| 1197 | Some(AppAction::OpenSetupWizardAt { |
| 1198 | step: SetupStep::Constitution |
| 1199 | }) |
| 1200 | ); |
| 1201 | } |
| 1202 | |
| 1203 | #[test] |
| 1204 | fn constitution_help_lists_repair_and_runtime_boundary() { |
| 1205 | let mut app = test_app(); |
| 1206 | app.ui_locale = Locale::En; |
| 1207 | |
| 1208 | let result = crate::commands::execute("/constitution help", &mut app); |
| 1209 | |
| 1210 | let message = result.message.expect("help message"); |
| 1211 | assert!(message.contains("Usage: /constitution")); |
| 1212 | assert!(message.contains("/constitution repair")); |
| 1213 | assert!(message.contains("/constitution posture")); |
| 1214 | assert!(message.contains("model guidance only")); |
| 1215 | assert!(message.contains("does not change approvals")); |
| 1216 | } |
| 1217 | |
| 1218 | #[test] |
| 1219 | fn constitution_repair_explains_invalid_file_and_opens_setup() { |
| 1220 | let _env_guard = crate::test_support::lock_test_env(); |
| 1221 | let tmp = tempdir().expect("tempdir"); |
| 1222 | let home = tmp.path().join("codewhale-home"); |
| 1223 | std::fs::create_dir_all(&home).expect("home"); |
| 1224 | std::fs::write(home.join("constitution.json"), "{not valid json").expect("invalid file"); |
| 1225 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 1226 | let mut app = test_app(); |
| 1227 | app.ui_locale = Locale::En; |
| 1228 | |
| 1229 | let result = crate::commands::execute("/constitution repair", &mut app); |
| 1230 | |
| 1231 | assert_eq!( |
| 1232 | result.action, |
| 1233 | Some(AppAction::OpenSetupWizardAt { |
| 1234 | step: SetupStep::Constitution |
| 1235 | }) |
| 1236 | ); |
| 1237 | let message = result.message.expect("repair message"); |
| 1238 | assert!(message.contains("User-global constitution repair")); |
| 1239 | assert!(message.contains("Current state: invalid; repair recommended")); |
| 1240 | assert!(message.contains("Validity: invalid")); |
| 1241 | assert!(message.contains("constitution.json")); |
| 1242 | assert!(message.contains("will not be injected")); |
| 1243 | assert!(message.contains("Runtime approval")); |
| 1244 | } |
| 1245 | |
| 1246 | #[test] |
| 1247 | fn constitution_preview_renders_structured_block() { |
| 1248 | let _env_guard = crate::test_support::lock_test_env(); |
| 1249 | let tmp = tempdir().expect("tempdir"); |
| 1250 | let home = tmp.path().join("codewhale-home"); |
| 1251 | std::fs::create_dir_all(&home).expect("home"); |
| 1252 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 1253 | let constitution = UserConstitution { |
| 1254 | about: Some("Maintains release lanes.".to_string()), |
| 1255 | ..UserConstitution::default() |
| 1256 | }; |
| 1257 | constitution.save().expect("save constitution"); |
| 1258 | let mut app = test_app(); |
| 1259 | |
| 1260 | let result = crate::commands::execute("/constitution preview", &mut app); |
| 1261 | |
| 1262 | assert!(result.message.is_none()); |
| 1263 | let body = pop_pager_body(&mut app); |
| 1264 | assert!(body.contains("<codewhale_user_constitution")); |
| 1265 | assert!(body.contains("Maintains release lanes.")); |
| 1266 | } |
| 1267 | |
| 1268 | /// Seal `CODEWHALE_HOME` to a temp dir and write a constitution there. |
| 1269 | fn sealed_home( |
| 1270 | tmp: &tempfile::TempDir, |
| 1271 | constitution: &UserConstitution, |
| 1272 | ) -> crate::test_support::EnvVarGuard { |
| 1273 | let home = tmp.path().join("codewhale-home"); |
| 1274 | std::fs::create_dir_all(&home).expect("home"); |
| 1275 | let guard = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 1276 | constitution |
| 1277 | .save_to(&home.join("constitution.json")) |
| 1278 | .expect("save constitution"); |
| 1279 | guard |
| 1280 | } |
| 1281 | |
| 1282 | fn with_suggestion() -> UserConstitution { |
| 1283 | UserConstitution { |
| 1284 | about: Some("Maintains release lanes.".to_string()), |
| 1285 | ..UserConstitution::default() |
| 1286 | } |
| 1287 | .with_recommendation(&codewhale_config::ConstitutionRecommendation { |
| 1288 | clauses: vec![codewhale_config::ConstitutionClause::suggested( |
| 1289 | "c1", |
| 1290 | "Always run the focused suite before claiming green.", |
| 1291 | )], |
| 1292 | rationale: Vec::new(), |
| 1293 | }) |
| 1294 | } |
| 1295 | |
| 1296 | #[test] |
| 1297 | fn constitution_base_previews_the_exact_next_turn_prompt() { |
| 1298 | let mut app = test_app(); |
| 1299 | |
| 1300 | let result = crate::commands::execute("/constitution base", &mut app); |
| 1301 | |
| 1302 | // Routed as an action so the preview is assembled by the same function |
| 1303 | // the dispatch path uses, with the session config in hand. |
| 1304 | assert_eq!(result.action, Some(AppAction::PreviewEffectiveBasePrompt)); |
| 1305 | assert!(result.message.is_none()); |
| 1306 | } |
| 1307 | |
| 1308 | #[test] |
| 1309 | fn suggestions_are_listed_but_never_previewed_as_law() { |
| 1310 | let _env_guard = crate::test_support::lock_test_env(); |
| 1311 | let tmp = tempdir().expect("tempdir"); |
| 1312 | let _home = sealed_home(&tmp, &with_suggestion()); |
| 1313 | let mut app = test_app(); |
| 1314 | app.ui_locale = Locale::En; |
| 1315 | |
| 1316 | crate::commands::execute("/constitution suggestions", &mut app); |
| 1317 | let suggestions = pop_pager_body(&mut app); |
| 1318 | assert!(suggestions.contains("[c1]")); |
| 1319 | assert!(suggestions.contains("focused suite")); |
| 1320 | assert!(suggestions.contains("Ratified clauses in force: 0")); |
| 1321 | |
| 1322 | // The same clause must be absent from the injected preview. |
| 1323 | crate::commands::execute("/constitution preview", &mut app); |
| 1324 | let preview = pop_pager_body(&mut app); |
| 1325 | assert!(preview.contains("<codewhale_user_constitution")); |
| 1326 | assert!( |
| 1327 | !preview.contains("focused suite"), |
| 1328 | "unratified advice reached the model-facing block: {preview}" |
| 1329 | ); |
| 1330 | } |
| 1331 | |
| 1332 | #[test] |
| 1333 | fn ratify_requires_an_id_and_then_makes_the_clause_law() { |
| 1334 | let _env_guard = crate::test_support::lock_test_env(); |
| 1335 | let tmp = tempdir().expect("tempdir"); |
| 1336 | let _home = sealed_home(&tmp, &with_suggestion()); |
| 1337 | let mut app = test_app(); |
| 1338 | app.ui_locale = Locale::En; |
| 1339 | |
| 1340 | let bare = crate::commands::execute("/constitution ratify", &mut app) |
| 1341 | .message |
| 1342 | .expect("usage message"); |
| 1343 | assert!(bare.contains("Usage: /constitution ratify <id>")); |
| 1344 | |
| 1345 | let unreviewed = crate::commands::execute("/constitution ratify c1", &mut app) |
| 1346 | .message |
| 1347 | .expect("refusal message"); |
| 1348 | assert!(unreviewed.contains("Nothing was ratified"), "{unreviewed}"); |
| 1349 | |
| 1350 | crate::commands::execute("/constitution suggestions", &mut app); |
| 1351 | pop_pager_body(&mut app); |
| 1352 | |
| 1353 | let unknown = crate::commands::execute("/constitution ratify nope", &mut app) |
| 1354 | .message |
| 1355 | .expect("refusal message"); |
| 1356 | assert!(unknown.contains("Nothing was ratified")); |
| 1357 | |
| 1358 | let ok = crate::commands::execute("/constitution ratify c1", &mut app) |
| 1359 | .message |
| 1360 | .expect("ratified message"); |
| 1361 | assert!(ok.contains("Ratified 1 clause(s): c1"), "{ok}"); |
| 1362 | assert!(ok.contains("Digest"), "{ok}"); |
| 1363 | |
| 1364 | // Now — and only now — it appears in the injected block. |
| 1365 | crate::commands::execute("/constitution preview", &mut app); |
| 1366 | assert!(pop_pager_body(&mut app).contains("focused suite")); |
| 1367 | } |
| 1368 | |
| 1369 | #[test] |
| 1370 | fn migrate_reports_a_receipt_and_rollback_restores() { |
| 1371 | let _env_guard = crate::test_support::lock_test_env(); |
| 1372 | let tmp = tempdir().expect("tempdir"); |
| 1373 | let home = tmp.path().join("codewhale-home"); |
| 1374 | std::fs::create_dir_all(&home).expect("home"); |
| 1375 | let _home_guard = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 1376 | let path = home.join("constitution.json"); |
| 1377 | let v1 = r#"{"schema_version":1,"about":"Legacy user."}"#; |
| 1378 | std::fs::write(&path, v1).expect("write v1"); |
| 1379 | let mut app = test_app(); |
| 1380 | app.ui_locale = Locale::En; |
| 1381 | |
| 1382 | let message = crate::commands::execute("/constitution migrate", &mut app) |
| 1383 | .message |
| 1384 | .expect("migrate receipt"); |
| 1385 | assert!(message.contains("Migrated schema v1"), "{message}"); |
| 1386 | assert!( |
| 1387 | message.contains("Preserved unknown fields: none"), |
| 1388 | "{message}" |
| 1389 | ); |
| 1390 | assert!( |
| 1391 | message.contains("the model receives the same text"), |
| 1392 | "a v1 file carries no clauses, so no model-facing byte moved: {message}" |
| 1393 | ); |
| 1394 | |
| 1395 | let rolled = crate::commands::execute("/constitution rollback", &mut app) |
| 1396 | .message |
| 1397 | .expect("rollback receipt"); |
| 1398 | assert!(rolled.contains("Restored the pre-migration constitution")); |
| 1399 | assert_eq!(std::fs::read_to_string(&path).expect("read back"), v1); |
| 1400 | } |
| 1401 | |
| 1402 | #[test] |
| 1403 | fn migrate_rejects_a_runtime_policy_key_and_changes_nothing() { |
| 1404 | let _env_guard = crate::test_support::lock_test_env(); |
| 1405 | let tmp = tempdir().expect("tempdir"); |
| 1406 | let home = tmp.path().join("codewhale-home"); |
| 1407 | std::fs::create_dir_all(&home).expect("home"); |
| 1408 | let _home_guard = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 1409 | let path = home.join("constitution.json"); |
| 1410 | let raw = r#"{"about":"x","approval_policy":"bypass"}"#; |
| 1411 | std::fs::write(&path, raw).expect("write file"); |
| 1412 | let mut app = test_app(); |
| 1413 | app.ui_locale = Locale::En; |
| 1414 | |
| 1415 | let message = crate::commands::execute("/constitution migrate", &mut app) |
| 1416 | .message |
| 1417 | .expect("rejection receipt"); |
| 1418 | assert!(message.contains("Not migrated"), "{message}"); |
| 1419 | assert!(message.contains("approval_policy"), "{message}"); |
| 1420 | assert_eq!(std::fs::read_to_string(&path).expect("read back"), raw); |
| 1421 | } |
| 1422 | |
| 1423 | #[test] |
| 1424 | fn help_and_manager_name_the_new_inspection_surfaces() { |
| 1425 | let mut app = test_app(); |
| 1426 | app.ui_locale = Locale::En; |
| 1427 | |
| 1428 | let help = crate::commands::execute("/constitution help", &mut app) |
| 1429 | .message |
| 1430 | .expect("help message"); |
| 1431 | assert!(help.contains("/constitution base")); |
| 1432 | assert!(help.contains("no provider request")); |
| 1433 | assert!(help.contains("/constitution ratify <id>")); |
| 1434 | assert!(help.contains("Refused if the base changed")); |
| 1435 | assert!(help.contains("/constitution migrate")); |
| 1436 | |
| 1437 | open_manager(&mut app, false, Ok(false)); |
| 1438 | let body = pop_pager_body(&mut app); |
| 1439 | assert!(body.contains("/constitution base")); |
| 1440 | assert!(body.contains("/constitution suggestions")); |
| 1441 | } |
| 1442 | |
| 1443 | #[test] |
| 1444 | fn constitution_manager_uses_zh_hans_copy() { |
| 1445 | let _env_guard = crate::test_support::lock_test_env(); |
| 1446 | let tmp = tempdir().expect("tempdir"); |
| 1447 | let home = tmp.path().join("codewhale-home"); |
| 1448 | std::fs::create_dir_all(&home).expect("home"); |
| 1449 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 1450 | let mut app = test_app(); |
| 1451 | app.ui_locale = codewhale_localization::Locale::ZhHans; |
| 1452 | |
| 1453 | open_manager(&mut app, false, Ok(false)); |
| 1454 | let body = pop_pager_body(&mut app); |
| 1455 | assert!(body.contains("宪章管理器")); |
| 1456 | assert!(body.contains("生效层级")); |
| 1457 | assert!(body.contains("用户全局宪章")); |
| 1458 | assert!(body.contains("/constitution preview 会")); |
| 1459 | assert!(!body.contains("宪法")); |
| 1460 | assert!(!body.contains("Constitution Manager")); |
| 1461 | } |
| 1462 | |
| 1463 | #[test] |
| 1464 | fn constitution_preview_missing_uses_zh_hans_copy() { |
| 1465 | let _env_guard = crate::test_support::lock_test_env(); |
| 1466 | let tmp = tempdir().expect("tempdir"); |
| 1467 | let home = tmp.path().join("codewhale-home"); |
| 1468 | std::fs::create_dir_all(&home).expect("home"); |
| 1469 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 1470 | let mut app = test_app(); |
| 1471 | app.ui_locale = codewhale_localization::Locale::ZhHans; |
| 1472 | |
| 1473 | let result = crate::commands::execute("/constitution preview", &mut app); |
| 1474 | |
| 1475 | assert!(result.message.is_none()); |
| 1476 | let body = pop_pager_body(&mut app); |
| 1477 | assert!(body.contains("未在")); |
| 1478 | assert!(body.contains("当前使用内置准则")); |
| 1479 | assert!(body.contains("/constitution edit")); |
| 1480 | assert!(!body.contains("宪法")); |
| 1481 | assert!(!body.contains("No structured user-global constitution")); |
| 1482 | } |
| 1483 | |
| 1484 | #[test] |
| 1485 | fn constitution_explanation_uses_zh_hans_copy() { |
| 1486 | let mut app = test_app(); |
| 1487 | app.ui_locale = codewhale_localization::Locale::ZhHans; |
| 1488 | |
| 1489 | let result = crate::commands::execute("/constitution explain", &mut app); |
| 1490 | |
| 1491 | assert!(result.message.is_none()); |
| 1492 | let body = pop_pager_body(&mut app); |
| 1493 | assert!(body.contains("AGENTS.md 与宪章")); |
| 1494 | assert!(body.contains(".codewhale/constitution.json")); |
| 1495 | assert!(body.contains("运行时姿态是独立设置")); |
| 1496 | assert!(!body.contains("宪法")); |
| 1497 | assert!(!body.contains("项目法律")); |
| 1498 | assert!(!body.contains("Runtime posture is separate")); |
| 1499 | } |
| 1500 | } |
| 1501 |