Add the desktop app loop driver with commit, notify, report and tools modules, and update the quit prompt, task dialog and meter

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-02 12:00:10 -08:00
1 parent 8db8df5791
commit 1f80fa6a7c
24 files changed
+9850 -64

No files matched your search

@@ -29,6 +29,12 @@ pub enum AgentState {
/// manager: it runs with the manager's state locked.
pub type BeforeFresh = Arc<dyn Fn() -> Option<String> + Send + Sync>;
/// Runs when the Implementation Loop starts a phase's fresh agent: the app
/// forgets the console session it was showing, so the new agent's `open`
/// makes a session of its own. Like `BeforeFresh`, it must not call back into
/// the manager.
pub type ForgetSession = Arc<dyn Fn() + Send + Sync>;
/// What the page needs to draw the bar. `generation` counts the agents started
/// so far: a new number means a fresh agent, so the terminal clears.
#[derive(Clone, Debug, Serialize)]
@@ -101,6 +107,7 @@ struct Shared {
folder: PathBuf,
sink: Sink,
before_fresh: Mutex<Option<BeforeFresh>>,
forget_session: Mutex<Option<ForgetSession>>,
/// Environment every agent this manager starts gets, on top of its own:
/// the in-app signal that sends the agent's console pages to this window.
extra_env: Mutex<Vec<(String, String)>>,
@@ -128,6 +135,7 @@ impl AgentManager {
folder,
sink,
before_fresh: Mutex::new(None),
forget_session: Mutex::new(None),
extra_env: Mutex::new(Vec::new()),
generation: AtomicU64::new(0),
inner: Mutex::new(Inner {
@@ -153,6 +161,20 @@ impl AgentManager {
}
}
/// Run `hook` whenever the loop starts a phase's fresh agent (`start_fresh`
/// and `forget_session`).
pub fn set_forget_session(&self, hook: ForgetSession) {
if let Ok(mut slot) = self.shared.forget_session.lock() {
*slot = Some(hook);
}
}
/// Make the app forget the console session it follows, so the next agent's
/// `open` starts a new one.
pub fn forget_session(&self) {
self.shared.forget();
}
/// Give every agent started from now on these variables (replacing any set before).
pub fn set_env(&self, env: Vec<(String, String)>) {
if let Ok(mut slot) = self.shared.extra_env.lock() {
@@ -197,6 +219,54 @@ impl AgentManager {
}
}
/// Start a fresh agent on the stored launch choice with `prompt` as its
/// only first prompt: the Implementation Loop's way to begin a phase. A
/// running agent is killed first (the same path as Restart), but without
/// Restart's brief note; the app still forgets the console session, so
/// the new agent's `open` makes a new one. An agent that ended, or never
/// ran, starts directly. Needs a launch choice from an earlier start.
pub fn start_fresh(&self, prompt: String) -> Result<(), String> {
let mut inner = lock(&self.shared.inner);
let (choice, _) = inner
.last_start
.clone()
.ok_or("no agent has been started")?;
inner.brief_note = None;
inner.last_start = Some((choice, Some(prompt)));
self.shared.forget();
if inner.state == AgentState::Running {
self.shared.generation.fetch_add(1, Ordering::SeqCst);
if let Some(old) = inner.running.take() {
let _ = old.host.kill();
}
}
match self.shared.spawn(&mut inner) {
Ok(()) => Ok(()),
Err(e) => {
inner.state = AgentState::Ended {
reason: format!("could not start the agent: {e}"),
};
self.shared.emit(&inner);
Err(e)
}
}
}
/// The stored launch choice: agent, model, effort and permission mode.
pub fn launch_choice(&self) -> Option<(Agent, Option<String>, Option<String>, PermissionMode)> {
lock(&self.shared.inner)
.last_start
.as_ref()
.map(|(choice, _)| {
(
choice.kind.clone(),
choice.model.clone(),
choice.effort.clone(),
choice.mode,
)
})
}
pub fn snapshot(&self) -> AgentSnapshot {
self.shared.snapshot(&lock(&self.shared.inner))
}
@@ -296,6 +366,17 @@ impl Shared {
}
}
fn forget(&self) {
let hook = self
.forget_session
.lock()
.ok()
.and_then(|slot| slot.clone());
if let Some(run) = hook {
run();
}
}
fn emit(&self, inner: &Inner) {
(self.sink)(AgentEvent::State(self.snapshot(inner)));
}
@@ -243,7 +243,7 @@ impl ConsoleSupervisor {
if !session.embed {
// Do not leave an old console running that the frame cannot show.
let _ = node_command(console_dir)
.args(["stop", "--session", &session.sid])
.args(stop_args(&session.sid))
.current_dir(project_dir)
.output();
return Err(OLD_CONSOLE.to_string());
@@ -327,13 +327,15 @@ impl ConsoleSupervisor {
Ok(true)
}
/// `console.mjs stop --session <sid>`: the console's own orderly shutdown.
/// `console.mjs stop --session <sid> --force`: the console's own orderly
/// shutdown. `--force` because the app's shutdown is not the agent's ending:
/// the session may be unfinished, and `stop` refuses a session with no finish.
pub fn stop(&mut self) -> Result<(), String> {
if self.stopped {
return Ok(());
}
let output = node_command(&self.console_dir)
.args(["stop", "--session", &self.session.sid])
.args(stop_args(&self.session.sid))
.current_dir(&self.project_dir)
.output()
.map_err(err)?;
@@ -382,10 +384,25 @@ impl Drop for ConsoleSupervisor {
}
}
/// The arguments of the app's own `stop`: always `--force`, since the app's
/// shutdown is not the agent's ending and `stop` refuses a session with no finish.
fn stop_args(sid: &str) -> [&str; 4] {
["stop", "--session", sid, "--force"]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_apps_stop_calls_pass_force() {
let args = stop_args("20261101-120000-abcdef");
assert_eq!(
args,
["stop", "--session", "20261101-120000-abcdef", "--force"]
);
}
#[test]
fn splits_the_session_url() {
let (host, port, path) = split_url("http://127.0.0.1:51617/s/abc/").unwrap();
+5
View File
@@ -7,6 +7,11 @@ pub mod attention;
pub mod brief;
pub mod console_supervisor;
pub mod handoff;
pub mod loop_commit;
pub mod loop_driver;
pub mod loop_notify;
pub mod loop_report;
pub mod loop_tools;
pub mod node_check;
pub mod project;
pub mod pty_host;
+861
View File
@@ -0,0 +1,861 @@
//! The commit step of the Implementation Loop: its order, and nothing else.
//!
//! A passed phase goes through five calls, in this order: `prepare` (everything
//! that can fail, before any file is touched), `stage_and_check` (stage, then
//! refuse a secret or an oversized file), `mark` (save the files, mark the
//! phase done, write the approval line), `commit` (stage the marked files and
//! commit) and, when the commit fails, `undo` (put the saved text back). The
//! driver decides what to say and where to stop; this module only does the work
//! and names the failure.
use std::path::{Path, PathBuf};
use std::time::Duration;
use serde_json::Value;
use crate::loop_driver::{with_approval_line, write_atomic};
use crate::loop_report::LoopReport;
use crate::loop_tools;
/// What `prepare` settled before any file was touched.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Prepared {
pub message: String,
pub phase_file: PathBuf,
}
/// The phase file named by a row of `specs.mjs status`, as a path under
/// `<project>/<spec>/`. Refuses a name that is missing, empty, climbs out of
/// the folder (`..`, a separator, a drive letter) or does not exist.
pub fn phase_file(project: &Path, spec: &str, entry: &Value) -> Result<PathBuf, String> {
let file = entry["file"].as_str().unwrap_or("").trim();
if file.is_empty() {
return Err("the spec names no phase file for this phase".to_string());
}
let unsafe_name = file.contains("..")
|| file.contains('/')
|| file.contains('\\')
|| file.contains('\0')
|| file.chars().nth(1) == Some(':');
if unsafe_name {
return Err(format!(
"the phase file name {file} is not a plain file name"
));
}
let path = project.join(spec).join(file);
if !path.is_file() {
return Err(format!("the phase file {file} does not exist in {spec}"));
}
Ok(path)
}
/// Everything that can fail before a file changes: the commit message and the
/// phase file. Nothing is written.
pub fn prepare(
project: &Path,
spec: &str,
entry: &Value,
subject: &str,
) -> Result<Prepared, String> {
let phase_file = phase_file(project, spec, entry)?;
let message = loop_tools::commit_message(project, subject)
.map_err(|e| format!("the commit message was refused: {e}"))?;
Ok(Prepared {
message,
phase_file,
})
}
/// The text of the two files `specs.mjs mark` changes, before and after the
/// loop wrote them.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Marked {
/// The phase file before the mark, and as the loop left it.
pub saved: String,
pub written: String,
/// The same for `overview.md`, whose checkbox the mark flips.
pub overview: PathBuf,
pub overview_saved: String,
pub overview_written: String,
}
fn read(file: &Path) -> Result<String, String> {
std::fs::read_to_string(file).map_err(|e| format!("{} could not be read ({e})", file.display()))
}
/// Why `mark` failed, and whether the files could be put back. When they could
/// not, the phase may be left marked done and the driver must say so.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MarkFailure {
pub message: String,
pub put_back_failed: bool,
}
/// Mark the phase done and write the approval line, keeping the text of both
/// files so `undo` can take it back. On any failure both files are put back
/// before the error is returned.
pub fn mark(
prepared: &Prepared,
project: &Path,
spec: &str,
phase: u32,
approval: &str,
) -> Result<Marked, MarkFailure> {
let plain = |message: String| MarkFailure {
message,
put_back_failed: false,
};
let overview = project.join(spec).join("overview.md");
let saved = read(&prepared.phase_file).map_err(plain)?;
let overview_saved = read(&overview).map_err(plain)?;
let fail = |message: String| {
let phase_back = write_atomic(&prepared.phase_file, &saved);
let overview_back = write_atomic(&overview, &overview_saved);
MarkFailure {
put_back_failed: phase_back.is_err() || overview_back.is_err(),
message,
}
};
let run = loop_tools::specs_mark_done(project, spec, phase);
if !run.ok {
return Err(fail(run.output.trim().to_string()));
}
let written = read(&prepared.phase_file)
.map(|text| with_approval_line(&text, approval))
.and_then(|text| {
write_atomic(&prepared.phase_file, &text)
.map(|()| text)
.map_err(|e| format!("the approval line could not be written ({e})"))
})
.map_err(&fail)?;
let overview_written = read(&overview).map_err(&fail)?;
Ok(Marked {
saved,
written,
overview,
overview_saved,
overview_written,
})
}
/// Take the mark back: both files get their saved text again, but only while
/// both still hold what the loop wrote, so an edit the person made in between
/// is never overwritten. Nothing is written unless both can be restored, so the
/// mark is either fully off or fully on; the error names each file that could
/// not be.
pub fn undo(prepared: &Prepared, marked: &Marked) -> Result<(), String> {
let files = [
(&prepared.phase_file, &marked.saved, &marked.written),
(
&marked.overview,
&marked.overview_saved,
&marked.overview_written,
),
];
let name = |file: &Path| {
file.file_name()
.map_or_else(String::new, |n| n.to_string_lossy().into_owned())
};
let changed: Vec<String> = files
.iter()
.filter(|(file, _, written)| std::fs::read_to_string(file).ok().as_ref() != Some(*written))
.map(|(file, _, _)| name(file))
.collect();
if !changed.is_empty() {
return Err(format!(
"{} changed since the loop wrote it, so it was not restored",
changed.join(" and ")
));
}
for (file, saved, _) in files {
write_atomic(file, saved)
.map_err(|e| format!("{} could not be restored ({e})", name(file)))?;
}
Ok(())
}
/// Which call failed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stage {
Add,
Commit,
}
/// A failed `git add` or `git commit`, with what it printed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommitFailure {
pub stage: Stage,
pub first_line: String,
pub output: String,
}
/// The first non-empty line of `output`, trimmed, at most 160 characters.
pub fn first_line(output: &str) -> String {
let line = output
.lines()
.map(str::trim)
.find(|l| !l.is_empty())
.unwrap_or("");
if line.chars().count() > 160 {
let cut: String = line.chars().take(157).collect();
format!("{cut}...")
} else {
line.to_string()
}
}
/// The largest file the loop will commit.
pub const MAX_STAGED_BYTES: u64 = 5 * 1024 * 1024;
/// File-name suffixes of a key or certificate.
const SECRET_SUFFIXES: [&str; 5] = [".pem", ".key", ".p12", ".pfx", ".keystore"];
/// Names an `.env` file may carry and still be committed: a template.
const ENV_TEMPLATES: [&str; 3] = [".example", ".sample", ".template"];
/// Private-key files with no suffix.
const KEY_NAMES: [&str; 2] = ["id_rsa", "id_ed25519"];
/// Why a staged file must not be committed, or `None`. Only the file name is
/// read (the part after the last separator, any case), so a folder named `.env`
/// does not match and `environment.md` or `monkey.txt` does not either.
pub fn denied(path: &str) -> Option<&'static str> {
let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
let name = name.to_lowercase();
if name == ".env"
|| (name.starts_with(".env.") && !ENV_TEMPLATES.iter().any(|suffix| name.ends_with(suffix)))
{
return Some("an environment file");
}
if SECRET_SUFFIXES.iter().any(|suffix| name.ends_with(suffix)) {
return Some("a key or certificate");
}
if KEY_NAMES.contains(&name.as_str()) {
return Some("a private key");
}
if name == "credentials.json" || name.starts_with("secrets.") {
return Some("a credentials file");
}
if name.ends_with(".loop-tmp") {
return Some("a temporary file of the loop");
}
None
}
/// A staged file and its size on disk.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StagedFile {
pub path: String,
pub bytes: u64,
}
/// Whether the file is over `MAX_STAGED_BYTES`.
pub fn too_big(file: &StagedFile) -> bool {
file.bytes > MAX_STAGED_BYTES
}
/// Staged files the loop refuses to commit, by their names.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StagedProblem {
pub files: Vec<String>,
pub why: &'static str,
/// Set when the files could not be taken out of the index again: git's
/// first line. They are still staged.
pub left_staged: Option<String>,
}
/// Why `stage_and_check` stopped: `git add` itself failed, or the staged list
/// holds something that must not be committed (and was unstaged again).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StageError {
Add(CommitFailure),
Problem(StagedProblem),
}
/// Stage everything and look at the list before anything is marked. Any
/// secret-looking or oversized file takes everything out of the index again and
/// returns every offending path.
pub fn stage_and_check(project: &Path) -> Result<(), StageError> {
let added = loop_tools::git_add_all(project);
if !added.ok {
return Err(StageError::Add(CommitFailure {
stage: Stage::Add,
first_line: first_line(&added.output),
output: added.output,
}));
}
let staged = loop_tools::git_staged(project).map_err(|output| {
StageError::Add(CommitFailure {
stage: Stage::Add,
first_line: first_line(&output),
output,
})
})?;
// Staged names are relative to the repository's top folder.
let top = loop_tools::git_toplevel(project).unwrap_or_else(|| project.to_path_buf());
let mut secrets = false;
let mut big = false;
let mut files = Vec::new();
for path in staged {
// A deleted file is gone from the tree: it counts as 0 bytes.
let bytes = std::fs::symlink_metadata(top.join(&path)).map_or(0, |m| m.len());
let file = StagedFile { path, bytes };
let is_secret = denied(&file.path).is_some();
let is_big = too_big(&file);
if is_secret || is_big {
secrets |= is_secret;
big |= is_big;
files.push(file.path);
}
}
if files.is_empty() {
return Ok(());
}
let unstaged = loop_tools::git_unstage_all(project);
let left_staged = (!unstaged.ok).then(|| first_line(&unstaged.output));
let why = match (secrets, big) {
(true, true) => "look like secrets or are over 5 MB",
(true, false) => "look like secrets",
_ => "are over 5 MB",
};
Err(StageError::Problem(StagedProblem {
files,
why,
left_staged,
}))
}
/// Commit what `stage_and_check` staged, plus the two files the mark changed
/// since: the phase file and `overview.md`. The short hash of the new commit.
/// `limit` is the commit's own time limit, for a slow hook.
pub fn commit(
project: &Path,
prepared: &Prepared,
marked: &Marked,
limit: Duration,
) -> Result<Option<String>, CommitFailure> {
let added = loop_tools::git_add_paths(project, &[&prepared.phase_file, &marked.overview]);
if !added.ok {
return Err(CommitFailure {
stage: Stage::Add,
first_line: first_line(&added.output),
output: added.output,
});
}
let done = loop_tools::git_commit_with(project, &prepared.message, limit);
if !done.ok {
// A cut-off commit says so on its last line, after whatever a hook
// printed first; lead with that.
let cut_off = done
.output
.lines()
.last()
.filter(|line| line.starts_with("(stopped after"))
.map(|line| {
format!(
"the commit was {} (a hook ran too long)",
line.trim_matches(|c| c == '(' || c == ')')
)
});
return Err(CommitFailure {
stage: Stage::Commit,
first_line: cut_off.unwrap_or_else(|| first_line(&done.output)),
output: done.output,
});
}
Ok(loop_tools::git_head_short(project))
}
/// Take what a failed commit left staged out of the index, so a commit the
/// person makes by hand does not carry a mark the loop took back.
pub fn unstage(project: &Path) {
let _ = loop_tools::git_unstage_all(project);
}
/// The phases the spec shows done (`done`) that the commit log does not hold:
/// one the loop built whose recorded commit is gone from the history, and the
/// phase a failed undo left marked. A phase the loop never recorded is trusted
/// (the person built it).
pub fn marks_without_commits(
project: &Path,
_spec: &str,
done: &[u32],
report: &LoopReport,
) -> Vec<u32> {
let mut missing: Vec<u32> = report
.passed()
.iter()
.filter(|entry| done.contains(&entry.phase))
.filter(|entry| {
entry
.commit
.as_deref()
.is_some_and(|hash| !loop_tools::git_commit_exists(project, hash))
})
.map(|entry| entry.phase)
.collect();
if let Some(left) = &report.marked_not_committed {
if done.contains(&left.phase) && !missing.contains(&left.phase) {
missing.push(left.phase);
}
}
missing.sort_unstable();
missing
}
/// With commit on, the phases `status` shows done that have no commit behind
/// them (see `marks_without_commits`). With commit off a mark is trusted.
/// Reads only: nothing is written until the person has confirmed the Start.
pub fn unbacked_marks(
project: &Path,
spec: &str,
status: &Value,
report: &LoopReport,
commit: bool,
) -> Vec<u32> {
if !commit {
return Vec::new();
}
let done: Vec<u32> = status["phases"]
.as_array()
.map(|all| {
all.iter()
.filter(|p| p["marker"].as_str() == Some("x"))
.filter_map(|p| u32::try_from(p["number"].as_u64()?).ok())
.collect()
})
.unwrap_or_default();
marks_without_commits(project, spec, &done, report)
}
/// Open each of `phases` again through `specs.mjs`: `open` first, which also
/// sets a Complete phase file back to In Progress, then `in-progress`.
pub fn reopen(project: &Path, spec: &str, phases: &[u32]) -> Result<(), String> {
for &n in phases {
for to in ["open", "in-progress"] {
let run = loop_tools::specs_mark(project, spec, n, to);
if !run.ok {
return Err(format!(
"Phase {n} is marked done with no commit, and could not be opened again: {}",
first_line(&run.output)
));
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn temp_spec(name: &str) -> (PathBuf, PathBuf) {
let base = std::env::temp_dir().join(format!(
"plan2code-loop-commit-{name}-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&base);
let spec = base.join("specs/lunch");
std::fs::create_dir_all(&spec).unwrap();
(base, spec)
}
#[test]
fn the_first_line_skips_blanks_and_is_cut_at_160_characters() {
assert_eq!(first_line("\n \n lint says no \nsecond"), "lint says no");
assert_eq!(first_line(""), "");
let long = "x".repeat(300);
let line = first_line(&long);
assert_eq!(line.chars().count(), 160);
assert!(line.ends_with("..."));
assert_eq!(first_line(&"y".repeat(160)).chars().count(), 160);
}
#[test]
fn a_phase_file_must_be_a_plain_name_that_exists() {
let (base, spec) = temp_spec("names");
std::fs::write(spec.join("phase-2.md"), "x").unwrap();
std::fs::write(base.join("secret.md"), "x").unwrap();
let ok = phase_file(&base, "specs/lunch", &json!({ "file": "phase-2.md" }));
assert_eq!(ok.unwrap(), spec.join("phase-2.md"));
for (entry, word) in [
(json!({}), "no phase file"),
(json!({ "file": "" }), "no phase file"),
(json!({ "file": " " }), "no phase file"),
(json!({ "file": "../../secret.md" }), "plain file name"),
(json!({ "file": "sub/phase-2.md" }), "plain file name"),
(json!({ "file": "sub\\phase-2.md" }), "plain file name"),
(json!({ "file": "C:phase-2.md" }), "plain file name"),
(json!({ "file": "phase-9.md" }), "does not exist"),
] {
let err = phase_file(&base, "specs/lunch", &entry).unwrap_err();
assert!(err.contains(word), "{entry}: {err}");
}
}
const OVERVIEW: &str =
"# Lunch - Overview\n\n## Phase Checklist\n\n- [/] [Phase 2: P2](./phase-2.md)\n";
const PHASE: &str = "# Phase 2: P2\n\n**Status:** In Progress\n\n## Tasks\n\n- [x] **Task 2.1:** First\n\n## Phase Completion Summary\n\nBuilt it.\n";
fn marked_spec(name: &str) -> (PathBuf, Prepared) {
let (base, spec) = temp_spec(name);
std::fs::write(spec.join("overview.md"), OVERVIEW).unwrap();
std::fs::write(spec.join("phase-2.md"), PHASE).unwrap();
let prepared = Prepared {
message: "Add it\n\nAI Assisted".to_string(),
phase_file: spec.join("phase-2.md"),
};
(base, prepared)
}
fn node_ready() -> bool {
loop_tools::skill_script("specs.mjs").is_some()
&& std::process::Command::new("node")
.arg("--version")
.output()
.is_ok_and(|out| out.status.success())
}
#[test]
fn mark_writes_the_approval_line_and_undo_puts_both_files_back() {
if !node_ready() {
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
return;
}
let (base, prepared) = marked_spec("undo");
let marked = mark(&prepared, &base, "specs/lunch", 2, "Approved by the loop.").unwrap();
let overview = std::fs::read_to_string(&marked.overview).unwrap();
assert!(overview.contains("[x] [Phase 2"), "{overview}");
let phase = std::fs::read_to_string(&prepared.phase_file).unwrap();
assert!(phase.contains("Approved by the loop."), "{phase}");
assert_eq!(phase, marked.written);
undo(&prepared, &marked).unwrap();
assert_eq!(
std::fs::read_to_string(&prepared.phase_file).unwrap(),
PHASE
);
assert_eq!(std::fs::read_to_string(&marked.overview).unwrap(), OVERVIEW);
}
#[test]
fn undo_will_not_overwrite_an_edit_made_since_and_names_the_file() {
if !node_ready() {
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
return;
}
let (base, prepared) = marked_spec("edited");
let marked = mark(&prepared, &base, "specs/lunch", 2, "Approved.").unwrap();
let mut edited = marked.written.clone();
edited.push_str("\nMy own note.\n");
std::fs::write(&prepared.phase_file, &edited).unwrap();
let err = undo(&prepared, &marked).unwrap_err();
assert!(err.contains("phase-2.md"), "{err}");
assert!(!err.contains("overview.md"), "{err}");
assert_eq!(
std::fs::read_to_string(&prepared.phase_file).unwrap(),
edited,
"the edit stays"
);
assert_eq!(
std::fs::read_to_string(&marked.overview).unwrap(),
marked.overview_written,
"nothing is restored unless both files can be"
);
}
#[test]
fn prepare_refuses_an_unsafe_phase_file_before_anything_is_touched() {
let (base, prepared) = marked_spec("prepare");
for file in ["../../secret.md", "", "phase-9.md"] {
let err =
prepare(&base, "specs/lunch", &json!({ "file": file }), "Add it").unwrap_err();
assert!(!err.is_empty());
}
assert_eq!(
std::fs::read_to_string(&prepared.phase_file).unwrap(),
PHASE
);
let overview = base.join("specs/lunch/overview.md");
assert_eq!(std::fs::read_to_string(overview).unwrap(), OVERVIEW);
}
#[test]
fn marks_are_found_with_commit_on_and_reopened_only_when_asked() {
if !node_ready() {
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
return;
}
let (base, prepared) = marked_spec("reopen");
mark(&prepared, &base, "specs/lunch", 2, "Approved.").unwrap();
let status = loop_tools::specs_status(&base, "specs/lunch").unwrap();
assert_eq!(status["phases"][0]["marker"], "x");
let mut report = LoopReport::new("specs/lunch", "now");
report.marked_not_committed = Some(crate::loop_report::MarkedNotCommitted {
phase: 2,
file: "phase-2.md".into(),
});
// Commit off: a mark is trusted.
assert!(unbacked_marks(&base, "specs/lunch", &status, &report, false).is_empty());
// Commit on: the saved fact names the phase, and finding it writes nothing.
let found = unbacked_marks(&base, "specs/lunch", &status, &report, true);
assert_eq!(found, vec![2]);
let still = loop_tools::specs_status(&base, "specs/lunch").unwrap();
assert_eq!(still["phases"][0]["marker"], "x");
// Reopening sets the overview and the phase file's Status back.
reopen(&base, "specs/lunch", &found).unwrap();
let after = loop_tools::specs_status(&base, "specs/lunch").unwrap();
assert_eq!(after["phases"][0]["marker"], "/");
let phase = std::fs::read_to_string(&prepared.phase_file).unwrap();
assert!(phase.contains("**Status:** In Progress"), "{phase}");
}
#[test]
fn a_failed_mark_leaves_both_files_as_they_were() {
if !node_ready() {
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
return;
}
let (base, prepared) = marked_spec("failed-mark");
// Phase 9 is not in the overview, so the script refuses.
let err = mark(&prepared, &base, "specs/lunch", 9, "Approved.").unwrap_err();
assert!(!err.message.is_empty());
assert!(!err.put_back_failed);
assert_eq!(
std::fs::read_to_string(&prepared.phase_file).unwrap(),
PHASE
);
let overview = base.join("specs/lunch/overview.md");
assert_eq!(std::fs::read_to_string(overview).unwrap(), OVERVIEW);
}
#[test]
fn a_report_that_names_a_marked_phase_is_rebuilt_only_when_the_spec_shows_it_done() {
let (base, _) = temp_spec("marks");
let mut report = LoopReport::new("specs/lunch", "now");
report.marked_not_committed = Some(crate::loop_report::MarkedNotCommitted {
phase: 3,
file: "phase-3.md".into(),
});
assert_eq!(
marks_without_commits(&base, "specs/lunch", &[1, 3], &report),
vec![3]
);
assert!(marks_without_commits(&base, "specs/lunch", &[1], &report).is_empty());
}
fn git_in(repo: &Path, args: &[&str]) -> String {
let out = std::process::Command::new("git")
.args(args)
.current_dir(repo)
.output()
.expect("run git");
assert!(
out.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
fn git_ready() -> bool {
let found = std::process::Command::new("git")
.arg("--version")
.output()
.is_ok_and(|out| out.status.success());
if !found {
assert!(std::env::var_os("CI").is_none(), "git is not on PATH");
}
found
}
#[test]
fn secret_looking_names_are_denied_and_templates_are_not() {
for name in [
".env",
".env.local",
".env.production",
".ENV",
"a/b/.env",
"server.pem",
"tls.KEY",
"cert.p12",
"cert.pfx",
"release.keystore",
"id_rsa",
"home/.ssh/id_ed25519",
"credentials.json",
"config\\credentials.json",
"secrets.yml",
"Secrets.json",
"x/y.loop-tmp",
] {
assert!(denied(name).is_some(), "{name} should be denied");
}
for name in [
".env.example",
".env.production.example",
".env.local.sample",
".env.sample",
".env.template",
"app/.env.EXAMPLE",
"environment.md",
"monkey.txt",
"keyboard.rs",
"id_rsa.pub",
"my-credentials.json.md",
"secretsauce.md",
"src/.env/readme.md",
"tmp.loop-tmp.md",
] {
assert_eq!(denied(name), None, "{name} should be allowed");
}
}
#[test]
fn a_file_is_too_big_only_over_five_megabytes() {
let file = |bytes| StagedFile {
path: "a.bin".into(),
bytes,
};
assert!(!too_big(&file(0)));
assert!(!too_big(&file(MAX_STAGED_BYTES)));
assert!(too_big(&file(MAX_STAGED_BYTES + 1)));
}
fn init_repo(name: &str) -> PathBuf {
let (base, _) = temp_spec(name);
git_in(&base, &["init", "-q"]);
for (key, value) in [
("user.name", "Loop Test"),
("user.email", "loop@example.com"),
("commit.gpgsign", "false"),
("core.autocrlf", "false"),
("core.hooksPath", ".git/hooks"),
] {
git_in(&base, &["config", key, value]);
}
base
}
#[test]
fn staging_stops_on_every_secret_and_oversized_file_and_unstages_all() {
if !git_ready() {
return;
}
let repo = init_repo("stage-problem");
std::fs::write(repo.join("ok.txt"), "fine").unwrap();
std::fs::write(repo.join(".env"), "KEY=1").unwrap();
std::fs::write(repo.join(".env.example"), "KEY=").unwrap();
std::fs::create_dir_all(repo.join("sub")).unwrap();
std::fs::write(repo.join("sub/server.pem"), "x").unwrap();
let big = std::fs::File::create(repo.join("big.bin")).unwrap();
big.set_len(MAX_STAGED_BYTES + 1).unwrap();
// No commit yet: unstaging must work without a HEAD.
let Err(StageError::Problem(problem)) = stage_and_check(&repo) else {
panic!("expected a problem");
};
let mut files = problem.files.clone();
files.sort();
assert_eq!(files, vec![".env", "big.bin", "sub/server.pem"]);
assert_eq!(problem.why, "look like secrets or are over 5 MB");
assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), "");
// Once the offenders are gone, the same call stages the rest.
std::fs::remove_file(repo.join(".env")).unwrap();
std::fs::remove_file(repo.join("big.bin")).unwrap();
std::fs::remove_file(repo.join("sub/server.pem")).unwrap();
stage_and_check(&repo).expect("a clean list passes");
let staged = git_in(&repo, &["diff", "--cached", "--name-only"]);
assert!(staged.contains("ok.txt") && staged.contains(".env.example"));
}
#[test]
fn a_deleted_ordinary_file_passes_and_a_big_one_alone_says_so() {
if !git_ready() {
return;
}
let repo = init_repo("stage-deleted");
std::fs::write(repo.join("a.txt"), "a").unwrap();
git_in(&repo, &["add", "-A"]);
git_in(&repo, &["commit", "-q", "-m", "First"]);
std::fs::remove_file(repo.join("a.txt")).unwrap();
stage_and_check(&repo).expect("a deletion of an ordinary file passes");
git_in(&repo, &["reset", "-q"]);
let big = std::fs::File::create(repo.join("huge.dat")).unwrap();
big.set_len(MAX_STAGED_BYTES + 1).unwrap();
let Err(StageError::Problem(problem)) = stage_and_check(&repo) else {
panic!("expected a problem");
};
assert_eq!(problem.files, vec!["huge.dat"]);
assert_eq!(problem.why, "are over 5 MB");
assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), "");
}
#[test]
fn commit_stages_the_marked_files_but_leaves_an_ignored_spec_folder_alone() {
if !git_ready() || !node_ready() {
return;
}
let repo = init_repo("commit-ignored");
std::fs::write(repo.join(".gitignore"), "specs/\n").unwrap();
std::fs::write(repo.join("a.txt"), "a").unwrap();
let spec = repo.join("specs/lunch");
std::fs::create_dir_all(&spec).unwrap();
std::fs::write(spec.join("overview.md"), OVERVIEW).unwrap();
std::fs::write(spec.join("phase-2.md"), PHASE).unwrap();
let prepared = Prepared {
message: "Add it\n\nAI Assisted".to_string(),
phase_file: spec.join("phase-2.md"),
};
stage_and_check(&repo).unwrap();
let marked = mark(&prepared, &repo, "specs/lunch", 2, "Approved.").unwrap();
let head = commit(&repo, &prepared, &marked, Duration::from_secs(30)).unwrap();
assert!(head.is_some());
let shown = git_in(&repo, &["show", "--name-only", "--format=%s", "HEAD"]);
assert!(shown.contains("a.txt"), "{shown}");
assert!(!shown.contains("specs/"), "{shown}");
}
#[test]
fn a_recorded_commit_hash_is_checked_against_the_history() {
if !git_ready() {
return;
}
let (base, _) = temp_spec("hashes");
git_in(&base, &["init", "-q"]);
for (key, value) in [
("user.name", "Loop Test"),
("user.email", "loop@example.com"),
("commit.gpgsign", "false"),
] {
git_in(&base, &["config", key, value]);
}
std::fs::write(base.join("a.txt"), "a").unwrap();
git_in(&base, &["add", "-A"]);
git_in(&base, &["commit", "-q", "-m", "First"]);
let real = git_in(&base, &["rev-parse", "--short", "HEAD"]);
assert!(loop_tools::git_commit_exists(&base, &real));
assert!(!loop_tools::git_commit_exists(&base, "deadbee"));
assert!(!loop_tools::git_commit_exists(&base, ""));
assert!(!loop_tools::git_commit_exists(&base, "--all"));
assert!(!loop_tools::git_commit_exists(&base, "HEAD"));
let entry = |phase: u32, commit: Option<&str>| crate::loop_report::ReportEntry {
phase,
commit: commit.map(str::to_string),
..crate::loop_report::ReportEntry::default()
};
let mut report = LoopReport::new("specs/lunch", "now");
report.entries.push(entry(2, Some(real.as_str())));
report.entries.push(entry(3, Some("deadbee")));
// Built with commit off: no hash, so nothing to check.
report.entries.push(entry(4, None));
// Never recorded by the loop (built by hand): trusted.
let done = [1, 2, 3, 4];
assert_eq!(
marks_without_commits(&base, "specs/lunch", &done, &report),
vec![3]
);
// A phase the spec no longer shows done is not listed.
assert!(marks_without_commits(&base, "specs/lunch", &[2], &report).is_empty());
}
}
File diff suppressed because it is too large. Load diff
+416
View File
@@ -0,0 +1,416 @@
//! The Implementation Loop's notification to a web address the person chose,
//! when it needs them or ends: a plain GET with the message in the query
//! string, or a POST in the shape a chat service's webhook wants. The kind, the
//! address and the name come from `loop-setup.json` and the app names them in
//! its own Start confirm; the message is written by the loop. A failed call
//! never changes what the loop does, and its reason never repeats the address,
//! which may hold a token.
use reqwest::{blocking::Client, header::CONTENT_TYPE, redirect::Policy, Url};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::time::Duration;
/// How the message reaches the address. To add a service: a variant here, its
/// body in `request_for`, its words in `describe`, and its row in the setup
/// screen's `NOTIFY_KINDS` and `loop-setup.mjs`'s list.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum NotifyKind {
/// A GET with the message in a query string parameter the person names.
#[default]
Query,
/// A POST of a JSON object with the message in a field the person names.
Json,
Discord,
Slack,
Teams,
GoogleChat,
}
impl NotifyKind {
/// Whether the person names the parameter or field that holds the message.
pub fn uses_param(self) -> bool {
matches!(self, NotifyKind::Query | NotifyKind::Json)
}
}
pub const DEFAULT_PARAM: &str = "message";
const MAX_URL: usize = 2000;
const MAX_PARAM: usize = 64;
const CALL_LIMIT: Duration = Duration::from_secs(10);
/// Whether `url` is an http or https address the app may call: printable ASCII
/// (anything else percent-encoded), a host, and no user name or password.
pub fn valid_url(url: &str) -> bool {
if url.len() > MAX_URL || !url.chars().all(|c| ('!'..='~').contains(&c)) {
return false;
}
let lower = url.to_ascii_lowercase();
let Some(rest) = lower
.strip_prefix("http://")
.or_else(|| lower.strip_prefix("https://"))
else {
return false;
};
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
!authority.is_empty()
&& !authority.contains('@')
&& Url::parse(url).is_ok_and(|u| u.host_str().is_some())
}
/// Whether `name` can stand as a query parameter's name without being encoded.
pub fn valid_param(name: &str) -> bool {
!name.is_empty()
&& name.len() <= MAX_PARAM
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '~'))
}
fn encode(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for byte in text.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
out.push(char::from(byte));
} else {
out.push_str(&format!("%{byte:02X}"));
}
}
out
}
/// `url` with `param=message` in its query. The address's other parameters and
/// fragment stay; a parameter of the same name is replaced.
pub fn target_url(url: &str, param: &str, message: &str) -> String {
let (rest, fragment) = match url.split_once('#') {
Some((rest, fragment)) => (rest, Some(fragment)),
None => (url, None),
};
let (base, query) = rest.split_once('?').unwrap_or((rest, ""));
let mut pairs: Vec<String> = query
.split('&')
.filter(|pair| !pair.is_empty() && pair.split('=').next() != Some(param))
.map(str::to_string)
.collect();
pairs.push(format!("{param}={}", encode(message)));
let mut out = format!("{base}?{}", pairs.join("&"));
if let Some(fragment) = fragment {
out.push('#');
out.push_str(fragment);
}
out
}
/// Whether the setup's notification fields can be used, for an address that is set.
pub fn valid_setup(kind: NotifyKind, url: &str, param: &str) -> bool {
valid_url(url) && (!kind.uses_param() || valid_param(param))
}
/// Slack treats these three as its own markup in message text.
fn slack_escaped(text: &str) -> String {
text.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
}
/// The address to call and, for a POST, the JSON body.
pub fn request_for(
kind: NotifyKind,
url: &str,
param: &str,
message: &str,
) -> (String, Option<Value>) {
let body = match kind {
NotifyKind::Query => return (target_url(url, param, message), None),
NotifyKind::Json => json!({ param: message }),
// No mentions, whatever a spec is called: this must never ping a channel.
NotifyKind::Discord => json!({ "content": message, "allowed_mentions": { "parse": [] } }),
NotifyKind::Slack => json!({ "text": slack_escaped(message) }),
NotifyKind::GoogleChat => json!({ "text": message }),
// A Teams workflow's "when a webhook request is received" trigger.
NotifyKind::Teams => json!({
"type": "message",
"attachments": [{
"contentType": "application/vnd.microsoft.card.adaptive",
"contentUrl": null,
"content": {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.4",
"body": [{ "type": "TextBlock", "text": message, "wrap": true }],
},
}],
}),
};
(url.to_string(), Some(body))
}
/// The Start confirm's words for what the app will do.
pub fn describe(kind: NotifyKind, url: &str, param: &str) -> String {
match kind {
NotifyKind::Query => format!("the app calls: {url} with a message in {param}"),
NotifyKind::Json => format!("the app posts to: {url} with a message in {param}"),
NotifyKind::Discord => format!("the app posts to Discord at: {url}"),
NotifyKind::Slack => format!("the app posts to Slack at: {url}"),
NotifyKind::Teams => format!("the app posts to Microsoft Teams at: {url}"),
NotifyKind::GoogleChat => format!("the app posts to Google Chat at: {url}"),
}
}
/// Send the message, within ten seconds. Any 2xx answer counts as sent. The
/// error is safe to show: it never holds the address.
pub fn send(kind: NotifyKind, url: &str, param: &str, message: &str) -> Result<(), String> {
let client = Client::builder()
.timeout(CALL_LIMIT)
.redirect(Policy::limited(5))
.build()
.map_err(|_| "the app could not prepare the call".to_string())?;
let (address, body) = request_for(kind, url, param, message);
let request = match body {
None => client.get(address),
Some(body) => client
.post(address)
.header(CONTENT_TYPE, "application/json")
.body(body.to_string()),
};
let response = request.send().map_err(|e| {
if e.is_timeout() {
"it did not answer within 10 seconds".to_string()
} else if e.is_connect() {
"the app could not connect to it".to_string()
} else {
"the call failed".to_string()
}
})?;
let status = response.status();
if status.is_success() {
Ok(())
} else {
Err(format!("it answered {}", status.as_u16()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::thread;
/// Answer one request with `status` on a local port; gives back the whole request.
fn one_call(status: &'static str) -> (String, thread::JoinHandle<String>) {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = listener.local_addr().unwrap().port();
let handle = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut request = String::new();
let mut buf = [0u8; 4096];
loop {
let n = stream.read(&mut buf).unwrap();
request.push_str(&String::from_utf8_lossy(&buf[..n]));
let Some((head, body)) = request.split_once("\r\n\r\n") else {
continue;
};
let length = head
.lines()
.find_map(|l| {
l.to_ascii_lowercase()
.strip_prefix("content-length: ")
.map(str::to_string)
})
.and_then(|l| l.parse::<usize>().ok())
.unwrap_or(0);
if n == 0 || body.len() >= length {
break;
}
}
let answer =
format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
stream.write_all(answer.as_bytes()).unwrap();
request
});
(format!("http://127.0.0.1:{port}/hook?team=a"), handle)
}
#[test]
fn only_http_and_https_addresses_with_a_host_are_valid() {
for good in [
"http://example.com",
"https://example.com/hook?x=1#top",
"HTTPS://EXAMPLE.COM/a%20b",
"http://127.0.0.1:8080/",
] {
assert!(valid_url(good), "{good}");
}
for bad in [
"",
"example.com",
"ftp://example.com",
"file:///c:/x",
"javascript:alert(1)",
"https:/example.com",
"https://",
"https://?x=1",
"https://exa mple.com",
"https://example.com/é",
"https://me:secret@example.com/",
"https://example.com/\nx",
] {
assert!(!valid_url(bad), "{bad}");
}
assert!(!valid_url(&format!(
"https://e.com/{}",
"x".repeat(MAX_URL)
)));
}
#[test]
fn a_parameter_name_needs_no_encoding() {
for good in ["message", "msg_1", "a-b.c~d", "M"] {
assert!(valid_param(good), "{good}");
}
for bad in ["", "a b", "a=b", "a&b", "a?b", "a#b", "a%20b", "é", "[x]"] {
assert!(!valid_param(bad), "{bad}");
}
assert!(!valid_param(&"x".repeat(MAX_PARAM + 1)));
}
#[test]
fn the_message_lands_encoded_in_the_query_beside_what_is_there() {
assert_eq!(
target_url("https://e.com/hook", "message", "a b&c=d/é"),
"https://e.com/hook?message=a%20b%26c%3Dd%2F%C3%A9"
);
assert_eq!(
target_url("https://e.com/hook?t=1&x=2#top", "msg", "hi"),
"https://e.com/hook?t=1&x=2&msg=hi#top"
);
assert_eq!(
target_url("https://e.com/?msg=old&t=1", "msg", "new"),
"https://e.com/?t=1&msg=new",
"a parameter of the same name is replaced"
);
}
#[test]
fn the_call_is_a_get_with_the_message_in_the_query() {
let (url, server) = one_call("200 OK");
assert_eq!(send(NotifyKind::Query, &url, "message", "all done"), Ok(()));
assert_eq!(
server.join().unwrap().lines().next().unwrap(),
"GET /hook?team=a&message=all%20done HTTP/1.1"
);
}
#[test]
fn a_webhook_gets_a_post_of_json_at_the_address_as_given() {
let (url, server) = one_call("204 No Content");
assert_eq!(
send(NotifyKind::Discord, &url, "ignored", "all done"),
Ok(())
);
let request = server.join().unwrap();
assert_eq!(
request.lines().next().unwrap(),
"POST /hook?team=a HTTP/1.1"
);
assert!(request
.to_ascii_lowercase()
.contains("content-type: application/json"));
let (_, body) = request.split_once("\r\n\r\n").unwrap();
let body: Value = serde_json::from_str(body).unwrap();
assert_eq!(body["content"], "all done");
}
#[test]
fn each_service_gets_the_shape_it_wants() {
let body = |kind, message| {
request_for(kind, "https://e.com/x", "note", message)
.1
.unwrap()
};
assert_eq!(body(NotifyKind::Json, "hi"), json!({ "note": "hi" }));
assert_eq!(
body(NotifyKind::Discord, "@everyone hi"),
json!({ "content": "@everyone hi", "allowed_mentions": { "parse": [] } }),
"a mention in a spec's name pings nobody"
);
assert_eq!(
body(NotifyKind::Slack, "a <b> & c"),
json!({ "text": "a &lt;b&gt; &amp; c" })
);
assert_eq!(body(NotifyKind::GoogleChat, "hi"), json!({ "text": "hi" }));
let teams = body(NotifyKind::Teams, "hi");
assert_eq!(teams["type"], "message");
let attachment = &teams["attachments"][0];
assert_eq!(
attachment["contentType"],
"application/vnd.microsoft.card.adaptive"
);
assert_eq!(attachment["content"]["type"], "AdaptiveCard");
assert_eq!(attachment["content"]["body"][0]["text"], "hi");
assert_eq!(
request_for(NotifyKind::Slack, "https://e.com/x", "n", "m").0,
"https://e.com/x"
);
assert_eq!(
request_for(NotifyKind::Query, "https://e.com/x", "n", "m"),
("https://e.com/x?n=m".to_string(), None)
);
}
#[test]
fn a_kind_reads_by_its_saved_name_and_only_some_need_a_name() {
for (name, kind) in [
("query", NotifyKind::Query),
("json", NotifyKind::Json),
("discord", NotifyKind::Discord),
("slack", NotifyKind::Slack),
("teams", NotifyKind::Teams),
("google-chat", NotifyKind::GoogleChat),
] {
assert_eq!(
serde_json::from_value::<NotifyKind>(json!(name)).unwrap(),
kind
);
}
assert!(valid_setup(NotifyKind::Slack, "https://e.com/", "a b"));
assert!(!valid_setup(NotifyKind::Query, "https://e.com/", "a b"));
assert!(!valid_setup(NotifyKind::Json, "https://e.com/", ""));
assert!(!valid_setup(NotifyKind::Slack, "e.com", "message"));
}
// Needs the internet, so only by hand: `cargo test live_https -- --ignored`.
#[test]
#[ignore]
fn live_https_reaches_a_real_certificate() {
assert_eq!(
send(NotifyKind::Query, "https://example.com/", "message", "test"),
Ok(())
);
}
#[test]
fn a_failed_call_says_why_without_the_address() {
let (url, server) = one_call("503 Service Unavailable");
assert_eq!(
send(NotifyKind::Query, &url, "message", "x"),
Err("it answered 503".to_string())
);
server.join().unwrap();
// A port nothing listens on.
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener);
let err = send(
NotifyKind::Slack,
&format!("http://127.0.0.1:{port}/secret-token"),
"message",
"x",
)
.unwrap_err();
assert!(!err.contains("secret-token"), "{err}");
}
}
+568
View File
@@ -0,0 +1,568 @@
//! The Implementation Loop's report: everything the loop did on the person's
//! behalf, across stops and resumes, until every phase is built.
//!
//! While a build is under way the report lives in `loop-reports.json` in the
//! console's folder, saved after every phase, retry and stop. It cannot live in
//! the project yet: a file there would dirty the tree, and Resume needs a clean
//! one to commit each phase. When the last phase is built it is written to
//! `specs/<feature>/LOOP-SUMMARY-<date>.md` and its entry here goes away.
use std::path::Path;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::loop_driver::{fold_key, write_atomic, Finding, Outcome};
pub const REPORTS_FILE: &str = "loop-reports.json";
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EntryResult {
#[default]
Passed,
Stopped,
Retried,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Assumption {
pub task: String,
pub note: String,
}
/// One thing that happened to a phase, in the order it happened.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct ReportEntry {
pub at: String,
pub phase: u32,
pub name: String,
pub result: EntryResult,
/// Why it stopped or was retried; empty for a phase that passed.
pub line: String,
pub commit: Option<String>,
pub subject: String,
pub summary: String,
pub tests: String,
/// Whether the phase got as far as reporting; false for a crash or a stop mid-build.
pub reported: bool,
pub review_ran: bool,
pub fixed: Vec<Finding>,
pub skipped: Vec<Finding>,
pub left_open: Vec<Finding>,
pub assumed: Vec<Assumption>,
pub blocked: Vec<String>,
pub conflicts: Vec<String>,
pub decisions: Vec<String>,
/// Things the app noticed that did not stop the phase (leftover Suggestions).
pub warnings: Vec<String>,
pub retries: u32,
}
impl ReportEntry {
/// An entry's review, tasks and decisions, from the phase's report.
pub fn with_outcome(mut self, outcome: &Outcome) -> ReportEntry {
self.reported = true;
self.subject.clone_from(&outcome.subject);
self.summary.clone_from(&outcome.summary);
self.tests = match &outcome.tests {
Some(t) if !t.summary.is_empty() => t.summary.clone(),
Some(t) if t.passed => "passed".to_string(),
Some(t) if t.ran => "failed".to_string(),
_ => "not reported".to_string(),
};
if let Some(review) = &outcome.review {
self.review_ran = review.ran;
self.fixed.clone_from(&review.fixed);
self.left_open.clone_from(&review.unfixed);
if let Some(triage) = &review.triage {
self.skipped.clone_from(&triage.skipped);
}
}
self.blocked.clone_from(&outcome.tasks.blocked);
self.conflicts.clone_from(&outcome.conflicts);
self.decisions.clone_from(&outcome.decisions);
for task in &outcome.tasks.assumed {
if !self.assumed.iter().any(|a| &a.task == task) {
self.assumed.push(Assumption {
task: task.clone(),
note: String::new(),
});
}
}
self
}
}
/// A phase the loop marked done whose commit failed and whose mark could not be
/// taken back: it survives an app restart, so Resume can rebuild the phase.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct MarkedNotCommitted {
pub phase: u32,
pub file: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct LoopReport {
pub spec: String,
pub started: String,
pub entries: Vec<ReportEntry>,
pub marked_not_committed: Option<MarkedNotCommitted>,
}
impl LoopReport {
pub fn new(spec: &str, started: &str) -> LoopReport {
LoopReport {
spec: spec.to_string(),
started: started.to_string(),
entries: Vec::new(),
marked_not_committed: None,
}
}
pub fn set_marked(&mut self, phase: u32, file: &str) {
self.marked_not_committed = Some(MarkedNotCommitted {
phase,
file: file.to_string(),
});
}
pub fn clear_marked(&mut self) {
self.marked_not_committed = None;
}
/// Each phase's latest pass, by phase number.
pub fn passed(&self) -> Vec<&ReportEntry> {
let mut seen: Vec<&ReportEntry> = Vec::new();
for entry in self
.entries
.iter()
.filter(|e| e.result == EntryResult::Passed)
{
seen.retain(|e| e.phase != entry.phase);
seen.push(entry);
}
seen.sort_by_key(|e| e.phase);
seen
}
}
// ------------------------------------------------------------- the store
fn key(project: &Path, spec: &str) -> String {
format!("{}|{spec}", fold_key(project))
}
fn read_store(home: &Path) -> Value {
std::fs::read_to_string(home.join(REPORTS_FILE))
.ok()
.and_then(|text| serde_json::from_str::<Value>(&text).ok())
.filter(|store| store["schema"].as_u64() == Some(1) && store["reports"].is_object())
.unwrap_or_else(|| json!({ "schema": 1, "reports": {} }))
}
/// The report under way for this spec, if a build of it has not finished.
pub fn load(home: &Path, project: &Path, spec: &str) -> Option<LoopReport> {
let store = read_store(home);
serde_json::from_value(store["reports"].get(key(project, spec))?.clone()).ok()
}
pub fn save(home: &Path, project: &Path, report: &LoopReport) -> Result<(), String> {
let mut store = read_store(home);
store["reports"][key(project, &report.spec)] = json!(report);
write_atomic(&home.join(REPORTS_FILE), &store.to_string())
}
pub fn remove(home: &Path, project: &Path, spec: &str) -> Result<(), String> {
let mut store = read_store(home);
let gone = store["reports"]
.as_object_mut()
.and_then(|all| all.remove(&key(project, spec)));
if gone.is_none() {
return Ok(());
}
write_atomic(&home.join(REPORTS_FILE), &store.to_string())
}
// ------------------------------------------------------ the phase file
/// The `[?]` tasks in a phase file and their `Assumed:` notes: on the task's own
/// line or on an indented line under it.
pub fn assumptions_in(phase_text: &str) -> Vec<Assumption> {
let mut found: Vec<Assumption> = Vec::new();
let mut open = false;
for line in phase_text.lines() {
let trimmed = line.trim_start();
let indented = trimmed.len() < line.len();
if let Some(rest) = trimmed.strip_prefix("- [?]") {
found.push(Assumption {
task: task_id(rest),
note: note_in(rest).unwrap_or_default(),
});
open = true;
} else if !indented {
open = false;
} else if open {
if let (Some(last), Some(note)) = (found.last_mut(), note_in(trimmed)) {
if last.note.is_empty() {
last.note = note;
}
}
}
}
found
}
fn note_in(text: &str) -> Option<String> {
let (_, note) = text.split_once("Assumed:")?;
let note = note.trim().trim_end_matches("**").trim();
(!note.is_empty()).then(|| note.to_string())
}
/// `2.4` from ` **Task 2.4:** Do it`; the line itself when it names no task.
fn task_id(rest: &str) -> String {
let id = rest.split_once("Task ").and_then(|(_, after)| {
let id: String = after
.chars()
.take_while(|c| c.is_ascii_digit() || *c == '.')
.collect();
(!id.is_empty()).then(|| id.trim_end_matches('.').to_string())
});
id.unwrap_or_else(|| rest.trim().to_string())
}
// ----------------------------------------------------------- the markdown
fn cell(text: &str) -> String {
text.replace('|', "\\|").replace(['\r', '\n'], " ")
}
fn finding_line(f: &Finding) -> String {
let file = if f.file.is_empty() {
String::new()
} else {
format!(" (`{}`)", cell(&f.file))
};
format!("- {}: {}{file}", f.level.word(), cell(&f.title))
}
fn section(md: &mut String, title: &str, lines: &[String], none: &str) {
md.push_str(&format!("\n**{title}**\n\n"));
if lines.is_empty() {
md.push_str(none);
md.push('\n');
} else {
md.push_str(&lines.join("\n"));
md.push('\n');
}
}
fn entry_markdown(md: &mut String, e: &ReportEntry) {
let word = match e.result {
EntryResult::Passed => "built",
EntryResult::Stopped => "stopped",
EntryResult::Retried => "retried",
};
md.push_str(&format!(
"\n### Phase {}: {} ({word}, {})\n\n",
e.phase,
cell(&e.name),
e.at
));
if !e.line.is_empty() {
md.push_str(&format!("{}\n\n", cell(&e.line)));
}
if let Some(commit) = &e.commit {
md.push_str(&format!("- Commit: `{commit}` {}\n", cell(&e.subject)));
} else if e.result == EntryResult::Passed {
md.push_str("- Commit: not committed\n");
}
if e.retries > 0 {
md.push_str(&format!("- Retries: {}\n", e.retries));
}
if !e.warnings.is_empty() {
let notes: Vec<String> = e.warnings.iter().map(|w| cell(w)).collect();
md.push_str(&format!("- Warnings: {}\n", notes.join("; ")));
}
if !e.reported {
md.push_str(
"- The agent ended before reporting, so its review and decisions are unknown.\n",
);
} else {
md.push_str(&format!("- Summary: {}\n", cell(&e.summary)));
md.push_str(&format!("- Tests: {}\n", cell(&e.tests)));
}
if !e.blocked.is_empty() {
md.push_str(&format!("- Blocked tasks: {}\n", e.blocked.join(", ")));
}
for conflict in &e.conflicts {
md.push_str(&format!("- Spec conflict: {}\n", cell(conflict)));
}
let assumed: Vec<String> = e
.assumed
.iter()
.map(|a| {
let note = if a.note.is_empty() {
"(no note in the phase file)"
} else {
&a.note
};
format!("- Task {}: {}", cell(&a.task), cell(note))
})
.collect();
if e.reported || !assumed.is_empty() {
section(md, "Assumptions it made", &assumed, "None.");
}
if !e.reported {
return;
}
let decisions: Vec<String> = e
.decisions
.iter()
.map(|d| format!("- {}", cell(d)))
.collect();
section(
md,
"Other decisions it reported",
&decisions,
"None reported.",
);
if !e.review_ran {
md.push_str("\n**Review:** did not run.\n");
return;
}
let fixed: Vec<String> = e.fixed.iter().map(finding_line).collect();
section(md, "Findings it fixed", &fixed, "None.");
let skipped: Vec<String> = e
.skipped
.iter()
.map(|f| {
format!(
"{}: {}",
finding_line(f),
cell(f.reason.as_deref().unwrap_or("(no reason given)"))
)
})
.collect();
section(md, "Findings it chose not to fix", &skipped, "None.");
let left: Vec<String> = e.left_open.iter().map(finding_line).collect();
section(md, "Findings left open", &left, "None.");
}
/// The report's body: the table of phases and every entry, oldest first.
pub fn body_markdown(report: &LoopReport) -> String {
let mut md = String::from(
"Everything below comes from each phase's report, as its agent wrote it, except the \
task marks, the quick check and the commits, which the app checked or made itself. \
An agent can only report the decisions it noticed making.\n",
);
let passed = report.passed();
if !passed.is_empty() {
md.push_str(
"\n## Phases\n\n| Phase | Commit | Subject | Fixed | Not fixed | Left open | Assumed | Other decisions | Retries |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
);
for e in &passed {
md.push_str(&format!(
"| Phase {}: {} | {} | {} | {} | {} | {} | {} | {} | {} |\n",
e.phase,
cell(&e.name),
e.commit.as_deref().unwrap_or("not committed"),
cell(&e.subject),
e.fixed.len(),
e.skipped.len(),
e.left_open.len(),
e.assumed.len(),
e.decisions.len(),
e.retries,
));
}
}
md.push_str("\n## What happened, in order\n");
if report.entries.is_empty() {
md.push_str("\nNo phase has finished or stopped yet.\n");
}
for entry in &report.entries {
entry_markdown(&mut md, entry);
}
md
}
#[cfg(test)]
mod tests {
use super::*;
use crate::loop_driver::FixLevel;
fn finding(title: &str, reason: Option<&str>) -> Finding {
Finding {
level: FixLevel::Warning,
title: title.into(),
file: "src/y.js".into(),
reason: reason.map(str::to_string),
}
}
fn entry(phase: u32, result: EntryResult) -> ReportEntry {
ReportEntry {
at: "2026-11-01 10:00".into(),
phase,
name: format!("P{phase}"),
result,
..ReportEntry::default()
}
}
#[test]
fn the_store_keeps_a_report_per_project_and_spec_until_it_is_removed() {
let home = std::env::temp_dir().join(format!("plan2code-report-{}", std::process::id()));
std::fs::create_dir_all(&home).unwrap();
let (a, b) = (Path::new("C:/one"), Path::new("C:/two"));
assert_eq!(load(&home, a, "specs/x"), None);
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
report.entries.push(entry(1, EntryResult::Passed));
save(&home, a, &report).unwrap();
save(&home, b, &LoopReport::new("specs/x", "later")).unwrap();
assert_eq!(load(&home, a, "specs/x").unwrap(), report);
assert_eq!(load(&home, a, "specs/other"), None);
remove(&home, a, "specs/x").unwrap();
assert_eq!(load(&home, a, "specs/x"), None);
assert_eq!(load(&home, b, "specs/x").unwrap().started, "later");
remove(&home, a, "specs/x").unwrap();
let _ = std::fs::remove_dir_all(&home);
}
#[test]
fn a_broken_store_reads_as_empty_and_is_replaced() {
let home =
std::env::temp_dir().join(format!("plan2code-report-bad-{}", std::process::id()));
std::fs::create_dir_all(&home).unwrap();
std::fs::write(home.join(REPORTS_FILE), "not json").unwrap();
assert_eq!(load(&home, Path::new("C:/one"), "specs/x"), None);
let report = LoopReport::new("specs/x", "now");
save(&home, Path::new("C:/one"), &report).unwrap();
assert_eq!(load(&home, Path::new("C:/one"), "specs/x").unwrap(), report);
let _ = std::fs::remove_dir_all(&home);
}
#[test]
fn assumptions_come_from_the_task_line_or_the_line_under_it() {
let text = "# Phase 2\n\n- [x] **Task 2.1:** Done\n - Assumed: not this one\n- [?] **Task 2.2:** Pick a store\n - Test: through the route\n - Assumed: SQLite, since the spec names no store\n- [?] **Task 2.3:** Pick a port. Assumed: 8080\n- [?] **Task 2.4:** No note\n\n## Notes\n\nAssumed: not under a task\n";
assert_eq!(
assumptions_in(text),
vec![
Assumption {
task: "2.2".into(),
note: "SQLite, since the spec names no store".into()
},
Assumption {
task: "2.3".into(),
note: "8080".into()
},
Assumption {
task: "2.4".into(),
note: String::new()
},
]
);
}
#[test]
fn the_report_lists_every_kind_of_decision_with_its_reason() {
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
let mut built = entry(2, EntryResult::Passed);
built.reported = true;
built.review_ran = true;
built.commit = Some("a1b2c3d".into());
built.subject = "Add | the driver".into();
built.summary = "Built it".into();
built.tests = "14 pass".into();
built.fixed.push(finding("Null check", None));
built
.skipped
.push(finding("Rename", Some("Outside this phase")));
built.left_open.push(finding("Name the timer", None));
built.assumed.push(Assumption {
task: "2.2".into(),
note: "SQLite".into(),
});
built.assumed.push(Assumption {
task: "2.3".into(),
note: String::new(),
});
built
.decisions
.push("Kept the old route for callers".into());
built.retries = 1;
report.entries.push(built);
let md = body_markdown(&report);
assert!(
md.contains("| Phase 2: P2 | a1b2c3d | Add \\| the driver | 1 | 1 | 1 | 2 | 1 | 1 |")
);
assert!(md.contains("- warning: Null check (`src/y.js`)"));
assert!(md.contains("- warning: Rename (`src/y.js`): Outside this phase"));
assert!(md.contains("- warning: Name the timer (`src/y.js`)"));
assert!(md.contains("- Task 2.2: SQLite"));
assert!(md.contains("- Task 2.3: (no note in the phase file)"));
assert!(md.contains("- Kept the old route for callers"));
assert!(md.contains("- Tests: 14 pass"));
assert!(md.contains("- Retries: 1"));
assert!(!md.contains('\u{2014}'));
}
#[test]
fn a_phase_that_never_reported_says_so_and_keeps_what_the_file_shows() {
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
let mut stopped = entry(3, EntryResult::Stopped);
stopped.line = "Phase 3 stopped: the agent crashed".into();
stopped.assumed.push(Assumption {
task: "3.1".into(),
note: "Port 8080".into(),
});
report.entries.push(stopped);
let md = body_markdown(&report);
assert!(md.contains("Phase 3 stopped: the agent crashed"));
assert!(md.contains("its review and decisions are unknown"));
assert!(md.contains("- Task 3.1: Port 8080"));
assert!(!md.contains("Findings it fixed"));
}
#[test]
fn a_later_pass_is_the_phases_row_and_earlier_attempts_stay_in_the_story() {
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
report.entries.push(entry(1, EntryResult::Stopped));
let mut first = entry(1, EntryResult::Passed);
first.subject = "first".into();
report.entries.push(first);
report.entries.push(entry(2, EntryResult::Passed));
let mut again = entry(1, EntryResult::Passed);
again.subject = "again".into();
report.entries.push(again);
let passed = report.passed();
assert_eq!(passed.len(), 2);
assert_eq!(passed[0].phase, 1);
assert_eq!(passed[0].subject, "again");
assert_eq!(passed[1].phase, 2);
assert_eq!(body_markdown(&report).matches("### Phase 1").count(), 3);
}
#[test]
fn warnings_show_under_the_phase_and_an_old_store_loads_without_them() {
let mut e = entry(2, EntryResult::Passed);
e.warnings = vec!["2 Suggestions left unfixed".into(), "a | b".into()];
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
report.entries.push(e);
let md = body_markdown(&report);
assert!(
md.contains("- Warnings: 2 Suggestions left unfixed; a \\| b"),
"{md}"
);
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
report.entries.push(entry(3, EntryResult::Passed));
assert!(!body_markdown(&report).contains("Warnings"));
let old: ReportEntry = serde_json::from_str(r#"{"phase":4,"name":"P4"}"#).unwrap();
assert!(old.warnings.is_empty());
}
}
+673
View File
@@ -0,0 +1,673 @@
//! The commands the Implementation Loop runs on its own: the spec scripts, git,
//! the console's `post` and the person's quick check. Each call has a time
//! limit and keeps its output. No shell runs here except the quick check, whose
//! text comes only from `loop-setup.json` (never from a page message).
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use crate::console_supervisor::find_console_dir;
/// What a finished (or stopped) call left behind.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ToolRun {
pub ok: bool,
pub code: Option<i32>,
pub output: String,
}
/// Output kept per call: the tail, which is where a failure says why.
const OUTPUT_LIMIT: usize = 200 * 1024;
/// The limit for node and git calls.
pub const QUICK_LIMIT: Duration = Duration::from_secs(60);
/// The limit for the person's quick check.
pub const CHECK_LIMIT: Duration = Duration::from_secs(15 * 60);
const POLL: Duration = Duration::from_millis(25);
/// Appends `bytes`, dropping from the front when over `limit`.
fn append_tail(buf: &mut Vec<u8>, bytes: &[u8], limit: usize) {
buf.extend_from_slice(bytes);
if buf.len() > limit {
let excess = buf.len() - limit;
buf.drain(..excess);
}
}
fn pump<R: Read + Send + 'static>(
mut source: R,
sink: Arc<Mutex<Vec<u8>>>,
) -> thread::JoinHandle<()> {
thread::spawn(move || {
let mut chunk = [0u8; 8192];
loop {
match source.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => {
if let Ok(mut buf) = sink.lock() {
append_tail(&mut buf, &chunk[..n], OUTPUT_LIMIT);
}
}
}
}
})
}
/// Run `cmd` to its end or `limit`, with `stdin` written when given. Stdout and
/// stderr share one kept `output`. The child is killed when the limit passes.
fn run_limited(cmd: Command, stdin: Option<&str>, limit: Duration) -> ToolRun {
run_limited_with(cmd, stdin, limit, true)
}
/// `run_limited`, with stderr dropped when `keep_stderr` is false: a list read
/// from stdout must not be mixed with a warning git printed beside it.
fn run_limited_with(
mut cmd: Command,
stdin: Option<&str>,
limit: Duration,
keep_stderr: bool,
) -> ToolRun {
cmd.env("PATH", crate::node_check::resolved_path());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
}
cmd.stdin(if stdin.is_some() {
Stdio::piped()
} else {
Stdio::null()
})
.stdout(Stdio::piped())
.stderr(if keep_stderr {
Stdio::piped()
} else {
Stdio::null()
});
let mut child = match cmd.spawn() {
Ok(child) => child,
Err(e) => {
return ToolRun {
ok: false,
code: None,
output: format!("could not start: {e}"),
}
}
};
let sink = Arc::new(Mutex::new(Vec::new()));
let readers = [
child.stdout.take().map(|s| pump(s, Arc::clone(&sink))),
child.stderr.take().map(|s| pump(s, Arc::clone(&sink))),
];
if let (Some(text), Some(mut pipe)) = (stdin, child.stdin.take()) {
// A child that exits before reading closes the pipe: not an error here.
let _ = pipe.write_all(text.as_bytes());
}
let pid = child.id();
let started = Instant::now();
let mut timed_out = false;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break Some(status),
Ok(None) => {
if started.elapsed() >= limit {
timed_out = true;
kill_tree(pid);
let _ = child.kill();
let _ = child.wait();
break None;
}
thread::sleep(POLL);
}
Err(_) => break None,
}
};
// A descendant that outlives the child can keep the pipes open: wait a
// short grace for the readers, then leave them behind.
let grace = Instant::now() + Duration::from_secs(3);
for reader in readers.into_iter().flatten() {
while !reader.is_finished() && Instant::now() < grace {
thread::sleep(POLL);
}
if reader.is_finished() {
let _ = reader.join();
}
}
let mut output = sink
.lock()
.map(|buf| String::from_utf8_lossy(&buf).into_owned())
.unwrap_or_default();
if timed_out {
if !output.is_empty() && !output.ends_with('\n') {
output.push('\n');
}
output.push_str(&format!("(stopped after {})", describe_limit(limit)));
}
ToolRun {
ok: status.is_some_and(|s| s.success()),
code: status.and_then(|s| s.code()),
output,
}
}
/// "1 minute", "15 minutes", "2 seconds".
fn describe_limit(limit: Duration) -> String {
let secs = limit.as_secs();
let (n, unit) = if secs >= 60 {
(secs / 60, "minute")
} else {
(secs.max(1), "second")
};
format!("{n} {unit}{}", if n == 1 { "" } else { "s" })
}
/// End a call's whole process tree, not just the program it started.
fn kill_tree(pid: u32) {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
let _ = Command::new("taskkill")
.args(["/PID", &pid.to_string(), "/T", "/F"])
.creation_flags(0x08000000)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
#[cfg(not(windows))]
{
let _ = Command::new("pkill")
.args(["-KILL", "-P", &pid.to_string()])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
}
fn node_script(script: &Path, project: &Path, args: &[&str]) -> Command {
let mut cmd = Command::new("node");
cmd.arg(script).args(args).current_dir(project);
cmd
}
fn git(project: &Path, args: &[&str]) -> Command {
let mut cmd = Command::new("git");
cmd.args(args).current_dir(project);
cmd
}
/// A skill script (`specs.mjs`, `commit-msg.mjs`): beside the console's skill
/// first (`<console dir>/../../scripts/`), then the Implement skills' own.
pub fn skill_script(name: &str) -> Option<PathBuf> {
let mut candidates = Vec::new();
// Tests run the repository's own scripts, so they need no installed skill
// (CI has none) and cannot drift from the source.
#[cfg(test)]
candidates.push(
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../src/skill-scripts")
.join(name),
);
if let Ok(console) = find_console_dir() {
if let Some(skill) = console.parent().and_then(Path::parent) {
candidates.push(skill.join("scripts").join(name));
}
}
if let Some(home) = std::env::home_dir() {
let skills = home.join(".agents").join("skills");
for skill in ["plan2code-3-implement", "plan2code-3-implement-review"] {
candidates.push(skills.join(skill).join("scripts").join(name));
}
}
candidates.into_iter().find(|path| path.is_file())
}
fn script_or_err(name: &str) -> Result<PathBuf, String> {
skill_script(name).ok_or_else(|| format!("the Plan2Code skill script {name} is not installed"))
}
/// `specs.mjs status <spec>`, parsed.
pub fn specs_status(project: &Path, spec: &str) -> Result<serde_json::Value, String> {
let script = script_or_err("specs.mjs")?;
let run = run_limited(
node_script(&script, project, &["status", spec]),
None,
QUICK_LIMIT,
);
parse_json_object(&run)
}
/// `specs.mjs mark <spec> --phase N --to done`.
pub fn specs_mark_done(project: &Path, spec: &str, phase: u32) -> ToolRun {
specs_mark(project, spec, phase, "done")
}
/// `specs.mjs mark <spec> --phase N --to <to>` (`in-progress` reopens a phase).
pub fn specs_mark(project: &Path, spec: &str, phase: u32, to: &str) -> ToolRun {
let script = match script_or_err("specs.mjs") {
Ok(script) => script,
Err(output) => {
return ToolRun {
ok: false,
code: None,
output,
}
}
};
let phase = phase.to_string();
run_limited(
node_script(
&script,
project,
&["mark", spec, "--phase", &phase, "--to", to],
),
None,
QUICK_LIMIT,
)
}
/// `commit-msg.mjs --subject <subject> --add-all`: the checked message. The
/// script's own subject checks are the only ones.
pub fn commit_message(project: &Path, subject: &str) -> Result<String, String> {
let script = script_or_err("commit-msg.mjs")?;
let run = run_limited(
node_script(&script, project, &["--subject", subject, "--add-all"]),
None,
QUICK_LIMIT,
);
parse_commit_msg(&run.output)
}
/// What `commit-msg.mjs` printed, read without a shell: its `message` when
/// `ok`, otherwise its error, otherwise whatever it printed.
fn parse_commit_msg(stdout: &str) -> Result<String, String> {
let run = ToolRun {
ok: true,
code: Some(0),
output: stdout.to_string(),
};
let value = parse_json_object(&run).map_err(|_| stdout.trim().to_string())?;
if value["ok"].as_bool() == Some(true) {
if let Some(message) = value["message"].as_str() {
return Ok(message.to_string());
}
}
// `error` is a machine code; `message` is the human text.
Err(value["message"]
.as_str()
.or_else(|| value["error"].as_str())
.map(str::to_string)
.unwrap_or_else(|| stdout.trim().to_string()))
}
pub fn git_add_all(project: &Path) -> ToolRun {
run_limited(git(project, &["add", "-A"]), None, QUICK_LIMIT)
}
/// `git commit -F -` with the message on stdin: no shell, nothing quoted.
pub fn git_commit(project: &Path, message: &str) -> ToolRun {
git_commit_with(project, message, QUICK_LIMIT)
}
/// `git_commit` with its own time limit: a slow hook is not killed at the
/// limit of the quick calls.
pub fn git_commit_with(project: &Path, message: &str, limit: Duration) -> ToolRun {
run_limited(git(project, &["commit", "-F", "-"]), Some(message), limit)
}
/// `git add -- <paths>`: stage exactly these files. A path git ignores (a
/// `specs/` folder in `.gitignore`) is left out, as `git add -A` leaves it out,
/// not refused.
pub fn git_add_paths(project: &Path, paths: &[&Path]) -> ToolRun {
let wanted: Vec<&Path> = paths
.iter()
.copied()
.filter(|path| {
let mut cmd = git(project, &["check-ignore", "-q", "--"]);
cmd.arg(path);
!run_limited(cmd, None, QUICK_LIMIT).ok
})
.collect();
if wanted.is_empty() {
return ToolRun {
ok: true,
code: Some(0),
output: String::new(),
};
}
let mut cmd = git(project, &["add", "--"]);
cmd.args(wanted);
run_limited(cmd, None, QUICK_LIMIT)
}
/// The names of the staged files, as `git diff --cached --name-only -z` prints
/// them: NUL-separated, so no path is quoted.
pub fn git_staged(project: &Path) -> Result<Vec<String>, String> {
let run = run_limited_with(
git(project, &["diff", "--cached", "--name-only", "-z"]),
None,
QUICK_LIMIT,
false,
);
if !run.ok {
return Err(run.output.trim().to_string());
}
Ok(split_nul(&run.output))
}
fn split_nul(text: &str) -> Vec<String> {
text.split('\0')
.filter(|name| !name.is_empty())
.map(str::to_string)
.collect()
}
/// The repository's top folder: staged names are relative to it, not to
/// `project`, which may be a subfolder.
pub fn git_toplevel(project: &Path) -> Option<PathBuf> {
let run = run_limited_with(
git(project, &["rev-parse", "--show-toplevel"]),
None,
QUICK_LIMIT,
false,
);
let top = run.output.trim();
(run.ok && !top.is_empty()).then(|| PathBuf::from(top))
}
/// Whether `HEAD` names a commit (false in a repository with no commit yet).
fn git_has_head(project: &Path) -> bool {
run_limited(
git(project, &["rev-parse", "--verify", "-q", "HEAD"]),
None,
QUICK_LIMIT,
)
.ok
}
/// Take everything out of the index again; the files keep their contents.
pub fn git_unstage_all(project: &Path) -> ToolRun {
if git_has_head(project) {
run_limited(git(project, &["reset", "-q"]), None, QUICK_LIMIT)
} else {
// Before a first commit there is no HEAD to reset to.
run_limited(
git(project, &["rm", "-r", "--cached", "-q", ":/"]),
None,
QUICK_LIMIT,
)
}
}
/// The branch `HEAD` is on: `Ok(None)` for a detached HEAD, an error when
/// `project` is not a git repository.
pub fn git_branch(project: &Path) -> Result<Option<String>, String> {
let run = run_limited(
git(project, &["symbolic-ref", "--short", "-q", "HEAD"]),
None,
QUICK_LIMIT,
);
let name = run.output.trim();
if run.ok && !name.is_empty() {
return Ok(Some(name.to_string()));
}
// `symbolic-ref -q` exits 1 and prints nothing for a detached HEAD; any
// other failure (not a repository, git missing) prints something.
if run.code == Some(1) && name.is_empty() {
return Ok(None);
}
Err(name.to_string())
}
/// Whether `hash` names a commit in this repository.
pub fn git_commit_exists(project: &Path, hash: &str) -> bool {
if hash.is_empty() || !hash.chars().all(|c| c.is_ascii_hexdigit()) {
return false;
}
let target = format!("{hash}^{{commit}}");
run_limited(
git(project, &["cat-file", "-e", &target]),
None,
QUICK_LIMIT,
)
.ok
}
pub fn git_head_short(project: &Path) -> Option<String> {
let run = run_limited(
git(project, &["rev-parse", "--short", "HEAD"]),
None,
QUICK_LIMIT,
);
let hash = run.output.trim();
(run.ok && !hash.is_empty()).then(|| hash.to_string())
}
/// The full hash of `HEAD`, when there is a commit.
pub fn git_head_full(project: &Path) -> Option<String> {
let run = run_limited(git(project, &["rev-parse", "HEAD"]), None, QUICK_LIMIT);
let hash = run.output.trim();
(run.ok && !hash.is_empty()).then(|| hash.to_string())
}
/// The paths `git status --porcelain=v1 -z` lists (renames name the new path).
pub fn git_status_porcelain(project: &Path) -> Result<Vec<String>, String> {
let run = run_limited_with(
git(project, &["status", "--porcelain=v1", "-z"]),
None,
QUICK_LIMIT,
false,
);
if !run.ok {
return Err(run.output.trim().to_string());
}
Ok(parse_porcelain(&run.output))
}
/// Read `git status --porcelain=v1 -z`: NUL-separated records of `XY path`, no
/// quoting. A rename or copy record is followed by one more field, the old
/// path, which is skipped (the new path is the one listed).
pub fn parse_porcelain(text: &str) -> Vec<String> {
let mut paths = Vec::new();
let mut fields = text.split('\0');
while let Some(record) = fields.next() {
let mut chars = record.chars();
let (Some(x), Some(y), Some(' ')) = (chars.next(), chars.next(), chars.next()) else {
continue;
};
let Some(path) = record.get(x.len_utf8() + y.len_utf8() + 1..) else {
continue;
};
if path.is_empty() {
continue;
}
if matches!(x, 'R' | 'C') || matches!(y, 'R' | 'C') {
fields.next();
}
paths.push(path.to_string());
}
paths
}
/// `node console.mjs post --session <sid> --file -` with `patch` on stdin.
pub fn console_post(console_dir: &Path, sid: &str, patch: &serde_json::Value) -> ToolRun {
let mut cmd = Command::new("node");
cmd.arg(console_dir.join("console.mjs"))
.args(["post", "--session", sid, "--file", "-"]);
run_limited(cmd, Some(&patch.to_string()), QUICK_LIMIT)
}
/// `node console.mjs open --resume <sid> --no-open --workflow <workflow>`: the
/// console holding a session again after it went away, without a browser.
pub fn console_resume(console_dir: &Path, sid: &str, workflow: &str) -> ToolRun {
let mut cmd = Command::new("node");
cmd.arg(console_dir.join("console.mjs")).args([
"open",
"--resume",
sid,
"--no-open",
"--workflow",
workflow,
]);
run_limited(cmd, None, QUICK_LIMIT)
}
/// The person's quick check through the platform shell, in `project`.
pub fn quick_check(project: &Path, command: &str, limit: Duration) -> ToolRun {
let mut cmd;
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd = Command::new("cmd");
// Raw, so a quoted argument reaches cmd.exe as typed (the usual
// argument quoting would turn each quote into a backslash-quote).
cmd.arg("/C").raw_arg(command);
}
#[cfg(not(windows))]
{
cmd = Command::new("sh");
cmd.args(["-c", command]);
}
cmd.current_dir(project);
run_limited(cmd, None, limit)
}
fn parse_json_object(run: &ToolRun) -> Result<serde_json::Value, String> {
let text = run.output.trim();
// Stderr shares the output: take the first line that starts the object.
let start = text.find('{').unwrap_or(0);
// Only the first value counts: stderr lines may trail the object.
let first = serde_json::Deserializer::from_str(&text[start..])
.into_iter::<serde_json::Value>()
.next();
match first {
Some(Ok(value)) if value.is_object() => Ok(value),
_ => Err(if text.is_empty() {
"the tool printed nothing".to_string()
} else {
text.to_string()
}),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_commit_message_is_read_from_the_scripts_output_without_a_shell() {
let ok = r#"{"ok":true,"subject":"Add it","message":"Add it\n\nAI Assisted"}"#;
assert_eq!(parse_commit_msg(ok).unwrap(), "Add it\n\nAI Assisted");
// Stderr noise before the object does not matter.
let noisy = format!("warning: something\n{ok}\n");
assert_eq!(parse_commit_msg(&noisy).unwrap(), "Add it\n\nAI Assisted");
assert_eq!(
parse_commit_msg(r#"{"ok":false,"error":"subject too long"}"#).unwrap_err(),
"subject too long"
);
assert_eq!(
parse_commit_msg(r#"{"ok":false,"message":"no subject"}"#).unwrap_err(),
"no subject"
);
assert_eq!(
parse_commit_msg("not json at all\n").unwrap_err(),
"not json at all"
);
assert!(parse_commit_msg("").is_err());
}
#[test]
fn a_refusal_as_the_script_really_prints_it_reads_as_its_message() {
let real = "{\n \"ok\": false,\n \"error\": \"unsafe-subject\",\n \"message\": \"The subject has a double quote.\",\n \"next\": \"Rephrase.\"\n}\nerror: The subject has a double quote.\nnext: Rephrase.\n";
assert_eq!(
parse_commit_msg(real).unwrap_err(),
"The subject has a double quote."
);
// ok without a message is still an error, never an empty commit.
assert!(parse_commit_msg(r#"{"ok":true}"#).is_err());
}
#[test]
fn the_kept_output_is_the_tail() {
let mut buf = Vec::new();
append_tail(&mut buf, b"0123456789", 6);
append_tail(&mut buf, b"AB", 6);
assert_eq!(buf, b"6789AB");
}
#[test]
fn porcelain_lists_paths_and_the_new_name_of_a_rename() {
let text = " M src/a.rs\0?? new file.txt\0R new.rs\0old.rs\0A \"quoted\".txt\0";
assert_eq!(
parse_porcelain(text),
vec!["src/a.rs", "new file.txt", "new.rs", "\"quoted\".txt"]
);
assert!(parse_porcelain("").is_empty());
}
#[test]
fn a_renames_old_path_is_never_read_as_a_record() {
// The old path could look like a record; it is skipped by position.
let text = "R new.rs\0 M fake.rs\0 M real.rs\0";
assert_eq!(parse_porcelain(text), vec!["new.rs", "real.rs"]);
// A work-tree rename (intent-to-add) carries the old path too.
assert_eq!(parse_porcelain(" R new.rs\0 M fake.rs\0"), vec!["new.rs"]);
}
#[test]
fn staged_names_are_split_on_nul() {
assert_eq!(
split_nul("a b.txt\0dir/c.rs\0"),
vec!["a b.txt", "dir/c.rs"]
);
assert!(split_nul("").is_empty());
}
#[test]
fn a_call_that_outlives_its_limit_is_stopped_and_says_so() {
#[cfg(windows)]
let cmd = {
let mut c = Command::new("ping");
c.args(["-n", "30", "127.0.0.1"]);
c
};
#[cfg(not(windows))]
let cmd = {
let mut c = Command::new("sleep");
c.arg("30");
c
};
let run = run_limited(cmd, None, Duration::from_millis(300));
assert!(!run.ok);
assert!(run.output.ends_with("(stopped after 1 second)"));
}
#[test]
fn stdin_reaches_the_child_and_its_output_is_kept() {
#[cfg(windows)]
let cmd = {
let mut c = Command::new("findstr");
c.arg("x*");
c
};
#[cfg(not(windows))]
let cmd = Command::new("cat");
let run = run_limited(cmd, Some("hello loop\n"), Duration::from_secs(10));
assert!(run.ok, "{}", run.output);
assert!(run.output.contains("hello loop"));
}
#[test]
fn the_first_json_object_in_mixed_output_is_parsed() {
let run = ToolRun {
ok: true,
code: Some(0),
output: "warning: noise\n{\"ok\":true,\"n\":1}\n".to_string(),
};
assert_eq!(parse_json_object(&run).unwrap()["n"], 1);
}
}
+404 -12
View File
@@ -11,9 +11,10 @@ use plan2code_app_lib::attention::{self, Badge, Signal};
use plan2code_app_lib::console_supervisor::{
app_origin, origin_of, session_on_disk, ConsoleSupervisor,
};
use plan2code_app_lib::loop_driver::{self, Hooks, LastLoop, LoopFacts, LoopSlot};
use plan2code_app_lib::node_check;
use plan2code_app_lib::project::{self, ProjectDir};
use plan2code_app_lib::quit_prompt::{quit_prompt, QuitCase};
use plan2code_app_lib::quit_prompt::{loop_quit_prompt, quit_prompt, QuitCase};
use plan2code_app_lib::restart_brief;
use plan2code_app_lib::settings;
#[cfg(windows)]
@@ -49,6 +50,13 @@ struct AppState {
// The app itself, once it is set up: the agent's sink clears the taskbar
// through it when the agent ends.
app: Arc<OnceLock<tauri::AppHandle>>,
// The Implementation Loop running now, if any: in memory only, so an app
// restart ends it (NFR-5).
loop_run: LoopSlot,
// The last loop's project, spec, launch choice and confirmed quick check,
// kept after the running record is gone so Resume, Fix it by hand and
// Finalize still work. Memory only.
last_loop: Mutex<Option<LastLoop>>,
}
// The console page's last state as the taskbar shows it (attention.rs), and
@@ -225,6 +233,7 @@ fn agent_for_project(state: &AppState) -> Result<Arc<AgentManager>, String> {
let sink = page_sink(Arc::clone(&state.page), Arc::clone(&state.app));
let agent = Arc::new(AgentManager::new(dir, sink));
agent.set_before_fresh(before_fresh_hook(state));
agent.set_forget_session(forget_session_hook(state));
*guard = Some(Arc::clone(&agent));
Ok(agent)
}
@@ -253,6 +262,19 @@ fn before_fresh_hook(state: &AppState) -> BeforeFresh {
})
}
// What the loop does before a phase's fresh agent starts: forget the console
// session the window follows, so the new agent's `open` starts its own.
fn forget_session_hook(state: &AppState) -> plan2code_app_lib::agent_manager::ForgetSession {
let announce = Arc::clone(&state.announce);
Arc::new(move || {
if let Ok(guard) = announce.lock() {
if let Some(server) = guard.as_ref() {
server.forget_current();
}
}
})
}
fn current_agent(state: &AppState) -> Option<Arc<AgentManager>> {
state.agent.lock().ok().and_then(|guard| guard.clone())
}
@@ -332,6 +354,20 @@ fn sync_agent_env(app: &tauri::AppHandle) {
// the same frontend id; dropping one (as happened here when it replaced the
// reattach registration) sends the frontend an "end" message that
// unregisters that id for good, breaking all future sends through it.
// The window's own commands that would end or replace the loop's agent refuse
// while a loop runs, between phases too (the slot holds a record then). The
// loop's own agent starts go through `loop_driver::start_with`, not these
// commands, and `agent_input` stays open so a trust or login prompt can be
// answered.
fn refuse_while_looping(state: &AppState, what: &str) -> Result<(), String> {
if loop_driver::is_running(&state.loop_run) {
return Err(format!(
"A loop is running. Stop it before you change the {what}."
));
}
Ok(())
}
#[tauri::command]
#[allow(clippy::too_many_arguments)] // one argument per key the frontend passes to invoke
fn agent_start(
@@ -344,6 +380,7 @@ fn agent_start(
cols: u16,
rows: u16,
) -> Result<(), String> {
refuse_while_looping(&state, "agent")?;
let kind = agents::find_agent(&kind).ok_or_else(|| format!("unknown agent: {kind}"))?;
let mode =
PermissionMode::from_id(&mode).ok_or_else(|| format!("unknown permission mode: {mode}"))?;
@@ -376,6 +413,7 @@ fn agent_resize(state: State<'_, AppState>, cols: u16, rows: u16) -> Result<(),
#[tauri::command]
fn agent_restart(state: State<'_, AppState>) -> Result<(), String> {
refuse_while_looping(&state, "agent")?;
current_agent(&state)
.ok_or("no agent has been started")?
.restart()
@@ -434,7 +472,11 @@ fn confirm_quit(app: &tauri::AppHandle) {
.lock()
.ok()
.and_then(|guard| guard.last);
let prompt = quit_prompt(last);
// A running loop has its own words, naming what is committed.
let prompt = match loop_driver::quit_facts(&app.state::<AppState>().loop_run) {
Some((phase, phases, committed)) => loop_quit_prompt(phase, phases, &committed),
None => quit_prompt(last),
};
#[cfg(windows)]
{
if let Some(parent) = app
@@ -462,12 +504,12 @@ fn confirm_quit(app: &tauri::AppHandle) {
// reads Esc as "not the first button".
let app = app.clone();
app.dialog()
.message(prompt.message)
.title(prompt.heading)
.message(prompt.message.clone())
.title(prompt.heading.clone())
.kind(kind)
.buttons(MessageDialogButtons::OkCancelCustom(
prompt.quit.to_string(),
prompt.stay.to_string(),
prompt.quit.clone(),
prompt.stay.clone(),
))
.show({
let app = app.clone();
@@ -480,13 +522,19 @@ fn confirm_quit(app: &tauri::AppHandle) {
});
}
// A running loop counts even between two phases, when no agent runs for a moment.
fn agent_is_active(app: &tauri::AppHandle) -> bool {
current_agent(&app.state::<AppState>()).is_some_and(|agent| agent.is_active())
let state = app.state::<AppState>();
loop_driver::is_running(&state.loop_run)
|| current_agent(&state).is_some_and(|agent| agent.is_active())
}
// Stops the agent, then the console, then exits.
// Stops the loop, the agent, then the console, then exits. The loop goes first:
// its record is dropped without a word to the page, so its watch thread never
// takes the ended agent for a crash.
fn quit_app(app: &tauri::AppHandle) {
let state = app.state::<AppState>();
loop_driver::abandon(&state.loop_run);
if let Some(agent) = current_agent(&state) {
agent.stop();
}
@@ -503,10 +551,17 @@ fn quit_app(app: &tauri::AppHandle) {
// person's move or needs attention while the window is not focused. An
// unknown word does nothing.
#[tauri::command]
fn set_attention(app: tauri::AppHandle, state: State<'_, AppState>, signal: String) {
let Some(next) = Signal::from_id(&signal) else {
return;
};
fn set_attention(app: tauri::AppHandle, signal: String) {
if let Some(next) = Signal::from_id(&signal) {
apply_signal(&app, next);
}
}
// The dot and the flash for a state. The page's `attention` message comes here,
// and so does the loop when a question starts holding it: the dot and flash
// then do not depend on the page, which is locked while the loop drives.
fn apply_signal(app: &tauri::AppHandle, next: Signal) {
let state = app.state::<AppState>();
let Some(window) = app.get_webview_window("main") else {
return;
};
@@ -733,6 +788,7 @@ fn pick_project_folder(
app: tauri::AppHandle,
state: State<'_, AppState>,
) -> Result<Option<String>, String> {
refuse_while_looping(&state, "project")?;
let picked = app
.dialog()
.file()
@@ -781,6 +837,7 @@ fn change_project(
app: tauri::AppHandle,
state: State<'_, AppState>,
) -> Result<Option<String>, String> {
refuse_while_looping(&state, "project")?;
let picked = app
.dialog()
.file()
@@ -844,6 +901,290 @@ fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
Ok(())
}
// What the setup screen shows about the agent a loop would use: the running
// agent's launch choice, else what the launcher chose.
#[tauri::command]
fn loop_facts(state: State<'_, AppState>) -> LoopFacts {
let running = state
.loop_run
.lock()
.map(|guard| guard.is_some())
.unwrap_or(false);
if let Some((agent, model, effort, mode)) =
current_agent(&state).and_then(|a| a.launch_choice())
{
return LoopFacts {
agent: Some(agent.id().to_string()),
agent_label: Some(agent.label().to_string()),
model,
effort,
permission_mode: Some(mode.id().to_string()),
prompt_support: loop_driver::prompt_support(&agent),
running,
};
}
let agent = state.launch.agent.as_deref().and_then(agents::find_agent);
LoopFacts {
agent: agent.as_ref().map(|a| a.id().to_string()),
agent_label: agent.as_ref().map(|a| a.label().to_string()),
model: state.launch.model.clone(),
effort: None,
permission_mode: None,
prompt_support: agent.as_ref().is_none_or(loop_driver::prompt_support),
running,
}
}
// What the loop tells the window and the taskbar: the strip's state on every
// change, and the app's own attention when a question holds it.
fn loop_hooks(app: &tauri::AppHandle) -> Hooks {
let for_strip = app.clone();
let for_attention = app.clone();
Hooks {
emit: Box::new(move |event| {
let _ = for_strip.emit("loop-state", &event);
}),
attention: Box::new(move || apply_signal(&for_attention, Signal::Attention)),
}
}
// Starts a loop on `spec`: checks, the app's own confirm, then the first phase.
// Async so the confirm's blocking dialog never waits on the main thread. The
// setup comes from `loop-setup.json`, never from the page's message. With
// `skip_confirm_if_same`, the confirm is skipped when the quick check and the
// web address are the ones the person last confirmed (Resume): a changed one is
// asked again.
async fn start_loop(
app: &tauri::AppHandle,
state: &AppState,
spec: String,
skip_confirm_if_same: bool,
) -> Result<bool, String> {
if loop_driver::is_running(&state.loop_run) {
return Err("A loop is already running".to_string());
}
let project = state
.project
.lock()
.map_err(|e| e.to_string())?
.as_ref()
.map(|p| p.dir.clone())
.ok_or("no project folder chosen")?;
let agent = current_agent(state)
.filter(|a| a.folder() == &project)
.ok_or("Start an agent first, with permission checks off.")?;
// A stopped agent has forgotten its launch choice; the last loop kept it.
let launch = agent
.launch_choice()
.or_else(|| {
state
.last_loop
.lock()
.ok()
.and_then(|last| last.as_ref().map(|l| l.launch.clone()))
})
.ok_or("Start an agent first, with permission checks off.")?;
// Resume (the only caller that skips the confirm) on a spec this app
// stopped: the stopped phase's uncommitted work is expected in the tree.
let resuming = skip_confirm_if_same
&& state.last_loop.lock().ok().is_some_and(|last| {
last.as_ref()
.is_some_and(|l| l.project == project && l.spec == spec)
});
let record = loop_driver::prepare(
&project,
&spec,
launch.3,
loop_driver::prompt_support(&launch.0),
resuming,
)?;
let check = record.setup.quick_check.clone();
let notify = loop_driver::confirmed_notify(&record.setup);
// A Resume that rebuilds a phase or takes uncommitted files into its commit
// is asked again: the confirm is where the person is told.
let unchanged = skip_confirm_if_same
&& record.rebuilt.is_empty()
&& record.resumed_files.is_none()
&& !loop_driver::commits_to_trunk(&record)
&& state
.last_loop
.lock()
.map_err(|e| e.to_string())?
.as_ref()
.is_some_and(|last| {
last.project == project
&& last.spec == spec
&& last.confirmed_check == check
&& last.confirmed_notify == notify
});
if !unchanged {
let go = app
.dialog()
.message(loop_driver::confirm_text(&record))
.title("Implementation Loop")
.kind(MessageDialogKind::Info)
.buttons(MessageDialogButtons::OkCancelCustom(
"Start".to_string(),
"Cancel".to_string(),
))
.blocking_show();
if !go {
return Ok(false);
}
}
loop_driver::reopen_rebuilt(&record)?;
loop_driver::begin(
&state.loop_run,
agent,
record,
launch.clone(),
loop_hooks(app),
)?;
if let Ok(mut last) = state.last_loop.lock() {
*last = Some(LastLoop {
project,
spec,
launch,
confirmed_check: check,
confirmed_notify: notify,
});
}
Ok(true)
}
#[tauri::command]
async fn loop_start(
app: tauri::AppHandle,
state: State<'_, AppState>,
spec: String,
) -> Result<bool, String> {
start_loop(&app, &state, spec, false).await
}
// Send a test: the setup screen saved first, and the address comes from
// `loop-setup.json`, never from the page's message. The app names it in its own
// confirm. Answers whether a test was sent: false when the person said no.
#[tauri::command]
async fn loop_notify_test(
app: tauri::AppHandle,
state: State<'_, AppState>,
) -> Result<bool, String> {
let project = state
.project
.lock()
.map_err(|e| e.to_string())?
.as_ref()
.map(|p| p.dir.clone())
.ok_or("no project folder chosen")?;
let setup = loop_driver::read_setup(&project)?;
let text = loop_driver::notify_test_confirm(&setup)?;
let go = app
.dialog()
.message(text)
.title("Implementation Loop")
.kind(MessageDialogKind::Info)
.buttons(MessageDialogButtons::OkCancelCustom(
"Send".to_string(),
"Cancel".to_string(),
))
.blocking_show();
if !go {
return Ok(false);
}
// The HTTP client blocks, and panics on an async runtime's own thread.
tauri::async_runtime::spawn_blocking(move || loop_driver::send_notify_test(&setup))
.await
.map_err(|e| e.to_string())??;
Ok(true)
}
// Stop after this phase: it finishes its review, mark and commit, then the
// loop stops instead of starting the next.
#[tauri::command]
fn loop_stop_after_phase(
app: tauri::AppHandle,
state: State<'_, AppState>,
on: bool,
) -> Result<(), String> {
let event = loop_driver::request_stop_after(&state.loop_run, on)?;
let _ = app.emit("loop-state", &event);
Ok(())
}
// Stop now: the flag is set first, then the agent (if one is running) ends at
// once. The page asked the person first ("End the agent now? This phase's
// changes stay uncommitted."); the strip says Stopping, and the driver tells
// the stop screen on its next look.
#[tauri::command]
fn loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> {
let agent = current_agent(&state);
// The event goes out before the agent is ended (which can take a while), so
// the strip's "ended" can never be followed by an older "Stopping".
loop_driver::request_stop_now(&state.loop_run, agent.as_deref(), |event| {
let _ = app.emit("loop-state", event);
})?;
Ok(())
}
// What the loop is doing, for a window that just loaded or just started
// listening: the strip event, or nothing when no loop runs.
#[tauri::command]
fn loop_state(state: State<'_, AppState>) -> Option<loop_driver::LoopStateEvent> {
loop_driver::current_event(&state.loop_run)
}
// The last loop, for the stop and finish screens' buttons.
fn last_loop(state: &AppState) -> Result<LastLoop, String> {
if loop_driver::is_running(&state.loop_run) {
return Err("A loop is running".to_string());
}
let last = state
.last_loop
.lock()
.map_err(|e| e.to_string())?
.clone()
.ok_or("No loop has run in this session")?;
let here = state
.project
.lock()
.map_err(|e| e.to_string())?
.as_ref()
.map(|p| p.dir.clone());
if here.as_ref() != Some(&last.project) {
return Err("The project changed since that loop".to_string());
}
Ok(last)
}
// Resume: start again on the same spec. The app reads the setup and the
// spec's marks afresh; the Start dialog is skipped only while the quick check
// is the one the person last confirmed.
#[tauri::command]
async fn loop_resume(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> {
let last = last_loop(&state)?;
start_loop(&app, &state, last.spec, true).await.map(|_| ())
}
// Fix it by hand: an ordinary Implement session on the stopped phase, with no
// `--loop`, so the person talks to the agent as usual.
#[tauri::command]
fn loop_fix(state: State<'_, AppState>) -> Result<(), String> {
let last = last_loop(&state)?;
let agent = current_agent(&state).ok_or("No agent is available")?;
loop_driver::start_with(&agent, &last.launch, loop_driver::fix_prompt(&last.spec))
}
#[tauri::command]
fn loop_finalize(state: State<'_, AppState>) -> Result<(), String> {
let last = last_loop(&state)?;
let agent = current_agent(&state).ok_or("No agent is available")?;
loop_driver::start_with(
&agent,
&last.launch,
loop_driver::finalize_prompt(&last.spec),
)
}
fn main() {
// Without Node 18+ the console and skills cannot run: say so and stop (FR-13).
let status = node_check::check_node();
@@ -890,6 +1231,15 @@ fn main() {
console_start,
console_status,
console_stop,
loop_start,
loop_notify_test,
loop_facts,
loop_stop_after_phase,
loop_stop_now,
loop_state,
loop_resume,
loop_fix,
loop_finalize,
set_attention,
clear_attention_cmd,
set_taskbar_signal
@@ -918,6 +1268,8 @@ fn main() {
let taken =
take_announced(&state, &notice, window_origin(&handle), session_on_disk);
if taken {
// A running loop follows its phase's session from here.
loop_driver::note_page(&state.loop_run, &notice.workflow, &notice.sid);
let _ = handle.emit("console-page", &notice);
} else {
eprintln!(
@@ -1204,6 +1556,46 @@ mod tests {
)
}
fn state_with_loop(running: bool) -> AppState {
let state = state_for("project-a");
if running {
*state.loop_run.lock().unwrap() = Some(loop_driver::RunningRecord::new(
PathBuf::from("project-a"),
"specs/x".into(),
loop_driver::LoopSetup::default(),
vec![],
));
}
state
}
#[test]
fn the_window_refuses_to_change_project_or_agent_while_a_loop_runs() {
let state = state_with_loop(true);
let project = refuse_while_looping(&state, "project").expect_err("a loop is running");
assert!(project.contains("A loop is running"), "{project:?}");
assert!(project.contains("project"), "{project:?}");
let agent = refuse_while_looping(&state, "agent").expect_err("a loop is running");
assert!(agent.contains("change the agent."), "{agent:?}");
}
#[test]
fn the_window_changes_project_and_agent_freely_with_no_loop() {
let state = state_with_loop(false);
assert!(refuse_while_looping(&state, "project").is_ok());
assert!(refuse_while_looping(&state, "agent").is_ok());
}
#[test]
fn loop_state_data_is_none_with_no_loop_and_the_strip_event_with_one() {
let idle = state_with_loop(false);
assert!(loop_driver::current_event(&idle.loop_run).is_none());
let busy = state_with_loop(true);
let event = loop_driver::current_event(&busy.loop_run).expect("a loop runs");
assert!(event.running);
assert_eq!(event.spec_name, "x");
}
#[test]
fn teardown_clears_the_console_so_console_start_refuses_not_reconnects() {
let Some(sup) = real_console() else { return };
+90 -26
View File
@@ -2,7 +2,9 @@
//! agent is not mid-step at all but waiting on the person's answer in the web
//! console, so the check reads the page's last taskbar signal (attention.rs)
//! and says which case it is. Anything it cannot be sure of is the working
//! case, the safer warning. Knows nothing about Tauri; main.rs shows it.
//! case, the safer warning. While the Implementation Loop builds a phase the
//! words are the loop's own (`loop_quit_prompt`). Knows nothing about Tauri;
//! main.rs shows it.
use crate::attention::Signal;
@@ -16,38 +18,73 @@ pub enum QuitCase {
}
/// Everything the box says.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QuitPrompt {
pub case: QuitCase,
pub title: &'static str,
pub heading: &'static str,
pub message: &'static str,
pub quit: &'static str,
pub stay: &'static str,
pub title: String,
pub heading: String,
pub message: String,
pub quit: String,
pub stay: String,
}
fn words(case: QuitCase, heading: &str, message: &str, quit: &str) -> QuitPrompt {
QuitPrompt {
case,
title: "Plan2Code".to_string(),
heading: heading.to_string(),
message: message.to_string(),
quit: quit.to_string(),
stay: "Stay".to_string(),
}
}
/// The prompt for the page's last signal (`None` before the page has sent one).
pub fn quit_prompt(last: Option<Signal>) -> QuitPrompt {
match last {
Some(Signal::Ready | Signal::Plain) => QuitPrompt {
case: QuitCase::Waiting,
title: "Plan2Code",
heading: "Done for now?",
message: "Your agent is just waiting on your next answer. Quit and this session ends.",
quit: "Quit",
stay: "Stay",
},
Some(Signal::Busy | Signal::Attention) | None => QuitPrompt {
case: QuitCase::Working,
title: "Plan2Code",
heading: "Leave while your agent is busy?",
message: "If you quit now, the agent stops mid-step. Everything it has saved so far stays put.",
quit: "Quit and stop it",
stay: "Stay",
},
Some(Signal::Ready | Signal::Plain) => words(
QuitCase::Waiting,
"Done for now?",
"Your agent is just waiting on your next answer. Quit and this session ends.",
"Quit",
),
Some(Signal::Busy | Signal::Attention) | None => words(
QuitCase::Working,
"Leave while your agent is busy?",
"If you quit now, the agent stops mid-step. Everything it has saved so far stays put.",
"Quit and stop it",
),
}
}
/// "Phase 1", "Phases 1 and 2", "Phases 1, 2 and 3".
fn phase_list(committed: &[u32]) -> String {
let numbers: Vec<String> = committed.iter().map(u32::to_string).collect();
match numbers.as_slice() {
[] => String::new(),
[one] => format!("Phase {one}"),
[init @ .., last] => format!("Phases {} and {last}", init.join(", ")),
}
}
/// The words for quitting while the Implementation Loop builds a phase.
/// `committed` lists the phase numbers already committed.
pub fn loop_quit_prompt(phase: u32, phases: u32, committed: &[u32]) -> QuitPrompt {
let done = match committed.len() {
0 => "No phase is committed yet".to_string(),
1 => format!("{} is committed", phase_list(committed)),
_ => format!("{} are committed", phase_list(committed)),
};
words(
QuitCase::Working,
"Stop the loop and quit?",
&format!(
"Phase {phase} of {phases} is mid-build. {done}; this phase's changes stay uncommitted."
),
"Quit and stop the loop",
)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -92,11 +129,38 @@ mod tests {
#[test]
fn no_text_carries_an_em_dash() {
for last in [None, Some(Signal::Busy), Some(Signal::Ready)] {
let p = quit_prompt(last);
for text in [p.title, p.heading, p.message, p.quit, p.stay] {
let mut all = vec![loop_quit_prompt(2, 4, &[1]), loop_quit_prompt(1, 4, &[])];
all.extend([None, Some(Signal::Busy), Some(Signal::Ready)].map(quit_prompt));
for p in all {
for text in [&p.title, &p.heading, &p.message, &p.quit, &p.stay] {
assert!(!text.contains('\u{2014}'), "{text}");
}
}
}
#[test]
fn the_loop_wording_names_what_is_committed() {
let none = loop_quit_prompt(1, 4, &[]);
assert_eq!(none.heading, "Stop the loop and quit?");
assert_eq!(none.title, "Plan2Code");
assert_eq!(none.quit, "Quit and stop the loop");
assert_eq!(none.stay, "Stay");
assert_eq!(none.case, QuitCase::Working);
assert_eq!(
none.message,
"Phase 1 of 4 is mid-build. No phase is committed yet; this phase's changes stay uncommitted."
);
assert_eq!(
loop_quit_prompt(2, 4, &[1]).message,
"Phase 2 of 4 is mid-build. Phase 1 is committed; this phase's changes stay uncommitted."
);
assert_eq!(
loop_quit_prompt(3, 4, &[1, 2]).message,
"Phase 3 of 4 is mid-build. Phases 1 and 2 are committed; this phase's changes stay uncommitted."
);
assert_eq!(
loop_quit_prompt(4, 4, &[1, 2, 3]).message,
"Phase 4 of 4 is mid-build. Phases 1, 2 and 3 are committed; this phase's changes stay uncommitted."
);
}
}
+5 -5
View File
@@ -53,11 +53,11 @@ unsafe extern "system" fn on_event(
/// Quit was pressed; anything else (Stay, Esc, the close button, a failure to
/// show the box) keeps the app open.
pub fn ask(parent: HWND, prompt: &QuitPrompt) -> bool {
let title = wide(prompt.title);
let heading = wide(prompt.heading);
let message = wide(prompt.message);
let quit = wide(prompt.quit);
let stay = wide(prompt.stay);
let title = wide(&prompt.title);
let heading = wide(&prompt.heading);
let message = wide(&prompt.message);
let quit = wide(&prompt.quit);
let stay = wide(&prompt.stay);
let buttons = [
TASKDIALOG_BUTTON {
nButtonID: ID_QUIT,