1use scc_api::{DetailRequest, ImpactRequest, StartupRequest, StructuralRequest, SurfaceRequest as ApiSurfaceRequest};
8use scc_context::startup::{allocate_startup_budget, build_startup, render_startup, task_delta_with_ids, visible_ids_from_startup, StartupContext};
9use scc_core::{ContextBudget, SurfaceRenderResult};
10use std::path::Path;
11
12pub struct SccContext<'a> {
14 pub(crate) engine: &'a crate::workspace::Engine<'a>,
15}
16
17pub(crate) fn record_visible_ids(
19 led: &mut scc_core::ContextLedger,
20 ctx: &scc_context::ContextCompiler,
21 ids: &[String],
22) {
23 for id in ids {
24 led.visible_entities.insert(id.clone());
25 if let Some(e) = ctx.view.entity(id) {
26 match e.kind.as_str() {
27 scc_core::kinds::SYMBOL => {
28 led.visible_symbols.insert(id.clone());
29 }
30 scc_core::kinds::COMPONENT => {
31 led.visible_components.insert(id.clone());
32 }
33 scc_core::kinds::FLOW => {
34 led.visible_flows.insert(id.clone());
35 }
36 _ => {}
37 }
38 }
39 }
40}
41
42fn record_rendered_entries(
44 led: &mut scc_core::ContextLedger,
45 entries: &[scc_core::SurfaceEntry],
46 rendered_ids: &[String],
47) {
48 if !entries.is_empty() {
49 for e in entries {
50 led.visible_entities.insert(e.symbol_id.clone());
51 led.visible_symbols.insert(e.symbol_id.clone());
52 led.visible_files.insert(e.path.clone());
53 if let Some(c) = &e.component {
54 led.visible_components.insert(c.clone());
55 }
56 }
57 return;
58 }
59 for id in rendered_ids {
60 led.visible_entities.insert(id.clone());
61 }
62}
63
64impl SccContext<'_> {
66 pub fn overview(&self) -> crate::Result<scc_context::ContextPack> {
68 Ok(self.engine.ctx().system_overview())
69 }
70
71 pub fn atlas(&self, budget: Option<usize>, full: bool, unbounded: bool) -> crate::Result<scc_context::ContextPack> {
73 let ctx = self.engine.ctx();
74 Ok(if full {
75 ctx.system_atlas_scoped(budget, scc_context::atlas::AtlasScope::Full, unbounded)
76 } else if unbounded {
77 ctx.system_atlas_scoped(budget, scc_context::atlas::AtlasScope::Production, true)
78 } else {
79 ctx.system_atlas(budget)
80 })
81 }
82
83 pub fn startup(&self, req: &StartupRequest) -> crate::Result<(StartupContext, String)> {
85 let ctx = self.engine.ctx();
86 let budget = allocate_startup_budget(&ctx, req.budget);
87 let startup = build_startup(&ctx, &budget, scc_context::startup::RENDERER_VERSION);
88 let text = render_startup(&startup);
89 let ledger_store = scc_context::context_ledger::ContextLedgerStore::new(self.engine.store);
90 let mut led = ledger_store.load();
91 let (syms, files, comps, flows) = visible_ids_from_startup(&ctx, &startup);
92 led.visible_entities.extend(syms.iter().cloned());
93 led.visible_symbols.extend(syms);
94 led.visible_files.extend(files);
95 led.visible_components.extend(comps);
96 led.visible_flows.extend(flows);
97 ledger_store.save(&led);
98 Ok((startup, text))
99 }
100
101 pub fn surface(&self, req: &ApiSurfaceRequest, semantic: Option<&dyn scc_context::rank::SemanticScorer>) -> crate::Result<(SurfaceRenderResult, String)> {
103 let ctx = self.engine.ctx();
104 let tokens = req.budget.unwrap_or(ContextBudget::default().surface);
105 let request = scc_context::surface::SurfaceRequest {
106 mode: match req.task.as_deref() {
107 Some(goal) => scc_context::surface::SurfaceMode::Task { goal, visible: None },
108 None => scc_context::surface::SurfaceMode::Global,
109 },
110 budget: tokens,
111 explain: req.explain,
112 policy: scc_context::surface::SurfacePolicy::defaults(tokens),
113 semantic,
114 };
115 let stages = req.stages.as_ref().map(|st| scc_context::surface::SurfacePipelineStages {
116 lexical: st.lexical, global_ppr: st.global_ppr, task_ppr: st.task_ppr,
117 mmr: st.mmr, quotas: st.quotas, optimizer: st.optimizer,
118 }).unwrap_or_default();
119 let result = scc_context::surface::build_surface_staged(&ctx, request, &stages);
120 let text = match req.task.as_deref() {
121 Some(goal) => {
122 let body = result.text.strip_prefix("SCC SYSTEM SURFACE MAP").unwrap_or(result.text.as_str());
123 format!("# SYSTEM SURFACE MAP (task-personalized: {goal}){body}")
124 }
125 None => result.text.clone(),
126 };
127 if !result.rendered_ids.is_empty() {
128 let store = self.engine.store;
129 let mut led = scc_context::context_ledger::ContextLedgerStore::new(store).load();
130 record_rendered_entries(&mut led, &result.rendered_entries, &result.rendered_ids);
131 scc_context::context_ledger::ContextLedgerStore::new(store).save(&led);
132 }
133 Ok((result, text))
134 }
135
136 pub fn important(&self, limit: usize, component: Option<&str>, task: Option<&str>) -> crate::Result<(Vec<scc_core::SurfaceEntry>, bool)> {
138 use scc_context::surface::{important_symbols, SurfaceMode};
139 let ctx = self.engine.ctx();
140 let mode = match task {
141 Some(goal) => SurfaceMode::Task { goal, visible: None },
142 None => SurfaceMode::Global,
143 };
144 let tasked = task.is_some();
145 let mut entries = important_symbols(&ctx, mode, 0);
146 if let Some(c) = component {
147 entries.retain(|e| e.component.as_deref().is_some_and(|s| s.contains(c)));
148 }
149 entries.truncate(limit.max(1));
150 Ok((entries, tasked))
151 }
152
153 pub fn subagent(&self, goal: &str, files: &[String], symbols: &[String], budget: Option<usize>) -> crate::Result<scc_context::ContextPack> {
155 let mut pack = self.engine.ctx().task_context(goal, files, symbols, budget);
156 pack.kind = "subagent".into();
157 let mut header = String::new();
158 header.push_str("# SUBAGENT SCOPE\n");
159 header.push_str("You are a delegated agent. Work ONLY within the context below; ");
160 header.push_str("do not re-derive the system model. If a needed fact is absent, ");
161 header.push_str("state it and ask rather than assume. Your goal is bounded to:\n");
162 header.push_str(&format!("> {goal}\n\n"));
163 pack.content = format!("{header}{}", pack.content);
164 Ok(pack)
165 }
166
167 pub fn component(&self, req: &DetailRequest) -> crate::Result<scc_context::ContextPack> {
169 let ctx = self.engine.ctx();
170 Ok(if req.unbounded { ctx.component_context_full(&req.id) } else { ctx.component_context(&req.id) })
171 }
172
173 pub fn flow(&self, req: &DetailRequest) -> crate::Result<scc_context::ContextPack> {
175 let ctx = self.engine.ctx();
176 Ok(if req.unbounded { ctx.flow_context_full(&req.id) } else { ctx.flow_context(&req.id) })
177 }
178
179 pub fn impact(&self, req: &ImpactRequest) -> crate::Result<scc_context::ContextPack> {
181 let ctx = self.engine.ctx();
182 Ok(if req.unbounded {
183 ctx.impact_context_full(&req.files, &req.symbols, req.diff.as_deref())
184 } else {
185 ctx.impact_context(&req.files, &req.symbols, req.diff.as_deref())
186 })
187 }
188
189 pub fn verify(&self, unbounded: bool) -> crate::Result<scc_context::ContextPack> {
191 let ctx = self.engine.ctx();
192 Ok(if unbounded { ctx.verify_context_full() } else { ctx.verify_context() })
193 }
194
195 pub fn structural(
197 &self,
198 req: &StructuralRequest,
199 root: &Path,
200 semantic: Option<&dyn scc_context::rank::SemanticScorer>,
201 ) -> crate::Result<String> {
202 let store = self.engine.store;
203 let ctx = self.engine.ctx();
204 let tokens = req.budget.unwrap_or(ContextBudget::default().structural_source);
205 let max_units = (tokens / 1000).clamp(1, 64);
206 let paths: Vec<String> = if !req.files.is_empty() {
207 let mut resolved = Vec::new();
208 for f in &req.files {
209 match scc_context::structural_source::resolve_handle_to_path(&store.root, f) {
210 Ok(p) => resolved.push(p),
211 Err(e) => return Ok(format!("# HANDLE REFUSED\n{e}\n")),
212 }
213 }
214 resolved
215 } else if let Some(goal) = req.task.as_deref() {
216 let goal = goal.trim();
217 if goal.is_empty() {
218 return Ok("# STRUCTURAL SOURCE\n\nPass --files <paths...> or --task \"<goal>\".".to_string());
219 }
220 super::task::surface_task_files(&ctx, goal, max_units, tokens.max(1), semantic)
221 } else {
222 return Ok("# STRUCTURAL SOURCE\n\nPass --files <paths...> or --task \"<goal>\".".to_string());
223 };
224 if paths.is_empty() {
225 return Ok("# STRUCTURAL SOURCE\n\nNo indexed files matched the task goal (run `scc index` first, or pass --files explicitly).".to_string());
226 }
227 let _ = root;
228 let units = scc_context::structural_source::structural_source(&ctx, &paths, max_units);
229 if units.is_empty() {
230 return Ok("# STRUCTURAL SOURCE\n\nNo indexed symbols in the requested files (run `scc index` first).".to_string());
231 }
232 Ok(scc_context::structural_source::render_structural(&units))
233 }
234
235 pub fn task_delta(&self, goal: &str, budget: usize, semantic: Option<&dyn scc_context::rank::SemanticScorer>) -> crate::Result<(String, Vec<String>)> {
237 let ctx = self.engine.ctx();
238 let ledger_store = scc_context::context_ledger::ContextLedgerStore::new(self.engine.store);
239 let visible = ledger_store.load();
240 Ok(task_delta_with_ids(&ctx, goal, &visible, budget, semantic))
241 }
242
243 pub fn record_task_delta_ids(&self, ids: &[String]) {
245 if ids.is_empty() {
246 return;
247 }
248 let ctx = self.engine.ctx();
249 let ledger_store = scc_context::context_ledger::ContextLedgerStore::new(self.engine.store);
250 let mut led = ledger_store.load();
251 record_visible_ids(&mut led, &ctx, ids);
252 ledger_store.save(&led);
253 }
254}