Skip to content

Commit 314f0c9

Browse files
committed
feat(worker_boot): emit .claw/worker-state.json on every status transition
WorkerStatus is fully tracked in worker_boot.rs but was invisible to external observers (clawhip, orchestrators) because opencode serve's HTTP server is upstream and not ours to extend. Solution: atomic file-based observability. - emit_state_file() writes .claw/worker-state.json on every push_event() call (tmp write + rename for atomicity) - Snapshot includes: worker_id, status, is_ready, trust_gate_cleared, prompt_in_flight, last_event, updated_at - Add 'claw state' CLI subcommand to read and print the file - Add regression test: emit_state_file_writes_worker_status_on_transition verifies spawning→ready_for_prompt transition is reflected on disk This closes the /state dogfood gap without requiring any upstream opencode changes. Clawhip can now distinguish a truly stalled worker (status: trust_required or running with no recent updated_at) from a quiet-but-progressing one.
1 parent 469ae01 commit 314f0c9

2 files changed

Lines changed: 116 additions & 0 deletions

File tree

rust/crates/runtime/src/worker_boot.rs

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -560,6 +560,7 @@ fn push_event(
560560
let timestamp = now_secs();
561561
let seq = worker.events.len() as u64 + 1;
562562
worker.updated_at = timestamp;
563+
worker.status = status;
563564
worker.events.push(WorkerEvent {
564565
seq,
565566
kind,
@@ -568,6 +569,45 @@ fn push_event(
568569
payload,
569570
timestamp,
570571
});
572+
emit_state_file(worker);
573+
}
574+
575+
/// Write current worker state to `.claw/worker-state.json` under the worker's cwd.
576+
/// This is the file-based observability surface: external observers (clawhip, orchestrators)
577+
/// poll this file instead of requiring an HTTP route on the opencode binary.
578+
fn emit_state_file(worker: &Worker) {
579+
let state_dir = std::path::Path::new(&worker.cwd).join(".claw");
580+
if let Err(_) = std::fs::create_dir_all(&state_dir) {
581+
return;
582+
}
583+
let state_path = state_dir.join("worker-state.json");
584+
let tmp_path = state_dir.join("worker-state.json.tmp");
585+
586+
#[derive(serde::Serialize)]
587+
struct StateSnapshot<'a> {
588+
worker_id: &'a str,
589+
status: WorkerStatus,
590+
is_ready: bool,
591+
trust_gate_cleared: bool,
592+
prompt_in_flight: bool,
593+
last_event: Option<&'a WorkerEvent>,
594+
updated_at: u64,
595+
}
596+
597+
let snapshot = StateSnapshot {
598+
worker_id: &worker.worker_id,
599+
status: worker.status,
600+
is_ready: worker.status == WorkerStatus::ReadyForPrompt,
601+
trust_gate_cleared: worker.trust_gate_cleared,
602+
prompt_in_flight: worker.prompt_in_flight,
603+
last_event: worker.events.last(),
604+
updated_at: worker.updated_at,
605+
};
606+
607+
if let Ok(json) = serde_json::to_string_pretty(&snapshot) {
608+
let _ = std::fs::write(&tmp_path, json);
609+
let _ = std::fs::rename(&tmp_path, &state_path);
610+
}
571611
}
572612

573613
fn path_matches_allowlist(cwd: &str, trusted_root: &str) -> bool {
@@ -1058,6 +1098,38 @@ mod tests {
10581098
.any(|event| event.kind == WorkerEventKind::Failed));
10591099
}
10601100

1101+
#[test]
1102+
fn emit_state_file_writes_worker_status_on_transition() {
1103+
let cwd_path = std::env::temp_dir().join(format!("claw-state-test-{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()));
1104+
std::fs::create_dir_all(&cwd_path).expect("test dir should create");
1105+
let cwd = cwd_path.to_str().expect("test path should be utf8");
1106+
let registry = WorkerRegistry::new();
1107+
let worker = registry.create(cwd, &[], true);
1108+
1109+
// After create the worker is Spawning — state file should exist
1110+
let state_path = cwd_path.join(".claw").join("worker-state.json");
1111+
assert!(state_path.exists(), "state file should exist after worker creation");
1112+
1113+
let raw = std::fs::read_to_string(&state_path).expect("state file should be readable");
1114+
let value: serde_json::Value = serde_json::from_str(&raw).expect("state file should be valid JSON");
1115+
assert_eq!(value["status"].as_str(), Some("spawning"), "initial status should be spawning");
1116+
assert_eq!(value["is_ready"].as_bool(), Some(false));
1117+
1118+
// Transition to ReadyForPrompt by observing trust-cleared text
1119+
registry
1120+
.observe(&worker.worker_id, "Ready for input\n>")
1121+
.expect("observe ready should succeed");
1122+
1123+
let raw = std::fs::read_to_string(&state_path).expect("state file should be readable after observe");
1124+
let value: serde_json::Value = serde_json::from_str(&raw).expect("state file should be valid JSON after observe");
1125+
assert_eq!(
1126+
value["status"].as_str(),
1127+
Some("ready_for_prompt"),
1128+
"status should be ready_for_prompt after observe"
1129+
);
1130+
assert_eq!(value["is_ready"].as_bool(), Some(true), "is_ready should be true when ReadyForPrompt");
1131+
}
1132+
10611133
#[test]
10621134
fn observe_completion_accepts_normal_finish_with_tokens() {
10631135
let registry = WorkerRegistry::new();

rust/crates/rusty-claude-cli/src/main.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,7 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
211211
CliAction::Login { output_format } => run_login(output_format)?,
212212
CliAction::Logout { output_format } => run_logout(output_format)?,
213213
CliAction::Doctor { output_format } => run_doctor(output_format)?,
214+
CliAction::State { output_format } => run_worker_state(output_format)?,
214215
CliAction::Init { output_format } => run_init(output_format)?,
215216
CliAction::Export {
216217
session_reference,
@@ -293,6 +294,9 @@ enum CliAction {
293294
Doctor {
294295
output_format: CliOutputFormat,
295296
},
297+
State {
298+
output_format: CliOutputFormat,
299+
},
296300
Init {
297301
output_format: CliOutputFormat,
298302
},
@@ -611,6 +615,7 @@ fn parse_single_word_command_alias(
611615
})),
612616
"sandbox" => Some(Ok(CliAction::Sandbox { output_format })),
613617
"doctor" => Some(Ok(CliAction::Doctor { output_format })),
618+
"state" => Some(Ok(CliAction::State { output_format })),
614619
other => bare_slash_command_guidance(other).map(Err),
615620
}
616621
}
@@ -1322,6 +1327,32 @@ fn run_doctor(output_format: CliOutputFormat) -> Result<(), Box<dyn std::error::
13221327
///
13231328
/// Tool descriptors come from [`tools::mvp_tool_specs`] and calls are
13241329
/// dispatched through [`tools::execute_tool`], so this server exposes exactly
1330+
/// Read `.claw/worker-state.json` from the current working directory and print it.
1331+
/// This is the file-based worker observability surface: `push_event()` in `worker_boot.rs`
1332+
/// atomically writes state transitions here so external observers (clawhip, orchestrators)
1333+
/// can poll current `WorkerStatus` without needing an HTTP route on the opencode binary.
1334+
fn run_worker_state(output_format: CliOutputFormat) -> Result<(), Box<dyn std::error::Error>> {
1335+
let cwd = env::current_dir()?;
1336+
let state_path = cwd.join(".claw").join("worker-state.json");
1337+
if !state_path.exists() {
1338+
match output_format {
1339+
CliOutputFormat::Text => println!("No worker state file found at {}", state_path.display()),
1340+
CliOutputFormat::Json => println!("{}", serde_json::json!({"error": "no_state_file", "path": state_path.display().to_string()})),
1341+
}
1342+
return Ok(());
1343+
}
1344+
let raw = std::fs::read_to_string(&state_path)?;
1345+
match output_format {
1346+
CliOutputFormat::Text => println!("{raw}"),
1347+
CliOutputFormat::Json => {
1348+
// Validate it parses as JSON before re-emitting
1349+
let _: serde_json::Value = serde_json::from_str(&raw)?;
1350+
println!("{raw}");
1351+
}
1352+
}
1353+
Ok(())
1354+
}
1355+
13251356
/// the same surface the in-process agent loop uses.
13261357
fn run_mcp_serve() -> Result<(), Box<dyn std::error::Error>> {
13271358
let tools = mvp_tool_specs()
@@ -8547,6 +8578,19 @@ mod tests {
85478578
output_format: CliOutputFormat::Text,
85488579
}
85498580
);
8581+
assert_eq!(
8582+
parse_args(&["state".to_string()]).expect("state should parse"),
8583+
CliAction::State {
8584+
output_format: CliOutputFormat::Text,
8585+
}
8586+
);
8587+
assert_eq!(
8588+
parse_args(&["state".to_string(), "--output-format".to_string(), "json".to_string()])
8589+
.expect("state --output-format json should parse"),
8590+
CliAction::State {
8591+
output_format: CliOutputFormat::Json,
8592+
}
8593+
);
85508594
assert_eq!(
85518595
parse_args(&["init".to_string()]).expect("init should parse"),
85528596
CliAction::Init {

0 commit comments

Comments
 (0)