Skip to main content

harn_vm/orchestration/
mod.rs

1use std::path::PathBuf;
2use std::{cell::RefCell, thread_local};
3
4use serde::{Deserialize, Serialize};
5
6use crate::llm::vm_value_to_json;
7use crate::value::{VmError, VmValue};
8
9pub(crate) fn now_rfc3339() -> String {
10    use std::time::{SystemTime, UNIX_EPOCH};
11    let ts = SystemTime::now()
12        .duration_since(UNIX_EPOCH)
13        .unwrap_or_default()
14        .as_secs();
15    format!("{ts}")
16}
17
18pub(crate) fn new_id(prefix: &str) -> String {
19    format!("{prefix}_{}", uuid::Uuid::now_v7())
20}
21
22pub(crate) fn default_run_dir() -> PathBuf {
23    let base = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
24    crate::runtime_paths::run_root(&base)
25}
26
27mod hooks;
28pub use hooks::*;
29
30mod pipeline_lifecycle;
31pub use pipeline_lifecycle::*;
32
33mod settlement_agent;
34pub use settlement_agent::*;
35
36mod lifecycle_receipts;
37pub use lifecycle_receipts::*;
38
39mod command_policy;
40pub use command_policy::*;
41
42mod compaction;
43pub use compaction::*;
44
45mod compact_lifecycle;
46pub use compact_lifecycle::*;
47
48mod compaction_policy_registry;
49pub use compaction_policy_registry::*;
50
51pub mod agent_inbox;
52
53mod artifacts;
54pub use artifacts::*;
55
56mod assemble;
57pub use assemble::*;
58
59mod handoffs;
60pub use handoffs::*;
61
62mod friction;
63pub use friction::*;
64
65mod crystallize;
66pub use crystallize::*;
67
68mod release_fixture;
69pub use release_fixture::*;
70
71mod replay_oracle;
72pub use replay_oracle::*;
73
74mod replay_bench;
75pub use replay_bench::*;
76
77mod policy;
78pub use policy::*;
79
80mod stage_options;
81pub use stage_options::*;
82
83mod workflow;
84pub use workflow::*;
85
86mod workflow_bundle;
87pub use workflow_bundle::*;
88
89mod workflow_patch;
90pub use workflow_patch::*;
91
92mod safe_function_tools;
93pub use safe_function_tools::*;
94
95mod nested_invocation;
96pub use nested_invocation::*;
97
98#[cfg(test)]
99mod workflow_test_fixtures;
100
101mod records;
102pub use records::*;
103
104mod context_eval;
105pub use context_eval::*;
106
107mod merge_captain_audit;
108pub use merge_captain_audit::*;
109
110mod merge_captain_driver;
111pub use merge_captain_driver::*;
112
113mod merge_captain_ladder;
114pub use merge_captain_ladder::*;
115
116mod merge_captain_iteration;
117pub use merge_captain_iteration::*;
118
119pub mod playground;
120
121thread_local! {
122    static CURRENT_MUTATION_SESSION: RefCell<Option<MutationSessionRecord>> = const { RefCell::new(None) };
123    /// Workflow-level skill context, installed by `workflow_execute` so
124    /// every per-node agent loop constructed inside `execute_stage_node`
125    /// can pick up the same `skills:` / `skill_match:` registry without
126    /// threading a new parameter through every helper. Cleared on
127    /// workflow exit (success or error) by `WorkflowSkillContextGuard`.
128    static CURRENT_WORKFLOW_SKILL_CONTEXT: RefCell<Option<WorkflowSkillContext>> = const { RefCell::new(None) };
129}
130
131/// Skill wiring threaded from `workflow_execute` into the per-stage
132/// agent loops via thread-local context. `VmValue` wraps `Rc` and is
133/// not `Send`, so we store it in a thread-local rather than a mutex —
134/// the workflow runner pins itself to one task via `LocalSet`, so
135/// every stage observes the same context.
136#[derive(Clone, Default)]
137pub struct WorkflowSkillContext {
138    pub registry: Option<VmValue>,
139    pub match_config: Option<VmValue>,
140}
141
142pub fn install_workflow_skill_context(context: Option<WorkflowSkillContext>) {
143    CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| {
144        *slot.borrow_mut() = context;
145    });
146}
147
148pub fn current_workflow_skill_context() -> Option<WorkflowSkillContext> {
149    CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| slot.borrow().clone())
150}
151
152/// RAII guard that clears the workflow skill context on drop. Paired
153/// with `install_workflow_skill_context` at the top of `execute_workflow`
154/// so the context never leaks past a workflow's scope.
155pub struct WorkflowSkillContextGuard;
156
157impl Drop for WorkflowSkillContextGuard {
158    fn drop(&mut self) {
159        install_workflow_skill_context(None);
160    }
161}
162
163#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
164#[serde(default)]
165pub struct MutationSessionRecord {
166    pub session_id: String,
167    pub parent_session_id: Option<String>,
168    pub run_id: Option<String>,
169    pub worker_id: Option<String>,
170    pub execution_kind: Option<String>,
171    pub mutation_scope: String,
172    /// Declarative per-tool approval policy for this session. When `None`,
173    /// no policy-driven approval is requested; the session update stream
174    /// remains the only host-observable surface for tool dispatch.
175    pub approval_policy: Option<ToolApprovalPolicy>,
176}
177
178impl MutationSessionRecord {
179    pub fn normalize(mut self) -> Self {
180        if self.session_id.is_empty() {
181            self.session_id = new_id("session");
182        }
183        if self.mutation_scope.is_empty() {
184            self.mutation_scope = "read_only".to_string();
185        }
186        self
187    }
188}
189
190pub fn install_current_mutation_session(session: Option<MutationSessionRecord>) {
191    CURRENT_MUTATION_SESSION.with(|slot| {
192        *slot.borrow_mut() = session.map(MutationSessionRecord::normalize);
193    });
194}
195
196pub fn current_mutation_session() -> Option<MutationSessionRecord> {
197    CURRENT_MUTATION_SESSION.with(|slot| slot.borrow().clone())
198}
199pub(crate) fn parse_json_payload<T: for<'de> Deserialize<'de>>(
200    json: serde_json::Value,
201    label: &str,
202) -> Result<T, VmError> {
203    let payload = json.to_string();
204    let mut deserializer = serde_json::Deserializer::from_str(&payload);
205    let mut tracker = serde_path_to_error::Track::new();
206    let path_deserializer = serde_path_to_error::Deserializer::new(&mut deserializer, &mut tracker);
207    T::deserialize(path_deserializer).map_err(|error| {
208        let snippet = if payload.len() > 600 {
209            format!("{}...", &payload[..600])
210        } else {
211            payload.clone()
212        };
213        VmError::Runtime(format!(
214            "{label} parse error at {}: {} | payload={}",
215            tracker.path(),
216            error,
217            snippet
218        ))
219    })
220}
221
222pub(crate) fn parse_json_value<T: for<'de> Deserialize<'de>>(
223    value: &VmValue,
224) -> Result<T, VmError> {
225    parse_json_payload(vm_value_to_json(value), "orchestration")
226}
227
228#[cfg(test)]
229mod tests;