Skip to main content

atman_runtime/tools/
anchor.rs

1use std::path::PathBuf;
2
3use crate::error::RuntimeError;
4use crate::tool::{ApprovalLevel, BoxFut, Tier, Tool, ToolArgs, ToolCtx, ToolResult};
5use crate::tools::anchor_fs::{self, AnchorError, StateStore};
6use crate::value::Value;
7
8pub struct AnchorRead;
9pub struct AnchorEdit;
10pub struct AnchorWrite;
11pub struct AnchorUndo;
12
13fn text(args: &ToolArgs, name: &str, required: bool) -> Result<Option<String>, RuntimeError> {
14    match args.named(name) {
15        Some(Value::Str(value)) => Ok(Some(value.clone())),
16        Some(Value::Unit) if !required => Ok(None),
17        None if !required => Ok(None),
18        Some(Value::Unit) | None => Err(RuntimeError::MissingArg(name.into())),
19        Some(value) => Err(RuntimeError::TypeMismatch {
20            expected: "string".into(),
21            actual: value.kind_name().into(),
22        }),
23    }
24}
25
26fn path(args: &ToolArgs) -> Result<PathBuf, RuntimeError> {
27    match args.named("path").or_else(|| args.positional.first()) {
28        Some(Value::Path(path)) => Ok(path.clone()),
29        Some(Value::Str(path)) => Ok(PathBuf::from(path)),
30        Some(value) => Err(RuntimeError::TypeMismatch {
31            expected: "path or string".into(),
32            actual: value.kind_name().into(),
33        }),
34        None => Err(RuntimeError::MissingArg("path".into())),
35    }
36}
37
38fn store(ctx: &ToolCtx) -> StateStore {
39    StateStore::new(
40        ctx.data_root
41            .clone()
42            .unwrap_or_else(|| PathBuf::from(".atman"))
43            .join("anchor"),
44    )
45}
46
47fn error(error: AnchorError) -> RuntimeError {
48    RuntimeError::ToolFailed(error.to_string())
49}
50
51fn change_value(change: &anchor_fs::ChangeRecord) -> Value {
52    Value::Struct(vec![
53        ("change_id".into(), Value::Str(change.change_id.clone())),
54        ("path".into(), Value::Str(change.path.clone())),
55        ("before_hash".into(), Value::Str(change.before_hash.clone())),
56        ("after_hash".into(), Value::Str(change.after_hash.clone())),
57    ])
58}
59
60fn schema(properties: serde_json::Value, required: &[&str]) -> serde_json::Value {
61    serde_json::json!({"type":"object", "properties":properties, "required":required})
62}
63
64impl Tool for AnchorRead {
65    fn name(&self) -> &str {
66        "anchor.read"
67    }
68    fn tier(&self) -> Tier {
69        Tier::Zero
70    }
71    fn description(&self) -> Option<&str> {
72        Some("Read a file with stable hashline anchors.")
73    }
74    fn input_schema(&self) -> serde_json::Value {
75        schema(
76            serde_json::json!({"path":{"type":["string","object"]}}),
77            &["path"],
78        )
79    }
80    fn call<'a>(&'a self, args: ToolArgs, ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
81        Box::pin(async move {
82            let p = path(&args)?;
83            anchor_fs::read_anchor_text(&p, &store(ctx))
84                .map(Value::Str)
85                .map_err(error)
86        })
87    }
88}
89
90impl Tool for AnchorEdit {
91    fn name(&self) -> &str {
92        "anchor.edit"
93    }
94    fn tier(&self) -> Tier {
95        Tier::Two
96    }
97    fn approval_level(&self, _: &ToolArgs, _: &ToolCtx) -> ApprovalLevel {
98        ApprovalLevel::Approve
99    }
100    fn description(&self) -> Option<&str> {
101        Some("Apply a strict replace, insert, or remove mutation using hashline anchors.")
102    }
103    fn input_schema(&self) -> serde_json::Value {
104        schema(
105            serde_json::json!({"path":{"type":"string"},"operation":{"enum":["replace","insert","remove"]},"target":{"type":"string"},"from":{"type":"string"},"to":{"type":"string"},"at":{"type":"string"},"position":{"enum":["before","after"]},"content":{"type":"string"}}),
106            &["path", "operation"],
107        )
108    }
109    fn call<'a>(&'a self, args: ToolArgs, ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
110        Box::pin(async move {
111            let p = path(&args)?;
112            let operation = text(&args, "operation", true)?.unwrap();
113            let change = anchor_fs::edit_by_anchor(
114                &p,
115                &operation,
116                text(&args, "target", false)?.as_deref(),
117                text(&args, "from", false)?.as_deref(),
118                text(&args, "to", false)?.as_deref(),
119                text(&args, "at", false)?.as_deref(),
120                text(&args, "position", false)?.as_deref(),
121                text(&args, "content", false)?.as_deref(),
122                &store(ctx),
123            )
124            .map_err(error)?;
125            Ok(change_value(&change))
126        })
127    }
128}
129
130impl Tool for AnchorWrite {
131    fn name(&self) -> &str {
132        "anchor.write"
133    }
134    fn tier(&self) -> Tier {
135        Tier::Two
136    }
137    fn approval_level(&self, _: &ToolArgs, _: &ToolCtx) -> ApprovalLevel {
138        ApprovalLevel::Approve
139    }
140    fn description(&self) -> Option<&str> {
141        Some("Overwrite a file only when its expected hash matches.")
142    }
143    fn input_schema(&self) -> serde_json::Value {
144        schema(
145            serde_json::json!({"path":{"type":"string"},"expected_file_hash":{"type":"string"},"content":{"type":"string"}}),
146            &["path", "expected_file_hash", "content"],
147        )
148    }
149    fn call<'a>(&'a self, args: ToolArgs, ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
150        Box::pin(async move {
151            let p = path(&args)?;
152            let h = text(&args, "expected_file_hash", true)?.unwrap();
153            let c = text(&args, "content", true)?.unwrap();
154            anchor_fs::overwrite_with_hash(&p, &h, &c, &store(ctx))
155                .map(|v| change_value(&v))
156                .map_err(error)
157        })
158    }
159}
160
161impl Tool for AnchorUndo {
162    fn name(&self) -> &str {
163        "anchor.undo"
164    }
165    fn tier(&self) -> Tier {
166        Tier::Two
167    }
168    fn approval_level(&self, _: &ToolArgs, _: &ToolCtx) -> ApprovalLevel {
169        ApprovalLevel::Approve
170    }
171    fn description(&self) -> Option<&str> {
172        Some("Undo the latest anchor change, refusing if the file changed since.")
173    }
174    fn input_schema(&self) -> serde_json::Value {
175        schema(
176            serde_json::json!({"path":{"type":"string"},"change_id":{"type":"string"}}),
177            &["path"],
178        )
179    }
180    fn call<'a>(&'a self, args: ToolArgs, ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
181        Box::pin(async move {
182            let p = path(&args);
183            let p = p?;
184            let s = store(ctx);
185            let id = text(&args, "change_id", false)?;
186            let change = match id {
187                Some(id) => s.change(&id),
188                None => s.latest_change(&p),
189            }
190            .map_err(error)?
191            .ok_or_else(|| {
192                RuntimeError::ToolFailed(format!("no anchor change for {}", p.display()))
193            })?;
194            let current = std::fs::read(&p).map_err(|e| RuntimeError::ToolFailed(e.to_string()))?;
195            s.undo_strict(&p, &change, &current).map_err(error)?;
196            Ok(change_value(&change))
197        })
198    }
199}