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