Prove repo swarm stop classification cases

This commit is contained in:
Meta Vens 2026-06-20 19:19:06 +01:00
commit f780984b9a
6 changed files with 475 additions and 36 deletions

View file

@ -0,0 +1,393 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use chrono::Utc;
use serde_json::Value;
use serde_json::json;
use std::env;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
fn main() -> Result<()> {
let args = Args::parse()?;
let result = run_smoke(args)?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
#[derive(Clone, Debug)]
struct Args {
root: PathBuf,
smoke_root: PathBuf,
}
impl Args {
fn parse() -> Result<Self> {
let mut root = env::current_dir().context("failed to resolve current directory")?;
let mut smoke_root = root.join(".epiphany-smoke");
let mut args = env::args().skip(1).peekable();
while let Some(arg) = args.next() {
match arg.as_str() {
"--root" => root = take_path(&mut args, "--root")?,
"--smoke-root" => smoke_root = take_path(&mut args, "--smoke-root")?,
other => return Err(anyhow!("unexpected argument {other:?}")),
}
}
Ok(Self { root, smoke_root })
}
}
fn run_smoke(args: Args) -> Result<Value> {
let root = args
.root
.canonicalize()
.with_context(|| format!("failed to resolve {}", args.root.display()))?;
let manifest = root.join("epiphany-core").join("Cargo.toml");
if !manifest.exists() {
return Err(anyhow!(
"could not find epiphany-core manifest at {}",
manifest.display()
));
}
fs::create_dir_all(&args.smoke_root)
.with_context(|| format!("failed to create {}", args.smoke_root.display()))?;
let stamp = Utc::now().format("%Y%m%d-%H%M%S").to_string();
let smoke_dir = args
.smoke_root
.join(format!("swarm-stop-classification-{stamp}"));
if smoke_dir.exists() {
fs::remove_dir_all(&smoke_dir)
.with_context(|| format!("failed to clear {}", smoke_dir.display()))?;
}
fs::create_dir_all(&smoke_dir)
.with_context(|| format!("failed to create {}", smoke_dir.display()))?;
let repo = smoke_dir.join("repo-body");
fs::create_dir_all(&repo).with_context(|| format!("failed to create {}", repo.display()))?;
git(["init"], &repo)?;
git(
["config", "user.email", "epiphany-smoke@example.invalid"],
&repo,
)?;
git(["config", "user.name", "Epiphany Smoke"], &repo)?;
fs::write(
repo.join("README.md"),
"# Swarm Stop Classification Smoke\n\nThis repository proves typed repo-swarm run stop classification.\n",
)
.with_context(|| format!("failed to seed {}", repo.join("README.md").display()))?;
git(["add", "README.md"], &repo)?;
git(
["commit", "-m", "Seed swarm stop classification smoke"],
&repo,
)?;
let runtime_id = "swarm-stop-classification-smoke";
let local_verse = repo.join(".epiphany").join("local-verse.ccmp");
cargo_json(
&manifest,
"epiphany-repo",
&[
"init",
"--workspace",
path_str(&repo)?,
"--epiphany-root",
path_str(&root)?,
"--swarm-id",
runtime_id,
"--topic",
"swarm-stop-classification",
],
&root,
)?;
cargo_json(
&manifest,
"epiphany-swarm",
&[
"online",
"--workspace",
path_str(&repo)?,
"--epiphany-root",
path_str(&root)?,
"--runtime-id",
runtime_id,
"--local-verse-store",
path_str(&local_verse)?,
],
&root,
)?;
let empty_run = cargo_json(
&manifest,
"epiphany-swarm",
&[
"run",
"--workspace",
path_str(&repo)?,
"--epiphany-root",
path_str(&root)?,
"--runtime-id",
runtime_id,
"--local-verse-store",
path_str(&local_verse)?,
"--max-iterations",
"1",
"--max-items",
"1",
"--cooldown-seconds",
"0",
],
&root,
)?;
require_eq(
&empty_run,
&["stopClassification", "schemaVersion"],
"epiphany.repo_swarm_run_stop_classification.v0",
)?;
require_eq(
&empty_run,
&["stopClassification", "category"],
"queue-empty",
)?;
require_eq(&empty_run, &["stopClassification", "owner"], "Gjallar")?;
require_eq(
&empty_run,
&["stopClassification", "authorityGate"],
"repo.work.overview",
)?;
require_eq(
&empty_run,
&["stopClassification", "blocker"],
"no-repo-work-rows",
)?;
require_bool(&empty_run, &["stopClassification", "mutatesState"], false)?;
require_bool(
&empty_run,
&["stopClassification", "requiresElevatedAuthority"],
false,
)?;
require_bool(
&empty_run,
&["stopClassification", "privateStateExposed"],
false,
)?;
let item = "dry-run-preview";
cargo_json(
&manifest,
"epiphany-work",
&[
"accept",
"--workspace",
path_str(&repo)?,
"--from",
"persona",
"--item",
item,
"--summary",
"Prove a dry-run swarm pulse can classify a ready-to-run queue row without mutation.",
"--candidate-action-ref",
"candidate-action://swarm-stop-classification/dry-run-preview",
"--public-discussion-ref",
"eve://epiphany/persona/swarm-stop-classification",
],
&root,
)?;
cargo_json(
&manifest,
"epiphany-work",
&[
"derive-plan",
"--workspace",
path_str(&repo)?,
"--item",
item,
"--action-family",
"planning-note",
"--model-ref",
"swarm-stop-classification-smoke-imagination-v1",
"--model-authored",
],
&root,
)?;
cargo_json(
&manifest,
"epiphany-work",
&["overview", "--workspace", path_str(&repo)?, "--item", item],
&root,
)?;
let dry_run = cargo_json(
&manifest,
"epiphany-swarm",
&[
"run",
"--workspace",
path_str(&repo)?,
"--epiphany-root",
path_str(&root)?,
"--runtime-id",
runtime_id,
"--local-verse-store",
path_str(&local_verse)?,
"--max-iterations",
"1",
"--max-items",
"1",
"--cooldown-seconds",
"0",
"--dry-run",
],
&root,
)?;
require_eq(
&dry_run,
&["stopClassification", "schemaVersion"],
"epiphany.repo_swarm_run_stop_classification.v0",
)?;
require_eq(
&dry_run,
&["stopClassification", "category"],
"dry-run-preview",
)?;
require_eq(&dry_run, &["stopClassification", "owner"], "Self")?;
require_eq(
&dry_run,
&["stopClassification", "authorityGate"],
"ready-to-run",
)?;
require_eq(&dry_run, &["stopClassification", "selectedItem"], item)?;
require_bool(&dry_run, &["stopClassification", "mutatesState"], false)?;
require_bool(
&dry_run,
&["stopClassification", "requiresElevatedAuthority"],
false,
)?;
require_bool(
&dry_run,
&["stopClassification", "privateStateExposed"],
false,
)?;
let summary = json!({
"schemaVersion": "epiphany.repo_swarm_stop_classification_smoke.v0",
"status": "ok",
"smokeDir": smoke_dir,
"repo": repo,
"emptyStopCategory": empty_run["stopClassification"]["category"],
"emptyStopOwner": empty_run["stopClassification"]["owner"],
"emptyStopGate": empty_run["stopClassification"]["authorityGate"],
"dryRunStopCategory": dry_run["stopClassification"]["category"],
"dryRunStopOwner": dry_run["stopClassification"]["owner"],
"dryRunStopGate": dry_run["stopClassification"]["authorityGate"],
"dryRunSelectedItem": dry_run["stopClassification"]["selectedItem"],
"mutatesState": false,
"requiresElevatedAuthority": false,
"privateStateExposed": false,
});
write_json(&smoke_dir.join("summary.json"), &summary)?;
Ok(summary)
}
fn cargo_json(manifest: &Path, bin: &str, args: &[&str], cwd: &Path) -> Result<Value> {
let output = Command::new("cargo")
.arg("run")
.arg("--quiet")
.arg("--manifest-path")
.arg(manifest)
.arg("--bin")
.arg(bin)
.arg("--")
.args(args)
.current_dir(cwd)
.output()
.with_context(|| format!("failed to run cargo bin {bin}"))?;
if !output.status.success() {
return Err(anyhow!(
"{bin} failed with status {:?}\nstdout:\n{}\nstderr:\n{}",
output.status.code(),
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
));
}
serde_json::from_slice(&output.stdout).with_context(|| {
format!(
"{bin} did not emit JSON on stdout:\n{}",
String::from_utf8_lossy(&output.stdout)
)
})
}
fn git<const N: usize>(args: [&str; N], cwd: &Path) -> Result<()> {
let output = Command::new("git")
.args(args)
.current_dir(cwd)
.output()
.with_context(|| format!("failed to run git in {}", cwd.display()))?;
if output.status.success() {
Ok(())
} else {
Err(anyhow!(
"git failed in {} with status {:?}\nstdout:\n{}\nstderr:\n{}",
cwd.display(),
output.status.code(),
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
))
}
}
fn write_json(path: &Path, value: &Value) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("failed to create {}", parent.display()))?;
}
fs::write(path, serde_json::to_vec_pretty(value)?)
.with_context(|| format!("failed to write {}", path.display()))
}
fn require_eq(value: &Value, path: &[&str], expected: &str) -> Result<()> {
let actual = path
.iter()
.try_fold(value, |current, key| current.get(*key))
.and_then(Value::as_str)
.unwrap_or("<missing>");
if actual == expected {
Ok(())
} else {
Err(anyhow!(
"expected {} to be {expected:?}, got {actual:?}",
path.join(".")
))
}
}
fn require_bool(value: &Value, path: &[&str], expected: bool) -> Result<()> {
let actual = path
.iter()
.try_fold(value, |current, key| current.get(*key))
.and_then(Value::as_bool);
if actual == Some(expected) {
Ok(())
} else {
Err(anyhow!(
"expected {} to be {expected}, got {:?}",
path.join("."),
actual
))
}
}
fn take_path(
args: &mut std::iter::Peekable<impl Iterator<Item = String>>,
flag: &str,
) -> Result<PathBuf> {
args.next()
.map(PathBuf::from)
.with_context(|| format!("missing value for {flag}"))
}
fn path_str(path: &Path) -> Result<&str> {
path.to_str()
.ok_or_else(|| anyhow!("path is not valid UTF-8: {}", path.display()))
}

View file

@ -543,34 +543,54 @@ fn classify_run_stop(
.and_then(|iteration| iteration.get("selectedRows"))
.and_then(Value::as_array)
.and_then(|rows| rows.first());
let selected_gate = selected_row
.and_then(|row| row.get("gate"))
.and_then(Value::as_str)
.unwrap_or("none");
let selected_blocker = selected_row
.and_then(|row| row.get("blocker"))
.and_then(Value::as_str)
.unwrap_or("none");
let selected_next_safe_move = selected_row
.and_then(|row| row.get("nextSafeMove"))
.and_then(Value::as_str)
.unwrap_or(next_safe_move);
let selected_item = selected_row
.and_then(|row| row.get("item"))
.and_then(Value::as_str)
.unwrap_or("none");
let selected_branch = selected_row
.and_then(|row| row.get("branch"))
.and_then(Value::as_str)
.unwrap_or("none");
let selected_output = final_iteration
.and_then(|iteration| iteration.get("outputs"))
.and_then(Value::as_array)
.and_then(|outputs| outputs.first());
let refreshed_overview = selected_output.and_then(|output| output.get("refreshedOverview"));
let selected_gate = selected_output
.and_then(|output| non_empty_string(output.get("gateBefore")))
.or_else(|| {
refreshed_overview.and_then(|overview| non_empty_string(overview.get("currentGate")))
})
.or_else(|| selected_row.and_then(|row| non_empty_string(row.get("gate"))))
.or_else(|| compact_row_field(selected_row, "gate"))
.unwrap_or_else(|| "none".to_string());
let selected_blocker = selected_output
.and_then(|output| non_empty_string(output.get("blockerBefore")))
.or_else(|| {
refreshed_overview.and_then(|overview| non_empty_string(overview.get("blocker")))
})
.or_else(|| selected_row.and_then(|row| non_empty_string(row.get("blocker"))))
.or_else(|| compact_row_field(selected_row, "blocker"))
.unwrap_or_else(|| "none".to_string());
let selected_next_safe_move = selected_output
.and_then(|output| output.get("tick"))
.and_then(|tick| non_empty_string(tick.get("nextSafeMove")))
.or_else(|| {
refreshed_overview.and_then(|overview| non_empty_string(overview.get("nextSafeMove")))
})
.or_else(|| selected_row.and_then(|row| non_empty_string(row.get("nextSafeMove"))))
.or_else(|| compact_row_field(selected_row, "next"))
.unwrap_or_else(|| next_safe_move.to_string());
let selected_item = selected_output
.and_then(|output| non_empty_string(output.get("item")))
.or_else(|| selected_row.and_then(|row| non_empty_string(row.get("item"))))
.or_else(|| compact_row_field(selected_row, "item"))
.unwrap_or_else(|| "none".to_string());
let selected_branch = refreshed_overview
.and_then(|overview| non_empty_string(overview.get("branch")))
.or_else(|| selected_row.and_then(|row| non_empty_string(row.get("branch"))))
.or_else(|| compact_row_field(selected_row, "branch"))
.unwrap_or_else(|| "none".to_string());
let (category, owner, gate, blocker, recommended_command, mutates_state, requires_elevation) =
match stop_reason {
"dry-run-preview-complete" => (
"dry-run-preview",
"Self",
selected_gate,
selected_blocker,
selected_gate.as_str(),
selected_blocker.as_str(),
"epiphany-swarm run --workspace <repo> --until blocked-or-published",
false,
false,
@ -594,14 +614,14 @@ fn classify_run_stop(
false,
),
"blocked-or-noop" if actionable_count == 0 => {
let owner = match selected_gate {
let owner = match selected_gate.as_str() {
"awaiting-publication" => "Bifrost",
"awaiting-sync" => "Bifrost/GitHub",
"awaiting-closure" => "Soul",
"ready-to-run" | "ready-to-adopt" | "ready-to-execute" => "Self",
_ => "Self",
};
let recommended = match selected_gate {
let recommended = match selected_gate.as_str() {
"awaiting-publication" => {
"epiphany-work publish --workspace <repo> --closure-receipt <receipt>"
}
@ -616,8 +636,8 @@ fn classify_run_stop(
(
"authority-gated",
owner,
selected_gate,
selected_blocker,
selected_gate.as_str(),
selected_blocker.as_str(),
recommended,
false,
false,
@ -626,8 +646,8 @@ fn classify_run_stop(
_ => (
"unknown",
"Self",
selected_gate,
selected_blocker,
selected_gate.as_str(),
selected_blocker.as_str(),
"epiphany-work overview --workspace <repo>",
false,
false,
@ -663,6 +683,27 @@ fn classify_run_stop(
})
}
fn non_empty_string(value: Option<&Value>) -> Option<String> {
value
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToString::to_string)
}
fn compact_row_field(row: Option<&Value>, field: &str) -> Option<String> {
let prefix = format!("{field}=");
row.and_then(Value::as_str)
.and_then(|row| {
row.split('|')
.map(str::trim)
.find_map(|part| part.strip_prefix(&prefix))
})
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToString::to_string)
}
fn queue_run_args(
args: &RunArgs,
workspace: &Path,