use crate::{
annotations,
context::{CmdError, input_path, input_root, resolve_paths, with_store},
plan_input::{PlanInput, expect_clean, position_encoding},
plan_schema::plan_input_schema,
receipt::{Mutation, run_mutation},
render::{self, PlanExpect},
respond,
verdict::{Outcome, Verbosity},
};
use griz_core::{Confidence, DiskSource, build_plan};
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>,
expect_syntax: Option<String>,
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.")
.examples(crate::usage::example("--root /path/to/repo --ops @edits.json --expect-edits 1 --expect-files 1 --purpose \"Plan edit\" --idempotency-key edit-plan --format json", "Plan one edit from JSON."))
.hint(crate::usage::MUTATION)
.mcp(annotations::records())
.mcp_input_schema(plan_input_schema::<PlanOptions>())
.done()
}
async fn plan(options: PlanOptions) -> Result<(Value, Outcome), CmdError> {
let level = Verbosity::resolve(options.verbosity.as_deref()).map_err(CmdError::invalid)?;
let root = input_root(options.root.as_deref())?;
let encoding = position_encoding(options.position_encoding.as_deref())?;
let input = PlanInput::parse(
&root,
options.ops,
options.patch.as_deref(),
options.workspace_edit,
encoding,
)?;
let expect = PlanExpect {
edits: options.expect_edits,
files: options.expect_files,
};
let expect_clean = expect_clean(options.expect_syntax.as_deref())?;
let mutation = Mutation {
command: "plan",
key: options.idempotency_key,
input: input.identity(expect, expect_clean),
};
let purpose = options.purpose;
with_store(move |store| {
run_mutation(
store,
&mutation,
level,
|store| {
let ops = input.operations()?;
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)?;
let rendered =
render::with_syntax(render::plan(&record, expect, level), syntax, &file_syntax);
Ok(render::expect_clean_syntax(rendered, syntax, expect_clean))
},
|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, level), syntax, &file_syntax);
let rendered = render::expect_clean_syntax(rendered, syntax, expect_clean);
Ok(rendered.with_outcome(outcome))
},
)
})
.await
}
#[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>,
#[incurs(default = false)]
resolved_only: bool,
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, confidence, or resolved_only. Use resolved_only to keep operations that produced edits without listing their ids. Writes no source file.")
.examples(crate::usage::example("PLAN --root /path/to/repo --paths \"src one.rs\" --paths \"src two.rs\" --purpose \"Select files\" --idempotency-key edit-select --format json", "Select files from a saved plan."))
.hint("CLI: PLAN is positional. Repeat --paths and --edits for multiple values. Check exit status and outcome == passed before using the new id.")
.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 = input_root(options.root.as_deref())?;
let selection = Selection {
paths: input_paths(&root, options.paths),
edits: options.edits.unwrap_or_default(),
resolved_only: options.resolved_only,
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| {
let mut selection = selection;
selection.paths = crate::path_filters::resolve(&selection.paths)?;
Ok(render::plan(
&store.select(&id, &selection, &purpose)?,
PlanExpect::default(),
level,
))
},
|store, id, outcome, _| {
Ok(render::plan(&store.plan(id)?, PlanExpect::default(), level)
.with_outcome(outcome))
},
)
})
.await
}
pub fn resolve_all(root: &Path, paths: Option<Vec<String>>) -> Result<Vec<PathBuf>, CmdError> {
resolve_paths(&input_paths(root, paths))
}
pub fn input_paths(root: &Path, paths: Option<Vec<String>>) -> Vec<PathBuf> {
paths
.unwrap_or_default()
.iter()
.map(|path| input_path(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"
))),
}
}