use crate::{
annotations,
context::{CmdError, resolve, resolve_op, root, with_store},
plan_schema::plan_input_schema,
receipt::{Mutation, run_mutation},
render::{self, PlanExpect},
respond,
verdict::{Outcome, Verbosity},
};
use griz_core::{
Confidence, DiskSource, Op, PositionEncoding, WorkspaceEdit, build_plan, parse_patch,
workspace_edit_to_ops,
};
use griz_store::Selection;
use incurs::command::{CommandDef, TypedContext};
use serde::Deserialize;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
#[derive(Deserialize, incurs::Options)]
struct PlanOptions {
ops: Option<Vec<Value>>,
patch: Option<String>,
workspace_edit: Option<Value>,
position_encoding: Option<String>,
root: Option<String>,
purpose: String,
idempotency_key: String,
expect_edits: Option<usize>,
expect_files: Option<usize>,
verbosity: Option<String>,
}
pub fn plan_command() -> CommandDef {
CommandDef::typed::<(), PlanOptions, (), Value, _, _>(
"plan",
|ctx: TypedContext<(), PlanOptions, ()>| async move { respond(plan(ctx.options).await) },
)
.description("Plan edits from operations or patch text. Writes no source file; returns a plan id for diff, select, and apply.")
.mcp(annotations::records())
.mcp_input_schema(plan_input_schema())
.done()
}
async fn plan(options: PlanOptions) -> Result<(Value, Outcome), CmdError> {
let level = Verbosity::resolve(options.verbosity.as_deref()).map_err(CmdError::invalid)?;
let root = root(options.root.as_deref())?;
let encoding = position_encoding(options.position_encoding.as_deref())?;
let ops = collect_ops(
&root,
options.ops,
options.patch.as_deref(),
options.workspace_edit,
encoding,
)?;
let expect = PlanExpect {
edits: options.expect_edits,
files: options.expect_files,
};
let mutation = Mutation {
command: "plan",
key: options.idempotency_key,
input: json!({ "ops": ops, "expect": [expect.edits, expect.files] }),
};
let purpose = options.purpose;
with_store(move |store| {
run_mutation(
store,
&mutation,
level,
|store| {
let mut plan = build_plan(&ops, &DiskSource);
let syntax = plan.syntax;
let file_syntax = std::mem::take(&mut plan.file_syntax);
let record = store.save_plan(&purpose, ops.clone(), plan)?;
Ok(render::with_syntax(
render::plan(&record, expect),
syntax,
&file_syntax,
))
},
|store, id, outcome| {
let record = store.plan(id)?;
let changes = store.plan_changes(&record)?;
let file_syntax = griz_core::annotate(&changes);
let syntax = griz_core::plan_syntax(&file_syntax);
let rendered =
render::with_syntax(render::plan(&record, expect), syntax, &file_syntax);
Ok(rendered.with_outcome(outcome))
},
)
})
.await
}
fn position_encoding(text: Option<&str>) -> Result<PositionEncoding, CmdError> {
match text {
Some(text) => PositionEncoding::parse(text).map_err(CmdError::invalid),
None => Ok(PositionEncoding::default()),
}
}
fn collect_ops(
root: &Path,
ops: Option<Vec<Value>>,
patch: Option<&str>,
workspace_edit: Option<Value>,
encoding: PositionEncoding,
) -> Result<Vec<Op>, CmdError> {
let mut all = Vec::new();
if let Some(patch) = patch {
let text = match patch.strip_prefix('@') {
Some(file) => std::fs::read_to_string(resolve(root, Path::new(file)))
.map_err(|e| CmdError::invalid(format!("reading patch file: {e}")))?,
None => patch.to_string(),
};
let resolver = |path: &str| resolve(root, Path::new(path));
all.extend(parse_patch(&text, &resolver).map_err(|e| CmdError::invalid(e.to_string()))?);
}
for (index, value) in normalize(ops.unwrap_or_default())?.into_iter().enumerate() {
let op: Op = serde_json::from_value(value)
.map_err(|e| CmdError::invalid(format!("ops[{index}]: {e}")))?;
all.push(resolve_op(root, op));
}
all.extend(collect_workspace_edit_ops(workspace_edit, encoding)?);
if all.is_empty() {
return Err(CmdError::invalid(
"give `ops`, `patch`, or `workspace_edit`",
));
}
Ok(all)
}
fn collect_workspace_edit_ops(
workspace_edit: Option<Value>,
encoding: PositionEncoding,
) -> Result<Vec<Op>, CmdError> {
let Some(value) = workspace_edit else {
return Ok(Vec::new());
};
let value = match value {
Value::String(text) => serde_json::from_str(&text)
.map_err(|e| CmdError::invalid(format!("workspace_edit must be JSON: {e}")))?,
other => other,
};
let edit: WorkspaceEdit = serde_json::from_value(value)
.map_err(|e| CmdError::invalid(format!("workspace_edit: {e}")))?;
workspace_edit_to_ops(&edit, encoding, &DiskSource)
.map_err(|e| CmdError::invalid(e.to_string()))
}
fn normalize(values: Vec<Value>) -> Result<Vec<Value>, CmdError> {
let mut out = Vec::with_capacity(values.len());
for value in values {
let parsed = match value {
Value::String(text) => serde_json::from_str(&text)
.map_err(|e| CmdError::invalid(format!("ops must be JSON: {e}")))?,
other => other,
};
match parsed {
Value::Array(items) => out.extend(items),
item => out.push(item),
}
}
Ok(out)
}
#[derive(Deserialize, incurs::Args)]
struct PlanArgs {
plan: String,
}
#[derive(Deserialize, incurs::Options)]
struct SelectOptions {
paths: Option<Vec<String>>,
edits: Option<Vec<String>>,
min_confidence: Option<String>,
root: Option<String>,
purpose: String,
idempotency_key: String,
verbosity: Option<String>,
}
pub fn select_command() -> CommandDef {
CommandDef::typed::<PlanArgs, SelectOptions, (), Value, _, _>(
"select",
|ctx: TypedContext<PlanArgs, SelectOptions, ()>| async move {
respond(select(ctx.args.plan, ctx.options).await)
},
)
.description("Make a new plan from part of another: by path, edit id, or confidence. Enables partial apply and partial undo.")
.mcp(annotations::records())
.done()
}
async fn select(id: String, options: SelectOptions) -> Result<(Value, Outcome), CmdError> {
let level = Verbosity::resolve(options.verbosity.as_deref()).map_err(CmdError::invalid)?;
let root = root(options.root.as_deref())?;
let selection = Selection {
paths: resolve_all(&root, options.paths),
edits: options.edits.unwrap_or_default(),
min_confidence: options
.min_confidence
.as_deref()
.map(confidence)
.transpose()?,
};
let mutation = Mutation {
command: "select",
key: options.idempotency_key,
input: json!({ "plan": id, "selection": selection }),
};
let purpose = options.purpose;
with_store(move |store| {
run_mutation(
store,
&mutation,
level,
|store| {
Ok(render::plan(
&store.select(&id, &selection, &purpose)?,
PlanExpect::default(),
))
},
|store, id, outcome| {
Ok(render::plan(&store.plan(id)?, PlanExpect::default()).with_outcome(outcome))
},
)
})
.await
}
pub fn resolve_all(root: &Path, paths: Option<Vec<String>>) -> Vec<PathBuf> {
paths
.unwrap_or_default()
.iter()
.map(|path| resolve(root, Path::new(path)))
.collect()
}
pub fn confidence(text: &str) -> Result<Confidence, CmdError> {
match text {
"machine" => Ok(Confidence::Machine),
"maybe" => Ok(Confidence::Maybe),
other => Err(CmdError::invalid(format!(
"unknown confidence `{other}`; use machine or maybe"
))),
}
}