Move MVP coordinator surface to Rust

This commit is contained in:
Meta Vens 2026-05-06 08:41:11 +01:00
commit a23cd0ab74
8 changed files with 902 additions and 959 deletions

View file

@ -0,0 +1,800 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use serde_json::Value;
use serde_json::json;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::thread;
use std::time::{Duration, Instant};
#[allow(dead_code)]
#[path = "epiphany-mvp-status.rs"]
mod status_cli;
const DEFAULT_APP_SERVER: &str = r"C:\Users\Meta\.cargo-target-codex\debug\codex-app-server.exe";
const REORIENT_BINDING_ID: &str = "reorient-worker";
const GRAPH_NODE_ID: &str = "reorient-target";
const WATCHED_RELATIVE_PATH: &str = "src/reorient_target.rs";
fn main() -> Result<()> {
let args = Args::parse()?;
let summary = run_coordinator(&args)?;
println!("{}", serde_json::to_string_pretty(&summary)?);
Ok(())
}
#[derive(Debug)]
struct Args {
app_server: PathBuf,
thread_id: Option<String>,
cwd: PathBuf,
codex_home: PathBuf,
artifact_dir: PathBuf,
agent_memory_dir: PathBuf,
mode: String,
max_steps: usize,
poll_seconds: f64,
timeout_seconds: u64,
max_runtime_seconds: u64,
ephemeral: bool,
auto_review: bool,
bootstrap_smoke_state: bool,
simulate_high_pressure: bool,
simulate_source_drift: bool,
dry_compact: bool,
}
impl Args {
fn parse() -> Result<Self> {
let root = env::current_dir().context("failed to resolve current dir")?;
let mut args = env::args().skip(1);
let mut parsed = Args {
app_server: PathBuf::from(DEFAULT_APP_SERVER),
thread_id: None,
cwd: root.clone(),
codex_home: env::var_os("CODEX_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| home_dir().join(".codex")),
artifact_dir: root.join(".epiphany-dogfood").join("coordinator"),
agent_memory_dir: root.join("state").join("agents.msgpack"),
mode: "plan".to_string(),
max_steps: 4,
poll_seconds: 5.0,
timeout_seconds: 240,
max_runtime_seconds: 180,
ephemeral: true,
auto_review: false,
bootstrap_smoke_state: false,
simulate_high_pressure: false,
simulate_source_drift: false,
dry_compact: false,
};
while let Some(arg) = args.next() {
match arg.as_str() {
"--app-server" => parsed.app_server = take_path(&mut args, "--app-server")?,
"--thread-id" => parsed.thread_id = Some(take_string(&mut args, "--thread-id")?),
"--cwd" => parsed.cwd = take_path(&mut args, "--cwd")?,
"--codex-home" => parsed.codex_home = take_path(&mut args, "--codex-home")?,
"--artifact-dir" => parsed.artifact_dir = take_path(&mut args, "--artifact-dir")?,
"--agent-memory-dir" => {
parsed.agent_memory_dir = take_path(&mut args, "--agent-memory-dir")?;
}
"--mode" => parsed.mode = take_string(&mut args, "--mode")?,
"--max-steps" => {
parsed.max_steps = take_string(&mut args, "--max-steps")?.parse()?
}
"--poll-seconds" => {
parsed.poll_seconds = take_string(&mut args, "--poll-seconds")?.parse()?;
}
"--timeout-seconds" => {
parsed.timeout_seconds =
take_string(&mut args, "--timeout-seconds")?.parse()?;
}
"--max-runtime-seconds" => {
parsed.max_runtime_seconds =
take_string(&mut args, "--max-runtime-seconds")?.parse()?;
}
"--ephemeral" => parsed.ephemeral = true,
"--no-ephemeral" => parsed.ephemeral = false,
"--auto-review" => parsed.auto_review = true,
"--test-complete-backend" => {
return Err(anyhow!(
"--test-complete-backend was removed: native coordinator refuses direct private state-store job mutation; use live workers or a future CultNet job-result API"
));
}
"--bootstrap-smoke-state" => parsed.bootstrap_smoke_state = true,
"--simulate-high-pressure" => parsed.simulate_high_pressure = true,
"--simulate-source-drift" => parsed.simulate_source_drift = true,
"--dry-compact" => parsed.dry_compact = true,
other => return Err(anyhow!("unknown argument: {other}")),
}
}
Ok(parsed)
}
}
fn run_coordinator(args: &Args) -> Result<Value> {
let app_server = status_cli::absolute_path(&args.app_server)?;
let mut cwd = status_cli::absolute_path(&args.cwd)?;
let codex_home = status_cli::absolute_path(&args.codex_home)?;
let artifact_dir = status_cli::absolute_path(&args.artifact_dir)?;
let agent_memory_dir = status_cli::absolute_path(&args.agent_memory_dir)?;
reset_artifact_dir(&artifact_dir)?;
fs::create_dir_all(&codex_home)?;
if args.bootstrap_smoke_state {
cwd = artifact_dir.join("workspace");
prepare_workspace(&cwd)?;
}
let transcript_path = artifact_dir.join("epiphany-transcript.jsonl");
let stderr_path = artifact_dir.join("epiphany-server.stderr.log");
let telemetry_path = artifact_dir.join("agent-function-telemetry.json");
let steps_path = artifact_dir.join("coordinator-steps.jsonl");
let mut steps = Vec::new();
let mut snapshots = Vec::new();
let mut startup_events = Vec::new();
let mut final_status = Value::Null;
let mut final_action = Value::Null;
let mut client = status_cli::AppServerClient::start(
&app_server,
&codex_home,
&transcript_path,
&stderr_path,
)?;
client.send(
"initialize",
Some(json!({
"clientInfo": {
"name": "epiphany-mvp-coordinator",
"title": "Epiphany MVP Coordinator",
"version": "0.1.0",
},
"capabilities": {"experimentalApi": true},
})),
true,
)?;
client.send("initialized", None, false)?;
let thread_id = if let Some(thread_id) = &args.thread_id {
let resumed = client.send("thread/resume", Some(json!({"threadId": thread_id})), true)?;
startup_events.push(thread_lifecycle_event("threadResume", &resumed));
thread_id.clone()
} else {
let started = client.send(
"thread/start",
Some(json!({"cwd": cwd, "ephemeral": args.ephemeral})),
true,
)?;
startup_events.push(thread_lifecycle_event("threadStart", &started));
text_at(&started, &["thread", "id"])?
};
if args.bootstrap_smoke_state {
client.send(
"thread/epiphany/update",
Some(json!({"threadId": thread_id, "expectedRevision": 0, "patch": reorient_patch()})),
true,
)?;
if args.simulate_source_drift {
let _ = client.send(
"thread/epiphany/freshness",
Some(json!({"threadId": thread_id})),
true,
);
fs::write(
cwd.join(WATCHED_RELATIVE_PATH),
"pub fn reorient_target() -> &'static str {\n \"after\"\n}\n",
)?;
thread::sleep(Duration::from_millis(500));
}
}
for index in 0..args.max_steps {
let status = collect_coordinator_status(&mut client, &thread_id)?;
let mut coordinator = status
.get("coordinator")
.cloned()
.unwrap_or_else(|| json!({"action": "regatherManually"}));
let mut action = coordinator["action"]
.as_str()
.unwrap_or("regatherManually")
.to_string();
if args.simulate_high_pressure && index == 0 {
action = "compactRehydrateReorient".to_string();
coordinator["action"] = json!(action);
coordinator["canAutoRun"] = json!(true);
coordinator["requiresReview"] = json!(false);
coordinator["reason"] = json!("Simulated high pressure requested by smoke test.");
}
let snapshot_name = format!("step-{index:02}-{action}.txt");
fs::write(
artifact_dir.join(&snapshot_name),
status_cli::render_status(&status_cli::sanitize_for_operator(status.clone())),
)?;
snapshots.push(snapshot_name);
let mut step = json!({
"index": index,
"action": action,
"coordinator": coordinator,
"stateRevision": state_revision(&status),
"events": [],
});
final_status = status.clone();
final_action = coordinator.clone();
if args.mode == "plan" {
append_jsonl(&steps_path, &step)?;
steps.push(step);
break;
}
if is_stop_action(&action) && !args.auto_review {
append_jsonl(&steps_path, &step)?;
steps.push(step);
break;
}
let revision = state_revision(&status);
match action.as_str() {
"reviewModelingResult" => {
let result = client.send(
"thread/epiphany/roleResult",
Some(json!({"threadId": thread_id, "roleId": "modeling"})),
true,
)?;
push_event(
&mut step,
json!({"type": "roleResult", "roleId": "modeling", "result": status_cli::sanitize_for_operator(result.clone())}),
);
let can_accept = args.auto_review
&& result.pointer("/finding/statePatch").is_some()
&& revision.is_some();
if !can_accept {
final_action =
json!({"action": "reviewModelingResult", "reason": result["note"]});
append_jsonl(&steps_path, &step)?;
steps.push(step);
break;
}
let accepted = client.send(
"thread/epiphany/roleAccept",
Some(json!({"threadId": thread_id, "roleId": "modeling", "expectedRevision": revision})),
true,
)?;
if let Some(memory) = maybe_apply_role_self_patch(&accepted, &agent_memory_dir)? {
let mut accepted_with_memory = accepted.clone();
accepted_with_memory["selfMemoryApply"] = memory;
push_event(
&mut step,
json!({"type": "roleAccept", "roleId": "modeling", "accepted": status_cli::sanitize_for_operator(accepted_with_memory)}),
);
} else {
push_event(
&mut step,
json!({"type": "roleAccept", "roleId": "modeling", "accepted": status_cli::sanitize_for_operator(accepted)}),
);
}
final_status = collect_coordinator_status(&mut client, &thread_id)?;
}
"launchModeling" | "launchVerification" => {
let role_id = if action == "launchModeling" {
"modeling"
} else {
"verification"
};
let launch = launch_role(
&mut client,
&thread_id,
role_id,
revision,
args.max_runtime_seconds,
)?;
push_event(
&mut step,
json!({"type": "roleLaunch", "roleId": role_id, "launch": status_cli::sanitize_for_operator(launch.clone())}),
);
let result = wait_for_role_result(&mut client, &thread_id, role_id, args)?;
push_event(
&mut step,
json!({"type": "roleResult", "roleId": role_id, "result": status_cli::sanitize_for_operator(result.clone())}),
);
final_status = collect_coordinator_status(&mut client, &thread_id)?;
if !args.auto_review {
final_action = json!({
"action": if role_id == "modeling" { "reviewModelingResult" } else { "reviewVerificationResult" },
"reason": result["note"],
});
append_jsonl(&steps_path, &step)?;
steps.push(step);
break;
}
}
"launchReorientWorker" => {
let launch =
launch_reorient(&mut client, &thread_id, revision, args.max_runtime_seconds)?;
push_event(
&mut step,
json!({"type": "reorientLaunch", "launch": status_cli::sanitize_for_operator(launch.clone())}),
);
let result = wait_for_reorient_result(&mut client, &thread_id, args)?;
push_event(
&mut step,
json!({"type": "reorientResult", "result": status_cli::sanitize_for_operator(result.clone())}),
);
final_status = collect_coordinator_status(&mut client, &thread_id)?;
if !args.auto_review {
final_action =
json!({"action": "reviewReorientResult", "reason": result["note"]});
append_jsonl(&steps_path, &step)?;
steps.push(step);
break;
}
}
"compactRehydrateReorient" => {
if args.dry_compact {
push_event(
&mut step,
json!({"type": "dryCompact", "threadId": thread_id}),
);
append_jsonl(&steps_path, &step)?;
steps.push(step);
continue;
}
push_event(
&mut step,
json!({"type": "compactUnsupportedInNativeSmoke"}),
);
}
_ => {}
}
append_jsonl(&steps_path, &step)?;
steps.push(step);
}
let operator_final_status = status_cli::sanitize_for_operator(final_status);
let final_rendered = status_cli::render_status(&operator_final_status);
let operator_steps = status_cli::sanitize_for_operator(Value::Array(steps));
let summary = json!({
"objective": "Coordinate the Epiphany MVP lanes over existing app-server APIs.",
"artifactDir": artifact_dir,
"codexHome": codex_home,
"workspace": cwd,
"threadId": operator_final_status["threadId"],
"mode": args.mode,
"startupEvents": startup_events,
"steps": operator_steps,
"snapshots": snapshots,
"finalAction": status_cli::sanitize_for_operator(final_action),
"finalStatus": operator_final_status,
"artifactManifest": [
"coordinator-summary.json",
"coordinator-steps.jsonl",
"coordinator-final-status.json",
"coordinator-final-status.txt",
"coordinator-final-action.txt",
"agent-function-telemetry.json"
],
"sealedArtifactManifest": [
{"path": "epiphany-transcript.jsonl", "reason": "sealed JSON-RPC audit trail; do not read during normal supervision"},
{"path": "epiphany-server.stderr.log", "reason": "sealed app-server diagnostics; inspect only for explicit debugging"}
]
});
write_json(&artifact_dir.join("coordinator-summary.json"), &summary)?;
write_json(
&artifact_dir.join("coordinator-final-status.json"),
&summary["finalStatus"],
)?;
fs::write(
artifact_dir.join("coordinator-final-status.txt"),
final_rendered,
)?;
fs::write(
artifact_dir.join("coordinator-final-action.txt"),
format!(
"{}\n",
serde_json::to_string_pretty(&summary["finalAction"])?
),
)?;
status_cli::write_transcript_telemetry(&transcript_path, &telemetry_path)?;
Ok(summary)
}
fn collect_coordinator_status(
client: &mut status_cli::AppServerClient,
thread_id: &str,
) -> Result<Value> {
let read = client.send(
"thread/read",
Some(json!({"threadId": thread_id, "includeTurns": false})),
true,
)?;
let scene = client.send(
"thread/epiphany/scene",
Some(json!({"threadId": thread_id})),
true,
)?;
let pressure = client.send(
"thread/epiphany/pressure",
Some(json!({"threadId": thread_id})),
true,
)?;
let reorient = client.send(
"thread/epiphany/reorient",
Some(json!({"threadId": thread_id})),
true,
)?;
let jobs = client.send(
"thread/epiphany/jobs",
Some(json!({"threadId": thread_id})),
true,
)?;
let roles = client.send(
"thread/epiphany/roles",
Some(json!({"threadId": thread_id})),
true,
)?;
let planning = client.send(
"thread/epiphany/planning",
Some(json!({"threadId": thread_id})),
true,
)?;
let role_results = json!({
"imagination": client.send("thread/epiphany/roleResult", Some(json!({"threadId": thread_id, "roleId": "imagination"})), true)?,
"modeling": client.send("thread/epiphany/roleResult", Some(json!({"threadId": thread_id, "roleId": "modeling"})), true)?,
"verification": client.send("thread/epiphany/roleResult", Some(json!({"threadId": thread_id, "roleId": "verification"})), true)?,
});
let reorient_result = client.send(
"thread/epiphany/reorientResult",
Some(json!({"threadId": thread_id})),
true,
)?;
let crrc = client.send(
"thread/epiphany/crrc",
Some(json!({"threadId": thread_id})),
true,
)?;
let coordinator = client.send(
"thread/epiphany/coordinator",
Some(json!({"threadId": thread_id})),
true,
)?;
let root = env::current_dir()?;
let heartbeat_dir = root.join(".epiphany-heartbeats");
let face_dir = root.join(".epiphany-face");
let heartbeat = status_cli::native_json(
"epiphany-heartbeat-store",
&[
"status",
"--store",
"state/agent-heartbeats.msgpack",
"--artifact-dir",
&heartbeat_dir.to_string_lossy(),
"--limit",
"8",
],
)?;
let latest_face = status_cli::native_json(
"epiphany-face-discord",
&[
"latest",
"--artifact-dir",
&face_dir.to_string_lossy(),
"--limit",
"8",
],
)
.unwrap_or_else(|_| json!({"latestArtifacts": []}));
Ok(json!({
"threadId": thread_id,
"read": read,
"scene": scene,
"pressure": pressure,
"reorient": reorient,
"jobs": jobs,
"roles": roles,
"planning": planning,
"roleResults": role_results,
"reorientResult": reorient_result,
"crrc": crrc,
"coordinator": coordinator,
"heartbeat": heartbeat,
"face": {
"status": "ready",
"artifactDir": face_dir,
"latestArtifacts": latest_face.get("latestArtifacts").cloned().unwrap_or_else(|| json!([])),
"availableActions": ["faceBubble"],
},
}))
}
fn launch_role(
client: &mut status_cli::AppServerClient,
thread_id: &str,
role_id: &str,
expected_revision: Option<i64>,
max_runtime_seconds: u64,
) -> Result<Value> {
let mut payload =
json!({"threadId": thread_id, "roleId": role_id, "maxRuntimeSeconds": max_runtime_seconds});
if let Some(revision) = expected_revision {
payload["expectedRevision"] = json!(revision);
}
client.send("thread/epiphany/roleLaunch", Some(payload), true)
}
fn launch_reorient(
client: &mut status_cli::AppServerClient,
thread_id: &str,
expected_revision: Option<i64>,
max_runtime_seconds: u64,
) -> Result<Value> {
let mut payload = json!({"threadId": thread_id, "maxRuntimeSeconds": max_runtime_seconds});
if let Some(revision) = expected_revision {
payload["expectedRevision"] = json!(revision);
}
client.send("thread/epiphany/reorientLaunch", Some(payload), true)
}
fn wait_for_role_result(
client: &mut status_cli::AppServerClient,
thread_id: &str,
role_id: &str,
args: &Args,
) -> Result<Value> {
let deadline = Instant::now() + Duration::from_secs(args.timeout_seconds);
let mut latest = Value::Null;
while Instant::now() < deadline {
latest = client.send(
"thread/epiphany/roleResult",
Some(json!({"threadId": thread_id, "roleId": role_id})),
true,
)?;
if matches!(
latest["status"].as_str(),
Some("completed" | "failed" | "cancelled")
) {
return Ok(latest);
}
thread::sleep(Duration::from_secs_f64(args.poll_seconds));
}
Ok(latest)
}
fn wait_for_reorient_result(
client: &mut status_cli::AppServerClient,
thread_id: &str,
args: &Args,
) -> Result<Value> {
let deadline = Instant::now() + Duration::from_secs(args.timeout_seconds);
let mut latest = Value::Null;
while Instant::now() < deadline {
latest = client.send(
"thread/epiphany/reorientResult",
Some(json!({"threadId": thread_id, "bindingId": REORIENT_BINDING_ID})),
true,
)?;
if matches!(
latest["status"].as_str(),
Some("completed" | "failed" | "cancelled")
) {
return Ok(latest);
}
thread::sleep(Duration::from_secs_f64(args.poll_seconds));
}
Ok(latest)
}
fn maybe_apply_role_self_patch(accepted: &Value, agent_memory_dir: &Path) -> Result<Option<Value>> {
let finding = &accepted["finding"];
let self_patch = &finding["selfPatch"];
let review = &finding["selfPersistence"];
if !self_patch.is_object() || !review.is_object() {
return Ok(None);
}
if review["status"].as_str() != Some("accepted") {
return Ok(Some(json!({
"status": "rejected",
"targetAgentId": review["targetAgentId"],
"targetPath": review["targetPath"],
"reasons": review["reasons"],
"applied": false,
})));
}
let role_id = accepted["roleId"]
.as_str()
.ok_or_else(|| anyhow!("roleAccept response did not include roleId"))?;
let patch = serde_json::to_string(self_patch)?;
let output = status_cli::native_json(
"epiphany-agent-memory-store",
&[
"apply-patch",
"--store",
&agent_memory_dir.to_string_lossy(),
"--role-id",
role_id,
"--patch",
&patch,
],
)?;
let mut output = output;
output["appliedFromRoleAccept"] = json!(true);
Ok(Some(output))
}
fn reorient_patch() -> Value {
json!({
"objective": "Decide whether a durable checkpoint still deserves to be resumed after rehydrate.",
"activeSubgoalId": "phase6-reorient-smoke",
"subgoals": [{
"id": "phase6-reorient-smoke",
"title": "Live-smoke CRRC reorientation policy",
"status": "active",
"summary": "Resume when the checkpoint is still aligned; regather when the touched file proves it isn't.",
}],
"graphs": {
"architecture": {"nodes": [{
"id": GRAPH_NODE_ID,
"title": "Reorient target",
"purpose": "Map the file the watcher will touch so reorientation can notice drift.",
"code_refs": [{"path": WATCHED_RELATIVE_PATH, "start_line": 1, "end_line": 3, "symbol": "reorient_target"}],
}]},
"dataflow": {"nodes": []},
"links": [],
},
"graphFrontier": {"active_node_ids": [GRAPH_NODE_ID], "dirty_paths": []},
"graphCheckpoint": {
"checkpoint_id": "ck-reorient-1",
"graph_revision": 1,
"summary": "Reorientation smoke graph checkpoint",
"frontier_node_ids": [GRAPH_NODE_ID],
},
"investigationCheckpoint": {
"checkpoint_id": "ix-reorient-1",
"kind": "source_gathering",
"disposition": "resume_ready",
"focus": "Verify the touched file before broad edits.",
"summary": "This checkpoint should remain resumable until the watched source moves.",
"next_action": "Resume the bounded slice if the watched source still matches the checkpoint.",
"captured_at_turn_id": "turn-phase6-reorient",
"code_refs": [{"path": WATCHED_RELATIVE_PATH, "start_line": 1, "end_line": 3, "symbol": "reorient_target"}],
},
"churn": {
"understanding_status": "ready",
"diff_pressure": "low",
"graph_freshness": "fresh",
"unexplained_writes": 0,
},
})
}
fn prepare_workspace(workspace: &Path) -> Result<()> {
if workspace.exists() {
fs::remove_dir_all(workspace)?;
}
let watched = workspace.join(WATCHED_RELATIVE_PATH);
fs::create_dir_all(watched.parent().unwrap())?;
fs::write(
watched,
"pub fn reorient_target() -> &'static str {\n \"before\"\n}\n",
)?;
Ok(())
}
fn reset_artifact_dir(path: &Path) -> Result<()> {
let root = env::current_dir()?
.join(".epiphany-dogfood")
.canonicalize()
.or_else(|_| {
let root = env::current_dir()?.join(".epiphany-dogfood");
fs::create_dir_all(&root)?;
root.canonicalize()
})?;
let resolved_parent = path.parent().unwrap_or_else(|| Path::new("."));
fs::create_dir_all(resolved_parent)?;
let resolved = if path.exists() {
path.canonicalize()?
} else {
resolved_parent
.canonicalize()?
.join(path.file_name().unwrap())
};
if resolved == root || !resolved.starts_with(&root) {
return Err(anyhow!(
"refusing to delete non-dogfood artifact dir: {}",
path.display()
));
}
if path.exists() {
fs::remove_dir_all(path)?;
}
fs::create_dir_all(path)?;
Ok(())
}
fn state_revision(status: &Value) -> Option<i64> {
status
.pointer("/read/thread/epiphanyState/revision")
.and_then(Value::as_i64)
.or_else(|| {
status
.pointer("/scene/scene/revision")
.and_then(Value::as_i64)
})
}
fn thread_lifecycle_event(kind: &str, response: &Value) -> Value {
json!({
"type": kind,
"threadId": response.pointer("/thread/id"),
"status": response.pointer("/thread/status"),
"cwd": response.pointer("/thread/cwd"),
"ephemeral": response.pointer("/thread/ephemeral"),
})
}
fn push_event(step: &mut Value, event: Value) {
step["events"].as_array_mut().unwrap().push(event);
}
fn is_stop_action(action: &str) -> bool {
matches!(
action,
"prepareCheckpoint"
| "reviewReorientResult"
| "regatherManually"
| "reviewModelingResult"
| "reviewVerificationResult"
| "continueImplementation"
)
}
fn write_json(path: &Path, value: &Value) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, format!("{}\n", serde_json::to_string_pretty(value)?))?;
Ok(())
}
fn append_jsonl(path: &Path, value: &Value) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
use std::io::Write;
let mut file = fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)?;
writeln!(file, "{}", serde_json::to_string(value)?)?;
Ok(())
}
fn text_at(value: &Value, path: &[&str]) -> Result<String> {
let mut cursor = value;
for key in path {
cursor = &cursor[*key];
}
cursor
.as_str()
.map(ToString::to_string)
.ok_or_else(|| anyhow!("missing string at {}", path.join(".")))
}
fn take_string(args: &mut impl Iterator<Item = String>, name: &str) -> Result<String> {
args.next()
.ok_or_else(|| anyhow!("{name} requires a value"))
}
fn take_path(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf> {
Ok(PathBuf::from(take_string(args, name)?))
}
fn home_dir() -> PathBuf {
env::var_os("USERPROFILE")
.or_else(|| env::var_os("HOME"))
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."))
}

View file

@ -262,7 +262,7 @@ fn run_status(args: &Args) -> Result<Value> {
Ok(sanitize_for_operator(status))
}
struct AppServerClient {
pub struct AppServerClient {
child: Child,
stdin: ChildStdin,
rx: mpsc::Receiver<Value>,
@ -271,7 +271,7 @@ struct AppServerClient {
}
impl AppServerClient {
fn start(
pub fn start(
app_server: &Path,
codex_home: &Path,
transcript_path: &Path,
@ -355,7 +355,7 @@ impl AppServerClient {
})
}
fn send(
pub fn send(
&mut self,
method: &str,
params: Option<Value>,
@ -436,7 +436,7 @@ impl Drop for AppServerClient {
}
}
fn render_status(status: &Value) -> String {
pub fn render_status(status: &Value) -> String {
let scene = &status["scene"]["scene"];
let pressure = &status["pressure"]["pressure"];
let reorient = &status["reorient"]["decision"];
@ -611,7 +611,7 @@ fn render_status(status: &Value) -> String {
format!("{}\n", lines.join("\n"))
}
fn sanitize_for_operator(value: Value) -> Value {
pub fn sanitize_for_operator(value: Value) -> Value {
match value {
Value::Object(map) => {
let mut sanitized = serde_json::Map::new();
@ -650,7 +650,7 @@ fn sealed_direct_thought(key: &str, value: &Value) -> Value {
sealed
}
fn write_transcript_telemetry(transcript: &Path, output: &Path) -> Result<()> {
pub fn write_transcript_telemetry(transcript: &Path, output: &Path) -> Result<()> {
let _ = native_json(
"epiphany-agent-telemetry",
&[
@ -662,7 +662,7 @@ fn write_transcript_telemetry(transcript: &Path, output: &Path) -> Result<()> {
Ok(())
}
fn native_json(bin_name: &str, args: &[&str]) -> Result<Value> {
pub fn native_json(bin_name: &str, args: &[&str]) -> Result<Value> {
let exe = PathBuf::from(
env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| DEFAULT_CARGO_TARGET_DIR.to_string()),
)
@ -718,7 +718,7 @@ fn home_dir() -> PathBuf {
.unwrap_or_else(|| PathBuf::from("."))
}
fn absolute_path(path: &Path) -> Result<PathBuf> {
pub fn absolute_path(path: &Path) -> Result<PathBuf> {
if path.is_absolute() {
Ok(path.to_path_buf())
} else {

View file

@ -84,7 +84,7 @@ The landed machine now has:
- review-gated Phase 6 modeling acceptance through `thread/epiphany/roleAccept`, limited to completed modeling/checkpoint `statePatch` findings that apply graph/frontier/checkpoint/scratch/investigation-checkpoint changes through the existing state validator
- first Phase 6 dogfood operator view through native `epiphany-mvp-status`
- first auditable Phase 6 dogfood runner through `tools/epiphany_mvp_dogfood.py`, producing local status snapshots, sealed app-server transcript diagnostics, operator-safe final status artifacts, truthful vanilla-reference output, and comparison notes
- first auditable Phase 6 fixed-lane coordinator runner through `tools/epiphany_mvp_coordinator.py`, producing coordinator summary, JSONL steps, rendered snapshots, transcript, stderr, and final next-action artifacts while keeping semantic findings review-gated by default
- first auditable Phase 6 fixed-lane coordinator runner through native `epiphany-mvp-coordinator`, producing coordinator summary, JSONL steps, rendered snapshots, transcript, stderr, and final next-action artifacts while keeping semantic findings review-gated by default
- first auditable Phase 6 live-specialist runner through `tools/epiphany_mvp_live_specialist.py`, proving `roleLaunch -> agent_jobs worker -> report_agent_job_result -> roleResult` without manual backend completion
- first Phase 6 Aquarium operator shell extracted to sibling repo `E:\Projects\EpiphanyAquarium`, a Tauri v2 + React/WebGL client over the existing status bridge, dogfood artifacts, and GUI action artifacts, with its own distilled interface state/memory/doctrine plus durable checkpoint preparation, bounded status/coordinator artifact buttons, fixed modeling/verification/reorient launch and read-back buttons, and explicit review-gated reorient acceptance
- first Unity editor/runtime bridge through native `epiphany-unity-bridge`, `tools/epiphany_unity_bridge_smoke.py`, and the GUI Inspect Unity action, resolving exact project-pinned editors and writing runtime artifacts while refusing wrong or missing versions
@ -212,7 +212,7 @@ harness-native role ownership, and first fixed role specialist launch/result
blockers are now landed as
`thread/epiphany/reorientResult`, `thread/epiphany/reorientAccept`,
`thread/epiphany/crrc`, native `epiphany-mvp-status`,
`thread/epiphany/coordinator`, `tools/epiphany_mvp_coordinator.py`, and
`thread/epiphany/coordinator`, native `epiphany-mvp-coordinator`, and
`thread/epiphany/roles`, `thread/epiphany/roleLaunch`,
`thread/epiphany/roleResult`, and `thread/epiphany/roleAccept`. A human can now ask the harness what it believes,
what it recommends, which role lane owns the next visible work, which fixed-lane
@ -372,7 +372,7 @@ Implementation slices:
landed. Review gates remain explicit; the GUI does not auto-promote
evidence or continue implementation after semantic findings.
3. **Dogfood launcher**: wrap `tools/epiphany_mvp_dogfood.py` and
`tools/epiphany_mvp_coordinator.py` as explicit operator actions that write
native `epiphany-mvp-coordinator` as explicit operator actions that write
artifact bundles and stream progress/status into Aquarium.
4. **Usability pass**: make the current recommendation, blocked lane, pending
review, and next safe action visually obvious enough that the user can test

View file

@ -33,13 +33,13 @@ remembers doctrine; the branch remembers the blade.
- Phase 1 through Phase 5 are complete enough.
- Phase 6 has read-only `thread/epiphany/scene`, `thread/epiphany/jobs`, `thread/epiphany/roles`, `thread/epiphany/freshness`, `thread/epiphany/context`, `thread/epiphany/graphQuery`, `thread/epiphany/planning`, `thread/epiphany/pressure`, `thread/epiphany/reorient`, `thread/epiphany/crrc`, `thread/epiphany/coordinator`, `thread/epiphany/reorientResult`, and `thread/epiphany/roleResult`; durable `jobBindings` now act as a thin Epiphany-owned launcher seam with launcher id, authority scope, and backend kind/job id, `thread/epiphany/jobLaunch` / `thread/epiphany/jobInterrupt` / `thread/epiphany/roleLaunch` now provide explicit bounded authority over that seam, jobs can overlay it onto live runtime `agent_jobs` progress for loaded threads, and `thread/epiphany/jobsUpdated` now translates live `agent_job_progress:{json}` background events into changed launcher-bound notifications without polling or scheduling. Freshness carries watcher-backed invalidation inputs, graphQuery traverses authoritative typed graph neighborhoods and path/symbol matches without mutation, planning projects typed captures/backlog/roadmap/objective drafts without adopting work, roles project implementation/imagination/modeling/verification/reorientation ownership from existing signals without becoming a scheduler, `roleLaunch` can launch fixed Imagination/planning, modeling/checkpoint, or verification/review specialists, `roleResult` reads those outputs back as reviewable findings without mutation, `thread/epiphany/roleAccept` can apply reviewed Imagination planning-only `statePatch` findings and reviewed modeling/checkpoint `statePatch` findings through the existing state validator, reorient turns checkpoint plus freshness/pressure/watcher signals into a read-only resume-versus-regather verdict, `thread/epiphany/reorientLaunch` is the explicit runtime consumer over that verdict, `thread/epiphany/reorientResult` reads the launched worker output back as a reviewable finding without mutation or promotion, `thread/epiphany/reorientAccept` explicitly banks completed findings into accepted observation/evidence plus optional scratch/checkpoint state, `thread/epiphany/crrc` recommends the next explicit CRRC action without launching, accepting, compacting, scheduling, or mutating, and `thread/epiphany/coordinator` composes those signals into a fixed-lane MVP action recommendation without becoming a writer.
- Native `epiphany-mvp-status` is the first dogfood operator view. It starts or reads a thread through app-server and prints scene, planning, pressure, reorient, jobs, roles, Imagination/modeling/verification role result read-backs, reorient result, heartbeat, Face bubbles, and CRRC recommendation as text or JSON. The Python status module is now compatibility tissue for still-Python coordinator/GUI drivers, not the smoked product path.
- `tools/epiphany_mvp_coordinator.py` is the first auditable fixed-lane coordinator runner. It starts or reads a thread through app-server, follows the harness-native coordinator action, can auto-launch modeling, verification, or reorient-worker jobs, keeps semantic findings review-gated by default, and writes summary, steps, rendered snapshots, transcript, stderr, and final next-action artifacts under `.epiphany-dogfood/coordinator` or a caller-provided artifact directory.
- Native `epiphany-mvp-coordinator` is the first auditable fixed-lane coordinator runner. It starts or reads a thread through app-server, follows the harness-native coordinator action, can auto-launch modeling, verification, or reorient-worker jobs, keeps semantic findings review-gated by default, and writes summary, steps, rendered snapshots, transcript, stderr, and final next-action artifacts under `.epiphany-dogfood/coordinator` or a caller-provided artifact directory. It refuses direct backend-completion mutation; full completion smoke needs live workers or a CultNet job-result API.
- Native CRRC automation is now landed only at turn-complete safe boundaries. It may submit `Op::Compact` for coordinator-approved `compactRehydrateReorient` or for a successful pre-compaction checkpoint intervention's pending compact handoff, and it may launch the fixed `reorient-worker` for coordinator-approved `launchReorientWorker`. It does not auto-launch Imagination/modeling/verification, accept findings, promote evidence, edit implementation code, or keep going after reviewable semantic output.
- Pre-compaction checkpoint intervention is now landed. On token-count events for loaded Epiphany threads, when current context usage reaches 80% of the active auto-compact/context limit, the harness steers the active turn once with a CRRC checkpoint directive so the agent banks working context before compaction/reorientation. Pressure ignores cumulative token spend; cumulative-only telemetry reports unknown instead of yelling. A successful steer now latches a turn-scoped compact handoff that is consumed at clean turn completion, preventing the brake from decaying into another implementation turn. This is still bounded steering plus compaction handoff, not automatic semantic acceptance, a broad scheduler, or implementation continuation.
- `tools/epiphany_mvp_dogfood.py` is the first auditable dogfood runner. It drives a bounded state/role/CRRC/reorientation loop and writes local artifacts under `.epiphany-dogfood/mvp-loop`, including sealed app-server transcript diagnostics, rendered snapshots, operator-safe final status, vanilla-reference prompt/output, and comparison notes. The runner now writes truthful vanilla/comparison artifacts whether the optional vanilla reference is skipped, fails, or completes.
- `tools/epiphany_mvp_live_specialist.py` is the first auditable live-specialist runner. It launches a real role specialist through `thread/epiphany/roleLaunch`, lets the spawned worker report through `report_agent_job_result`, reads it back through `thread/epiphany/roleResult`, and writes local artifacts under `.epiphany-dogfood/live-specialist`.
- The Aquarium operator UI now lives in sibling repo `E:\Projects\EpiphanyAquarium`, not under `apps/epiphany-gui`. It is a Tauri v2 + React/WebGL interface organism over the existing status bridge, dogfood artifacts, and GUI action artifacts, not a new throne of truth. It has its own `AGENTS.md`, persistent `state/map.yaml`, `state/memory.json`, scratch/evidence files, and interface doctrine. EpiphanyAgent remains the authoritative harness/backend forge.
- Internal `agent_job:` workers now get the reporting tool independent of the user-facing CSV spawn feature, and ephemeral worker sessions can initialize the sqlite state runtime on demand so specialist reports land in the shared backend.
- Internal `agent_job:` workers now get the reporting tool independent of the user-facing CSV spawn feature, and ephemeral worker sessions can initialize the private Codex state runtime on demand so specialist reports land in the shared backend.
- Durable in-flight investigation checkpointing is now landed in authoritative typed state, writable through `thread/epiphany/update` or accepted `thread/epiphany/promote`, rendered into the prompt, and reflected through scene/context.
- The prompt doctrine pass is landed. Shared Epiphany prompts now carry distilled memory/evidence discipline. Rendered state intro/doctrine text lives in `epiphany-core/src/prompts/`, and lane/control prompt text lives in `vendor/codex/codex-rs/app-server/src/prompts/epiphany_specialists.toml`: modeling is the Body, implementation is the Hands and GUI-launched main coding lane, verification is the Soul, reorientation is Life, coordinator remains the read-only Self, and CRRC owns the pre-compaction intervention template.
- The Ghostlight memory pass is landed. `epiphany_specialists.toml` now has a shared persistent-memory projection prepended by the harness to fixed role specialists, reorientation workers, coordinator notes, and CRRC checkpoint interventions; `tools/epiphany_gui_action.py` prepends the same memory to GUI-launched implementation prompts. The rendered base doctrine also states the Perfect Machine rule directly: prompt is projection, durable typed state is the mind, every lane must improve its own memory/model/prompt/evidence habit or name the repair, and each lane phrases that duty in its own organ language so the salience sticks.
@ -467,7 +467,7 @@ Live `thread/epiphany/scene`, `thread/epiphany/jobs`, `thread/epiphany/roles`,
`thread/epiphany/freshness`, `thread/epiphany/context`,
`thread/epiphany/graphQuery`, `thread/epiphany/planning`, `thread/epiphany/pressure`,
`thread/epiphany/reorient`, `thread/epiphany/crrc`, `thread/epiphany/coordinator`,
native `epiphany-mvp-status`, `tools/epiphany_mvp_coordinator.py`, and
native `epiphany-mvp-status`, native `epiphany-mvp-coordinator`, and
`tools/epiphany_phase6_graph_query_smoke.py` / `tools/epiphany_phase6_planning_smoke.py`
/ `tools/epiphany_gui_planning_smoke.py`
smokes are now guardrails, not the next organs.

Binary file not shown.

View file

@ -107,7 +107,7 @@ accepted_design:
- `thread/epiphany/coordinator` is the first harness-native fixed-lane coordinator surface: it composes roles, pressure, reorient, CRRC, roleResult, and reorientResult into a read-only action recommendation with target role, source signals, review requirements, automation eligibility, reason, and current lane summaries without mutating state or launching work.
- Coordinator implementation clearance is stricter than review acceptance: an accepted verification/review finding only opens the implementation gate when its verdict is `pass`; accepted `needs-evidence`, `needs-review`, or `fail` findings send the loop back toward modeling/checkpoint strengthening or reorientation instead of blessing a sick machine.
- Coordinator regather handling is now fixed-lane first, not supervisor improvisation: `regatherManually` is a fallback only after reorient/modeling/verification review and launch lanes cannot advance the state, completed modeling findings must be reviewed before verification, and the CLI coordinator's explicit test-only `--auto-review` mode may accept modeling state patches before launching verification while production semantics remain review-gated.
- `tools/epiphany_mvp_coordinator.py` is the first auditable coordinator runner: it drives the fixed single-user lanes through app-server APIs, may auto-launch modeling, verification, or reorient-worker jobs, keeps semantic findings review-gated by default, and writes coordinator summaries, JSONL steps, rendered snapshots, transcript, stderr, and final next-action artifacts.
- Native `epiphany-mvp-coordinator` is the first auditable coordinator runner: it drives the fixed single-user lanes through app-server APIs, may auto-launch modeling, verification, or reorient-worker jobs, keeps semantic findings review-gated by default, and writes coordinator summaries, JSONL steps, rendered snapshots, transcript, stderr, and final next-action artifacts. It refuses direct backend-completion mutation; full specialist completion smoke must use live workers or a proper CultNet job-result API.
- Limited native CRRC automation is now wired only at turn-complete safe boundaries: it can submit a compact operation when the read-only coordinator recommends `compactRehydrateReorient` or when a successful pre-compaction checkpoint intervention left a pending compact handoff for the completed turn, and it can launch the fixed `reorient-worker` when the coordinator recommends `launchReorientWorker`. It does not auto-launch modeling or verification, auto-accept findings, promote evidence, edit implementation code, or continue after reviewable semantic results; the rite may carry the stretcher, not declare the patient healed.
- Pre-compaction checkpoint intervention is now wired at token-count boundaries: when a loaded Epiphany thread crosses the existing `shouldPrepareCompaction` pressure threshold during an active turn, the harness steers the active agent once for that turn with a bounded CRRC directive to bank scratch/checkpoint/map/evidence before compaction/reorientation. A successful steer marks a turn-scoped pending compact handoff consumed at clean turn completion; this is banking the fire before the dark, not semantic acceptance, broad scheduling, or automatic implementation continuation.
- Native `epiphany-mvp-status` is the first dogfood operator view: it starts or reads a thread through app-server and renders scene, planning, pressure, reorient, jobs, role result read-backs, reorient result, CRRC recommendation, heartbeat, Face bubbles, and MVP role lanes as text or JSON without becoming a state store. The Python status module remains compatibility tissue for still-Python coordinator/GUI drivers until those organs are cut over.
@ -120,7 +120,7 @@ accepted_design:
- After `thread/epiphany/reorientAccept`, CRRC recognizes the accepted reorientation finding and does not recommend accepting the same completed result again.
- `tools/epiphany_mvp_dogfood.py` is the auditable MVP dogfood runner: it drives state, role launch/result, CRRC drift, reorient launch/result/accept, rendered status snapshots, operator-safe status artifacts, and sealed app-server transcript diagnostics into a local artifact bundle, and it now writes truthful comparison artifacts whether the optional vanilla Codex reference is skipped, fails, or completes.
- `tools/epiphany_mvp_live_specialist.py` is the auditable live-specialist MVP runner: it launches a real modeling/checkpoint or verification/review specialist through `thread/epiphany/roleLaunch`, lets the spawned worker report through `report_agent_job_result`, reads the projected finding back through `thread/epiphany/roleResult`, and writes sealed transcript plus operator-safe status artifacts without manually completing backend rows.
- Internal `agent_job:` workers expose `report_agent_job_result` even when the user-facing CSV spawn feature is disabled, and ephemeral worker sessions can initialize the sqlite state runtime on demand so role specialists can report into the shared `agent_jobs` backend.
- Internal `agent_job:` workers expose `report_agent_job_result` even when the user-facing CSV spawn feature is disabled, and ephemeral worker sessions can initialize the private Codex state runtime on demand so role specialists can report into the shared `agent_jobs` backend.
- Epiphany safety doctrine is to separate cognition from actuation, keep authority explicit, make interruption sacred, stage capability release, and treat operator misuse as a normal design input rather than a rude hypothetical. The machine must have brakes before it receives larger engines.
- Epiphany is built in the open, but publication mode is not one-size-fits-all: use FOSS where viable, source-available licensing where economics or capability risk demand it, and commercial terms where organizations extract real enterprise value.
- `thread/epiphany/jobLaunch` and `thread/epiphany/jobInterrupt` are the first bounded authority surfaces over the thin job seam: they mutate durable `job_bindings`, create or cancel the current `agent_jobs` backend binding, and preserve explicit launcher identity and interruption without turning `thread/epiphany/jobs` into a scheduler.
@ -181,7 +181,7 @@ landed_baseline:
- Phase 6 role ownership: read-only `thread/epiphany/roles` over implementation, modeling/checkpoint, verification/review, and reorientation lanes.
- Phase 6 role specialists: explicit `thread/epiphany/roleLaunch` and read-only `thread/epiphany/roleResult` templates for modeling/checkpoint and verification/review.
- Phase 6 modeling role acceptance: explicit `thread/epiphany/roleAccept` for reviewed modeling/checkpoint `statePatch` findings that can grow graphs/frontier/checkpoints through the existing state validator.
- Phase 6 coordinator: read-only `thread/epiphany/coordinator` plus `tools/epiphany_mvp_coordinator.py` and smoke coverage for the fixed-lane MVP loop.
- Phase 6 coordinator: read-only `thread/epiphany/coordinator` plus native `epiphany-mvp-coordinator` and smoke coverage for the fixed-lane MVP loop.
- Phase 6 safe-boundary CRRC automation: turn-complete automation limited to coordinator-approved compact, successful pre-compaction handoff compact, and fixed reorient-worker launch actions.
- Phase 6 pre-compaction checkpoint intervention: token-count pressure hook that steers active turns once when `shouldPrepareCompaction` is reached so working context is banked before compaction, then latches a pending compact handoff for clean turn completion.
- Phase 6 Aquarium extraction: the Tauri v2 + React/WebGL operator console moved from embedded `apps/epiphany-gui` into sibling repo `E:\Projects\EpiphanyAquarium`, with its own distilled interface state, memory, doctrine, build, visual smoke, and Tauri check.

View file

@ -1,805 +0,0 @@
from __future__ import annotations
import argparse
import json
import os
import shutil
import subprocess
import time
from pathlib import Path
from typing import Any
from epiphany_mvp_status import DEFAULT_APP_SERVER
from epiphany_mvp_status import collect_status
from epiphany_mvp_status import render_status
from epiphany_mvp_status import sanitize_for_operator
from epiphany_mvp_status import write_transcript_telemetry
from epiphany_phase5_smoke import AppServerClient
from epiphany_phase5_smoke import ROOT
from epiphany_phase5_smoke import require
from epiphany_phase6_reorient_launch_smoke import BINDING_ID as REORIENT_BINDING_ID
from epiphany_phase6_reorient_launch_smoke import complete_reorient_backend_job
from epiphany_phase6_reorient_smoke import prepare_workspace
from epiphany_phase6_reorient_smoke import reorient_patch
from epiphany_phase6_role_smoke import MODELING_BINDING_ID
from epiphany_phase6_role_smoke import VERIFICATION_BINDING_ID
from epiphany_phase6_role_smoke import complete_role_backend_job
DEFAULT_ARTIFACT_DIR = ROOT / ".epiphany-dogfood" / "coordinator"
DEFAULT_CODEX_HOME = Path(os.environ.get("CODEX_HOME", Path.home() / ".codex"))
DEFAULT_AGENT_MEMORY_DIR = ROOT / "state" / "agents.msgpack"
TERMINAL_ROLE_STATUSES = {"completed", "failed", "cancelled"}
TERMINAL_REORIENT_STATUSES = {"completed", "failed", "cancelled"}
STOP_ACTIONS = {
"prepareCheckpoint",
"reviewReorientResult",
"regatherManually",
"reviewModelingResult",
"reviewVerificationResult",
"continueImplementation",
}
def native_agent_memory(*args: str) -> dict[str, Any]:
exe = Path(os.environ.get("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex")) / "debug" / "epiphany-agent-memory-store.exe"
if exe.exists():
command = [str(exe), *args]
else:
command = [
"cargo",
"run",
"--quiet",
"--manifest-path",
str(ROOT / "epiphany-core" / "Cargo.toml"),
"--bin",
"epiphany-agent-memory-store",
"--",
*args,
]
completed = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, check=False)
if completed.returncode != 0:
raise RuntimeError(completed.stderr.strip() or completed.stdout.strip() or "epiphany-agent-memory-store failed")
return json.loads(completed.stdout)
def maybe_apply_role_self_patch(
response: dict[str, Any], *, agent_memory_dir: Path
) -> dict[str, Any] | None:
finding = response.get("finding")
if not isinstance(finding, dict):
return None
self_patch = finding.get("selfPatch")
review = finding.get("selfPersistence")
if not isinstance(self_patch, dict) or not isinstance(review, dict):
return None
if review.get("status") != "accepted":
return {
"status": "rejected",
"targetAgentId": review.get("targetAgentId"),
"targetPath": review.get("targetPath"),
"reasons": review.get("reasons") or ["coordinator refused the selfPatch"],
"applied": False,
}
role_id = response.get("roleId")
if not isinstance(role_id, str) or not role_id:
return {
"status": "rejected",
"reasons": ["roleAccept response did not include a roleId for selfPatch application"],
"applied": False,
}
result = native_agent_memory(
"apply-patch",
"--store",
str(agent_memory_dir),
"--role-id",
role_id,
"--patch",
json.dumps(self_patch),
)
result["appliedFromRoleAccept"] = True
return result
def reset_artifact_dir(path: Path) -> None:
root = (ROOT / ".epiphany-dogfood").resolve()
resolved = path.resolve()
if resolved == root or root not in resolved.parents:
raise ValueError(f"refusing to delete non-dogfood artifact dir: {path}")
if path.exists():
shutil.rmtree(path)
path.mkdir(parents=True, exist_ok=True)
def write_json(path: Path, value: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
def write_text(path: Path, value: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(value, encoding="utf-8")
def append_jsonl(path: Path, value: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(value, ensure_ascii=False) + "\n")
def thread_lifecycle_event(kind: str, response: dict[str, Any]) -> dict[str, Any]:
thread = response.get("thread")
if not isinstance(thread, dict):
return {"type": kind}
return {
"type": kind,
"threadId": thread.get("id"),
"status": thread.get("status"),
"cwd": thread.get("cwd"),
"ephemeral": thread.get("ephemeral"),
}
def state_revision(status: dict[str, Any]) -> int | None:
state = status.get("read", {}).get("thread", {}).get("epiphanyState")
if isinstance(state, dict):
revision = state.get("revision")
if isinstance(revision, int):
return revision
scene_revision = status.get("scene", {}).get("scene", {}).get("revision")
return scene_revision if isinstance(scene_revision, int) else None
def coordinator_from_status(status: dict[str, Any]) -> dict[str, Any]:
coordinator = status.get("coordinator")
if isinstance(coordinator, dict):
return coordinator
recommendation = status["crrc"]["recommendation"]
return {
"action": recommendation["action"],
"targetRole": None,
"recommendedSceneAction": recommendation.get("recommendedSceneAction"),
"requiresReview": recommendation["action"] in {"acceptReorientResult", "reviewReorientResult"},
"canAutoRun": recommendation["action"] == "launchReorientWorker",
"reason": recommendation["reason"],
"sourceSignals": {},
"roles": status["roles"]["roles"],
"note": "local fallback from CRRC recommendation",
}
def collect_coordinator_status(
client: AppServerClient,
*,
thread_id: str,
cwd: Path,
ephemeral: bool,
) -> dict[str, Any]:
status = collect_status(client, thread_id=thread_id, cwd=cwd, ephemeral=ephemeral)
status["coordinator"] = client.send(
"thread/epiphany/coordinator", {"threadId": thread_id}
)
return status
def wait_for_role_result(
client: AppServerClient,
*,
thread_id: str,
role_id: str,
timeout_seconds: int,
poll_seconds: float,
) -> dict[str, Any]:
deadline = time.time() + timeout_seconds
latest: dict[str, Any] | None = None
while time.time() < deadline:
latest = client.send(
"thread/epiphany/roleResult",
{"threadId": thread_id, "roleId": role_id},
)
assert latest is not None
if latest.get("status") in TERMINAL_ROLE_STATUSES:
return latest
time.sleep(poll_seconds)
assert latest is not None
return latest
def wait_for_reorient_result(
client: AppServerClient,
*,
thread_id: str,
timeout_seconds: int,
poll_seconds: float,
) -> dict[str, Any]:
deadline = time.time() + timeout_seconds
latest: dict[str, Any] | None = None
while time.time() < deadline:
latest = client.send(
"thread/epiphany/reorientResult",
{"threadId": thread_id, "bindingId": REORIENT_BINDING_ID},
)
assert latest is not None
if latest.get("status") in TERMINAL_REORIENT_STATUSES:
return latest
time.sleep(poll_seconds)
assert latest is not None
return latest
def wait_for_any_notification(
client: AppServerClient,
methods: set[str],
*,
start_index: int,
timeout: float,
) -> dict[str, Any]:
deadline = time.time() + timeout
while time.time() < deadline:
assert client.proc is not None
if client.proc.poll() is not None:
ordered = ", ".join(sorted(methods))
raise RuntimeError(
f"app-server exited with {client.proc.returncode} before notification {ordered}"
)
for msg in client.notifications[start_index:]:
if msg.get("method") in methods:
return msg
time.sleep(0.1)
ordered = ", ".join(sorted(methods))
raise TimeoutError(f"timed out waiting for notification {ordered}")
def launch_role(
client: AppServerClient,
*,
thread_id: str,
role_id: str,
expected_revision: int | None,
max_runtime_seconds: int,
) -> dict[str, Any]:
payload: dict[str, Any] = {
"threadId": thread_id,
"roleId": role_id,
"maxRuntimeSeconds": max_runtime_seconds,
}
if expected_revision is not None:
payload["expectedRevision"] = expected_revision
launch = client.send("thread/epiphany/roleLaunch", payload)
assert launch is not None
return launch
def launch_reorient(
client: AppServerClient,
*,
thread_id: str,
expected_revision: int | None,
max_runtime_seconds: int,
) -> dict[str, Any]:
payload: dict[str, Any] = {
"threadId": thread_id,
"maxRuntimeSeconds": max_runtime_seconds,
}
if expected_revision is not None:
payload["expectedRevision"] = expected_revision
launch = client.send("thread/epiphany/reorientLaunch", payload)
assert launch is not None
return launch
def maybe_complete_role_backend(
args: argparse.Namespace,
launch: dict[str, Any],
*,
role_id: str,
evidence_ids: list[str] | None = None,
) -> dict[str, Any] | None:
if not args.test_complete_backend:
return None
backend_job_id = launch.get("job", {}).get("backendJobId")
if not backend_job_id:
return None
binding_id = MODELING_BINDING_ID if role_id == "modeling" else VERIFICATION_BINDING_ID
verdict = "checkpoint-ready" if role_id == "modeling" else "pass"
return complete_role_backend_job(
args.codex_home.resolve(),
backend_job_id,
binding_id=binding_id,
role_id=role_id,
verdict=verdict,
evidence_ids=evidence_ids,
)
def maybe_complete_reorient_backend(
args: argparse.Namespace,
launch: dict[str, Any],
) -> dict[str, Any] | None:
if not args.test_complete_backend:
return None
backend_job_id = launch.get("job", {}).get("backendJobId")
if not backend_job_id:
return None
return complete_reorient_backend_job(
args.codex_home.resolve(),
backend_job_id,
mode="regather",
)
def run_coordinator(args: argparse.Namespace) -> dict[str, Any]:
app_server = args.app_server.resolve()
if not app_server.exists():
raise FileNotFoundError(f"codex app-server binary not found: {app_server}")
artifact_dir = args.artifact_dir.resolve()
reset_artifact_dir(artifact_dir)
transcript_path = artifact_dir / "epiphany-transcript.jsonl"
stderr_path = artifact_dir / "epiphany-server.stderr.log"
telemetry_path = artifact_dir / "agent-function-telemetry.json"
steps_path = artifact_dir / "coordinator-steps.jsonl"
cwd = args.cwd.resolve()
codex_home = args.codex_home.resolve()
codex_home.mkdir(parents=True, exist_ok=True)
if args.bootstrap_smoke_state:
cwd = artifact_dir / "workspace"
prepare_workspace(cwd)
steps: list[dict[str, Any]] = []
startup_events: list[dict[str, Any]] = []
snapshots: list[str] = []
final_status: dict[str, Any] | None = None
final_action: dict[str, Any] | None = None
accepted_modeling_evidence_id: str | None = None
with AppServerClient(app_server, codex_home, transcript_path, stderr_path) as client:
client.send(
"initialize",
{
"clientInfo": {
"name": "epiphany-mvp-coordinator",
"title": "Epiphany MVP Coordinator",
"version": "0.1.0",
},
"capabilities": {"experimentalApi": True},
},
)
client.send("initialized", expect_response=False)
if args.thread_id is None:
started = client.send(
"thread/start",
{"cwd": str(cwd), "ephemeral": args.ephemeral},
)
assert started is not None
thread_id = started["thread"]["id"]
startup_events.append(thread_lifecycle_event("threadStart", started))
else:
thread_id = args.thread_id
resumed = client.send("thread/resume", {"threadId": thread_id})
assert resumed is not None
startup_events.append(thread_lifecycle_event("threadResume", resumed))
if args.bootstrap_smoke_state:
update = client.send(
"thread/epiphany/update",
{"threadId": thread_id, "expectedRevision": 0, "patch": reorient_patch()},
)
assert update is not None
if args.simulate_source_drift:
client.send("thread/epiphany/freshness", {"threadId": thread_id})
watched = cwd / "src" / "reorient_target.rs"
watched.write_text(
"pub fn reorient_target() -> &'static str {\n \"after\"\n}\n",
encoding="utf-8",
)
time.sleep(0.5)
for index in range(args.max_steps):
status = collect_coordinator_status(
client,
thread_id=thread_id,
cwd=cwd,
ephemeral=args.ephemeral,
)
coordinator = coordinator_from_status(status)
action = coordinator["action"]
if args.simulate_high_pressure and index == 0:
action = "compactRehydrateReorient"
coordinator = {
**coordinator,
"action": action,
"canAutoRun": True,
"requiresReview": False,
"reason": "Simulated high pressure requested by smoke test.",
}
snapshot_name = f"step-{index:02d}-{action}.txt"
write_text(artifact_dir / snapshot_name, render_status(sanitize_for_operator(status)))
snapshots.append(snapshot_name)
step: dict[str, Any] = {
"index": index,
"action": action,
"coordinator": coordinator,
"stateRevision": state_revision(status),
"events": [],
}
steps.append(step)
final_status = status
final_action = coordinator
if args.mode == "plan":
append_jsonl(steps_path, step)
break
if action in STOP_ACTIONS and not args.auto_review:
append_jsonl(steps_path, step)
break
revision = state_revision(status)
if action == "reviewModelingResult":
result = client.send(
"thread/epiphany/roleResult",
{"threadId": thread_id, "roleId": "modeling"},
)
step["events"].append(
{
"type": "roleResult",
"roleId": "modeling",
"result": sanitize_for_operator(result),
}
)
finding = result.get("finding") if isinstance(result, dict) else None
if not (
args.auto_review
and isinstance(finding, dict)
and isinstance(finding.get("statePatch"), dict)
and revision is not None
):
final_action = {
"action": "reviewModelingResult",
"reason": result.get("note") if isinstance(result, dict) else coordinator.get("reason"),
}
append_jsonl(steps_path, step)
break
accepted = client.send(
"thread/epiphany/roleAccept",
{
"threadId": thread_id,
"roleId": "modeling",
"expectedRevision": revision,
},
)
self_memory = maybe_apply_role_self_patch(
accepted, agent_memory_dir=args.agent_memory_dir
)
if self_memory is not None:
accepted["selfMemoryApply"] = self_memory
step["events"].append(
{
"type": "roleAccept",
"roleId": "modeling",
"accepted": sanitize_for_operator(accepted),
}
)
if isinstance(accepted, dict):
accepted_id = accepted.get("acceptedEvidenceId")
if isinstance(accepted_id, str) and accepted_id:
accepted_modeling_evidence_id = accepted_id
final_status = collect_coordinator_status(
client,
thread_id=thread_id,
cwd=cwd,
ephemeral=args.ephemeral,
)
append_jsonl(steps_path, step)
continue
if action == "launchModeling":
launch = launch_role(
client,
thread_id=thread_id,
role_id="modeling",
expected_revision=revision,
max_runtime_seconds=args.max_runtime_seconds,
)
step["events"].append(
{
"type": "roleLaunch",
"roleId": "modeling",
"launch": sanitize_for_operator(launch),
}
)
completed = maybe_complete_role_backend(args, launch, role_id="modeling")
if completed is not None:
step["events"].append(
{"type": "testCompleteBackend", "payload": sanitize_for_operator(completed)}
)
result = wait_for_role_result(
client,
thread_id=thread_id,
role_id="modeling",
timeout_seconds=args.timeout_seconds,
poll_seconds=args.poll_seconds,
)
step["events"].append(
{
"type": "roleResult",
"roleId": "modeling",
"result": sanitize_for_operator(result),
}
)
final_status = collect_coordinator_status(
client,
thread_id=thread_id,
cwd=cwd,
ephemeral=args.ephemeral,
)
if not args.auto_review:
final_action = {"action": "reviewModelingResult", "reason": result.get("note")}
append_jsonl(steps_path, step)
break
append_jsonl(steps_path, step)
continue
if action == "launchVerification":
launch = launch_role(
client,
thread_id=thread_id,
role_id="verification",
expected_revision=revision,
max_runtime_seconds=args.max_runtime_seconds,
)
step["events"].append(
{
"type": "roleLaunch",
"roleId": "verification",
"launch": sanitize_for_operator(launch),
}
)
verification_evidence_ids = (
["ev-checkpoint", accepted_modeling_evidence_id]
if accepted_modeling_evidence_id
else None
)
completed = maybe_complete_role_backend(
args,
launch,
role_id="verification",
evidence_ids=verification_evidence_ids,
)
if completed is not None:
step["events"].append(
{"type": "testCompleteBackend", "payload": sanitize_for_operator(completed)}
)
result = wait_for_role_result(
client,
thread_id=thread_id,
role_id="verification",
timeout_seconds=args.timeout_seconds,
poll_seconds=args.poll_seconds,
)
step["events"].append(
{
"type": "roleResult",
"roleId": "verification",
"result": sanitize_for_operator(result),
}
)
final_status = collect_coordinator_status(
client,
thread_id=thread_id,
cwd=cwd,
ephemeral=args.ephemeral,
)
if not args.auto_review:
final_action = {"action": "reviewVerificationResult", "reason": result.get("note")}
append_jsonl(steps_path, step)
break
append_jsonl(steps_path, step)
continue
if action == "launchReorientWorker":
launch = launch_reorient(
client,
thread_id=thread_id,
expected_revision=revision,
max_runtime_seconds=args.max_runtime_seconds,
)
step["events"].append({"type": "reorientLaunch", "launch": sanitize_for_operator(launch)})
completed = maybe_complete_reorient_backend(args, launch)
if completed is not None:
step["events"].append(
{"type": "testCompleteBackend", "payload": sanitize_for_operator(completed)}
)
result = wait_for_reorient_result(
client,
thread_id=thread_id,
timeout_seconds=args.timeout_seconds,
poll_seconds=args.poll_seconds,
)
step["events"].append({"type": "reorientResult", "result": sanitize_for_operator(result)})
final_status = collect_coordinator_status(
client,
thread_id=thread_id,
cwd=cwd,
ephemeral=args.ephemeral,
)
if not args.auto_review:
final_action = {"action": "reviewReorientResult", "reason": result.get("note")}
append_jsonl(steps_path, step)
break
append_jsonl(steps_path, step)
continue
if action == "compactRehydrateReorient":
if args.dry_compact:
step["events"].append({"type": "dryCompact", "threadId": thread_id})
append_jsonl(steps_path, step)
continue
notification_start_index = len(client.notifications)
compact = client.send("thread/compact/start", {"threadId": thread_id})
step["events"].append({"type": "compactStart", "response": sanitize_for_operator(compact)})
try:
notification = wait_for_any_notification(
client,
{"thread/compacted", "turn/completed"},
start_index=notification_start_index,
timeout=args.timeout_seconds,
)
step["events"].append(
{"type": "compacted", "notification": sanitize_for_operator(notification)}
)
except TimeoutError as exc:
step["events"].append({"type": "compactWaitTimeout", "error": str(exc)})
final_action = {
"action": "reviewReorientResult",
"reason": "Compaction did not finish before timeout.",
}
append_jsonl(steps_path, step)
break
resumed = client.send("thread/resume", {"threadId": thread_id})
step["events"].append({"type": "resume", "response": sanitize_for_operator(resumed)})
post_compact_status = collect_coordinator_status(
client,
thread_id=thread_id,
cwd=cwd,
ephemeral=args.ephemeral,
)
post_compact_crrc = post_compact_status.get("crrc", {}).get("recommendation", {})
step["events"].append(
{"type": "postCompactCrrc", "recommendation": sanitize_for_operator(post_compact_crrc)}
)
final_status = post_compact_status
if post_compact_crrc.get("action") == "launchReorientWorker":
launch = launch_reorient(
client,
thread_id=thread_id,
expected_revision=state_revision(post_compact_status),
max_runtime_seconds=args.max_runtime_seconds,
)
step["events"].append(
{"type": "reorientLaunch", "launch": sanitize_for_operator(launch)}
)
completed = maybe_complete_reorient_backend(args, launch)
if completed is not None:
step["events"].append(
{
"type": "testCompleteBackend",
"payload": sanitize_for_operator(completed),
}
)
result = wait_for_reorient_result(
client,
thread_id=thread_id,
timeout_seconds=args.timeout_seconds,
poll_seconds=args.poll_seconds,
)
step["events"].append(
{"type": "reorientResult", "result": sanitize_for_operator(result)}
)
final_status = collect_coordinator_status(
client,
thread_id=thread_id,
cwd=cwd,
ephemeral=args.ephemeral,
)
if not args.auto_review:
final_action = {
"action": "reviewReorientResult",
"reason": result.get("note"),
}
append_jsonl(steps_path, step)
break
append_jsonl(steps_path, step)
continue
if action in STOP_ACTIONS:
append_jsonl(steps_path, step)
break
append_jsonl(steps_path, step)
if final_status is None:
final_status = collect_coordinator_status(
client, thread_id=thread_id, cwd=cwd, ephemeral=args.ephemeral
)
operator_final_status = sanitize_for_operator(final_status)
final_rendered = render_status(operator_final_status)
operator_steps = sanitize_for_operator(steps)
operator_final_action = sanitize_for_operator(final_action)
summary = {
"objective": "Coordinate the Epiphany MVP lanes over existing app-server APIs.",
"artifactDir": str(artifact_dir),
"codexHome": str(codex_home),
"workspace": str(cwd),
"threadId": final_status["threadId"] if final_status else args.thread_id,
"mode": args.mode,
"startupEvents": sanitize_for_operator(startup_events),
"steps": operator_steps,
"snapshots": snapshots,
"finalAction": operator_final_action,
"finalStatus": operator_final_status,
"artifactManifest": [
"coordinator-summary.json",
"coordinator-steps.jsonl",
"coordinator-final-status.json",
"coordinator-final-status.txt",
"coordinator-final-action.txt",
"agent-function-telemetry.json",
*snapshots,
],
"sealedArtifactManifest": [
{
"path": "epiphany-transcript.jsonl",
"reason": "sealed JSON-RPC audit trail; do not read during normal supervision",
},
{
"path": "epiphany-server.stderr.log",
"reason": "sealed app-server diagnostics; inspect only for explicit debugging",
},
],
}
write_json(artifact_dir / "coordinator-summary.json", summary)
write_json(artifact_dir / "coordinator-final-status.json", operator_final_status)
write_text(artifact_dir / "coordinator-final-status.txt", final_rendered)
write_text(
artifact_dir / "coordinator-final-action.txt",
json.dumps(operator_final_action, indent=2, ensure_ascii=False) + "\n",
)
write_transcript_telemetry(transcript_path, telemetry_path)
return summary
def main() -> int:
parser = argparse.ArgumentParser(
description="Run an auditable fixed-lane Epiphany MVP coordinator."
)
parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER)
parser.add_argument("--thread-id")
parser.add_argument("--cwd", type=Path, default=ROOT)
parser.add_argument("--codex-home", type=Path, default=DEFAULT_CODEX_HOME)
parser.add_argument("--artifact-dir", type=Path, default=DEFAULT_ARTIFACT_DIR)
parser.add_argument("--agent-memory-dir", type=Path, default=DEFAULT_AGENT_MEMORY_DIR)
parser.add_argument("--mode", choices=["plan", "run"], default="plan")
parser.add_argument("--max-steps", type=int, default=4)
parser.add_argument("--poll-seconds", type=float, default=5.0)
parser.add_argument("--timeout-seconds", type=int, default=240)
parser.add_argument("--max-runtime-seconds", type=int, default=180)
parser.add_argument("--ephemeral", action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--auto-review", action="store_true")
parser.add_argument("--test-complete-backend", action="store_true")
parser.add_argument("--bootstrap-smoke-state", action="store_true")
parser.add_argument("--simulate-high-pressure", action="store_true")
parser.add_argument("--simulate-source-drift", action="store_true")
parser.add_argument("--dry-compact", action="store_true")
args = parser.parse_args()
result = run_coordinator(args)
print(json.dumps(result, indent=2, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -2,42 +2,38 @@ from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import shutil
import subprocess
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from epiphany_mvp_coordinator import DEFAULT_APP_SERVER
from epiphany_mvp_coordinator import DEFAULT_AGENT_MEMORY_DIR
from epiphany_mvp_coordinator import run_coordinator
from epiphany_phase5_smoke import ROOT
from epiphany_mvp_status import DEFAULT_APP_SERVER
from epiphany_mvp_status import ROOT
from epiphany_phase5_smoke import require
DEFAULT_ARTIFACT_ROOT = ROOT / ".epiphany-dogfood" / "coordinator-smoke"
def native_agent_memory(*args: str) -> dict[str, Any]:
exe = Path(r"C:\Users\Meta\.cargo-target-codex") / "debug" / "epiphany-agent-memory-store.exe"
def native_coordinator_exe() -> Path:
exe = Path(os.environ.get("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex")) / "debug" / "epiphany-mvp-coordinator.exe"
if exe.exists():
command = [str(exe), *args]
else:
command = [
return exe
subprocess.run(
[
"cargo",
"run",
"--quiet",
"build",
"--manifest-path",
str(ROOT / "epiphany-core" / "Cargo.toml"),
"--bin",
"epiphany-agent-memory-store",
"--",
*args,
]
completed = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, check=False)
if completed.returncode != 0:
raise RuntimeError(completed.stderr.strip() or completed.stdout.strip() or "epiphany-agent-memory-store failed")
return json.loads(completed.stdout)
"epiphany-mvp-coordinator",
],
cwd=ROOT,
check=True,
)
require(exe.exists(), f"native coordinator binary was not built: {exe}")
return exe
def reset_artifact_root(path: Path) -> None:
@ -50,41 +46,47 @@ def reset_artifact_root(path: Path) -> None:
path.mkdir(parents=True, exist_ok=True)
def coordinator_args(
def run_native(
*,
exe: Path,
app_server: Path,
artifact_root: Path,
name: str,
mode: str = "plan",
bootstrap_smoke_state: bool = False,
simulate_source_drift: bool = False,
simulate_high_pressure: bool = False,
dry_compact: bool = False,
auto_review: bool = False,
max_steps: int = 4,
agent_memory_store: Path | None = None,
) -> argparse.Namespace:
max_steps: int = 1,
) -> dict[str, Any]:
artifact_dir = artifact_root / name
return SimpleNamespace(
app_server=app_server,
thread_id=None,
cwd=ROOT,
codex_home=artifact_dir / "codex-home",
artifact_dir=artifact_dir,
agent_memory_dir=agent_memory_store or artifact_root / "agent-memory.msgpack",
mode=mode,
max_steps=max_steps,
poll_seconds=0.1,
timeout_seconds=20,
max_runtime_seconds=30,
ephemeral=True,
auto_review=auto_review,
test_complete_backend=True,
bootstrap_smoke_state=bootstrap_smoke_state,
simulate_high_pressure=simulate_high_pressure,
simulate_source_drift=simulate_source_drift,
dry_compact=dry_compact,
)
command = [
str(exe),
"--app-server",
str(app_server),
"--artifact-dir",
str(artifact_dir),
"--codex-home",
str(artifact_dir / "codex-home"),
"--cwd",
str(ROOT),
"--mode",
mode,
"--max-steps",
str(max_steps),
"--poll-seconds",
"0.1",
"--timeout-seconds",
"3",
]
if bootstrap_smoke_state:
command.append("--bootstrap-smoke-state")
if simulate_high_pressure:
command.append("--simulate-high-pressure")
if dry_compact:
command.append("--dry-compact")
completed = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, check=False)
require(completed.returncode == 0, completed.stderr or completed.stdout)
return json.loads(completed.stdout)
def require_artifacts(summary: dict[str, Any]) -> None:
@ -97,6 +99,7 @@ def require_artifacts(summary: dict[str, Any]) -> None:
"coordinator-final-action.txt",
"epiphany-transcript.jsonl",
"epiphany-server.stderr.log",
"agent-function-telemetry.json",
):
require((artifact_dir / name).exists(), f"missing coordinator artifact {name}")
@ -123,16 +126,13 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
artifact_root = args.artifact_root.resolve()
reset_artifact_root(artifact_root)
agent_memory_store = artifact_root / "agent-memory.msgpack"
shutil.copy2(DEFAULT_AGENT_MEMORY_DIR, agent_memory_store)
exe = native_coordinator_exe()
cold = run_coordinator(
coordinator_args(
app_server=app_server,
artifact_root=artifact_root,
name="cold",
agent_memory_store=agent_memory_store,
)
cold = run_native(
exe=exe,
app_server=app_server,
artifact_root=artifact_root,
name="cold",
)
require(
cold["finalAction"]["action"] == "prepareCheckpoint",
@ -141,83 +141,15 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
require_artifacts(cold)
require_operator_safe(cold)
modeling = run_coordinator(
coordinator_args(
app_server=app_server,
artifact_root=artifact_root,
name="modeling",
mode="run",
bootstrap_smoke_state=True,
max_steps=1,
)
)
require(
modeling["finalAction"]["action"] == "reviewModelingResult",
"modeling run should stop with a reviewable modeling result",
)
require_artifacts(modeling)
require_operator_safe(modeling)
verification = run_coordinator(
coordinator_args(
app_server=app_server,
artifact_root=artifact_root,
name="verification",
mode="run",
bootstrap_smoke_state=True,
auto_review=True,
max_steps=4,
)
)
require(
verification["steps"][-1]["action"] == "reviewVerificationResult",
"auto-review smoke should drive through verification and stop at review",
)
require_artifacts(verification)
require_operator_safe(verification)
projected_memory = artifact_root / "agent-memory-projection"
native_agent_memory(
"project-json-dir",
"--store",
str(agent_memory_store),
"--output-dir",
str(projected_memory),
)
require(
"mem-body-phase6-role-smoke"
in (projected_memory / "body.agent-state.json").read_text(encoding="utf-8"),
"auto-review coordinator smoke should apply accepted selfPatch to isolated agent memory",
)
drift = run_coordinator(
coordinator_args(
app_server=app_server,
artifact_root=artifact_root,
name="drift",
mode="run",
bootstrap_smoke_state=True,
simulate_source_drift=True,
max_steps=1,
)
)
require(
drift["finalAction"]["action"] == "reviewReorientResult",
"source drift should launch reorient worker and stop for review",
)
require_artifacts(drift)
require_operator_safe(drift)
pressure = run_coordinator(
coordinator_args(
app_server=app_server,
artifact_root=artifact_root,
name="pressure",
mode="run",
bootstrap_smoke_state=True,
simulate_high_pressure=True,
dry_compact=True,
max_steps=1,
)
pressure = run_native(
exe=exe,
app_server=app_server,
artifact_root=artifact_root,
name="pressure",
mode="run",
bootstrap_smoke_state=True,
simulate_high_pressure=True,
dry_compact=True,
)
require(
pressure["steps"][0]["action"] == "compactRehydrateReorient",
@ -230,13 +162,29 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
require_artifacts(pressure)
require_operator_safe(pressure)
rejected = subprocess.run(
[
str(exe),
"--artifact-dir",
str(artifact_root / "rejected-private-store-completion"),
"--test-complete-backend",
],
cwd=ROOT,
text=True,
capture_output=True,
check=False,
)
require(
rejected.returncode != 0 and "CultNet job-result API" in rejected.stderr,
"native coordinator should reject direct backend-completion mutation",
)
result = {
"artifactRoot": str(artifact_root),
"coldAction": cold["finalAction"]["action"],
"modelingAction": modeling["finalAction"]["action"],
"verificationAction": verification["steps"][-1]["action"],
"driftAction": drift["finalAction"]["action"],
"pressureAction": pressure["steps"][0]["action"],
"directBackendCompletionRejected": True,
"note": "Native smoke does not fake specialist completion by mutating Codex state storage; full completion smoke needs a CultNet job-result API.",
}
(artifact_root / "coordinator-smoke-summary.json").write_text(
json.dumps(result, indent=2, ensure_ascii=False) + "\n",
@ -247,7 +195,7 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
def main() -> int:
parser = argparse.ArgumentParser(
description="Smoke the auditable Epiphany MVP coordinator over fixed lanes."
description="Smoke the native auditable Epiphany MVP coordinator."
)
parser.add_argument("--app-server", type=Path, default=DEFAULT_APP_SERVER)
parser.add_argument("--artifact-root", type=Path, default=DEFAULT_ARTIFACT_ROOT)