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