Move coordinator smoke to Rust

This commit is contained in:
Meta Vens 2026-05-06 09:33:17 +01:00
commit b3adfe6fc4
6 changed files with 358 additions and 220 deletions

View file

@ -0,0 +1,352 @@
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::process::Command;
const DEFAULT_APP_SERVER: &str = r"C:\Users\Meta\.cargo-target-codex\debug\codex-app-server.exe";
fn main() -> Result<()> {
let args = Args::parse()?;
let result = run_smoke(&args)?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
#[derive(Debug)]
struct Args {
app_server: PathBuf,
artifact_root: PathBuf,
coordinator_exe: Option<PathBuf>,
}
impl Args {
fn parse() -> Result<Self> {
let root = env::current_dir().context("failed to resolve current dir")?;
let mut parsed = Self {
app_server: PathBuf::from(DEFAULT_APP_SERVER),
artifact_root: root.join(".epiphany-dogfood").join("coordinator-smoke"),
coordinator_exe: None,
};
let mut args = env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--app-server" => parsed.app_server = take_path(&mut args, "--app-server")?,
"--artifact-root" => {
parsed.artifact_root = take_path(&mut args, "--artifact-root")?;
}
"--coordinator-exe" => {
parsed.coordinator_exe = Some(take_path(&mut args, "--coordinator-exe")?);
}
other => return Err(anyhow!("unknown argument: {other}")),
}
}
Ok(parsed)
}
}
fn run_smoke(args: &Args) -> Result<Value> {
let root = env::current_dir().context("failed to resolve current dir")?;
let app_server = absolute_path(&args.app_server)?;
if !app_server.exists() {
return Err(anyhow!(
"codex app-server binary not found: {}",
app_server.display()
));
}
let artifact_root = absolute_path(&args.artifact_root)?;
reset_artifact_root(&root, &artifact_root)?;
let coordinator = match &args.coordinator_exe {
Some(path) => absolute_path(path)?,
None => sibling_exe("epiphany-mvp-coordinator")?,
};
ensure_coordinator_built(&root, &coordinator)?;
let cold = run_coordinator(
&root,
&coordinator,
&app_server,
&artifact_root,
RunOptions {
name: "cold",
mode: "plan",
bootstrap_smoke_state: false,
simulate_high_pressure: false,
dry_compact: false,
max_steps: 1,
},
)?;
require(
cold.pointer("/finalAction/action").and_then(Value::as_str) == Some("prepareCheckpoint"),
"cold start should stop at prepareCheckpoint",
)?;
require_artifacts(&cold)?;
require_operator_safe(&cold, "$")?;
let pressure = run_coordinator(
&root,
&coordinator,
&app_server,
&artifact_root,
RunOptions {
name: "pressure",
mode: "run",
bootstrap_smoke_state: true,
simulate_high_pressure: true,
dry_compact: true,
max_steps: 1,
},
)?;
require(
pressure.pointer("/steps/0/action").and_then(Value::as_str)
== Some("compactRehydrateReorient"),
"simulated high pressure should select compact/rehydrate/reorient",
)?;
require(
pressure
.pointer("/steps/0/events/0/type")
.and_then(Value::as_str)
== Some("dryCompact"),
"dry compact smoke should record the compaction action",
)?;
require_artifacts(&pressure)?;
require_operator_safe(&pressure, "$")?;
let rejected = Command::new(&coordinator)
.current_dir(&root)
.arg("--artifact-dir")
.arg(artifact_root.join("rejected-private-store-completion"))
.arg("--test-complete-backend")
.output()
.context("failed to run rejected completion check")?;
let rejected_stderr = String::from_utf8_lossy(&rejected.stderr);
require(
!rejected.status.success() && rejected_stderr.contains("CultNet job-result API"),
"native coordinator should reject direct backend-completion mutation",
)?;
let result = json!({
"artifactRoot": artifact_root,
"coldAction": cold["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 live workers while execution is cauterized into CultNet.",
});
write_json(
&artifact_root.join("coordinator-smoke-summary.json"),
&result,
)?;
Ok(result)
}
struct RunOptions {
name: &'static str,
mode: &'static str,
bootstrap_smoke_state: bool,
simulate_high_pressure: bool,
dry_compact: bool,
max_steps: usize,
}
fn run_coordinator(
root: &Path,
coordinator: &Path,
app_server: &Path,
artifact_root: &Path,
options: RunOptions,
) -> Result<Value> {
let artifact_dir = artifact_root.join(options.name);
let mut command = Command::new(coordinator);
command
.current_dir(root)
.arg("--app-server")
.arg(app_server)
.arg("--artifact-dir")
.arg(&artifact_dir)
.arg("--runtime-store")
.arg(artifact_dir.join("runtime-spine.msgpack"))
.arg("--codex-home")
.arg(artifact_dir.join("codex-home"))
.arg("--cwd")
.arg(root)
.arg("--mode")
.arg(options.mode)
.arg("--max-steps")
.arg(options.max_steps.to_string())
.arg("--poll-seconds")
.arg("0.1")
.arg("--timeout-seconds")
.arg("3");
if options.bootstrap_smoke_state {
command.arg("--bootstrap-smoke-state");
}
if options.simulate_high_pressure {
command.arg("--simulate-high-pressure");
}
if options.dry_compact {
command.arg("--dry-compact");
}
let output = command
.output()
.context("failed to run native coordinator")?;
if !output.status.success() {
return Err(anyhow!(
"native coordinator failed: {}{}",
String::from_utf8_lossy(&output.stderr),
String::from_utf8_lossy(&output.stdout)
));
}
serde_json::from_slice(&output.stdout).context("failed to decode coordinator summary")
}
fn require_artifacts(summary: &Value) -> Result<()> {
let artifact_dir = PathBuf::from(
summary
.get("artifactDir")
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("summary missing artifactDir"))?,
);
for name in [
"coordinator-summary.json",
"coordinator-steps.jsonl",
"coordinator-final-status.json",
"coordinator-final-status.txt",
"coordinator-final-action.txt",
"epiphany-transcript.jsonl",
"epiphany-server.stderr.log",
"agent-function-telemetry.json",
"runtime-spine-status.json",
] {
require(
artifact_dir.join(name).exists(),
&format!("missing coordinator artifact {name}"),
)?;
}
require(
artifact_dir.join("runtime-spine.msgpack").exists(),
"missing native runtime spine store",
)?;
let runtime_status: Value = serde_json::from_str(&fs::read_to_string(
artifact_dir.join("runtime-spine-status.json"),
)?)?;
require(
runtime_status["present"].as_bool() == Some(true),
"native runtime spine should be present",
)?;
require(
runtime_status["sessions"].as_u64().unwrap_or(0) >= 1,
"native runtime spine should record a session",
)?;
Ok(())
}
fn require_operator_safe(value: &Value, path: &str) -> Result<()> {
match value {
Value::Object(map) => {
if let Some(raw_result) = map.get("rawResult") {
require(
raw_result.get("sealed").and_then(Value::as_bool) == Some(true),
&format!("{path}.rawResult should be sealed in operator-facing artifacts"),
)?;
}
for (key, item) in map {
require_operator_safe(item, &format!("{path}.{key}"))?;
}
}
Value::Array(items) => {
for (index, item) in items.iter().enumerate() {
require_operator_safe(item, &format!("{path}[{index}]"))?;
}
}
_ => {}
}
Ok(())
}
fn reset_artifact_root(root: &Path, path: &Path) -> Result<()> {
let dogfood_root = root.join(".epiphany-dogfood").canonicalize().or_else(|_| {
let dogfood_root = root.join(".epiphany-dogfood");
fs::create_dir_all(&dogfood_root)?;
dogfood_root.canonicalize()
})?;
let parent = path.parent().unwrap_or_else(|| Path::new("."));
fs::create_dir_all(parent)?;
let resolved = if path.exists() {
path.canonicalize()?
} else {
parent.canonicalize()?.join(path.file_name().unwrap())
};
if resolved == dogfood_root || !resolved.starts_with(&dogfood_root) {
return Err(anyhow!(
"refusing to delete non-dogfood artifact root: {}",
path.display()
));
}
if path.exists() {
fs::remove_dir_all(path)?;
}
fs::create_dir_all(path)?;
Ok(())
}
fn sibling_exe(name: &str) -> Result<PathBuf> {
let mut exe = env::current_exe().context("failed to resolve current executable")?;
exe.set_file_name(format!("{name}{}", env::consts::EXE_SUFFIX));
Ok(exe)
}
fn ensure_coordinator_built(root: &Path, coordinator: &Path) -> Result<()> {
if coordinator.exists() {
return Ok(());
}
let status = Command::new("cargo")
.current_dir(root)
.arg("build")
.arg("--manifest-path")
.arg(root.join("epiphany-core").join("Cargo.toml"))
.arg("--bin")
.arg("epiphany-mvp-coordinator")
.status()
.context("failed to build epiphany-mvp-coordinator")?;
require(
status.success() && coordinator.exists(),
&format!(
"native coordinator binary was not built: {}",
coordinator.display()
),
)
}
fn absolute_path(path: &Path) -> Result<PathBuf> {
if path.is_absolute() {
Ok(path.to_path_buf())
} else {
Ok(env::current_dir()?.join(path))
}
}
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 require(condition: bool, message: &str) -> Result<()> {
if condition {
Ok(())
} else {
Err(anyhow!("{message}"))
}
}
fn take_path(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf> {
args.next()
.map(PathBuf::from)
.ok_or_else(|| anyhow!("{name} requires a value"))
}

View file

@ -481,7 +481,7 @@ Before modifying explicit role launch/read-back behavior, run:
Before modifying the fixed-lane MVP coordinator endpoint or runner, run:
```powershell
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_mvp_coordinator_smoke.py'
cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-mvp-coordinator-smoke
```
On this Windows machine, use:

View file

@ -32,7 +32,7 @@ remembers doctrine; the branch remembers the blade.
- Do not copy exact branch or HEAD from this note. Run `git status --short --branch` and `git log --oneline -5`.
- 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.
- 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 quarantine tissue for still-Python GUI/status callers, not the smoked product path.
- Native `epiphany-mvp-coordinator` is the first auditable fixed-lane coordinator runner. It starts or reads a thread through app-server, opens a native runtime-spine session, follows the harness-native coordinator action, can auto-launch modeling, verification, or reorient-worker jobs, records native runtime job/result receipts for terminal launched work, keeps semantic findings review-gated by default, and writes summary, steps, rendered snapshots, transcript, stderr, runtime-spine status, 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 while execution is being cauterized into CultNet.
- Native `epiphany-runtime-spine` is the first Codex-independent runtime vertebra. It owns typed CultCache documents for runtime identity, sessions, jobs, job results, and events; opens/completes native jobs; projects job-result counts; and can emit a framed CultNet hello message advertising the native document contract. Treat Codex app-server as a temporary evacuation bridge for launch/read-back until runtime sessions, jobs, and specialist results migrate to this spine.
- 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.
@ -155,7 +155,7 @@ The current spine, blessed but not yet finished:
- live reorientation app-server smoke through `tools/epiphany_phase6_reorient_smoke.py`
- live reorient-guided worker launch smoke through `tools/epiphany_phase6_reorient_launch_smoke.py`
- live MVP operator status smoke through `tools/epiphany_mvp_status_smoke.py`
- live MVP coordinator smoke through `tools/epiphany_mvp_coordinator_smoke.py`
- live MVP coordinator smoke through native `epiphany-mvp-coordinator-smoke`
- live job-control app-server smoke through `tools/epiphany_phase6_job_control_smoke.py`
- live specialist MVP pass through `tools/epiphany_mvp_live_specialist.py`
- Tauri v2 + React/WebGL Aquarium operator shell under `E:\Projects\EpiphanyAquarium`, including visual smoke, durable checkpoint preparation, fixed lane launch/read-back controls, explicit Imagination planning acceptance, explicit review-gated reorient acceptance, and bounded artifact-writing buttons
@ -268,7 +268,7 @@ states.
For the fixed-lane MVP coordinator endpoint and runner, run:
```powershell
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_mvp_coordinator_smoke.py'
cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-mvp-coordinator-smoke
```
For the first MVP operator status view, run:

Binary file not shown.

View file

@ -111,7 +111,7 @@ accepted_design:
- Native `epiphany-runtime-spine` is the first Codex-independent runtime vertebra: it initializes and inspects typed CultCache `epiphany.runtime.identity`, `epiphany.runtime.session`, `epiphany.runtime.job`, `epiphany.runtime.job_result`, and `epiphany.runtime.event` documents, opens/completes native jobs with result records, and can emit a framed CultNet hello message advertising the native document contract. This is the new source-of-truth target for runtime identity/session/job/result/event state; Codex app-server is only a temporary evacuation bridge until those flows are migrated.
- 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.
- 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 quarantine tissue for still-Python GUI/status callers until those organs are cut over.
- `thread/epiphany/roles` is the first harness-native role ownership surface: it projects implementation, Imagination/planning, modeling/checkpoint, verification/review, and reorientation lanes from authoritative typed state, bound jobs, pressure/reorient/CRRC, and worker result status without launching, scheduling, accepting, compacting, or mutating state.
- `thread/epiphany/roleLaunch` and `thread/epiphany/roleResult` are the first explicit role-scoped specialist templates: Imagination/planning, modeling/checkpoint, and verification/review can be launched through fixed bindings over the existing job-control seam and read back as reviewable findings, while implementation stays owned by the main coding agent and reorientation stays on the CRRC-specific launch/result path.
- `thread/epiphany/roleAccept` is the first review-gated role finding acceptance path: it accepts completed Imagination/planning findings only when they return a valid planning-only `statePatch` with draft Objective Draft review gates, accepts completed modeling/checkpoint findings only with a modeling-safe `statePatch`, appends audit observation/evidence, and rejects verification, implementation, reorientation, job binding, objective adoption, or broad authority fields.
@ -213,7 +213,7 @@ landed_baseline:
- Use `tools/epiphany_phase6_reorient_launch_smoke.py` before modifying the bounded reorient-worker result read-back surface.
- Use `tools/epiphany_phase6_reorient_launch_smoke.py` before modifying the read-only CRRC coordinator recommendation surface.
- Use `tools/epiphany_mvp_status_smoke.py` before modifying the MVP operator status view.
- Use `tools/epiphany_mvp_coordinator_smoke.py` before modifying the fixed-lane MVP coordinator endpoint or runner.
- Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-mvp-coordinator-smoke` before modifying the fixed-lane MVP coordinator endpoint or runner.
- Use `cargo test --manifest-path .\epiphany-core\Cargo.toml --lib runtime_spine -- --nocapture` and `cargo build --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-runtime-spine` before modifying native runtime-spine state or CultNet hello emission.
- Use `tools/epiphany_phase6_role_smoke.py` before modifying explicit role launch/read-back/acceptance behavior.
- Use `cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-agent-memory-store -- smoke --store .\state\agents.msgpack` before modifying role self-memory dossiers or `selfPatch` persistence policy.

View file

@ -1,214 +0,0 @@
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import shutil
import subprocess
from typing import Any
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_coordinator_exe() -> Path:
exe = Path(os.environ.get("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex")) / "debug" / "epiphany-mvp-coordinator.exe"
subprocess.run(
[
"cargo",
"build",
"--manifest-path",
str(ROOT / "epiphany-core" / "Cargo.toml"),
"--bin",
"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:
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 root: {path}")
if path.exists():
shutil.rmtree(path)
path.mkdir(parents=True, exist_ok=True)
def run_native(
*,
exe: Path,
app_server: Path,
artifact_root: Path,
name: str,
mode: str = "plan",
bootstrap_smoke_state: bool = False,
simulate_high_pressure: bool = False,
dry_compact: bool = False,
max_steps: int = 1,
) -> dict[str, Any]:
artifact_dir = artifact_root / name
command = [
str(exe),
"--app-server",
str(app_server),
"--artifact-dir",
str(artifact_dir),
"--runtime-store",
str(artifact_dir / "runtime-spine.msgpack"),
"--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:
artifact_dir = Path(summary["artifactDir"])
for name in (
"coordinator-summary.json",
"coordinator-steps.jsonl",
"coordinator-final-status.json",
"coordinator-final-status.txt",
"coordinator-final-action.txt",
"epiphany-transcript.jsonl",
"epiphany-server.stderr.log",
"agent-function-telemetry.json",
"runtime-spine-status.json",
):
require((artifact_dir / name).exists(), f"missing coordinator artifact {name}")
require((artifact_dir / "runtime-spine.msgpack").exists(), "missing native runtime spine store")
runtime_status = json.loads((artifact_dir / "runtime-spine-status.json").read_text(encoding="utf-8"))
require(runtime_status["present"] is True, "native runtime spine should be present")
require(runtime_status["sessions"] >= 1, "native runtime spine should record a session")
def require_operator_safe(value: Any, path: str = "$") -> None:
if isinstance(value, dict):
if "rawResult" in value:
raw_result = value["rawResult"]
require(
isinstance(raw_result, dict) and raw_result.get("sealed") is True,
f"{path}.rawResult should be sealed in operator-facing artifacts",
)
for key, item in value.items():
require_operator_safe(item, f"{path}.{key}")
elif isinstance(value, list):
for index, item in enumerate(value):
require_operator_safe(item, f"{path}[{index}]")
def run_smoke(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_root = args.artifact_root.resolve()
reset_artifact_root(artifact_root)
exe = native_coordinator_exe()
cold = run_native(
exe=exe,
app_server=app_server,
artifact_root=artifact_root,
name="cold",
)
require(
cold["finalAction"]["action"] == "prepareCheckpoint",
"cold start should stop at prepareCheckpoint",
)
require_artifacts(cold)
require_operator_safe(cold)
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",
"simulated high pressure should select compact/rehydrate/reorient",
)
require(
pressure["steps"][0]["events"][0]["type"] == "dryCompact",
"dry compact smoke should record the compaction action",
)
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"],
"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",
encoding="utf-8",
)
return result
def main() -> int:
parser = argparse.ArgumentParser(
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)
args = parser.parse_args()
result = run_smoke(args)
print(json.dumps(result, indent=2, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())