1use super::store::{is_run_stale, is_withheld_sentinel};
8use super::types::WorkflowRun;
9
10const CONTROL_TOOL: &str = "ctx_workflow";
13
14const WRAPPER_TOOL: &str = "ctx_call";
19
20#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum ToolGate {
23 Expired,
26 Pass,
28 Refuse(String),
30}
31
32#[must_use]
44pub fn tool_gate(run: &WorkflowRun, tool: &str, passthrough: &[&str]) -> ToolGate {
45 if is_withheld_sentinel(run) {
46 return if matches!(tool, CONTROL_TOOL | WRAPPER_TOOL | "ctx") {
49 ToolGate::Pass
50 } else {
51 ToolGate::Refuse(format!(
52 "Tool '{tool}' blocked: the stored workflow is withheld by the context gateway. \
53 Use ctx_workflow(action=\"status\") to check it again, or \
54 ctx_workflow(action=\"stop\") to discard it."
55 ))
56 };
57 }
58 if tool == CONTROL_TOOL {
59 return ToolGate::Pass;
60 }
61 if run.current == "done" || is_run_stale(run) {
62 return ToolGate::Expired;
63 }
64 if passthrough.contains(&tool) {
65 return ToolGate::Pass;
66 }
67 let Some(allowed) = run
68 .spec
69 .state(&run.current)
70 .and_then(|state| state.allowed_tools.as_ref())
71 else {
72 return ToolGate::Pass;
73 };
74 if allowed.iter().any(|permitted| permitted == tool) {
75 return ToolGate::Pass;
76 }
77 let mut shown = allowed.clone();
78 shown.sort();
79 shown.truncate(30);
80 ToolGate::Refuse(format!(
81 "Tool '{tool}' blocked by workflow '{}' (state: {}). Allowed: {}. Use ctx_workflow(action=\"stop\") to exit.",
82 run.spec.name,
83 run.current,
84 shown.join(", ")
85 ))
86}
87
88#[cfg(test)]
89pub(crate) mod tests {
90 use super::{ToolGate, tool_gate};
91 use crate::core::context_admission::stored::lineage_support::{governed, project, scoped};
92 use crate::core::policy::runtime::TestPolicyOverride;
93 use crate::core::workflow::store::{
94 is_run_stale, is_withheld_sentinel, load_active, save_active,
95 };
96 use crate::core::workflow::types::{StateSpec, WorkflowRun, WorkflowSpec};
97
98 const PASSTHROUGH: &[&str] = crate::server::WORKFLOW_PASSTHROUGH_TOOLS;
100
101 pub(crate) fn review() -> WorkflowRun {
104 let now = chrono::Utc::now();
105 WorkflowRun {
106 spec: WorkflowSpec {
107 name: "review".to_string(),
108 description: Some("Check the parser change".to_string()),
109 initial: "planning".to_string(),
110 states: vec![StateSpec {
111 name: "planning".to_string(),
112 description: None,
113 allowed_tools: Some(vec!["ctx_overview".to_string()]),
114 requires_evidence: None,
115 }],
116 transitions: Vec::new(),
117 },
118 current: "planning".to_string(),
119 started_at: now,
120 updated_at: now,
121 transitions: Vec::new(),
122 evidence: Vec::new(),
123 }
124 }
125
126 pub(crate) fn workflow_file() -> std::path::PathBuf {
128 crate::core::data_dir::lean_ctx_data_dir()
129 .expect("data dir")
130 .join("workflows")
131 .join("active.json")
132 }
133
134 #[test]
138 fn the_withheld_stand_in_is_closed_and_never_expires() {
139 let _data = governed();
140 let _community = TestPolicyOverride::set(None);
141 let (_directory, root) = project();
142 let (_other_directory, other) = project();
143 scoped(&root, || save_active(&review())).expect("saved in its project");
144 let stored = std::fs::read(workflow_file()).expect("stored workflow");
145
146 let mut closed = scoped(&other, load_active)
147 .expect("load")
148 .expect("a withheld workflow is still a workflow");
149 assert!(is_withheld_sentinel(&closed));
150 closed.updated_at = chrono::Utc::now() - chrono::Duration::minutes(45);
152 assert!(!is_run_stale(&closed));
153 for tool in [
154 "ctx_read",
155 "ctx_session",
156 "ctx_ledger",
157 "ctx_search",
158 "ctx_overview",
159 ] {
160 let ToolGate::Refuse(reason) = tool_gate(&closed, tool, PASSTHROUGH) else {
161 panic!("{tool} must be refused under the stand-in");
162 };
163 assert!(
164 reason.contains("withheld by the context gateway"),
165 "{reason}"
166 );
167 assert!(!reason.contains("review"), "no workflow name: {reason}");
168 assert!(!reason.contains("planning"), "no state name: {reason}");
169 assert!(!reason.contains("active.json"), "no file name: {reason}");
170 }
171 assert_eq!(
172 tool_gate(&closed, "ctx_workflow", PASSTHROUGH),
173 ToolGate::Pass
174 );
175 assert_eq!(tool_gate(&closed, "ctx_call", PASSTHROUGH), ToolGate::Pass);
176 assert_eq!(
177 std::fs::read(workflow_file()).expect("stored workflow"),
178 stored,
179 "the withheld workflow is byte-identical on disk"
180 );
181
182 let real = scoped(&root, load_active).expect("load").expect("active");
184 assert!(!is_withheld_sentinel(&real));
185 assert_eq!(real.spec.name, "review");
186 assert_eq!(
187 tool_gate(&real, "ctx_overview", PASSTHROUGH),
188 ToolGate::Pass
189 );
190 }
191
192 #[test]
196 fn a_withheld_workflow_is_not_deleted_for_its_age() {
197 let _data = governed();
198 let _community = TestPolicyOverride::set(None);
199 let (_directory, root) = project();
200 let (_other_directory, other) = project();
201 let mut old = review();
202 old.updated_at = chrono::Utc::now() - chrono::Duration::minutes(45);
203 scoped(&root, || save_active(&old)).expect("saved in its project");
204 let stored = std::fs::read(workflow_file()).expect("stored workflow");
205
206 let closed = scoped(&other, load_active).expect("load").expect("closed");
207 assert!(is_withheld_sentinel(&closed));
208 assert_eq!(std::fs::read(workflow_file()).expect("kept"), stored);
209
210 assert!(scoped(&root, load_active).expect("load").is_none());
211 assert!(
212 !workflow_file().exists(),
213 "a served stale run is cleared as before"
214 );
215 }
216
217 #[test]
219 fn a_real_run_goes_stale_and_keeps_its_pass_through_tools() {
220 let _data = crate::core::data_dir::isolated_data_dir();
221 let _community = TestPolicyOverride::set(None);
222 let mut run = review();
223 assert_eq!(tool_gate(&run, "ctx_read", PASSTHROUGH), ToolGate::Pass);
224 assert_eq!(tool_gate(&run, "ctx_session", PASSTHROUGH), ToolGate::Pass);
225 assert_eq!(tool_gate(&run, "ctx_overview", PASSTHROUGH), ToolGate::Pass);
226 assert_eq!(tool_gate(&run, "ctx_workflow", PASSTHROUGH), ToolGate::Pass);
227 assert_eq!(
228 tool_gate(&run, "ctx_shell", PASSTHROUGH),
229 ToolGate::Refuse(
230 "Tool 'ctx_shell' blocked by workflow 'review' (state: planning). Allowed: ctx_overview. Use ctx_workflow(action=\"stop\") to exit."
231 .to_string()
232 )
233 );
234
235 run.updated_at = chrono::Utc::now() - chrono::Duration::minutes(31);
236 assert!(is_run_stale(&run));
237 assert_eq!(tool_gate(&run, "ctx_shell", PASSTHROUGH), ToolGate::Expired);
238 assert_eq!(tool_gate(&run, "ctx_read", PASSTHROUGH), ToolGate::Expired);
239 assert_eq!(tool_gate(&run, "ctx_workflow", PASSTHROUGH), ToolGate::Pass);
240
241 run.updated_at = chrono::Utc::now();
242 run.current = "done".to_string();
243 assert_eq!(tool_gate(&run, "ctx_shell", PASSTHROUGH), ToolGate::Expired);
244 }
245}