use crate::{
annotations,
context::{CmdError, resolve, resolve_op, root, with_store},
receipt::{Mutation, run_mutation},
render::{self, PlanExpect},
respond,
verdict::{Outcome, Verbosity},
};
use griz_core::{Confidence, DiskSource, Op, build_plan, parse_patch};
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>,
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()
}
fn plan_input_schema() -> Value {
let mut op_schema = serde_json::to_value(schemars::schema_for!(Op))
.unwrap_or_else(|e| unreachable!("Op derives JsonSchema: {e}"));
let defs = op_schema
.as_object_mut()
.and_then(|schema| schema.remove("$defs"))
.unwrap_or_else(|| json!({}));
if let Some(schema) = op_schema.as_object_mut() {
schema.remove("$schema");
}
json!({
"type": "object",
"properties": {
"ops": {
"type": "array",
"description": "Operations as JSON objects, applied in order. Each is a replace, insert, create, delete, or move (or JSON text for CLI callers).",
"items": {
"oneOf": [op_schema, { "type": "string" }],
},
},
"patch": {
"type": "string",
"description": "Codex patch text, or `@path` to read the patch from a file.",
},
"root": {
"type": "string",
"description": "Directory relative paths resolve from. Defaults to the current directory.",
},
"purpose": {
"type": "string",
"description": "Why this plan is being made.",
},
"idempotency_key": {
"type": "string",
"description": "Key that makes a retry return the original plan instead of a new one.",
},
"expect_edits": {
"type": "number",
"description": "Number of edits the plan must contain.",
},
"expect_files": {
"type": "number",
"description": "Number of files the plan must change.",
},
"verbosity": {
"type": "string",
"description": "Response detail: off, error, warn, info, debug, or trace.",
},
},
"required": ["purpose", "idempotency_key"],
"$defs": defs,
})
}
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 ops = collect_ops(&root, options.ops, options.patch.as_deref())?;
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 plan = build_plan(&ops, &DiskSource);
Ok(render::plan(
&store.save_plan(&purpose, ops.clone(), plan)?,
expect,
))
},
|store, id, outcome| Ok(render::plan(&store.plan(id)?, expect).with_outcome(outcome)),
)
})
.await
}
fn collect_ops(
root: &Path,
ops: Option<Vec<Value>>,
patch: Option<&str>,
) -> 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));
}
if all.is_empty() {
return Err(CmdError::invalid("give `ops`, `patch`, or both"));
}
Ok(all)
}
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"
))),
}
}