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
9/// Current time as a decimal Unix-seconds string.
10///
11/// Renamed from `now_rfc3339`, which it never was: the orchestration records
12/// it stamps (`created_at`, `generated_at`, `selected_at`) carry values like
13/// `"1753000000"`, not RFC3339. Correcting the *format* would change the shape
14/// of already-persisted records, so the name is corrected here instead — both
15/// to stop the next reader assuming RFC3339 and to keep this from being folded
16/// into `harn_clock::system_now_rfc3339` as if it were another copy.
17pub(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_policy_registry;
64pub use compaction_policy_registry::*;
65
66pub mod agent_inbox;
67
68mod artifacts;
69pub use artifacts::*;
70
71mod assemble;
72pub use assemble::*;
73
74mod handoffs;
75pub use handoffs::*;
76
77mod friction;
78pub use friction::*;
79
80mod crystallize;
81pub use crystallize::*;
82
83mod release_fixture;
84pub use release_fixture::*;
85
86mod replay_oracle;
87pub use replay_oracle::*;
88
89mod replay_bench;
90pub use replay_bench::*;
91
92mod policy;
93#[cfg(test)]
94pub(crate) use policy::swap_execution_policy_stack;
95pub use policy::*;
96
97mod ambient_scope;
98pub(crate) use ambient_scope::{
99    scope_ambient, scope_ambient_transaction, scope_inline_subtask, scope_run_event_sink,
100    AmbientExecutionScope,
101};
102pub use ambient_scope::{
103    scope_llm_runtime_overrides, scope_llm_runtime_overrides_with_provider_endpoints,
104};
105
106mod stage_options;
107pub use stage_options::*;
108
109mod workflow;
110pub use workflow::*;
111
112mod workflow_bundle;
113pub use workflow_bundle::*;
114
115mod workflow_patch;
116pub use workflow_patch::*;
117
118mod safe_function_tools;
119pub use safe_function_tools::*;
120
121mod nested_invocation;
122pub use nested_invocation::*;
123
124#[cfg(test)]
125mod workflow_test_fixtures;
126
127mod records;
128pub use records::*;
129
130mod context_eval;
131pub use context_eval::*;
132
133mod skill_gate;
134pub use skill_gate::*;
135
136mod merge_captain_audit;
137pub use merge_captain_audit::*;
138
139mod merge_captain_driver;
140pub use merge_captain_driver::*;
141
142mod merge_captain_ladder;
143pub use merge_captain_ladder::*;
144
145mod merge_captain_iteration;
146pub use merge_captain_iteration::*;
147
148pub mod playground;
149
150thread_local! {
151    static CURRENT_MUTATION_SESSION: RefCell<Option<MutationSessionRecord>> = const { RefCell::new(None) };
152    /// Workflow-level skill context, installed by `workflow_execute` so
153    /// every per-node agent loop constructed inside `execute_stage_node`
154    /// can pick up the same `skills:` / `skill_match:` registry without
155    /// threading a new parameter through every helper. Cleared on
156    /// workflow exit (success or error) by `WorkflowSkillContextGuard`.
157    static CURRENT_WORKFLOW_SKILL_CONTEXT: RefCell<Option<WorkflowSkillContext>> = const { RefCell::new(None) };
158}
159
160/// Skill wiring threaded from `workflow_execute` into the per-stage
161/// agent loops via thread-local context. The workflow runner pins itself
162/// to one task via `LocalSet`, so every stage observes the same context
163/// without cross-task synchronization.
164#[derive(Clone, Default)]
165pub struct WorkflowSkillContext {
166    pub registry: Option<VmValue>,
167    pub match_config: Option<VmValue>,
168}
169
170pub fn install_workflow_skill_context(context: Option<WorkflowSkillContext>) {
171    CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| {
172        *slot.borrow_mut() = context;
173    });
174}
175
176pub fn current_workflow_skill_context() -> Option<WorkflowSkillContext> {
177    CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| slot.borrow().clone())
178}
179
180/// RAII guard that clears the workflow skill context on drop. Paired
181/// with `install_workflow_skill_context` at the top of `execute_workflow`
182/// so the context never leaks past a workflow's scope.
183pub struct WorkflowSkillContextGuard;
184
185impl Drop for WorkflowSkillContextGuard {
186    fn drop(&mut self) {
187        install_workflow_skill_context(None);
188    }
189}
190
191#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
192#[serde(default)]
193pub struct MutationSessionRecord {
194    pub session_id: String,
195    pub parent_session_id: Option<String>,
196    pub run_id: Option<String>,
197    pub worker_id: Option<String>,
198    pub execution_kind: Option<String>,
199    pub mutation_scope: String,
200    /// Declarative per-tool approval policy for this session. When `None`,
201    /// no policy-driven approval is requested; the session update stream
202    /// remains the only host-observable surface for tool dispatch.
203    pub approval_policy: Option<ToolApprovalPolicy>,
204}
205
206impl MutationSessionRecord {
207    pub fn normalize(mut self) -> Self {
208        if self.session_id.is_empty() {
209            self.session_id = new_id("session");
210        }
211        if self.mutation_scope.is_empty() {
212            self.mutation_scope = "read_only".to_string();
213        }
214        self
215    }
216}
217
218pub fn install_current_mutation_session(session: Option<MutationSessionRecord>) {
219    CURRENT_MUTATION_SESSION.with(|slot| {
220        *slot.borrow_mut() = session.map(MutationSessionRecord::normalize);
221    });
222}
223
224pub fn current_mutation_session() -> Option<MutationSessionRecord> {
225    CURRENT_MUTATION_SESSION.with(|slot| slot.borrow().clone())
226}
227
228/// Per-task ambient-scope swap of the current mutation session. See
229/// `orchestration::ambient_scope`: the mutation session attributes audit
230/// records, `run_id`, approval policy, and secret-access scope to the running
231/// task, so a worker holding it across an `.await` must keep its OWN copy rather
232/// than read whatever a cooperatively-scheduled fan-out sibling left behind. The
233/// helper is `pub(crate)` — only the ambient combinator moves whole sessions;
234/// ordinary code uses `install_current_mutation_session`/`current_mutation_session`.
235pub(crate) fn swap_mutation_session(
236    next: Option<MutationSessionRecord>,
237) -> Option<MutationSessionRecord> {
238    CURRENT_MUTATION_SESSION.with(|slot| std::mem::replace(&mut *slot.borrow_mut(), next))
239}
240pub(crate) fn parse_json_payload<T: for<'de> Deserialize<'de>>(
241    json: serde_json::Value,
242    label: &str,
243) -> Result<T, VmError> {
244    let payload = json.to_string();
245    let mut deserializer = serde_json::Deserializer::from_str(&payload);
246    let mut tracker = serde_path_to_error::Track::new();
247    let path_deserializer = serde_path_to_error::Deserializer::new(&mut deserializer, &mut tracker);
248    T::deserialize(path_deserializer).map_err(|error| {
249        let snippet = if payload.len() > 600 {
250            format!("{}...", &payload[..600])
251        } else {
252            payload.clone()
253        };
254        VmError::Runtime(format!(
255            "{label} parse error at {}: {} | payload={}",
256            tracker.path(),
257            error,
258            snippet
259        ))
260    })
261}
262
263pub(crate) fn parse_json_value<T: for<'de> Deserialize<'de>>(
264    value: &VmValue,
265) -> Result<T, VmError> {
266    parse_json_payload(vm_value_to_json(value), "orchestration")
267}
268
269#[cfg(test)]
270mod tests;
271
272#[cfg(test)]
273mod policy_restriction_tests;
274
275#[cfg(test)]
276mod typed_options_parity;