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