| 1 | //! Anchor command: keep critical facts across compaction. |
| 2 | //! |
| 3 | //! Unlike `/note` (active lookup), anchors are passive. They are automatically |
| 4 | //! re-injected into context after compaction in trusted workspaces. Use anchors to |
| 5 | //! preserve invariants like "This API's status field is unreliable" or |
| 6 | //! ".ssh/ must never be touched". |
| 7 | |
| 8 | use codewhale_command_contract::facets::CommandWorkspaceContext; |
| 9 | use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts, CommandHandler}; |
| 10 | use codewhale_command_contract::metadata::{CommandInfo, RegisterCommand}; |
| 11 | use codewhale_command_contract::navigation::AnchorWriteError; |
| 12 | use codewhale_command_contract::outcome::CoreNavigationCommandResult as CommandResult; |
| 13 | |
| 14 | const USAGE: &str = "/anchor <text> | /anchor list | /anchor remove <n>"; |
| 15 | |
| 16 | pub const COMMAND_INFO: CommandInfo = CommandInfo { |
| 17 | name: "anchor", |
| 18 | aliases: &["maodian"], |
| 19 | usage: USAGE, |
| 20 | description_key: "cmd_anchor_description", |
| 21 | }; |
| 22 | |
| 23 | pub struct AnchorCmd; |
| 24 | |
| 25 | impl RegisterCommand<CommandResult> for AnchorCmd { |
| 26 | fn info() -> &'static CommandInfo { |
| 27 | &COMMAND_INFO |
| 28 | } |
| 29 | fn handler() -> CommandHandler<CommandResult> { |
| 30 | CommandHandler::Contextual { |
| 31 | capabilities: CommandCapabilities::WORKSPACE, |
| 32 | handler: anchor, |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | fn anchor(contexts: CommandContexts<'_>, content: Option<&str>) -> CommandResult { |
| 38 | let input = match content { |
| 39 | Some(content) => content.trim(), |
| 40 | None => return CommandResult::error(format!("Usage: {USAGE}")), |
| 41 | }; |
| 42 | if input.is_empty() { |
| 43 | return CommandResult::error(format!("Usage: {USAGE}")); |
| 44 | } |
| 45 | let Some(workspace) = contexts.into_parts().workspace else { |
| 46 | return CommandResult::error("Command capability unavailable: workspace"); |
| 47 | }; |
| 48 | if input.eq_ignore_ascii_case("list") { |
| 49 | return list_anchors(workspace); |
| 50 | } |
| 51 | if let Some((verb, rest)) = input.split_once(char::is_whitespace) |
| 52 | && ["remove", "rm", "delete"] |
| 53 | .iter() |
| 54 | .any(|removal| verb.eq_ignore_ascii_case(removal)) |
| 55 | && !rest.trim().contains(char::is_whitespace) |
| 56 | { |
| 57 | return remove_anchor(workspace, rest.trim()); |
| 58 | } |
| 59 | let parts: &[&[u8]] = &[b"\n---\n", input.as_bytes(), b"\n"]; |
| 60 | match workspace.append_anchor_bytes(parts) { |
| 61 | Ok(path) => { |
| 62 | CommandResult::message(format!("Anchor pinned.\nStored in: {}", path.display())) |
| 63 | } |
| 64 | Err(AnchorWriteError::Open(error)) => { |
| 65 | CommandResult::error(format!("Failed to open anchors file: {error}")) |
| 66 | } |
| 67 | Err(AnchorWriteError::Write(error)) => { |
| 68 | CommandResult::error(format!("Failed to write anchor: {error}")) |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | fn read_anchors(workspace: &dyn CommandWorkspaceContext) -> Result<Vec<String>, String> { |
| 74 | let Some(content) = workspace |
| 75 | .read_anchor_document() |
| 76 | .map_err(|error| format!("Failed to read anchors file: {error}"))? |
| 77 | else { |
| 78 | return Ok(Vec::new()); |
| 79 | }; |
| 80 | Ok(content |
| 81 | .split("\n---\n") |
| 82 | .map(|text| text.trim().to_string()) |
| 83 | .filter(|text| !text.is_empty()) |
| 84 | .collect()) |
| 85 | } |
| 86 | |
| 87 | fn list_anchors(workspace: &dyn CommandWorkspaceContext) -> CommandResult { |
| 88 | let anchors = match read_anchors(workspace) { |
| 89 | Ok(anchors) => anchors, |
| 90 | Err(error) => return CommandResult::error(error), |
| 91 | }; |
| 92 | if anchors.is_empty() { |
| 93 | return CommandResult::message( |
| 94 | "No anchors set. Use /anchor <text> to pin a fact that survives compaction.", |
| 95 | ); |
| 96 | } |
| 97 | let mut output = format!("Pinned anchors ({} total):\n", anchors.len()); |
| 98 | for (index, anchor) in anchors.iter().enumerate() { |
| 99 | output.push_str(&format!("\n {}. {}", index + 1, anchor)); |
| 100 | } |
| 101 | output.push_str("\n\nUse /anchor remove <n> to remove an anchor."); |
| 102 | CommandResult::message(output) |
| 103 | } |
| 104 | |
| 105 | fn remove_anchor(workspace: &mut dyn CommandWorkspaceContext, index_str: &str) -> CommandResult { |
| 106 | let index: usize = match index_str.parse() { |
| 107 | Ok(index) if index >= 1 => index, |
| 108 | _ => { |
| 109 | return CommandResult::error( |
| 110 | "Invalid index. Use /anchor list to see anchor numbers, then /anchor remove <n>.", |
| 111 | ); |
| 112 | } |
| 113 | }; |
| 114 | let mut anchors = match read_anchors(workspace) { |
| 115 | Ok(anchors) => anchors, |
| 116 | Err(error) => return CommandResult::error(error), |
| 117 | }; |
| 118 | if index > anchors.len() { |
| 119 | return CommandResult::error(format!( |
| 120 | "Anchor #{index} does not exist. You have {} anchor(s). Use /anchor list to see them.", |
| 121 | anchors.len() |
| 122 | )); |
| 123 | } |
| 124 | let removed = anchors.remove(index - 1); |
| 125 | if let Err(error) = workspace.replace_anchor_document(anchors.join("\n---\n").as_bytes()) { |
| 126 | return CommandResult::error(format!("Failed to write anchors file: {error}")); |
| 127 | } |
| 128 | CommandResult::message(format!("Removed anchor #{index}: {removed}")) |
| 129 | } |
| 130 |