| 1 | use codewhale_command_contract::constitution::{ConstitutionAction, ConstitutionLocale}; |
| 2 | use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts, CommandHandler}; |
| 3 | use codewhale_command_contract::metadata::{CommandInfo, RegisterCommand}; |
| 4 | use codewhale_command_contract::model_setup::resolve_action; |
| 5 | use codewhale_command_contract::outcome::CommandResult; |
| 6 | |
| 7 | const COMMAND_INFO: CommandInfo = CommandInfo { |
| 8 | name: "constitution", |
| 9 | aliases: &["law"], |
| 10 | usage: "/constitution [status|preview|base|suggestions|ratify <id>|migrate|rollback|bundled|edit|review|repair|repo|explain|posture|help]", |
| 11 | description_key: "cmd_constitution_description", |
| 12 | }; |
| 13 | |
| 14 | pub struct ConstitutionCmd; |
| 15 | |
| 16 | impl<A: TryFrom<ConstitutionAction>> RegisterCommand<CommandResult<A>> for ConstitutionCmd |
| 17 | where |
| 18 | A::Error: std::fmt::Display, |
| 19 | { |
| 20 | fn info() -> &'static CommandInfo { |
| 21 | &COMMAND_INFO |
| 22 | } |
| 23 | |
| 24 | fn handler() -> CommandHandler<CommandResult<A>> { |
| 25 | CommandHandler::Contextual { |
| 26 | capabilities: CommandCapabilities::CONSTITUTION, |
| 27 | handler: constitution, |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | fn constitution<A: TryFrom<ConstitutionAction>>( |
| 33 | mut contexts: CommandContexts<'_>, |
| 34 | arg: Option<&str>, |
| 35 | ) -> CommandResult<A> |
| 36 | where |
| 37 | A::Error: std::fmt::Display, |
| 38 | { |
| 39 | let target = arg.map(str::trim).filter(|arg| !arg.is_empty()); |
| 40 | match target { |
| 41 | None | Some("status" | "home" | "manager") => { |
| 42 | return resolve_action(ConstitutionAction::OpenManager { review: false }, None); |
| 43 | } |
| 44 | Some("review" | "existing") => { |
| 45 | return resolve_action(ConstitutionAction::OpenManager { review: true }, None); |
| 46 | } |
| 47 | Some("edit" | "guided" | "custom") => { |
| 48 | return resolve_action(ConstitutionAction::OpenSetupConstitution, None); |
| 49 | } |
| 50 | Some("posture" | "runtime-posture") => { |
| 51 | return resolve_action(ConstitutionAction::OpenSetupPosture, None); |
| 52 | } |
| 53 | Some("bundled" | "default" | "use-bundled" | "use-default") => { |
| 54 | return resolve_action(ConstitutionAction::UseBundled, None); |
| 55 | } |
| 56 | Some("base" | "prompt" | "base-prompt" | "effective") => { |
| 57 | return resolve_action(ConstitutionAction::PreviewEffectiveBasePrompt, None); |
| 58 | } |
| 59 | _ => {} |
| 60 | } |
| 61 | |
| 62 | let Some(ctx) = contexts.take_constitution() else { |
| 63 | return CommandResult::error("Command capability unavailable: constitution"); |
| 64 | }; |
| 65 | |
| 66 | match target { |
| 67 | Some("preview") => { |
| 68 | let locale = ctx.locale(); |
| 69 | let text = format!("{}\n\n{}", preview_preamble(locale), ctx.preview_text()); |
| 70 | ctx.open_pager(rendered_title(locale), &text); |
| 71 | CommandResult::ok() |
| 72 | } |
| 73 | Some("repo" | "repo-local" | "law") => { |
| 74 | let locale = ctx.locale(); |
| 75 | let text = ctx |
| 76 | .repo_constitution_block() |
| 77 | .unwrap_or_else(|| no_repo_law_text(locale).to_string()); |
| 78 | ctx.open_pager(repo_title(locale), &text); |
| 79 | CommandResult::ok() |
| 80 | } |
| 81 | Some("explain" | "agents") => { |
| 82 | let locale = ctx.locale(); |
| 83 | ctx.open_pager(explanation_title(locale), agents_explanation(locale)); |
| 84 | CommandResult::ok() |
| 85 | } |
| 86 | Some("repair" | "fix") => { |
| 87 | let message = ctx.repair_text(); |
| 88 | resolve_action(ConstitutionAction::OpenSetupConstitution, Some(message)) |
| 89 | } |
| 90 | Some("suggestions" | "proposed") => { |
| 91 | let locale = ctx.locale(); |
| 92 | ctx.show_pending_suggestions(suggestions_title(locale)); |
| 93 | CommandResult::ok() |
| 94 | } |
| 95 | Some("migrate") => CommandResult::message(ctx.migrate()), |
| 96 | Some("rollback" | "undo-migrate") => CommandResult::message(ctx.rollback()), |
| 97 | Some(rest) if rest.starts_with("ratify") => { |
| 98 | let ids: Vec<&str> = rest |
| 99 | .trim_start_matches("ratify") |
| 100 | .split_whitespace() |
| 101 | .collect(); |
| 102 | CommandResult::message(ctx.ratify_clauses(&ids)) |
| 103 | } |
| 104 | Some("help") => CommandResult::message(help_text(ctx.locale())), |
| 105 | Some(other) => CommandResult::error(format!( |
| 106 | "Unknown /constitution target '{other}'. Try `/constitution` for the manager." |
| 107 | )), |
| 108 | None => unreachable!(), |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | fn preview_preamble(locale: ConstitutionLocale) -> &'static str { |
| 113 | match locale { |
| 114 | ConstitutionLocale::ZhHans => { |
| 115 | "这是本机宪章预览。已登录账户的宪章(包括默认值)优先;请在账户设置中预览。" |
| 116 | } |
| 117 | ConstitutionLocale::En => { |
| 118 | "This previews the local constitution. The signed-in profile constitution, including its defaults, takes precedence; preview it in account settings." |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | fn rendered_title(locale: ConstitutionLocale) -> &'static str { |
| 124 | match locale { |
| 125 | ConstitutionLocale::ZhHans => "渲染后的用户宪章", |
| 126 | ConstitutionLocale::En => "Rendered User Constitution", |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | fn repo_title(locale: ConstitutionLocale) -> &'static str { |
| 131 | match locale { |
| 132 | ConstitutionLocale::ZhHans => "仓库本地宪章", |
| 133 | ConstitutionLocale::En => "Repo-Local Constitution", |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | fn explanation_title(locale: ConstitutionLocale) -> &'static str { |
| 138 | match locale { |
| 139 | ConstitutionLocale::ZhHans => "AGENTS.md 与宪章", |
| 140 | ConstitutionLocale::En => "AGENTS.md vs Constitution", |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | fn suggestions_title(locale: ConstitutionLocale) -> &'static str { |
| 145 | match locale { |
| 146 | ConstitutionLocale::ZhHans => "待批准的建议条款", |
| 147 | ConstitutionLocale::En => "Suggested Clauses", |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | fn no_repo_law_text(locale: ConstitutionLocale) -> &'static str { |
| 152 | match locale { |
| 153 | ConstitutionLocale::ZhHans => "此工作区未找到仓库本地宪章 .codewhale/constitution.json。", |
| 154 | ConstitutionLocale::En => { |
| 155 | "No repo-local constitution found at .codewhale/constitution.json for this workspace." |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | fn agents_explanation(locale: ConstitutionLocale) -> &'static str { |
| 161 | match locale { |
| 162 | ConstitutionLocale::ZhHans => { |
| 163 | "\ |
| 164 | AGENTS.md 与宪章 |
| 165 | |
| 166 | 内置基础准则是精简的全局判断约定:身份、事实、验证、克制和优先级顺序。 |
| 167 | |
| 168 | 用户全局宪章是个人长期偏好。它是结构化数据,确定性渲染,并低于当前用户请求和内置基础准则。 |
| 169 | |
| 170 | .codewhale/constitution.json 是仓库本地宪章。它属于某个工作区,并作为独立的仓库宪章块渲染。 |
| 171 | |
| 172 | AGENTS.md 和项目说明是项目规则/实现指导。它们可以描述构建命令、仓库规范和本地流程;按优先级顺序,它们低于当前用户请求和内置基础准则,高于用户全局长期偏好、记忆和交接。 |
| 173 | |
| 174 | WHALE.md 已忽略。将普通项目说明迁移到 AGENTS.md,将 Codewhale 专属权限策略迁移到 .codewhale/constitution.json。 |
| 175 | |
| 176 | 运行时姿态是独立设置。宪章可以建议主动性,但不会改变批准策略、沙盒、Shell、网络、信任、MCP 权限或默认模式。使用 /constitution posture 查看这些控制。" |
| 177 | } |
| 178 | ConstitutionLocale::En => { |
| 179 | "\ |
| 180 | AGENTS.md vs constitution |
| 181 | |
| 182 | The bundled Constitution is the compact global judgment contract: identity, ground truth, verification, restraint, and precedence. |
| 183 | |
| 184 | The user-global constitution is personal standing preference law. It is structured, rendered deterministically, and subordinate to the current user request and the bundled Constitution. |
| 185 | |
| 186 | .codewhale/constitution.json is repo-local law. It belongs to a workspace and is rendered as a separate repo constitution block. |
| 187 | |
| 188 | AGENTS.md and project instructions are project law / implementation guidance. They can describe build commands, repository norms, and local workflows. Under “Whose word wins,” they sit below the current user request and bundled Constitution, and above user-global standing preferences, memory, and handoff. |
| 189 | |
| 190 | WHALE.md is ignored. Move ordinary project instructions to AGENTS.md and Codewhale-specific authority policy to .codewhale/constitution.json. |
| 191 | |
| 192 | Runtime posture is separate. A constitution can recommend autonomy, but it does not change approval policy, sandbox, shell, network, trust, MCP permissions, or default mode. Use /constitution posture to review those controls." |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | fn help_text(locale: ConstitutionLocale) -> String { |
| 198 | match locale { |
| 199 | ConstitutionLocale::ZhHans => "\ |
| 200 | 用法:/constitution [status|preview|base|suggestions|ratify <id>|migrate|rollback|bundled|edit|review|repair|repo|explain|posture|help] |
| 201 | |
| 202 | 常用命令: |
| 203 | - /constitution:打开宪章管理器和当前层级。 |
| 204 | - /constitution preview:显示会注入模型的确切用户全局宪章块;缺失、空、无效或不可读时显示修复说明。 |
| 205 | - /constitution edit:打开 /setup 的引导式宪章步骤;用 1-6 调整,按 G 预览,再按 G 保存。 |
| 206 | - /constitution repair:说明当前文件状态,然后打开同一个引导式修复步骤。 |
| 207 | - /constitution bundled:记录使用内置/默认准则,不创建自定义文件。 |
| 208 | - /constitution repo:查看 .codewhale/constitution.json 仓库本地准则。 |
| 209 | - /constitution explain:解释内置基础准则、用户全局宪章、仓库宪章、AGENTS.md、记忆和交接的区别。 |
| 210 | - /constitution base:显示下一轮实际组装的确切基础提示词,附来源、摘要和字节/词元度量;只读,不发送请求,也不展开工具目录。 |
| 211 | - /constitution suggestions:查看待批准的建议条款;它们不会注入模型,也不影响提示词缓存。 |
| 212 | - /constitution ratify <id>:明确批准某条建议条款;若基线在审阅后发生变化则拒绝批准。 |
| 213 | - /constitution migrate:把宪章文件迁移到当前架构版本并给出回执;被拒绝时文件保持原样。 |
| 214 | - /constitution rollback:恢复迁移前的备份。 |
| 215 | - /constitution posture:打开运行时姿态;宪章只提供模型指导,不会更改批准、沙盒、Shell、网络、信任或 MCP 权限。", |
| 216 | ConstitutionLocale::En => "\ |
| 217 | Usage: /constitution [status|preview|base|suggestions|ratify <id>|migrate|rollback|bundled|edit|review|repair|repo|explain|posture|help] |
| 218 | |
| 219 | Common commands: |
| 220 | - /constitution: open the constitution manager and active stack. |
| 221 | - /constitution preview: show the exact user-global constitution block that would be injected; missing, empty, invalid, or unreadable files show repair guidance instead. |
| 222 | - /constitution edit: open the guided /setup Constitution step; tune 1-6, press G to preview, then G again to save. |
| 223 | - /constitution repair: explain the current file state, then open the same guided repair step. |
| 224 | - /constitution bundled: record bundled/default law without creating a custom file. |
| 225 | - /constitution repo: inspect repo-local .codewhale/constitution.json law. |
| 226 | - /constitution explain: compare Constitution, user-global law, repo law, AGENTS.md, memory, and handoff. |
| 227 | - /constitution base: show the exact effective base prompt assembled for the next turn, with per-block provenance, digests, and byte/token measures. Read-only: no provider request, no tool-catalog expansion. |
| 228 | - /constitution suggestions: review suggested clauses awaiting ratification; they are not injected and do not move the prompt-cache digest. |
| 229 | - /constitution ratify <id>: explicitly ratify a suggested clause. Refused if the base changed after you reviewed it. |
| 230 | - /constitution migrate: migrate the constitution file to the current schema with a receipt; a rejected file is left exactly as it was. |
| 231 | - /constitution rollback: restore the pre-migration backup. |
| 232 | - /constitution posture: open runtime posture; constitution text is model guidance only and does not change approvals, sandbox, shell, network, trust, or MCP permissions.", |
| 233 | } |
| 234 | .to_string() |
| 235 | } |
| 236 | |
| 237 | #[cfg(test)] |
| 238 | mod tests { |
| 239 | use super::*; |
| 240 | use codewhale_command_contract::constitution::CommandConstitutionContext; |
| 241 | |
| 242 | struct MockConstitutionContext { |
| 243 | locale: ConstitutionLocale, |
| 244 | pagers: Vec<(String, String)>, |
| 245 | reviewed_digest: Option<String>, |
| 246 | ratified_ids: Vec<String>, |
| 247 | } |
| 248 | |
| 249 | impl Default for MockConstitutionContext { |
| 250 | fn default() -> Self { |
| 251 | Self { |
| 252 | locale: ConstitutionLocale::En, |
| 253 | pagers: Vec::new(), |
| 254 | reviewed_digest: None, |
| 255 | ratified_ids: Vec::new(), |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | impl CommandConstitutionContext for MockConstitutionContext { |
| 261 | fn locale(&self) -> ConstitutionLocale { |
| 262 | self.locale |
| 263 | } |
| 264 | fn open_pager(&mut self, title: &str, body: &str) { |
| 265 | self.pagers.push((title.to_string(), body.to_string())); |
| 266 | } |
| 267 | fn preview_text(&self) -> String { |
| 268 | "<codewhale_user_constitution/>".to_string() |
| 269 | } |
| 270 | fn repo_constitution_block(&self) -> Option<String> { |
| 271 | None |
| 272 | } |
| 273 | fn show_pending_suggestions(&mut self, title: &str) { |
| 274 | self.reviewed_digest = Some("digest-1".to_string()); |
| 275 | self.pagers.push((title.to_string(), "pending".to_string())); |
| 276 | } |
| 277 | fn ratify_clauses(&mut self, ids: &[&str]) -> String { |
| 278 | self.ratified_ids = ids.iter().map(|s| (*s).to_string()).collect(); |
| 279 | format!("ratified:{}", ids.join(",")) |
| 280 | } |
| 281 | fn migrate(&self) -> String { |
| 282 | "migrated".to_string() |
| 283 | } |
| 284 | fn rollback(&self) -> String { |
| 285 | "rolled back".to_string() |
| 286 | } |
| 287 | fn repair_text(&self) -> String { |
| 288 | "repair guidance".to_string() |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | fn run( |
| 293 | ctx: &mut MockConstitutionContext, |
| 294 | arg: Option<&str>, |
| 295 | ) -> CommandResult<ConstitutionAction> { |
| 296 | let CommandHandler::Contextual { |
| 297 | capabilities, |
| 298 | handler, |
| 299 | } = ConstitutionCmd::handler() |
| 300 | else { |
| 301 | panic!("expected contextual handler"); |
| 302 | }; |
| 303 | assert_eq!(capabilities, CommandCapabilities::CONSTITUTION); |
| 304 | let contexts = CommandContexts::empty().with_constitution(ctx); |
| 305 | handler(contexts, arg) |
| 306 | } |
| 307 | |
| 308 | #[test] |
| 309 | fn action_subcommands_dispatch_without_host_context() { |
| 310 | let CommandHandler::Contextual { handler, .. } = ConstitutionCmd::handler() else { |
| 311 | panic!("expected contextual handler"); |
| 312 | }; |
| 313 | let res: CommandResult<ConstitutionAction> = handler(CommandContexts::empty(), None); |
| 314 | assert_eq!( |
| 315 | res.action, |
| 316 | Some(ConstitutionAction::OpenManager { review: false }) |
| 317 | ); |
| 318 | let res: CommandResult<ConstitutionAction> = |
| 319 | handler(CommandContexts::empty(), Some("bundled")); |
| 320 | assert_eq!(res.action, Some(ConstitutionAction::UseBundled)); |
| 321 | let res: CommandResult<ConstitutionAction> = |
| 322 | handler(CommandContexts::empty(), Some("base")); |
| 323 | assert_eq!( |
| 324 | res.action, |
| 325 | Some(ConstitutionAction::PreviewEffectiveBasePrompt) |
| 326 | ); |
| 327 | } |
| 328 | |
| 329 | #[test] |
| 330 | fn contextual_subcommands_fail_without_capability() { |
| 331 | let CommandHandler::Contextual { handler, .. } = ConstitutionCmd::handler() else { |
| 332 | panic!("expected contextual handler"); |
| 333 | }; |
| 334 | let res: CommandResult<ConstitutionAction> = |
| 335 | handler(CommandContexts::empty(), Some("preview")); |
| 336 | assert!(res.is_error); |
| 337 | assert_eq!( |
| 338 | res.message.as_deref(), |
| 339 | Some("Error: Command capability unavailable: constitution") |
| 340 | ); |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn suggestions_and_ratify_update_host_state() { |
| 345 | let mut ctx = MockConstitutionContext::default(); |
| 346 | let res = run(&mut ctx, Some("suggestions")); |
| 347 | assert!(!res.is_error); |
| 348 | assert_eq!(ctx.reviewed_digest.as_deref(), Some("digest-1")); |
| 349 | assert_eq!(ctx.pagers.len(), 1); |
| 350 | |
| 351 | let res = run(&mut ctx, Some("ratify c1 c2")); |
| 352 | assert_eq!(res.message.as_deref(), Some("ratified:c1,c2")); |
| 353 | assert_eq!(ctx.ratified_ids, vec!["c1", "c2"]); |
| 354 | } |
| 355 | } |
| 356 |