From 34d75d05d11852fdc9ebacc2d08f9f63a774114a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 11 Aug 2026 07:47:38 +0200 Subject: [PATCH] Expose grant-owned lifecycle sight --- .../src/bin/epiphany-mvp-coordinator.rs | 11 ++ epiphany-core/src/resident_self.rs | 111 +++++++++++-- .../src/bin/epiphany-openai-runtime.rs | 11 ++ epiphany-openai-runtime/src/lib.rs | 27 +++- epiphany-tool-mcp-runtime/src/main.rs | 146 +++++++++++++++++- 5 files changed, 291 insertions(+), 15 deletions(-) diff --git a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs index c63bc9a4..f849cfe5 100644 --- a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs +++ b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs @@ -404,6 +404,7 @@ fn run_coordinator(args: &Args) -> Result { &codex_home, &mcp_config, &cwd, + args.resident_state_store.as_deref(), &worker_job_id, "imagination", 0, @@ -463,6 +464,7 @@ fn run_coordinator(args: &Args) -> Result { &codex_home, &mcp_config, &cwd, + args.resident_state_store.as_deref(), &worker_job_id, "imagination", 0, @@ -511,6 +513,7 @@ fn run_coordinator(args: &Args) -> Result { &codex_home, &mcp_config, &cwd, + args.resident_state_store.as_deref(), &worker_job_id, "modeling", 0, @@ -674,6 +677,7 @@ fn run_coordinator(args: &Args) -> Result { &codex_home, &mcp_config, &cwd, + args.resident_state_store.as_deref(), &worker_job_id, "imagination-frontier-planning", index, @@ -730,6 +734,7 @@ fn run_coordinator(args: &Args) -> Result { &codex_home, &mcp_config, &cwd, + args.resident_state_store.as_deref(), &worker_job_id, "mind-frontier-plan-review", index, @@ -952,6 +957,7 @@ fn run_coordinator(args: &Args) -> Result { &codex_home, &mcp_config, &cwd, + args.resident_state_store.as_deref(), &worker_job_id, role_id, index, @@ -1012,6 +1018,7 @@ fn run_coordinator(args: &Args) -> Result { &codex_home, &mcp_config, &cwd, + args.resident_state_store.as_deref(), &worker_job_id, "reorient-worker", index, @@ -2055,6 +2062,7 @@ fn launch_worker_runtime_detached( codex_home: &Path, mcp_config: &Path, cwd: &Path, + resident_store: Option<&Path>, job_id: &str, role_id: &str, step_index: usize, @@ -2098,6 +2106,9 @@ fn launch_worker_runtime_detached( .arg(cwd) .arg("--max-tool-rounds") .arg(WORKER_AUTO_TOOL_MAX_ROUNDS.to_string()); + if let Some(resident_store) = resident_store { + command.arg("--resident-store").arg(resident_store); + } } let stdout_file = fs::File::create(&stdout_path) .with_context(|| format!("failed to create {}", stdout_path.display()))?; diff --git a/epiphany-core/src/resident_self.rs b/epiphany-core/src/resident_self.rs index dd2a1dde..6eb8c697 100644 --- a/epiphany-core/src/resident_self.rs +++ b/epiphany-core/src/resident_self.rs @@ -119,6 +119,33 @@ pub struct ResidentSelfHeartbeatGrant { pub terminal_status: Option, } +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ResidentSelfGrantLifecycleProjection { + pub grant_id: String, + pub pressure_id: String, + pub pressure_kind: String, + pub heartbeat_schedule_id: String, + pub heartbeat_action_id: String, + pub issued_at_millis: u64, + pub consumed_at_millis: Option, + pub terminal_at_millis: Option, + pub terminal_status: Option, + pub active: bool, + pub prepared: bool, + pub launchable: bool, +} + +fn resident_self_grant_is_pending( + grant: &ResidentSelfHeartbeatGrant, + legacy_terminal_grant_ids: &BTreeSet, +) -> bool { + grant.consumed_at_millis.is_none() + && grant.terminal_at_millis.is_none() + && !(grant.schema_version == "epiphany.resident_self.heartbeat_grant.v0" + && legacy_terminal_grant_ids.contains(&grant.grant_id)) +} + #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache( type = "epiphany.resident_self.terminal_ack.v0", @@ -1297,10 +1324,7 @@ pub fn heartbeat_issue_resident_self_grant( let grants = cache.get_all::()?; if grants.iter().any(|grant| { (grant.heartbeat_schedule_id == schedule_id && grant.heartbeat_action_id == action_id) - || (grant.consumed_at_millis.is_none() - && grant.terminal_at_millis.is_none() - && !(grant.schema_version == "epiphany.resident_self.heartbeat_grant.v0" - && legacy_terminal_grant_ids.contains(&grant.grant_id))) + || resident_self_grant_is_pending(grant, &legacy_terminal_grant_ids) }) { return Ok(None); } @@ -1388,6 +1412,63 @@ pub fn resident_self_pressures(path: &Path) -> Result> Ok(pressure) } +pub fn resident_self_grant_lifecycle_projection( + path: &Path, + grant_id: Option<&str>, + limit: usize, +) -> Result> { + let cache = state_cache(path)?; + let state = cache + .get::(RESIDENT_SELF_STATE_KEY)? + .unwrap_or_default(); + let legacy_terminal_grant_ids = cache + .get_all::()? + .into_iter() + .map(|ack| ack.grant_id) + .collect::>(); + let mut grants = cache + .get_all::()? + .into_iter() + .filter(|grant| grant_id.is_none_or(|id| grant.grant_id == id)) + .collect::>(); + grants.sort_by(|left, right| { + right + .issued_at_millis + .cmp(&left.issued_at_millis) + .then(right.grant_id.cmp(&left.grant_id)) + }); + grants.truncate(limit.clamp(1, 100)); + Ok(grants + .into_iter() + .map(|grant| { + let active = state.active_turn.as_ref().map(|lease| lease.grant_id.as_str()) + == Some(grant.grant_id.as_str()); + let prepared = state + .prepared_launch + .as_ref() + .map(|prepared| prepared.grant.grant_id.as_str()) + == Some(grant.grant_id.as_str()); + let launchable = resident_self_grant_is_pending(&grant, &legacy_terminal_grant_ids) + && !active + && !prepared; + ResidentSelfGrantLifecycleProjection { + grant_id: grant.grant_id, + pressure_id: grant.pressure_id, + pressure_kind: grant.pressure_kind, + heartbeat_schedule_id: grant.heartbeat_schedule_id, + heartbeat_action_id: grant.heartbeat_action_id, + issued_at_millis: grant.issued_at_millis, + consumed_at_millis: grant.consumed_at_millis, + terminal_at_millis: grant.terminal_at_millis, + terminal_status: grant.terminal_status, + active, + prepared, + launchable, + } + }) + .collect()) +} + /// Runtime retention consumes this resident-owned projection as its /// cross-store liveness fence. pub fn live_resident_self_typed_request_ids(path: &Path) -> Result> { @@ -1951,12 +2032,7 @@ pub fn pending_resident_self_grant(path: &Path) -> Result()? .into_iter() - .filter(|grant| { - grant.consumed_at_millis.is_none() - && grant.terminal_at_millis.is_none() - && !(grant.schema_version == "epiphany.resident_self.heartbeat_grant.v0" - && legacy_terminal_grant_ids.contains(&grant.grant_id)) - }) + .filter(|grant| resident_self_grant_is_pending(grant, &legacy_terminal_grant_ids)) .collect::>(); grants.sort_by(|a, b| { a.issued_at_millis @@ -4509,6 +4585,21 @@ mod tests { assert_eq!(retry_grant.pressure_id, first_grant.pressure_id); assert_ne!(retry_grant.grant_id, first_grant.grant_id); assert!(retry_grant.grant_id.contains("-attempt-2-")); + let projection = resident_self_grant_lifecycle_projection(&store, None, 10)?; + assert_eq!(projection.len(), 2); + assert_eq!(projection[0].grant_id, retry_grant.grant_id); + assert!(projection[0].launchable); + assert_eq!(projection[1].grant_id, first_grant.grant_id); + assert_eq!(projection[1].terminal_status.as_deref(), Some("unfulfilled")); + assert!(!projection[1].launchable); + assert_eq!( + resident_self_grant_lifecycle_projection( + &store, + Some(&first_grant.grant_id), + 1, + )?[0], + projection[1] + ); let prepared = prepare_resident_self_launch(&store, &policy, 9)?.expect("retry preparation"); let retry_process = LaunchedCoordinator { diff --git a/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs b/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs index 16cfcf4e..3fd3a9a0 100644 --- a/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs +++ b/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs @@ -525,6 +525,7 @@ struct RunWorkerCliOptions { auto_tools: bool, tool_adapter_bin: Option, cwd: Option, + resident_store: Option, max_tool_rounds: usize, max_runtime_seconds: Option, activation_token_sha256: String, @@ -626,6 +627,7 @@ fn parse_run_worker_options(args: Vec) -> Result { let mut auto_tools = false; let mut tool_adapter_bin = None; let mut cwd = None; + let mut resident_store = None; let mut max_tool_rounds = 4usize; let mut max_runtime_seconds = None; let mut activation_token_sha256 = None; @@ -645,6 +647,9 @@ fn parse_run_worker_options(args: Vec) -> Result { tool_adapter_bin = Some(PathBuf::from(next_value(&mut iter, "--tool-adapter-bin")?)) } "--cwd" => cwd = Some(PathBuf::from(next_value(&mut iter, "--cwd")?)), + "--resident-store" => { + resident_store = Some(PathBuf::from(next_value(&mut iter, "--resident-store")?)) + } "--max-tool-rounds" => { max_tool_rounds = next_value(&mut iter, "--max-tool-rounds")?.parse()? } @@ -668,6 +673,7 @@ fn parse_run_worker_options(args: Vec) -> Result { auto_tools, tool_adapter_bin, cwd, + resident_store, max_tool_rounds, max_runtime_seconds, activation_token_sha256: activation_token_sha256 @@ -917,6 +923,7 @@ async fn run_worker_launch_with_tool_continuation( &options.store_path, options.mcp_config.as_ref(), options.cwd.as_ref(), + options.resident_store.as_ref(), &intent_id, )?); } @@ -1789,6 +1796,7 @@ fn run_tool_adapter( store_path: &PathBuf, mcp_config: Option<&PathBuf>, cwd: Option<&PathBuf>, + resident_store: Option<&PathBuf>, intent_id: &str, ) -> Result { let mut command = Command::new(tool_adapter_bin); @@ -1804,6 +1812,9 @@ fn run_tool_adapter( if let Some(cwd) = cwd { command.arg("--cwd").arg(cwd); } + if let Some(resident_store) = resident_store { + command.arg("--resident-store").arg(resident_store); + } let output = command .output() .with_context(|| format!("failed to spawn {}", tool_adapter_bin.display()))?; diff --git a/epiphany-openai-runtime/src/lib.rs b/epiphany-openai-runtime/src/lib.rs index f436328c..e5a70e55 100644 --- a/epiphany-openai-runtime/src/lib.rs +++ b/epiphany-openai-runtime/src/lib.rs @@ -593,11 +593,11 @@ pub fn build_worker_model_request( let mut instructions = worker_instructions(launch_request, &launch_document, &output_schema_json); if launch_request.binding_id == epiphany_core::EPIPHANY_VERIFICATION_ROLE_BINDING_ID { - instructions.push_str("\n\nTool mandate: before returning `needs-evidence` because source files, artifact directories, command artifacts, commit diffs, or Hands receipt bodies are not inspectable, call the read-only source tools available on this request. Use `mcp__epiphany_source__read_file` for cited source/artifact files, `mcp__epiphany_source__directory_inventory` for bounded workspace directory counts and bytes, `mcp__epiphany_source__git_show` for commit diffs, and `mcp__epiphany_source__read_hands_receipt` for Hands patch/command/commit receipts. Directory totals are authoritative only when the tool reports `complete=true`. If a tool fails, cite that failed tool result and the exact remaining blocker."); + instructions.push_str("\n\nTool mandate: before returning `needs-evidence` because source files, artifact directories, command artifacts, commit diffs, Hands receipt bodies, or resident grant lifecycle are not inspectable, call the governed read-only tools available on this request. Use `mcp__epiphany_source__read_file` for cited source/artifact files, `mcp__epiphany_source__directory_inventory` for bounded workspace directory counts and bytes, `mcp__epiphany_source__git_show` for commit diffs, `mcp__epiphany_source__read_hands_receipt` for Hands patch/command/commit receipts, and `mcp__epiphany_state__resident_grant_lifecycle` for exact or bounded recent grant-owned lifecycle state. Directory totals are authoritative only when the tool reports `complete=true`. Grant launchability is authoritative only from the typed state projection, never artifact names or acknowledgement presence. If a tool fails, cite that failed tool result and the exact remaining blocker."); } else if launch_request.binding_id == epiphany_core::EPIPHANY_RESEARCH_ROLE_BINDING_ID { - instructions.push_str("\n\nTool mandate: Eyes must inspect current repository sources before emitting evidence. Call the bounded read-only file, directory-inventory, or Git tools, cite the exact inspected paths/revisions in filesInspected and evidence, and report a source gap if the required body cannot be observed. Directory totals are authoritative only when the inventory reports `complete=true`."); + instructions.push_str("\n\nTool mandate: Eyes must inspect current repository sources or typed resident state before emitting evidence. Call the bounded read-only file, directory-inventory, Git, or `mcp__epiphany_state__resident_grant_lifecycle` tool appropriate to the claim; cite exact inspected paths/revisions or grant identities in filesInspected and evidence, and report a source gap if the required body cannot be observed. Directory totals are authoritative only when the inventory reports `complete=true`; grant launchability is authoritative only from the typed lifecycle projection."); } else if launch_request.binding_id == epiphany_core::EPIPHANY_MODELING_ROLE_BINDING_ID { - instructions.push_str("\n\nTool mandate: Modeling must inspect current repository sources before proposing repository anatomy. Call the bounded read-only file, directory-inventory, or Git tools, cite the exact inspected paths/revisions in filesInspected and evidence, and emit regather-needed instead of inventing unobserved structure. Directory totals are authoritative only when the inventory reports `complete=true`."); + instructions.push_str("\n\nTool mandate: Modeling must inspect current repository sources or typed resident state before proposing repository anatomy. Call the bounded read-only file, directory-inventory, Git, or `mcp__epiphany_state__resident_grant_lifecycle` tool appropriate to the claim; cite exact inspected paths/revisions or grant identities in filesInspected and evidence, and emit regather-needed instead of inventing unobserved structure. Directory totals are authoritative only when the inventory reports `complete=true`; grant launchability is authoritative only from the typed lifecycle projection."); } let mut request = EpiphanyModelRequest::new( request_id, @@ -1151,6 +1151,19 @@ fn repository_source_tools() -> Vec { }) .to_string(), }, + EpiphanyModelToolDefinition { + name: "mcp__epiphany_state__resident_grant_lifecycle".to_string(), + description: "Read grant-owned resident Self lifecycle state from the explicitly launch-bound resident store. Use an exact grantId when known or a bounded recent limit. This is observation only; terminal and launchable fields remain derived from the typed grant/state owner.".to_string(), + parameters_json: serde_json::json!({ + "type": "object", + "additionalProperties": false, + "properties": { + "grantId": {"type": "string"}, + "limit": {"type": "integer", "minimum": 1, "maximum": 100} + } + }) + .to_string(), + }, ] } @@ -2842,6 +2855,10 @@ mod tests { .tools .iter() .any(|tool| tool.name == "mcp__epiphany_source__directory_inventory")); + assert!(model_request + .tools + .iter() + .any(|tool| tool.name == "mcp__epiphany_state__resident_grant_lifecycle")); assert!(model_request.instructions.contains("Modeling must inspect")); let openai_summary = EpiphanyOpenAiRuntimeRunSummary { store: store.display().to_string(), @@ -2993,12 +3010,16 @@ mod tests { assert!(tool_names.contains(&"mcp__epiphany_source__directory_inventory")); assert!(tool_names.contains(&"mcp__epiphany_source__git_show")); assert!(tool_names.contains(&"mcp__epiphany_source__read_hands_receipt")); + assert!(tool_names.contains(&"mcp__epiphany_state__resident_grant_lifecycle")); assert!(model_request .instructions .contains("mcp__epiphany_source__read_file")); assert!(model_request .instructions .contains("mcp__epiphany_source__directory_inventory")); + assert!(model_request + .instructions + .contains("mcp__epiphany_state__resident_grant_lifecycle")); Ok(()) } diff --git a/epiphany-tool-mcp-runtime/src/main.rs b/epiphany-tool-mcp-runtime/src/main.rs index b69d506b..3b0268a4 100644 --- a/epiphany-tool-mcp-runtime/src/main.rs +++ b/epiphany-tool-mcp-runtime/src/main.rs @@ -30,6 +30,7 @@ struct RunOptions { intent_id: String, mcp_config: Option, cwd: Option, + resident_store: Option, } impl Cli { @@ -40,12 +41,16 @@ impl Cli { "smoke" => Err(anyhow!("smoke accepts no arguments")), "run" => { let flags = flags(rest)?; - reject_unknown(&flags, &["store", "intent-id", "mcp-config", "cwd"])?; + reject_unknown( + &flags, + &["store", "intent-id", "mcp-config", "cwd", "resident-store"], + )?; Ok(Self::Run(RunOptions { store: PathBuf::from(required(&flags, "store")?), intent_id: required(&flags, "intent-id")?.to_string(), mcp_config: flags.get("mcp-config").map(PathBuf::from), cwd: flags.get("cwd").map(PathBuf::from), + resident_store: flags.get("resident-store").map(PathBuf::from), })) } _ => Err(anyhow!(usage())), @@ -90,6 +95,33 @@ async fn execute_to_receipt( None => std::env::current_dir()?, }; execute_epiphany_source(intent, &options.store, &cwd) + } else if intent.server == "epiphany_state" { + let resident_store = options.resident_store.as_ref().ok_or_else(|| { + anyhow!("epiphany_state requires an explicitly bound --resident-store") + })?; + if intent.tool_name != "resident_grant_lifecycle" { + return Err(anyhow!("unknown epiphany_state tool {:?}", intent.tool_name)); + } + let arguments: serde_json::Value = serde_json::from_str(&intent.arguments_json) + .context("arguments_json is not valid JSON")?; + let grant_id = arguments.get("grantId").and_then(serde_json::Value::as_str); + let limit = arguments + .get("limit") + .and_then(serde_json::Value::as_u64) + .unwrap_or(20) + .clamp(1, 100) as usize; + let grants = epiphany_core::resident_self_grant_lifecycle_projection( + resident_store, + grant_id, + limit, + )?; + Ok(serde_json::json!({ + "schemaVersion": "epiphany.resident_self.grant_lifecycle_projection.v0", + "grantId": grant_id, + "limit": limit, + "grants": grants, + "privateStateExposed": false + })) } else { let path = options.mcp_config.as_ref().ok_or_else(|| { anyhow!( @@ -167,7 +199,7 @@ fn reject_unknown(flags: &BTreeMap, allowed: &[&str]) -> Result< } } fn usage() -> &'static str { - "usage: epiphany-tool-mcp-runtime run --store PATH --intent-id ID [--mcp-config PATH] [--cwd PATH] | smoke" + "usage: epiphany-tool-mcp-runtime run --store PATH --intent-id ID [--mcp-config PATH] [--cwd PATH] [--resident-store PATH] | smoke" } #[derive(Serialize)] @@ -329,6 +361,7 @@ mod tests { intent_id: intent.intent_id.clone(), mcp_config: None, cwd: Some(temp.path().to_path_buf()), + resident_store: None, }) .await?; @@ -342,6 +375,114 @@ mod tests { Ok(()) } + #[tokio::test] + async fn resident_state_tool_requires_explicit_store_and_projects_grant_owner() -> Result<()> { + let temp = tempfile::tempdir()?; + let runtime_store = temp.path().join("runtime.cc"); + let resident_store = temp.path().join("resident.cc"); + epiphany_core::initialize_runtime_spine( + &runtime_store, + epiphany_core::RuntimeSpineInitOptions { + runtime_id: "state-tool-test".into(), + display_name: "State Tool Test".into(), + created_at: "now".into(), + }, + )?; + epiphany_core::enqueue_resident_self_pressure( + &resident_store, + &epiphany_core::ResidentSelfPressure { + schema_version: epiphany_core::RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), + pressure_id: "pressure-state-tool".into(), + kind: "operator-objective".into(), + provenance_ref: "operator://state-tool-test".into(), + objective: "Observe exact grant lifecycle.".into(), + created_at_millis: 1, + status: "pending".into(), + consumed_by_grant_id: None, + private_state_exposed: false, + }, + )?; + let grant = epiphany_core::heartbeat_issue_resident_self_grant( + &resident_store, + "schedule-state-tool", + "action-state-tool", + 2, + )? + .expect("grant"); + let intent = EpiphanyToolInvocationIntent::new( + "native-state-read", + EPIPHANY_TOOL_RUNTIME_ADAPTER_ID, + "epiphany_state", + "resident_grant_lifecycle", + format!(r#"{{"grantId":"{}"}}"#, grant.grant_id), + "test", + "prove grant-owned state observation", + "now", + ); + epiphany_core::create_runtime_session( + &runtime_store, + epiphany_core::RuntimeSpineSessionOptions { + session_id: "state-tool-session".into(), + objective: "Observe resident state.".into(), + created_at: "2026-08-11T00:00:00Z".into(), + coordinator_note: "test".into(), + }, + )?; + epiphany_core::create_runtime_job( + &runtime_store, + epiphany_core::RuntimeSpineJobOptions { + job_id: "state-tool-job".into(), + session_id: "state-tool-session".into(), + role: "tool-runtime".into(), + created_at: "2026-08-11T00:00:01Z".into(), + summary: "Observe resident state.".into(), + artifact_refs: vec![], + }, + )?; + epiphany_core::put_runtime_tool_execution_intent( + &runtime_store, + "state-tool-session", + "state-tool-job", + &intent, + "2026-08-11T00:00:02Z", + )?; + + let unbound = execute_to_receipt( + &intent, + &RunOptions { + store: runtime_store.clone(), + intent_id: intent.intent_id.clone(), + mcp_config: None, + cwd: None, + resident_store: None, + }, + ) + .await; + assert_eq!(unbound.status, "failed"); + assert!(unbound.error.as_deref().unwrap().contains("explicitly bound")); + + let summary = run(RunOptions { + store: runtime_store.clone(), + intent_id: intent.intent_id.clone(), + mcp_config: None, + cwd: None, + resident_store: Some(resident_store), + }) + .await?; + assert_eq!(summary.status, "completed"); + let cache = open_store(&runtime_store)?; + let receipt = cache.get_required::( + &tool_invocation_receipt_key(&intent.intent_id), + )?; + let body: serde_json::Value = serde_json::from_str( + receipt.result_json.as_deref().expect("state projection body"), + )?; + assert_eq!(body["grants"][0]["grantId"], grant.grant_id); + assert_eq!(body["grants"][0]["launchable"], true); + assert_eq!(body["privateStateExposed"], false); + Ok(()) + } + #[tokio::test] async fn unbound_intent_is_refused_before_tool_execution() -> Result<()> { let temp = tempfile::tempdir()?; @@ -372,6 +513,7 @@ mod tests { intent_id: intent.intent_id.clone(), mcp_config: None, cwd: Some(temp.path().to_path_buf()), + resident_store: None, }) .await {