harn_vm/orchestration/
mod.rs1use 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_unix_seconds_text() -> String {
18 use std::time::{SystemTime, UNIX_EPOCH};
19 let ts = SystemTime::now()
20 .duration_since(UNIX_EPOCH)
21 .unwrap_or_default()
22 .as_secs();
23 format!("{ts}")
24}
25
26pub(crate) fn new_id(prefix: &str) -> String {
27 format!("{prefix}_{}", uuid::Uuid::now_v7())
28}
29
30pub(crate) fn default_run_dir() -> PathBuf {
31 let base = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
32 crate::runtime_paths::run_root(&base)
33}
34
35mod hooks;
36pub use hooks::*;
37#[cfg(test)]
38mod tests_lazy_hooks;
39
40mod pipeline_lifecycle;
41pub use pipeline_lifecycle::*;
42
43mod settlement_agent;
44pub use settlement_agent::*;
45
46mod lifecycle_receipts;
47pub use lifecycle_receipts::*;
48
49mod command_policy;
50pub use command_policy::*;
51
52mod tool_precheck;
53pub use tool_precheck::*;
54
55mod compaction;
56pub use compaction::*;
57
58mod repair_ledger;
59
60mod compact_lifecycle;
61pub use compact_lifecycle::*;
62
63mod compaction_receipt;
64pub use compaction_receipt::*;
65
66mod compaction_policy_registry;
67pub use compaction_policy_registry::*;
68
69pub mod agent_inbox;
70
71mod artifacts;
72pub use artifacts::*;
73
74mod assemble;
75pub use assemble::*;
76
77mod handoffs;
78pub use handoffs::*;
79
80mod friction;
81pub use friction::*;
82
83mod crystallize;
84pub use crystallize::*;
85
86mod release_fixture;
87pub use release_fixture::*;
88
89mod replay_oracle;
90pub use replay_oracle::*;
91
92mod replay_bench;
93pub use replay_bench::*;
94
95mod policy;
96#[cfg(test)]
97pub(crate) use policy::swap_execution_policy_stack;
98pub use policy::*;
99
100mod ambient_scope;
101pub use ambient_scope::blocking::run_blocking_with_ambient;
102pub(crate) use ambient_scope::{
103 scope_ambient, scope_ambient_transaction, scope_approval_policy, scope_autonomy_policy,
104 scope_command_policy, scope_dynamic_permissions, scope_inline_subtask, scope_run_event_sink,
105 scope_spawned_source_dir, AmbientExecutionScope,
106};
107pub use ambient_scope::{
108 scope_execution_policy, scope_llm_runtime_overrides,
109 scope_llm_runtime_overrides_with_provider_endpoints,
110};
111
112mod stage_options;
113pub use stage_options::*;
114
115mod workflow;
116pub use workflow::*;
117
118mod workflow_bundle;
119pub use workflow_bundle::*;
120
121mod workflow_patch;
122pub use workflow_patch::*;
123
124mod safe_function_tools;
125pub use safe_function_tools::*;
126
127mod nested_invocation;
128pub use nested_invocation::*;
129
130#[cfg(test)]
131mod workflow_test_fixtures;
132
133mod records;
134pub use records::*;
135
136mod run_review;
137pub use run_review::*;
138
139mod run_view_fixtures;
140pub use run_view_fixtures::*;
141
142mod training_example;
143pub use training_example::*;
144
145mod context_eval;
146pub use context_eval::*;
147
148mod skill_gate;
149pub use skill_gate::*;
150
151mod merge_captain_audit;
152pub use merge_captain_audit::*;
153
154mod merge_captain_driver;
155pub use merge_captain_driver::*;
156
157mod merge_captain_ladder;
158pub use merge_captain_ladder::*;
159
160mod merge_captain_iteration;
161pub use merge_captain_iteration::*;
162
163pub mod playground;
164
165thread_local! {
166 static CURRENT_MUTATION_SESSION: RefCell<Option<MutationSessionRecord>> = const { RefCell::new(None) };
167 static CURRENT_WORKFLOW_SKILL_CONTEXT: RefCell<Option<WorkflowSkillContext>> = const { RefCell::new(None) };
173}
174
175#[derive(Clone, Default)]
180pub struct WorkflowSkillContext {
181 pub registry: Option<VmValue>,
182 pub match_config: Option<VmValue>,
183}
184
185pub fn install_workflow_skill_context(context: Option<WorkflowSkillContext>) {
186 CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| {
187 *slot.borrow_mut() = context;
188 });
189}
190
191pub fn current_workflow_skill_context() -> Option<WorkflowSkillContext> {
192 CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| slot.borrow().clone())
193}
194
195pub struct WorkflowSkillContextGuard;
199
200impl Drop for WorkflowSkillContextGuard {
201 fn drop(&mut self) {
202 install_workflow_skill_context(None);
203 }
204}
205
206#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
207#[serde(default)]
208pub struct MutationSessionRecord {
209 pub session_id: String,
210 pub parent_session_id: Option<String>,
211 pub run_id: Option<String>,
212 pub worker_id: Option<String>,
213 pub execution_kind: Option<String>,
214 pub mutation_scope: String,
215 pub approval_policy: Option<ToolApprovalPolicy>,
219}
220
221impl MutationSessionRecord {
222 pub fn normalize(mut self) -> Self {
223 if self.session_id.is_empty() {
224 self.session_id = new_id("session");
225 }
226 if self.mutation_scope.is_empty() {
227 self.mutation_scope = "read_only".to_string();
228 }
229 self
230 }
231}
232
233pub fn install_current_mutation_session(session: Option<MutationSessionRecord>) {
234 CURRENT_MUTATION_SESSION.with(|slot| {
235 *slot.borrow_mut() = session.map(MutationSessionRecord::normalize);
236 });
237}
238
239pub fn current_mutation_session() -> Option<MutationSessionRecord> {
240 CURRENT_MUTATION_SESSION.with(|slot| slot.borrow().clone())
241}
242
243pub(crate) fn swap_mutation_session(
251 next: Option<MutationSessionRecord>,
252) -> Option<MutationSessionRecord> {
253 CURRENT_MUTATION_SESSION.with(|slot| std::mem::replace(&mut *slot.borrow_mut(), next))
254}
255
256const PAYLOAD_SNIPPET_MAX_BYTES: usize = 600;
258
259pub(crate) fn parse_json_payload<T: for<'de> Deserialize<'de>>(
260 json: serde_json::Value,
261 label: &str,
262) -> Result<T, VmError> {
263 let payload = json.to_string();
264 let mut deserializer = serde_json::Deserializer::from_str(&payload);
265 let mut tracker = serde_path_to_error::Track::new();
266 let path_deserializer = serde_path_to_error::Deserializer::new(&mut deserializer, &mut tracker);
267 T::deserialize(path_deserializer).map_err(|error| {
268 let snippet = crate::text::truncate_end_bytes(&payload, PAYLOAD_SNIPPET_MAX_BYTES);
269 VmError::Runtime(format!(
270 "{label} parse error at {}: {} | payload={}",
271 tracker.path(),
272 error,
273 snippet
274 ))
275 })
276}
277
278pub(crate) fn parse_json_value<T: for<'de> Deserialize<'de>>(
279 value: &VmValue,
280) -> Result<T, VmError> {
281 parse_json_payload(vm_value_to_json(value), "orchestration")
282}
283
284#[cfg(test)]
285mod tests;
286
287#[cfg(test)]
288mod policy_restriction_tests;
289
290#[cfg(test)]
291mod typed_options_parity;