Plan for parallel agents, check plans with a fresh agent, keep run history
The planning prompt now has rules for parallel tasks, git, worktrees and consolidation steps, and each task is told which tasks run beside it. A second agent with a clean context checks every generated workflow and fixes it; its changes show on the review screen. The VM takes the host git identity at boot. Each run is saved as run.json beside its evidence and reloads on reopen, with the exact prompt and final summary of every task. Approved workflows are read-only, and the run screen shows the selected task's decisions, acceptance criteria and evidence. The prompt editor drops the files list and the live label. Co-Authored-By: Claude Opus 5.5
This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.
@@ -2,24 +2,61 @@ use crate::workflow::model::{Task, Workflow};
22
33 const SCHEMA: &str = r#"{"tasks":[{"id":"T1","step":1,"title":"short imperative title","decisions":["a decision you made and why"],"acceptance":["a checkable acceptance criterion"],"evidence":["test-output.txt"]}]}"#;
44
5+const RULES: &str = "\
6+How cast runs a workflow:
7+- Steps run in ascending order. Tasks with the same step number run at the same time, each with its own agent, in the same /work checkout.
8+- Each agent sees only the original prompt and its own task, so every task must carry the decisions and context it needs.
9+- Each task lists the decisions it made, its acceptance criteria and the evidence to attach.
10+- Evidence is the bare file names the task will write as proof, such as test output, logs or screenshots. Cast picks the folder, so give no directory.
11+
12+Rules for tasks that run at the same time:
13+- Read the code to find the files each task will create or change. Tasks in one step must not change the same files, including shared ones such as lockfiles, manifests, generated code, snapshots, docs and changelogs.
14+- If two tasks need the same files, put them in different steps, or have each work in its own git worktree on its own branch and add a later task that merges them.
15+- They never commit, stash, reset, rebase, check out or clean, and never revert changes they did not make: another agent may be in the middle of its work.
16+- They do not run commands that rewrite files they do not own, such as project-wide formatters or code generators.
17+
18+Rules for git:
19+- If /work is not a git repository, no task uses git, and parallel tasks keep to separate files.
20+- Only a task that runs alone in its step commits. When parallel tasks change the project, follow them with a consolidation task that reviews the combined diff, merges any worktree branches, resolves conflicts, runs the full checks and commits the work.
21+- Group commits by logical change and follow the project's own instructions, such as CLAUDE.md, AGENTS.md or CONTRIBUTING.md, on commits and checks.
22+- A task that adds worktrees removes them once its branch is merged.";
23+
524 pub fn workflow(prompt: &str, prior: Option<(&Workflow, &str)>) -> String {
625 let mut out = format!(
726 "You plan software work. The working directory /work is the user's project; read it as needed but do not change any files.\n\
8- Turn the user's prompt below into a workflow of tasks.\n\
9- - Tasks with the same step number run in parallel; steps run in ascending order.\n\
10- - Each task lists the decisions it made, its acceptance criteria and the evidence to attach.\n\
11- - Evidence is the bare file names the task will write as proof, such as test output, logs or screenshots. Cast picks the folder, so give no directory.\n\
27+ Turn the user's prompt below into a workflow of tasks.\n\n{RULES}\n\n\
1228 Answer with only JSON matching this shape, no prose and no code fence:\n{SCHEMA}\n\n<prompt>\n{prompt}\n</prompt>\n"
1329 );
1430 if let Some((wf, feedback)) = prior {
15- let json = serde_json::to_string_pretty(&wf.tasks).unwrap_or_default();
1631 out += &format!(
17- "\nThis is the current workflow:\n{json}\n\nRevise it with this feedback:\n{feedback}\n"
32+ "\nThis is the current workflow:\n{}\n\nRevise it with this feedback:\n{feedback}\n",
33+ json(wf)
1834 );
1935 }
2036 out
2137 }
2238
39+pub fn check(prompt: &str, draft: &Workflow) -> String {
40+ format!(
41+ "You review a workflow that another agent planned from the user's prompt. The working directory /work is the user's project; read it as needed but do not change any files.\n\
42+ Make sure the workflow is ready to run and correct, and fix it where it is not.\n\n{RULES}\n\n\
43+ Check each of these against the prompt and the code:\n\
44+ - It does everything the prompt asks and nothing it does not.\n\
45+ - Tasks in the same step change separate files. Open the files to confirm it.\n\
46+ - Each task depends only on tasks in earlier steps.\n\
47+ - Commits come only from tasks that run alone, and parallel work is consolidated before anything builds on it.\n\
48+ - Every acceptance criterion can be checked by running something or reading the evidence.\n\
49+ - Every task has the decisions and context its agent needs without seeing the other tasks.\n\n\
50+ Answer with only JSON, no prose and no code fence: the corrected workflow in this shape, plus \"changes\", a list with one short sentence for each change you made and why. Leave \"changes\" empty if the workflow was already right.\n\
51+ {SCHEMA}\n\n<prompt>\n{prompt}\n</prompt>\n\n<workflow>\n{}\n</workflow>\n",
52+ json(draft)
53+ )
54+}
55+
56+fn json(wf: &Workflow) -> String {
57+ serde_json::to_string_pretty(&wf.tasks).unwrap_or_default()
58+}
59+
2360 pub fn assist(doc: &str, range: (usize, usize), instruction: &str) -> String {
2461 let (a, b) = range;
2562 let doc = format!("{}<<<{}>>>{}", &doc[..a], &doc[a..b], &doc[b..]);
@@ -36,13 +73,28 @@ pub fn assist(doc: &str, range: (usize, usize), instruction: &str) -> String {
3673
3774 pub fn task(wf: &Workflow, task: &Task, evidence_dir: &str, prompt: &str) -> String {
3875 let list = |xs: &[String]| xs.iter().map(|x| format!("- {x}\n")).collect::<String>();
76+ let others: Vec<String> = wf
77+ .tasks
78+ .iter()
79+ .filter(|t| t.step == task.step && t.id != task.id)
80+ .map(|t| format!("{}: {}", t.id, t.title))
81+ .collect();
82+ let parallel = if others.is_empty() {
83+ String::new()
84+ } else {
85+ format!(
86+ "\nThese tasks run at the same time as yours, each with its own agent, in the same /work:\n{}\
87+ Change only the files your task needs. Do not commit, stash, reset, rebase, check out or clean, do not revert changes you did not make, and do not run project-wide formatters or generators. If your task says to use a git worktree, work only inside it.\n",
88+ list(&others)
89+ )
90+ };
3991 format!(
4092 "You are running task {id} of a workflow in /work, the user's project.\n\
4193 Original prompt:\n<prompt>\n{prompt}\n</prompt>\n\n\
42- Task {id}: {title}\nDecisions already made:\n{d}\nAcceptance criteria:\n{a}\nEvidence to attach:\n{e}\n\
94+ Task {id}: {title}\nDecisions already made:\n{d}\nAcceptance criteria:\n{a}\nEvidence to attach:\n{e}{parallel}\n\
4395 Do the work. Save every piece of evidence into {evidence_dir}/ (create it).\n\
4496 Finish with a short summary of what changed and how each acceptance criterion was met.\n\
45- Workflow {name} v{v}.\n",
97+ Workflow {name} v{v}, step {step} of {steps}.\n",
4698 id = task.id,
4799 title = task.title,
48100 d = list(&task.decisions),
@@ -50,5 +102,34 @@ pub fn task(wf: &Workflow, task: &Task, evidence_dir: &str, prompt: &str) -> Str
50102 e = list(&task.evidence),
51103 name = wf.prompt,
52104 v = wf.version,
105+ step = task.step,
106+ steps = wf.steps().len(),
53107 )
54108 }
109+
110+#[cfg(test)]
111+mod tests {
112+ use crate::workflow::model::{Task, Workflow};
113+
114+ #[test]
115+ fn a_task_prompt_names_only_the_tasks_running_beside_it() {
116+ let task = |id: &str, step, title: &str| Task {
117+ id: id.into(),
118+ step,
119+ title: title.into(),
120+ ..Task::default()
121+ };
122+ let wf = Workflow {
123+ tasks: vec![
124+ task("T1", 1, "api"),
125+ task("T2", 1, "ui"),
126+ task("T3", 2, "merge"),
127+ ],
128+ ..Workflow::default()
129+ };
130+ let p = super::task(&wf, &wf.tasks[0], "/cast/runs/x/T1", "go");
131+ assert!(p.contains("T2: ui") && !p.contains("T3: merge") && p.contains("Do not commit"));
132+ let alone = super::task(&wf, &wf.tasks[2], "/cast/runs/x/T3", "go");
133+ assert!(!alone.contains("Do not commit"));
134+ }
135+}
@@ -20,7 +20,7 @@ impl App {
2020 r.logs[i].push(line);
2121 }
2222 }
23- Some(JobKind::Generate(stem) | JobKind::Assist(stem)) => {
23+ Some(JobKind::Generate(stem) | JobKind::Check(stem, _) | JobKind::Assist(stem)) => {
2424 let stem = stem.clone();
2525 self.activity(&stem, line);
2626 }
@@ -28,6 +28,7 @@ impl App {
2828 },
2929 Event::Job(id, JobEvent::Done(result)) => match self.jobs.remove(&id) {
3030 Some(JobKind::Generate(stem)) => self.generated(&stem, result),
31+ Some(JobKind::Check(stem, draft)) => self.checked(&stem, draft, result),
3132 Some(JobKind::Assist(stem)) => self.assisted(&stem, id, result),
3233 Some(JobKind::Task(stem, i)) => self.task_done(&stem, i, result),
3334 None => {}
@@ -12,6 +12,7 @@ use crate::settings::Form;
1212 use crate::setup::Setup;
1313 use crate::ui::images::Images;
1414 use crate::vm::{self, Vm};
15+use crate::workflow::model::Workflow;
1516 use crate::workflow::review::Review;
1617 use crate::workspace::Workspace;
1718 use bus::{Bus, Event};
@@ -27,6 +28,7 @@ pub use view::view;
2728
2829 pub enum JobKind {
2930 Generate(String),
31+ Check(String, Workflow),
3032 Assist(String),
3133 Task(String, usize),
3234 }
@@ -48,7 +50,6 @@ pub struct App {
4850 pub jobs: HashMap<u64, JobKind>,
4951 pub settings: Form,
5052 pub notice: Option<String>,
51- pub epoch: std::time::Instant,
5253 tick: f64,
5354 scratch: TextEdit,
5455 }
@@ -75,7 +76,6 @@ impl App {
7576 jobs: HashMap::new(),
7677 settings,
7778 notice: None,
78- epoch: std::time::Instant::now(),
7979 tick: 0.0,
8080 scratch: TextEdit::new(""),
8181 }
@@ -110,7 +110,9 @@ impl App {
110110 }
111111
112112 pub fn now(&self) -> f64 {
113- self.epoch.elapsed().as_secs_f64()
113+ std::time::SystemTime::now()
114+ .duration_since(std::time::UNIX_EPOCH)
115+ .map_or(0.0, |d| d.as_secs_f64())
114116 }
115117
116118 pub fn fail(&mut self, msg: impl Into<String>) {
@@ -191,7 +191,7 @@ fn preview(s: &App, e: &Editor, k: &Kit) -> El {
191191 .grow(1.0)
192192 .min_w(0.0)
193193 .h_full()
194- .child(ph(lbl("Preview"), lbl("● live").color(p.ok)))
194+ .child(ph(lbl("Preview"), el()))
195195 .child(
196196 col()
197197 .key("preview-scroll")
@@ -1,4 +1,4 @@
1-#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1+#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
22 pub enum Status {
33 Queued,
44 Running,
@@ -44,6 +44,13 @@ impl Machine {
4444 }
4545 }
4646
47+ pub fn restore(steps: Vec<u32>, status: Vec<Status>) -> Machine {
48+ Machine {
49+ status,
50+ ..Machine::new(steps)
51+ }
52+ }
53+
4754 pub fn current_step(&self) -> Option<u32> {
4855 self.steps
4956 .iter()
@@ -1,3 +1,4 @@
11 pub mod machine;
2+pub mod record;
23 pub mod run;
34 pub mod view;
@@ -0,0 +1,79 @@
1+use crate::exec::machine::{Machine, Status};
2+use crate::exec::run::Run;
3+use crate::workflow::model::Workflow;
4+use serde::{Deserialize, Serialize};
5+use std::path::Path;
6+
7+const INTERRUPTED: &str = "✕ interrupted: cast closed while this task ran";
8+
9+#[derive(Serialize, Deserialize, Default)]
10+#[serde(default)]
11+pub struct TaskRecord {
12+ pub status: Option<Status>,
13+ pub started: Option<f64>,
14+ pub ended: Option<f64>,
15+ pub prompt: Option<String>,
16+ pub summary: Option<String>,
17+ pub log: Vec<String>,
18+ pub evidence: Vec<String>,
19+}
20+
21+#[derive(Serialize, Deserialize, Default)]
22+#[serde(default)]
23+pub struct Record {
24+ pub workflow: Workflow,
25+ pub prompt: String,
26+ pub tasks: Vec<TaskRecord>,
27+}
28+
29+pub fn save(dir: &Path, r: &Run) -> std::io::Result<()> {
30+ let tasks = (0..r.wf.tasks.len())
31+ .map(|i| TaskRecord {
32+ status: Some(r.machine.status[i]),
33+ started: r.started[i],
34+ ended: r.ended[i],
35+ prompt: r.prompts[i].clone(),
36+ summary: r.summaries[i].clone(),
37+ log: r.logs[i].clone(),
38+ evidence: r.evidence[i].clone(),
39+ })
40+ .collect();
41+ let rec = Record {
42+ workflow: r.wf.clone(),
43+ prompt: r.prompt.clone(),
44+ tasks,
45+ };
46+ std::fs::create_dir_all(dir)?;
47+ std::fs::write(dir.join("run.json"), serde_json::to_vec_pretty(&rec)?)
48+}
49+
50+pub fn load(dir: &Path) -> Option<Run> {
51+ let rec: Record = serde_json::from_slice(&std::fs::read(dir.join("run.json")).ok()?).ok()?;
52+ let n = rec.workflow.tasks.len();
53+ if rec.tasks.len() != n {
54+ return None;
55+ }
56+ let mut r = Run::new(rec.workflow, rec.prompt);
57+ let mut status = Vec::with_capacity(n);
58+ for (i, t) in rec.tasks.into_iter().enumerate() {
59+ let mut s = t.status.unwrap_or(Status::Queued);
60+ let mut log = t.log;
61+ if s == Status::Running {
62+ s = Status::Failed;
63+ log.push(INTERRUPTED.into());
64+ }
65+ status.push(s);
66+ r.started[i] = t.started;
67+ r.ended[i] = t.ended.or(t.started);
68+ r.prompts[i] = t.prompt;
69+ r.summaries[i] = t.summary;
70+ r.logs[i] = log;
71+ r.evidence[i] = t.evidence;
72+ }
73+ r.machine = Machine::restore(r.wf.tasks.iter().map(|t| t.step).collect(), status);
74+ Some(r)
75+}
76+
77+#[cfg(test)]
78+#[path = "record_tests.rs"]
79+mod tests;
@@ -0,0 +1,36 @@
1+use super::{INTERRUPTED, load, save};
2+use crate::exec::machine::Status;
3+use crate::exec::run::Run;
4+use crate::workflow::model::{Task, Workflow};
5+
6+#[test]
7+fn a_saved_run_loads_back_and_a_running_task_reads_as_interrupted() {
8+ let task = |id: &str, step| Task {
9+ id: id.into(),
10+ step,
11+ ..Task::default()
12+ };
13+ let wf = Workflow {
14+ prompt: "p".into(),
15+ version: 2,
16+ tasks: vec![task("T1", 1), task("T2", 2)],
17+ ..Workflow::default()
18+ };
19+ let mut r = Run::new(wf, "do it".into());
20+ r.machine.status = vec![Status::Done, Status::Running];
21+ r.logs[0] = vec!["✓ T1 done".into()];
22+ r.summaries[0] = Some("all good".into());
23+ r.prompts[1] = Some("task prompt".into());
24+ r.started[1] = Some(10.0);
25+ let dir = std::env::temp_dir().join(format!("cast-record-test-{}", std::process::id()));
26+ save(&dir, &r).unwrap();
27+ let back = load(&dir).unwrap();
28+ std::fs::remove_dir_all(&dir).unwrap();
29+ assert_eq!(back.wf.version, 2);
30+ assert_eq!(back.prompt, "do it");
31+ assert_eq!(back.machine.status, vec![Status::Done, Status::Failed]);
32+ assert_eq!(back.summaries[0].as_deref(), Some("all good"));
33+ assert_eq!(back.prompts[1].as_deref(), Some("task prompt"));
34+ assert_eq!(back.logs[1].last().map(String::as_str), Some(INTERRUPTED));
35+ assert_eq!(back.ended[1], Some(10.0));
36+}
@@ -2,6 +2,7 @@ use crate::agent::{job, prompts};
22 use crate::app::tabs::Tab;
33 use crate::app::{App, JobKind};
44 use crate::exec::machine::{Control, Machine, Status};
5+use crate::exec::record;
56 use crate::workflow::model::Workflow;
67 use crate::workspace::Workspace;
78
@@ -14,11 +15,13 @@ pub struct Run {
1415 pub started: Vec<Option<f64>>,
1516 pub ended: Vec<Option<f64>>,
1617 pub evidence: Vec<Vec<String>>,
18+ pub prompts: Vec<Option<String>>,
19+ pub summaries: Vec<Option<String>>,
1720 pub view: usize,
1821 }
1922
2023 impl Run {
21- fn new(wf: Workflow, prompt: String) -> Run {
24+ pub fn new(wf: Workflow, prompt: String) -> Run {
2225 let n = wf.tasks.len();
2326 let machine = Machine::new(wf.tasks.iter().map(|t| t.step).collect());
2427 Run {
@@ -30,6 +33,8 @@ impl Run {
3033 started: vec![None; n],
3134 ended: vec![None; n],
3235 evidence: vec![vec![]; n],
36+ prompts: vec![None; n],
37+ summaries: vec![None; n],
3338 view: 0,
3439 }
3540 }
@@ -70,8 +75,20 @@ impl App {
7075 .as_ref()
7176 .map(|w| w.read_prompt(stem))
7277 .unwrap_or_default();
73- self.runs.retain(|r| r.wf.prompt != stem);
74- self.runs.push(Run::new(wf, prompt));
78+ let saved = self
79+ .ws
80+ .as_ref()
81+ .map(|w| w.resolve(&Workspace::run_dir(stem, wf.version)))
82+ .and_then(|d| record::load(&d));
83+ let keep = self
84+ .runs
85+ .iter()
86+ .any(|r| r.wf.prompt == stem && r.wf.version == wf.version);
87+ if !keep {
88+ self.runs.retain(|r| r.wf.prompt != stem);
89+ self.runs
90+ .push(saved.unwrap_or_else(|| Run::new(wf, prompt)));
91+ }
7592 }
7693 self.open(Tab::Run(stem.into()));
7794 }
@@ -98,7 +115,9 @@ impl App {
98115 }
99116
100117 pub fn pump(&mut self, ri: usize) {
101- let Some(port) = self.vm.port() else { return };
118+ let Some(port) = self.vm.port() else {
119+ return self.save_run(ri);
120+ };
102121 let started = self.runs[ri].machine.next();
103122 for i in started {
104123 let r = &self.runs[ri];
@@ -111,7 +130,7 @@ impl App {
111130 job::Spec {
112131 agent,
113132 model: self.cfg.model(),
114- prompt,
133+ prompt: prompt.clone(),
115134 },
116135 );
117136 self.jobs.insert(id, JobKind::Task(r.wf.prompt.clone(), i));
@@ -120,6 +139,8 @@ impl App {
120139 r.jobs[i] = Some(id);
121140 r.started[i] = Some(now);
122141 r.ended[i] = None;
142+ r.prompts[i] = Some(prompt);
143+ r.summaries[i] = None;
123144 r.logs[i].push(format!(
124145 "▶ {} started on {}",
125146 r.wf.tasks[i].id,
@@ -127,6 +148,21 @@ impl App {
127148 ));
128149 r.view = i;
129150 }
151+ self.save_run(ri);
152+ }
153+
154+ fn save_run(&mut self, ri: usize) {
155+ let r = &self.runs[ri];
156+ let Some(dir) = self
157+ .ws
158+ .as_ref()
159+ .map(|w| w.resolve(&Workspace::run_dir(&r.wf.prompt, r.wf.version)))
160+ else {
161+ return;
162+ };
163+ if let Err(e) = record::save(&dir, r) {
164+ self.fail(format!("could not save the run: {e}"));
165+ }
130166 }
131167
132168 pub fn task_done(&mut self, stem: &str, i: usize, result: Result<String, String>) {
@@ -146,6 +182,7 @@ impl App {
146182 Ok(_) => r.logs[i].push(format!("✓ {} done", r.wf.tasks[i].id)),
147183 Err(e) => r.logs[i].push(format!("✕ {e}")),
148184 }
185+ r.summaries[i] = result.ok();
149186 r.evidence[i] = dir
150187 .and_then(|d| std::fs::read_dir(d).ok())
151188 .into_iter()
@@ -5,6 +5,7 @@ use crate::paths;
55 use crate::ui::theme::{self, pal};
66 use crate::ui::widgets::{Kind, bar, btn, chip_btn, lbl, mono, stat};
77 use crate::workflow::dag::{self, Look};
8+use crate::workflow::details;
89 use rune::{El, col, row, text};
910
1011 fn phase_label(p: Phase) -> (&'static str, rune::Color) {
@@ -105,6 +106,17 @@ pub fn view(s: &App, stem: &str) -> El {
105106 .child(stats)
106107 .child(bar(pct, p.accent))
107108 .child(graph)
109+ .child(
110+ col()
111+ .key("run-task")
112+ .max_h(260.0)
113+ .padding(16.0)
114+ .border_sides([1.0, 0.0, 0.0, 0.0], p.border)
115+ .scroll(rune::ScrollSpec {
116+ stick_bottom: false,
117+ })
118+ .child(details::view(&r.wf, r.view, rune::el())),
119+ )
108120 .child(terminal(s, r, stem))
109121 }
110122
@@ -113,8 +113,9 @@ pub fn hd(left: &str, right: &str) -> El {
113113 .px(12.0)
114114 .pt(10.0)
115115 .pb(4.0)
116+ .gap(8.0)
116117 .justify_between()
117- .child(lbl(left).color(pal().faint))
118+ .child(lbl(left).color(pal().faint).truncate().min_w(0.0))
118119 .child(lbl(right).color(pal().faint))
119120 }
120121
@@ -1,4 +1,5 @@
11 use crate::config::{CLAUDE_ENV, Config, OPENCODE_ENV};
2+use crate::vm::ssh;
23
34 pub fn render(cfg: &Config) -> String {
45 let mut out = String::from(
@@ -9,7 +10,7 @@ pub fn render(cfg: &Config) -> String {
910 (OPENCODE_ENV, cfg.opencode_key()),
1011 ] {
1112 if let Some(s) = secret {
12- out += &format!("export {name}='{}'\n", s.value.replace('\'', "'\\''"));
13+ out += &format!("export {name}={}\n", ssh::quote(&s.value));
1314 }
1415 }
1516 out
@@ -0,0 +1,18 @@
1+use crate::vm::ssh;
2+use std::process::Command;
3+
4+fn host(key: &str) -> Option<String> {
5+ let out = Command::new("git")
6+ .args(["config", "--get", key])
7+ .output()
8+ .ok()?;
9+ let value = String::from_utf8_lossy(&out.stdout).trim().to_string();
10+ (out.status.success() && !value.is_empty()).then_some(value)
11+}
12+
13+pub fn identity() -> String {
14+ ["user.name", "user.email"]
15+ .iter()
16+ .filter_map(|k| host(k).map(|v| format!("git config --global {k} {}\n", ssh::quote(&v))))
17+ .collect()
18+}
@@ -2,6 +2,7 @@ pub mod bake;
22 mod download;
33 pub mod env;
44 pub mod files;
5+mod git;
56 mod qemu;
67 mod seed;
78 pub mod ssh;
@@ -57,10 +58,12 @@ pub fn boot(bus: &Bus, dir: &Path, state: &Path) -> std::io::Result<Machine> {
5758 .stderr(Stdio::null())
5859 .spawn()?;
5960 let bus = bus.clone();
61+ let identity = git::identity();
6062 std::thread::spawn(move || {
6163 let start = Instant::now();
6264 while start.elapsed() < Duration::from_secs(180) {
6365 if ssh::run(port, "mountpoint -q /work && mountpoint -q /cast") {
66+ ssh::run(port, &identity);
6467 return bus.send(Event::Vm(Ok(port)));
6568 }
6669 std::thread::sleep(Duration::from_secs(2));
@@ -33,8 +33,20 @@ pub fn spawn(port: u16, script: &str) -> std::io::Result<Child> {
3333 Ok(child)
3434 }
3535
36+pub fn quote(s: &str) -> String {
37+ format!("'{}'", s.replace('\'', "'\\''"))
38+}
39+
3640 pub fn run(port: u16, script: &str) -> bool {
3741 spawn(port, script)
3842 .and_then(|c| c.wait_with_output())
3943 .is_ok_and(|o| o.status.success())
4044 }
45+
46+#[cfg(test)]
47+mod tests {
48+ #[test]
49+ fn quote_survives_single_quotes() {
50+ assert_eq!(super::quote("O'Neil"), r"'O'\''Neil'");
51+ }
52+}
@@ -20,11 +20,15 @@ impl App {
2020 let Some(text) = self.ws.as_ref().map(|w| w.read_prompt(stem)) else {
2121 return;
2222 };
23+ let prior = feedback.and_then(|f| self.review(stem).map(|r| (r.wf.clone(), f)));
24+ let prompt = prompts::workflow(&text, prior.as_ref().map(|(w, f)| (w, f.as_str())));
25+ self.plan(port, stem, prompt, JobKind::Generate(stem.into()));
26+ }
27+
28+ fn plan(&mut self, port: u16, stem: &str, prompt: String, kind: JobKind) {
2329 let agent = self
2430 .editor(stem)
2531 .map_or(self.cfg.default_agent, |e| e.agent);
26- let prior = feedback.and_then(|f| self.review(stem).map(|r| (r.wf.clone(), f)));
27- let prompt = prompts::workflow(&text, prior.as_ref().map(|(w, f)| (w, f.as_str())));
2832 let id = job::spawn(
2933 &self.bus,
3034 port,
@@ -34,7 +38,7 @@ impl App {
3438 prompt,
3539 },
3640 );
37- self.jobs.insert(id, JobKind::Generate(stem.into()));
41+ self.jobs.insert(id, kind);
3842 if let Some(e) = self.editor_mut(stem) {
3943 e.generating = Some(id);
4044 e.activity.clear();
@@ -66,17 +70,53 @@ impl App {
6670 return;
6771 };
6872 let version = store::versions(&dir, stem).last().map_or(1, |v| v + 1);
69- match result.and_then(|answer| Workflow::parse(stem, version, &answer)) {
70- Ok(wf) => {
71- if let Err(e) = store::save(&dir, &wf) {
72- return self.fail(e.to_string());
73- }
74- self.show_review(wf);
73+ let draft = match result.and_then(|answer| Workflow::parse(stem, version, &answer)) {
74+ Ok(draft) => draft,
75+ Err(e) => return self.fail(e),
76+ };
77+ let text = self.ws.as_ref().map(|w| w.read_prompt(stem));
78+ match (self.port(), text) {
79+ (Some(port), Some(text)) => {
80+ let prompt = prompts::check(&text, &draft);
81+ self.plan(port, stem, prompt, JobKind::Check(stem.into(), draft));
82+ self.activity(stem, "checking the draft with a fresh agent".into());
7583 }
76- Err(e) => self.fail(e),
84+ _ => self.keep(draft),
7785 }
7886 }
7987
88+ pub fn checked(&mut self, stem: &str, draft: Workflow, result: Result<String, String>) {
89+ if let Some(e) = self.editor_mut(stem) {
90+ e.generating = None;
91+ }
92+ if let Some(r) = self.review_mut(stem) {
93+ r.job = None;
94+ }
95+ let mut wf = result
96+ .and_then(|answer| Workflow::parse(stem, draft.version, &answer))
97+ .unwrap_or_else(|e| Workflow {
98+ notes: vec![format!(
99+ "The check pass failed, so this is the unchecked draft: {e}"
100+ )],
101+ ..draft
102+ });
103+ if wf.notes.is_empty() {
104+ wf.notes
105+ .push("No changes: the draft was ready to run.".into());
106+ }
107+ self.keep(wf);
108+ }
109+
110+ fn keep(&mut self, wf: Workflow) {
111+ let Some(dir) = self.ws.as_ref().map(|w| w.state.clone()) else {
112+ return;
113+ };
114+ if let Err(e) = store::save(&dir, &wf) {
115+ return self.fail(e.to_string());
116+ }
117+ self.show_review(wf);
118+ }
119+
80120 pub fn open_review(&mut self, stem: &str, version: u32) {
81121 let Some(dir) = self.ws.as_ref().map(|w| w.state.clone()) else {
82122 return;
@@ -149,6 +189,10 @@ impl App {
149189 };
150190 r.wf.approved = true;
151191 self.save_review(stem);
192+ let task = Tab::Task(stem.into());
193+ if let Some(i) = self.tabs.iter().position(|t| *t == task) {
194+ self.close(i);
195+ }
152196 if let Some(ws) = self.ws.as_mut() {
153197 ws.rescan();
154198 }
@@ -162,12 +206,15 @@ impl App {
162206 }
163207
164208 pub fn edit_task(&mut self, stem: &str, i: usize) {
209+ if self.review(stem).is_none_or(|r| r.wf.approved) {
210+ return;
211+ }
165212 self.select_task(stem, i);
166213 self.open(Tab::Task(stem.into()));
167214 }
168215
169216 pub fn add_task(&mut self, stem: &str) {
170- let Some(r) = self.review_mut(stem) else {
217+ let Some(r) = self.review_mut(stem).filter(|r| !r.wf.approved) else {
171218 return;
172219 };
173220 let step = r.wf.steps().last().map_or(1, |s| s + 1);
@@ -0,0 +1,67 @@
1+use crate::ui::theme::{self, pal};
2+use crate::ui::widgets::{lbl, mono};
3+use crate::workflow::model::Workflow;
4+use crate::workflow::review::relations;
5+use rune::{El, col, row, text};
6+
7+pub fn view(wf: &Workflow, i: usize, right: El) -> El {
8+ let p = pal();
9+ let t = &wf.tasks[i];
10+ let (after, with, _) = relations(wf, t);
11+ let mut meta = format!("STEP {}", t.step);
12+ if !with.is_empty() {
13+ meta += &format!(" · ∥ {}", with.join(" "));
14+ }
15+ if !after.is_empty() {
16+ meta += &format!(" · AFTER {}", after.join(" "));
17+ }
18+ let head = row()
19+ .gap(12.0)
20+ .center_y()
21+ .child(text(t.id.clone()).font(theme::BIG).color(p.accent))
22+ .child(
23+ col()
24+ .child(
25+ text(t.title.clone())
26+ .font(theme::TITLE)
27+ .color(p.white)
28+ .selectable(true),
29+ )
30+ .child(mono(meta, p.muted)),
31+ );
32+ col()
33+ .gap(12.0)
34+ .child(row().justify_between().center_y().child(head).child(right))
35+ .child(
36+ row()
37+ .gap(24.0)
38+ .items_start()
39+ .child(section("Decisions", &t.decisions, "◆", p.accent))
40+ .child(section("Acceptance", &t.acceptance, "☐", p.muted))
41+ .child(section("Evidence", &t.evidence, "⎘", p.muted)),
42+ )
43+}
44+
45+fn section(title: &str, items: &[String], glyph: &str, color: rune::Color) -> El {
46+ let p = pal();
47+ col()
48+ .grow(1.0)
49+ .min_w(0.0)
50+ .gap(2.0)
51+ .selection_group(true)
52+ .child(lbl(&format!("{title} · {}", items.len())).mb(4.0))
53+ .children(items.iter().map(|x| {
54+ row()
55+ .gap(6.0)
56+ .child(text(glyph).font(theme::MONO_SM).color(color))
57+ .child(
58+ text(x.clone())
59+ .font(theme::UI)
60+ .color(p.text)
61+ .wrap()
62+ .selectable(true)
63+ .grow(1.0)
64+ .min_w(0.0),
65+ )
66+ }))
67+}
@@ -1,5 +1,6 @@
11 pub mod actions;
22 pub mod dag;
3+pub mod details;
34 pub mod model;
45 pub mod review;
56 pub mod steps;
@@ -21,11 +21,15 @@ pub struct Workflow {
2121 pub version: u32,
2222 pub approved: bool,
2323 pub tasks: Vec<Task>,
24+ #[serde(skip_serializing_if = "Vec::is_empty")]
25+ pub notes: Vec<String>,
2426 }
2527
2628 #[derive(Deserialize)]
2729 struct Answer {
2830 tasks: Vec<Task>,
31+ #[serde(default)]
32+ changes: Vec<String>,
2933 }
3034
3135 impl Workflow {
@@ -35,9 +39,8 @@ impl Workflow {
3539 (Some(a), Some(b)) if a < b => &answer[a..=b],
3640 _ => return Err("the agent's answer had no JSON workflow".into()),
3741 };
38- let tasks = serde_json::from_str::<Answer>(json)
39- .map_err(|e| format!("bad workflow JSON: {e}"))?
40- .tasks;
42+ let Answer { tasks, changes } =
43+ serde_json::from_str(json).map_err(|e| format!("bad workflow JSON: {e}"))?;
4144 if tasks.is_empty() {
4245 return Err("the agent returned no tasks".into());
4346 }
@@ -46,6 +49,7 @@ impl Workflow {
4649 version,
4750 approved: false,
4851 tasks,
52+ notes: changes,
4953 };
5054 wf.normalize();
5155 Ok(wf)
@@ -126,6 +130,17 @@ mod tests {
126130 }
127131 }
128132
133+ #[test]
134+ fn parse_keeps_the_review_pass_changes_as_notes() {
135+ let w = Workflow::parse(
136+ "p",
137+ 1,
138+ r#"{"tasks":[{"id":"T1","step":1}],"changes":["moved T2 to step 2"]}"#,
139+ )
140+ .unwrap();
141+ assert_eq!(w.notes, vec!["moved T2 to step 2"]);
142+ }
143+
129144 #[test]
130145 fn parse_finds_json_inside_prose() {
131146 let w = Workflow::parse(
@@ -2,6 +2,7 @@ use crate::app::App;
22 use crate::ui::theme::{self, pal};
33 use crate::ui::widgets::{Kind, btn, chip, input, lbl, mono, stat};
44 use crate::workflow::dag::{self, Look};
5+use crate::workflow::details;
56 use crate::workflow::model::{Task, Workflow};
67 use crate::workflow::task_form::TaskForm;
78 use rune::{El, TextEdit, col, row, text};
@@ -53,30 +54,6 @@ pub fn relations(wf: &Workflow, t: &Task) -> (Vec<String>, Vec<String>, Vec<Stri
5354 (ids(t.step.saturating_sub(1)), ids(t.step), ids(t.step + 1))
5455 }
5556
56-fn section(title: &str, items: &[String], glyph: &str, color: rune::Color) -> El {
57- let p = pal();
58- col()
59- .grow(1.0)
60- .min_w(0.0)
61- .gap(2.0)
62- .selection_group(true)
63- .child(lbl(&format!("{title} · {}", items.len())).mb(4.0))
64- .children(items.iter().map(|x| {
65- row()
66- .gap(6.0)
67- .child(text(glyph).font(theme::MONO_SM).color(color))
68- .child(
69- text(x.clone())
70- .font(theme::UI)
71- .color(p.text)
72- .wrap()
73- .selectable(true)
74- .grow(1.0)
75- .min_w(0.0),
76- )
77- }))
78-}
79-
8057 pub fn view(s: &App, stem: &str, k: &Kit) -> El {
8158 let p = pal();
8259 let Some(r) = s.review(stem) else {
@@ -140,72 +117,35 @@ pub fn view(s: &App, stem: &str, k: &Kit) -> El {
140117 },
141118 move |s: &mut App, i| s.select_task(&st, i),
142119 ));
143- let t = &wf.tasks[r.selected];
144- let (after, with, _) = relations(wf, t);
145- let mut meta = format!("STEP {}", t.step);
146- if !with.is_empty() {
147- meta += &format!(" · ∥ {}", with.join(" "));
148- }
149- if !after.is_empty() {
150- meta += &format!(" · AFTER {}", after.join(" "));
151- }
152120 let (st, sel) = (stem.to_string(), r.selected);
153- let agent = t.agent.unwrap_or(s.cfg.default_agent);
154- let detail = col()
121+ let agent = wf.tasks[sel].agent.unwrap_or(s.cfg.default_agent);
122+ let mut right = row().gap(8.0).center_y().child(chip(
123+ row()
124+ .child(mono("AGENT: ", p.text))
125+ .child(mono(agent.label(), p.blue)),
126+ ));
127+ if !wf.approved {
128+ right = right.child(
129+ btn(
130+ "Edit ✎",
131+ Kind::Normal,
132+ Some(move |s: &mut App| s.edit_task(&st, sel)),
133+ )
134+ .key("edit-task"),
135+ );
136+ }
137+ let mut detail = col()
155138 .grow(1.0)
156139 .min_h(0.0)
157140 .padding(16.0)
158141 .gap(12.0)
159142 .scroll(rune::ScrollSpec {
160143 stick_bottom: false,
161- })
162- .child(
163- row()
164- .justify_between()
165- .center_y()
166- .child(
167- row()
168- .gap(12.0)
169- .center_y()
170- .child(text(t.id.clone()).font(theme::BIG).color(p.accent))
171- .child(
172- col()
173- .child(
174- text(t.title.clone())
175- .font(theme::TITLE)
176- .color(p.white)
177- .selectable(true),
178- )
179- .child(mono(meta, p.muted)),
180- ),
181- )
182- .child(
183- row()
184- .gap(8.0)
185- .center_y()
186- .child(chip(
187- row()
188- .child(mono("AGENT: ", p.text))
189- .child(mono(agent.label(), p.blue)),
190- ))
191- .child(
192- btn(
193- "Edit ✎",
194- Kind::Normal,
195- Some(move |s: &mut App| s.edit_task(&st, sel)),
196- )
197- .key("edit-task"),
198- ),
199- ),
200- )
201- .child(
202- row()
203- .gap(24.0)
204- .items_start()
205- .child(section("Decisions", &t.decisions, "◆", p.accent))
206- .child(section("Acceptance", &t.acceptance, "☐", p.muted))
207- .child(section("Evidence", &t.evidence, "⎘", p.muted)),
208- );
144+ });
145+ if !wf.notes.is_empty() {
146+ detail = detail.child(notes(&wf.notes));
147+ }
148+ let detail = detail.child(details::view(wf, sel, right));
209149 view_with_footer(
210150 s,
211151 stem,
@@ -219,6 +159,25 @@ pub fn view(s: &App, stem: &str, k: &Kit) -> El {
219159 )
220160 }
221161
162+fn notes(notes: &[String]) -> El {
163+ let p = pal();
164+ col()
165+ .gap(4.0)
166+ .padding(10.0)
167+ .fill(p.panel)
168+ .border(1.0, p.border)
169+ .radius(4.0)
170+ .selection_group(true)
171+ .child(lbl("Review pass").color(p.accent))
172+ .children(notes.iter().map(|n| {
173+ text(format!("· {n}"))
174+ .font(theme::UI)
175+ .color(p.text)
176+ .wrap()
177+ .selectable(true)
178+ }))
179+}
180+
222181 fn view_with_footer(s: &App, stem: &str, k: &Kit, body: El) -> El {
223182 let p = pal();
224183 let Some(r) = s.review(stem) else { return body };
@@ -228,9 +187,14 @@ fn view_with_footer(s: &App, stem: &str, k: &Kit, body: El) -> El {
228187 };
229188 let st = stem.to_string();
230189 let busy = r.job.is_some();
190+ let approved = r.wf.approved;
231191 let feedback = input(
232192 &r.feedback,
233- "FEEDBACK › tell the agent how to change this workflow",
193+ if approved {
194+ "FEEDBACK › approved and read-only; refining makes a new version"
195+ } else {
196+ "FEEDBACK › tell the agent how to change this workflow"
197+ },
234198 move |s: &mut App| match s.reviews.iter().position(|r| r.wf.prompt == st) {
235199 Some(i) => &mut s.reviews[i].feedback,
236200 None => s.scratch(),
@@ -277,7 +241,7 @@ fn view_with_footer(s: &App, stem: &str, k: &Kit, body: El) -> El {
277241 .child(btn(
278242 "Discard",
279243 Kind::Danger,
280- (!busy).then_some(at(|s, k| s.discard(k))),
244+ (!busy && !approved).then_some(at(|s, k| s.discard(k))),
281245 ))
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.