Skip to main content

glass_dev/
tools.rs

1//! Governed tool routing into one resident development workspace.
2
3use crate::agents::AgentSpec;
4use crate::browser::BrowserStartConfig;
5use crate::debugger::{DebugAdapterConfig, SourceBreakpoint};
6use crate::development::{
7    AgentToolGateway, DevelopmentError, DevelopmentResult, ToolAuthorization, ToolCall,
8    ToolDescriptor,
9};
10use crate::kernels::KernelKind;
11use crate::pi_runtime::PiSessionRequest;
12use crate::tasks::{TaskId, TaskSpec};
13use crate::workspace::DevelopmentWorkspace;
14use crate::{DevelopmentNode, DevelopmentNodeKind, ObservableEventInput, WorkspaceTrust};
15use glass_browser::browser::session::{
16    SemanticObservationLevel, WorkflowRecordingSession, record_semantic_events,
17};
18use glass_browser::workspace::{WorkspaceId, WorkspaceStore};
19use serde_json::Value;
20use std::path::PathBuf;
21use std::time::Duration;
22
23const RESULT_LIMIT: usize = 512 * 1024;
24
25#[derive(Debug, Clone)]
26pub struct DevelopmentToolContext {
27    pub authorization: ToolAuthorization,
28    pub initiator: Option<crate::development::Actor>,
29    pub expected_generation: u64,
30    pub expected_project_revision: u64,
31}
32
33/// Routes Glass Agent operations through authoritative resident services.
34#[derive(Debug, Clone)]
35pub struct DevelopmentToolRouter {
36    core: AgentToolGateway,
37    descriptors: Vec<ToolDescriptor>,
38}
39
40impl Default for DevelopmentToolRouter {
41    fn default() -> Self {
42        let core = AgentToolGateway::default();
43        let service = service_descriptors();
44        let mut descriptors = core
45            .descriptors()
46            .into_iter()
47            .filter(|descriptor| {
48                !service
49                    .iter()
50                    .any(|candidate| candidate.name == descriptor.name)
51            })
52            .collect::<Vec<_>>();
53        descriptors.extend(service);
54        Self { core, descriptors }
55    }
56}
57
58impl DevelopmentToolRouter {
59    pub fn with_customization(customization: &crate::Customization, trust: WorkspaceTrust) -> Self {
60        let mut router = Self::default();
61        let custom = customization.descriptors(trust);
62        router
63            .descriptors
64            .retain(|descriptor| !custom.iter().any(|item| item.name == descriptor.name));
65        router.descriptors.extend(custom);
66        router
67    }
68
69    pub fn descriptors(&self) -> Vec<ToolDescriptor> {
70        self.descriptors.clone()
71    }
72
73    pub fn execute(
74        &self,
75        workspace: &mut DevelopmentWorkspace,
76        call: &ToolCall,
77        context: &DevelopmentToolContext,
78    ) -> DevelopmentResult<Value> {
79        if workspace.generation() != context.expected_generation {
80            return Err(DevelopmentError::Conflict(format!(
81                "stale workspace generation {}; current generation is {}",
82                context.expected_generation,
83                workspace.generation()
84            )));
85        }
86        if workspace.project().revision() != context.expected_project_revision {
87            return Err(DevelopmentError::Conflict(format!(
88                "stale project revision {}; current revision is {}",
89                context.expected_project_revision,
90                workspace.project().revision()
91            )));
92        }
93        let descriptor = self
94            .descriptors
95            .iter()
96            .find(|descriptor| descriptor.name == call.name)
97            .ok_or_else(|| DevelopmentError::NotFound(format!("tool {}", call.name)))?;
98        if !descriptor.available {
99            return Err(DevelopmentError::Conflict(
100                descriptor
101                    .unavailable_reason
102                    .clone()
103                    .unwrap_or_else(|| format!("tool {} is unavailable", call.name)),
104            ));
105        }
106        if workspace.trust() == WorkspaceTrust::Untrusted && !untrusted_tool_allowed(&call.name) {
107            return Err(DevelopmentError::Conflict(format!(
108                "tool {} is blocked until the workspace is trusted",
109                call.name
110            )));
111        }
112        if descriptor.mutating
113            && (!context.authorization.allow_mutation || !context.authorization.confirmed)
114        {
115            return Err(DevelopmentError::Conflict(format!(
116                "tool {} requires mutation authority and confirmation",
117                call.name
118            )));
119        }
120        let actor_id = context.authorization.actor.id.clone();
121        let initiator_id = context
122            .initiator
123            .as_ref()
124            .map(|actor| actor.id.as_str())
125            .unwrap_or(actor_id.as_str());
126        let project_revision = workspace.project().revision();
127        let resource = format!("tool:{}", call.id);
128        let argument_bytes = serde_json::to_vec(&call.arguments)?.len();
129        workspace.intelligence_mut().upsert_node(DevelopmentNode {
130            id: resource.clone(),
131            kind: DevelopmentNodeKind::ToolCall,
132            label: call.name.clone(),
133            revision: project_revision,
134            stale: false,
135            evidence: serde_json::json!({
136                "toolCallId":call.id,
137                "name":call.name,
138                "mutating":descriptor.mutating,
139                "argumentBytes":argument_bytes
140            }),
141        })?;
142        workspace.intelligence_mut().link(
143            "repository:root",
144            &resource,
145            "receivedToolCall",
146            project_revision,
147            &actor_id,
148            serde_json::json!({"name":call.name,"initiator":initiator_id,"executor":actor_id}),
149        )?;
150        workspace.intelligence_mut().record(ObservableEventInput {
151            actor: &actor_id,
152            subsystem: "tool",
153            kind: "called",
154            resource: Some(&resource),
155            workspace_revision: project_revision,
156            evidence: serde_json::json!({"name":call.name,"mutating":descriptor.mutating,"initiator":initiator_id,"executor":actor_id}),
157            rationale: None,
158        })?;
159        if workspace.trust().permits_project_execution() {
160            workspace.customization().run_hooks(
161                "tool.before",
162                &serde_json::json!({"id":call.id,"name":call.name,"actor":&actor_id}),
163                workspace.trust(),
164                &actor_id,
165            )?;
166        }
167        let result = if service_descriptors()
168            .iter()
169            .any(|descriptor| descriptor.name == call.name)
170        {
171            self.execute_service(workspace, call, context)
172        } else if workspace.customization().custom_tool(&call.name).is_some() {
173            workspace.customization().execute_tool(
174                &call.name,
175                &call.arguments,
176                workspace.trust(),
177                &actor_id,
178            )
179        } else if let Some(name) = call.name.strip_prefix("glass.command.") {
180            workspace
181                .customization()
182                .execute_command(name, workspace.trust(), &actor_id)
183        } else {
184            self.core
185                .execute(workspace.project_mut(), call, &context.authorization)
186        };
187        match result {
188            Ok(result) => {
189                if workspace.trust().permits_project_execution() {
190                    workspace.customization().run_hooks(
191                        "tool.after",
192                        &serde_json::json!({"id":call.id,"name":call.name,"actor":&actor_id,"ok":true}),
193                        workspace.trust(),
194                        &actor_id,
195                    )?;
196                }
197                let result_bytes = serde_json::to_vec(&result)?.len();
198                if result_bytes > RESULT_LIMIT {
199                    return Err(DevelopmentError::InvalidInput(format!(
200                        "tool result exceeds the {RESULT_LIMIT} byte limit"
201                    )));
202                }
203                let resulting_revision = workspace.project().revision();
204                project_observable_result(
205                    workspace,
206                    call,
207                    &actor_id,
208                    project_revision,
209                    resulting_revision,
210                    &result,
211                )?;
212                workspace.intelligence_mut().record(ObservableEventInput {
213                    actor: &actor_id,
214                    subsystem: "tool",
215                    kind: "completed",
216                    resource: Some(&resource),
217                    workspace_revision: resulting_revision,
218                    evidence: serde_json::json!({"name":call.name,"resultBytes":result_bytes}),
219                    rationale: None,
220                })?;
221                Ok(result)
222            }
223            Err(error) => {
224                if workspace.trust().permits_project_execution() {
225                    workspace.customization().run_hooks(
226                        "tool.after",
227                        &serde_json::json!({"id":call.id,"name":call.name,"actor":&actor_id,"ok":false,"error":error.to_string()}),
228                        workspace.trust(),
229                        &actor_id,
230                    )?;
231                }
232                let resulting_revision = workspace.project().revision();
233                workspace.intelligence_mut().record(ObservableEventInput {
234                    actor: &actor_id,
235                    subsystem: "tool",
236                    kind: "failed",
237                    resource: Some(&resource),
238                    workspace_revision: resulting_revision,
239                    evidence: serde_json::json!({"name":call.name,"error":error.to_string()}),
240                    rationale: None,
241                })?;
242                Err(error)
243            }
244        }
245    }
246
247    fn execute_service(
248        &self,
249        workspace: &mut DevelopmentWorkspace,
250        call: &ToolCall,
251        context: &DevelopmentToolContext,
252    ) -> DevelopmentResult<Value> {
253        let string = |name: &str| required_string(call, name);
254        let actor = normalized_actor_id(&context.authorization.actor.id);
255        match call.name.as_str() {
256            "glass.editor.open" => map_service(
257                workspace
258                    .project_mut()
259                    .open_buffer(string("path")?, context.authorization.actor.clone()),
260            ),
261            "glass.editor.selection" => {
262                let path = string("path")?;
263                workspace
264                    .project()
265                    .buffer(path)
266                    .cloned()
267                    .map(|buffer| {
268                        serde_json::json!({
269                            "path":buffer.path,
270                            "line":buffer.cursor_line,
271                            "column":buffer.cursor_column,
272                            "actor":buffer.actor,
273                            "dirty":buffer.dirty
274                        })
275                    })
276                    .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))
277            }
278            "glass.editor.replace" => {
279                let matches = workspace.project_mut().replace_in_buffer(
280                    string("path")?,
281                    string("oldText")?,
282                    string("newText")?,
283                    context.authorization.actor.clone(),
284                )?;
285                Ok(serde_json::json!({"replacements":matches}))
286            }
287            "glass.editor.save" => {
288                map_service(workspace.project_mut().save_buffer(string("path")?))
289            }
290            "glass.editor.diff" => map_service(workspace.project_mut().diff()),
291            "glass.editor.buffers" => Ok(serde_json::to_value(
292                workspace.project().buffers().cloned().collect::<Vec<_>>(),
293            )?),
294            "glass.process.start" => map_service(workspace.project_mut().start_process(
295                string("name")?,
296                required_string(call, "command")?,
297            )),
298            "glass.process.stop" => {
299                map_service(workspace.project_mut().stop_process(string("name")?))
300            }
301            "glass.process.logs" => {
302                let name = string("name")?;
303                let processes = workspace.project_mut().processes();
304                processes.poll()?;
305                Ok(serde_json::json!({
306                    "name": name,
307                    "output": processes.output(name)?,
308                }))
309            }
310            "glass.process.list" => {
311                map_service(workspace.project_mut().processes().list_checked())
312            }
313
314            "glass.process.restart" => {
315                map_service(workspace.project_mut().processes().restart(string("name")?))
316            }
317            "glass.process.input" => {
318                workspace
319                    .project_mut()
320                    .processes()
321                    .send_input(string("name")?, string("input")?)?;
322                Ok(serde_json::json!({"sent":true}))
323            }
324            "glass.process.resize" => {
325                let cols = u16_value(call, "cols")?;
326                let rows = u16_value(call, "rows")?;
327                workspace
328                    .project_mut()
329                    .processes()
330                    .resize(string("name")?, cols, rows)?;
331                Ok(serde_json::json!({"resized":true,"cols":cols,"rows":rows}))
332            }
333            "glass.process.health" => {
334                let name = string("name")?;
335                let snapshot = workspace
336                    .project_mut()
337                    .processes()
338                    .list_checked()?
339                    .into_iter()
340                    .find(|snapshot| snapshot.name == name)
341                    .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?;
342                Ok(serde_json::json!({
343                    "name":snapshot.name,
344                    "pid":snapshot.pid,
345                    "state":snapshot.state,
346                    "health":snapshot.health,
347                    "detectedUrls":snapshot.detected_urls
348                }))
349            }
350            "glass.process.ports" => {
351                let snapshots = workspace.project_mut().processes().list_checked()?;
352                Ok(serde_json::json!({
353                    "processes":snapshots.into_iter().map(|snapshot| serde_json::json!({
354                        "name":snapshot.name,
355                        "pid":snapshot.pid,
356                        "urls":snapshot.detected_urls
357                    })).collect::<Vec<_>>()
358                }))
359            }
360            "glass.browser.start" => {
361                let config: BrowserStartConfig = serde_json::from_value(call.arguments.clone())?;
362                workspace.browser().start(config)
363            }
364            "glass.browser.stop" => workspace.browser().stop(),
365            "glass.browser.attach" => {
366                let mut config: BrowserStartConfig = serde_json::from_value(call.arguments.clone())?;
367                config.attach = true;
368                workspace.browser().start(config)
369            }
370            "glass.browser.reconnect" => workspace.browser().reconnect(),
371            "glass.browser.state" => workspace.browser().state(),
372            "glass.browser.observe" => workspace.browser().observe(),
373            "glass.browser.snapshot" => workspace.browser().snapshot(),
374            "glass.browser.semantic" => workspace.browser().semantic(match optional_string(call, "level").unwrap_or("structured") {
375                "summary" => SemanticObservationLevel::Summary,
376                "interactive" => SemanticObservationLevel::Interactive,
377                "structured" => SemanticObservationLevel::Structured,
378                "detailed" => SemanticObservationLevel::Detailed,
379                "raw" => SemanticObservationLevel::Raw,
380                _ => return Err(DevelopmentError::InvalidInput("browser semantic level must be summary, interactive, structured, detailed, or raw".into())),
381            }),
382            "glass.browser.diff" => workspace.browser().diff(),
383            "glass.browser.targets" => workspace.browser().targets(),
384            "glass.browser.target.select" => workspace
385                .browser()
386                .select_target(string("targetId")?.into()),
387            "glass.browser.navigate" => workspace.browser().navigate(
388                string("url")?.into(),
389                unsigned(call, "browserRevision", 0)?,
390                timeout(call, 180)?.unwrap_or(Duration::from_secs(30)),
391            ),
392            "glass.browser.act" => {
393                let revision = unsigned(call, "browserRevision", 0)?;
394                match string("action")? {
395                    "back" => workspace.browser().back(revision),
396                    "forward" => workspace.browser().forward(revision),
397                    "reload" => workspace.browser().reload(revision),
398                    "stopLoading" => workspace.browser().stop_loading(revision),
399                    "click" => workspace
400                        .browser()
401                        .click(string("target")?.into(), revision),
402                    "type" => workspace.browser().type_text(
403                        string("text")?.into(),
404                        optional_string(call, "target").map(str::to_string),
405                        revision,
406                    ),
407                    "scroll" => workspace.browser().scroll(
408                        number(call, "dx", 0.0)?,
409                        number(call, "dy", 0.0)?,
410                        revision,
411                    ),
412                    action => Err(DevelopmentError::InvalidInput(format!(
413                        "unsupported browser action {action}; expected back, forward, reload, stopLoading, click, type, or scroll"
414                    ))),
415                }
416            }
417            "glass.browser.screenshot" => workspace.browser().screenshot(),
418            "glass.browser.remote-view.open" => workspace.browser().open_remote_view(),
419            "glass.browser.remote-view.status" => workspace.browser().remote_view_status(),
420            "glass.browser.remote-view.revoke" => workspace.browser().revoke_remote_view(),
421            "glass.workflow.list" => workspace.browser().list_workflows(),
422            "glass.workflow.run" => workspace.browser().run_workflow(
423                required_value(call, "definition")?.clone(),
424                value_map(call, "inputs")?,
425            ),
426            "glass.workflow.pause" => workspace.browser().pause_workflow(),
427            "glass.workflow.resume" => workspace.browser().resume_workflow(
428                required_value(call, "definition")?.clone(),
429                value_map(call, "inputs")?,
430                required_value(call, "checkpoint")?.clone(),
431            ),
432            "glass.workflow.cancel" => workspace.browser().cancel_workflow(),
433            "glass.workflow.verify" => workspace.browser().verify_workflow(),
434            "glass.workflow.record" => {
435                let session: WorkflowRecordingSession = serde_json::from_value(
436                    required_value(call, "session")?.clone(),
437                )?;
438                Ok(serde_json::to_value(record_semantic_events(session).map_err(|error| {
439                    DevelopmentError::InvalidInput(error.to_string())
440                })?)?)
441            }
442            "glass.memory.retrieve" => {
443                if let Some(record_id) = optional_string(call, "recordId") {
444                    Ok(serde_json::to_value(
445                        workspace
446                            .knowledge()
447                            .get(record_id)
448                            .ok_or_else(|| DevelopmentError::NotFound(format!("memory record {record_id}")))?,
449                    )?)
450                } else {
451                    Ok(serde_json::json!({
452                        "records":workspace.knowledge().records(),
453                        "stats":workspace.knowledge().stats().map_err(|error| DevelopmentError::Process(error.to_string()))?
454                    }))
455                }
456            }
457            "glass.memory.explain" => {
458                let record_id = string("recordId")?;
459                let record = workspace
460                    .knowledge()
461                    .get(record_id)
462                    .ok_or_else(|| DevelopmentError::NotFound(format!("memory record {record_id}")))?;
463                Ok(serde_json::json!({
464                    "record":record,
465                    "advisory":true,
466                    "authority":"fresh browser evidence remains authoritative"
467                }))
468            }
469            "glass.memory.forget" => {
470                let record_id = string("recordId")?;
471                let change = workspace
472                    .knowledge_mut()
473                    .remove(record_id)
474                    .map_err(|error| DevelopmentError::Process(error.to_string()))?;
475                Ok(serde_json::to_value(change)?)
476            }
477            "glass.semantic.inspect" => workspace
478                .browser()
479                .semantic(SemanticObservationLevel::Structured),
480            "glass.semantic.diff" => workspace.browser().diff(),
481            "glass.semantic.links" => Ok(serde_json::json!({
482                "nodes":workspace.intelligence().nodes().collect::<Vec<_>>(),
483                "edges":workspace.intelligence().edges().collect::<Vec<_>>()
484            })),
485            "glass.git.status" => git_value(workspace.git(), |git| git.status()),
486            "glass.git.diff" => git_value(workspace.git(), |git| {
487                git.diff(
488                    boolean(call, "staged", false),
489                    optional_string(call, "path"),
490                )
491            }),
492            "glass.git.stage" => {
493                let paths = string_array(call, "paths")?;
494                git_mutation(workspace.git(), |git| git.stage(&paths))?;
495                Ok(serde_json::json!({"staged":paths}))
496            }
497            "glass.git.unstage" => {
498                let paths = string_array(call, "paths")?;
499                git_mutation(workspace.git(), |git| git.unstage(&paths))?;
500                Ok(serde_json::json!({"unstaged":paths}))
501            }
502            "glass.git.discard" => {
503                let paths = string_array(call, "paths")?;
504                git_mutation(workspace.git(), |git| git.discard(&paths))?;
505                Ok(serde_json::json!({"discarded":paths}))
506            }
507            "glass.git.push" => {
508                git_mutation(workspace.git(), |git| {
509                    git.push(optional_string(call, "remote"), optional_string(call, "branch"))
510                })?;
511                Ok(serde_json::json!({"pushed":true}))
512            }
513            "glass.git.commit" => {
514                let message = string("message")?;
515                git_value(workspace.git(), |git| git.commit(message))
516            }
517            "glass.git.branches" => git_value(workspace.git(), |git| git.branches()),
518            "glass.git.branch.create" => {
519                let name = string("name")?;
520                let start_point = optional_string(call, "startPoint");
521                git_mutation(workspace.git(), |git| git.create_branch(name, start_point))?;
522                Ok(serde_json::json!({"created":name}))
523            }
524            "glass.git.branch.switch" => {
525                let name = string("name")?;
526                let create = boolean(call, "create", false);
527                git_mutation(workspace.git(), |git| git.switch_branch(name, create))?;
528                Ok(serde_json::json!({"current":name}))
529            }
530            "glass.git.blame" => {
531                let path = string("path")?;
532                let start = unsigned(call, "startLine", 1)?;
533                let end = unsigned(call, "endLine", 1)?;
534                git_value(workspace.git(), |git| git.blame(path, start, end))
535            }
536            "glass.git.conflicts" => git_value(workspace.git(), |git| git.conflicts()),
537            "glass.git.stash.list" => git_value(workspace.git(), |git| git.stash_list()),
538            "glass.git.stash.push" => {
539                let message = string("message")?;
540                let include_untracked = boolean(call, "includeUntracked", false);
541                git_mutation(workspace.git(), |git| {
542                    git.stash_push(message, include_untracked)
543                })?;
544                Ok(serde_json::json!({"stashed":true}))
545            }
546            "glass.git.stash.pop" => {
547                let reference = string("reference")?;
548                git_mutation(workspace.git(), |git| git.stash_pop(reference))?;
549                Ok(serde_json::json!({"restored":reference}))
550            }
551            "glass.git.worktree.list" => git_value(workspace.git(), |git| git.worktrees()),
552            "glass.git.worktree.create" => {
553                let path = PathBuf::from(string("path")?);
554                let branch = string("branch")?;
555                let create_branch = boolean(call, "createBranch", true);
556                git_mutation(workspace.git(), |git| {
557                    git.create_worktree(&path, branch, create_branch)
558                })?;
559                Ok(serde_json::json!({"path":path,"created":true}))
560            }
561            "glass.git.worktree.remove" => {
562                let path = PathBuf::from(string("path")?);
563                git_mutation(workspace.git(), |git| {
564                    git.remove_worktree(&path, boolean(call, "force", false))
565                })?;
566                Ok(serde_json::json!({"path":path,"removed":true}))
567            }
568            "glass.test.discover" => Ok(serde_json::to_value(
569                workspace.tests().suites().collect::<Vec<_>>(),
570            )?),
571            "glass.test.run" => {
572                let revision = workspace.project().revision();
573                map_service(workspace.tests_mut().start(
574                    string("runId")?,
575                    string("suiteId")?,
576                    &actor,
577                    revision,
578                    timeout(call, 3_600)?,
579                ))
580            }
581            "glass.test.run-affected" => {
582                let paths = string_array(call, "changedPaths")?;
583                let suite_ids = workspace
584                    .tests()
585                    .affected_suites(paths.iter().map(String::as_str))
586                    .into_iter()
587                    .map(|suite| suite.id.clone())
588                    .collect::<Vec<_>>();
589                let revision = workspace.project().revision();
590                let prefix = optional_string(call, "runPrefix").unwrap_or("affected");
591                let mut runs = Vec::new();
592                for (index, suite_id) in suite_ids.into_iter().enumerate() {
593                    runs.push(map_service(workspace.tests_mut().start(
594                        &format!("{prefix}-{index}"),
595                        &suite_id,
596                        &actor,
597                        revision,
598                        timeout(call, 3_600)?,
599                    ))?);
600                }
601                Ok(serde_json::to_value(runs)?)
602            }
603            "glass.test.cancel" => {
604                map_service(workspace.tests_mut().cancel(string("runId")?))?;
605                Ok(serde_json::json!({"cancelled":string("runId")?}))
606            }
607            "glass.test.results" => {
608                let finished = map_service(workspace.tests_mut().poll())?;
609                Ok(serde_json::json!({
610                    "finished":finished,
611                    "running":workspace.tests().running().collect::<Vec<_>>(),
612                    "results":workspace.tests().results().collect::<Vec<_>>()
613                }))
614            }
615            "glass.test.watch" => {
616                let revision = workspace.project().revision();
617                map_service(workspace.tests_mut().watch(string("suiteId")?, revision))?;
618                Ok(serde_json::json!({"watching":string("suiteId")?}))
619            }
620            "glass.eval.start" => {
621                let kind = parse_kernel_kind(string("kind")?)?;
622                let name = string("name")?;
623                let capabilities = string_array_or_empty(call, "capabilities")?;
624                let mutation_authority = boolean(call, "mutationAuthority", false)
625                    && context.authorization.allow_mutation
626                    && context.authorization.confirmed;
627                map_service(workspace.kernels_mut().start_governed(
628                    name,
629                    kind,
630                    &format!("kernel:{name}"),
631                    &capabilities,
632                    mutation_authority,
633                ))?;
634                Ok(serde_json::json!({"started":name,"kind":kind,"capabilities":capabilities,"mutationAuthority":mutation_authority}))
635            }
636            "glass.eval.execute" => {
637                map_service(workspace.execute_kernel(
638                    string("name")?,
639                    string("code")?,
640                    &context.authorization,
641                    timeout(call, 600)?,
642                ))
643            }
644            "glass.eval.list" => Ok(serde_json::to_value(
645                workspace.kernels().snapshots().collect::<Vec<_>>(),
646            )?),
647            "glass.eval.reset" => {
648                map_service(workspace.kernels_mut().reset(string("name")?, &actor))?;
649                Ok(serde_json::json!({"reset":string("name")?}))
650            }
651            "glass.eval.cancel" => map_service(workspace.kernels_mut().cancel(string("name")?)),
652            "glass.eval.stop" => map_service(workspace.kernels_mut().stop(string("name")?)),
653            "glass.lsp.start" => {
654                let server = string("server")?;
655                let configured = workspace.customization().config().lsp.get(server).cloned();
656                let config = match (optional_string(call, "command"), configured) {
657                    (Some(command), _) => crate::lsp::LanguageServerConfig {
658                        command: command.to_string(),
659                        arguments: string_array_or_empty(call, "arguments")?,
660                    },
661                    (None, Some(config)) => crate::lsp::LanguageServerConfig {
662                        command: config.command,
663                        arguments: config.args,
664                    },
665                    (None, None) => return Err(DevelopmentError::InvalidInput(
666                        "lsp start requires command or a matching glass.toml lsp entry".into(),
667                    )),
668                };
669                map_service(workspace.language().start(server, &config))?;
670                Ok(serde_json::json!({"started":server}))
671            }
672            "glass.lsp.stop" => {
673                map_service(workspace.language().stop(string("server")?))?;
674                Ok(serde_json::json!({"stopped":string("server")?}))
675            }
676            "glass.lsp.list" => Ok(serde_json::json!({
677                "servers":workspace.language().names().collect::<Vec<_>>()
678            })),
679            "glass.lsp.events" => Ok(serde_json::to_value(
680                workspace.language().events(unsigned(call, "since", 0)?),
681            )?),
682            "glass.lsp.raw" => map_service(workspace.language().raw_request(
683                string("server")?,
684                &actor,
685                string("method")?,
686                call.arguments
687                    .get("params")
688                    .cloned()
689                    .unwrap_or_else(|| serde_json::json!({})),
690                timeout(call, 60)?.unwrap_or(Duration::from_secs(10)),
691            )),
692            "glass.lsp.diagnostics" => map_service(workspace.language().diagnostics(
693                string("server")?,
694                &actor,
695                string("path")?,
696            )),
697            "glass.lsp.hover" => map_service(workspace.language().hover(
698                string("server")?,
699                &actor,
700                string("path")?,
701                unsigned(call, "line", 1)? as u32,
702                unsigned(call, "character", 1)? as u32,
703            )),
704            "glass.lsp.completion" => map_service(workspace.language().completion(
705                string("server")?,
706                &actor,
707                string("path")?,
708                unsigned(call, "line", 1)? as u32,
709                unsigned(call, "character", 1)? as u32,
710            )),
711            "glass.lsp.definition" => map_service(workspace.language().definition(
712                string("server")?,
713                &actor,
714                string("path")?,
715                u32_value(call, "line")?,
716                u32_value(call, "character")?,
717            )),
718            "glass.lsp.declaration" => map_service(workspace.language().declaration(
719                string("server")?,
720                &actor,
721                string("path")?,
722                u32_value(call, "line")?,
723                u32_value(call, "character")?,
724            )),
725            "glass.lsp.implementation" => map_service(workspace.language().implementation(
726                string("server")?,
727                &actor,
728                string("path")?,
729                u32_value(call, "line")?,
730                u32_value(call, "character")?,
731            )),
732            "glass.lsp.references" => map_service(workspace.language().references(
733                string("server")?,
734                &actor,
735                string("path")?,
736                u32_value(call, "line")?,
737                u32_value(call, "character")?,
738            )),
739            "glass.lsp.document_symbols" => map_service(workspace.language().document_symbols(
740                string("server")?,
741                &actor,
742                string("path")?,
743            )),
744            "glass.lsp.workspace_symbols" => map_service(workspace.language().workspace_symbols(
745                string("server")?,
746                &actor,
747                string("query")?,
748            )),
749            "glass.lsp.signature_help" => map_service(workspace.language().signature_help(
750                string("server")?,
751                &actor,
752                string("path")?,
753                u32_value(call, "line")?,
754                u32_value(call, "character")?,
755            )),
756            "glass.lsp.code_actions" => map_service(workspace.language().code_actions(
757                string("server")?,
758                &actor,
759                string("path")?,
760                position(call, "start")?,
761                position(call, "end")?,
762                value_array_or_empty(call, "diagnostics")?,
763            )),
764            "glass.lsp.formatting" => map_service(workspace.language().formatting(
765                string("server")?,
766                &actor,
767                string("path")?,
768            )),
769            "glass.lsp.range_formatting" => map_service(workspace.language().range_formatting(
770                string("server")?,
771                &actor,
772                string("path")?,
773                position(call, "start")?,
774                position(call, "end")?,
775            )),
776            "glass.lsp.semantic_tokens" => map_service(workspace.language().semantic_tokens(
777                string("server")?,
778                &actor,
779                string("path")?,
780            )),
781            "glass.lsp.rename" => map_service(workspace.language().rename(
782                string("server")?,
783                &actor,
784                string("path")?,
785                u32_value(call, "line")?,
786                u32_value(call, "character")?,
787                string("newName")?,
788            )),
789            "glass.debug.start" => {
790                let session = string("session")?;
791                let configured = workspace.customization().config().dap.get(session).cloned();
792                let (mut config, configured_tcp, configured_connect_timeout_ms) =
793                    match (optional_string(call, "command"), configured) {
794                    (Some(command), _) => (
795                        DebugAdapterConfig::new(
796                            command,
797                            string_array_or_empty(call, "arguments")?,
798                        ),
799                        None,
800                        5_000,
801                    ),
802                    (None, Some(config)) => (
803                        DebugAdapterConfig::new(config.command, config.args),
804                        config.tcp_address,
805                        config.connect_timeout_ms,
806                    ),
807                    (None, None) => return Err(DevelopmentError::InvalidInput(
808                        "debug start requires command or a matching glass.toml dap entry".into(),
809                    )),
810                };
811                if let Some(address) = optional_string(call, "tcpAddress")
812                    .map(str::to_string)
813                    .or(configured_tcp)
814                {
815                    let address = address.parse().map_err(|_| {
816                        DevelopmentError::InvalidInput(
817                            "debug tcpAddress must be a loopback IP socket address".into(),
818                        )
819                    })?;
820                    config = config.with_tcp(
821                        address,
822                        Duration::from_millis(unsigned(
823                            call,
824                            "connectTimeoutMs",
825                            configured_connect_timeout_ms,
826                        )?),
827                    );
828                }
829                map_debug(workspace.start_debugger(
830                    session,
831                    &config,
832                    Duration::from_secs(unsigned(call, "timeoutSeconds", 30)?),
833                ))?;
834                Ok(serde_json::json!({"started":session}))
835            }
836            "glass.debug.launch" => map_debug(
837                debugger(workspace, string("session")?)?.launch(
838                    call.arguments
839                        .get("configuration")
840                        .cloned()
841                        .unwrap_or(Value::Null),
842                ),
843            ),
844            "glass.debug.attach" => map_debug(
845                debugger(workspace, string("session")?)?.attach(
846                    call.arguments
847                        .get("configuration")
848                        .cloned()
849                        .unwrap_or(Value::Null),
850                ),
851            ),
852            "glass.debug.configuration_done" => {
853                map_debug(debugger(workspace, string("session")?)?.configuration_done())
854            }
855            "glass.debug.restart" => map_debug(
856                debugger(workspace, string("session")?)?.restart(
857                    call.arguments
858                        .get("configuration")
859                        .cloned()
860                        .unwrap_or_else(|| serde_json::json!({})),
861                ),
862            ),
863            "glass.debug.breakpoint.set" => {
864                let lines = unsigned_array(call, "lines")?;
865                let breakpoints = lines
866                    .iter()
867                    .copied()
868                    .map(SourceBreakpoint::line)
869                    .collect::<Vec<_>>();
870                map_debug(
871                    debugger(workspace, string("session")?)?
872                        .set_source_breakpoints(&PathBuf::from(string("path")?), &breakpoints),
873                )
874            }
875            "glass.debug.breakpoint.remove" => map_debug(
876                debugger(workspace, string("session")?)?
877                    .set_source_breakpoints(&PathBuf::from(string("path")?), &[]),
878            ),
879            "glass.debug.exception.set" => map_debug(
880                debugger(workspace, string("session")?)?
881                    .set_exception_breakpoints(&string_array_or_empty(call, "filters")?),
882            ),
883            "glass.debug.continue" => map_debug(
884                debugger(workspace, string("session")?)?
885                    .continue_thread(integer(call, "threadId")?),
886            ),
887            "glass.debug.pause" => map_debug(
888                debugger(workspace, string("session")?)?.pause(integer(call, "threadId")?),
889            ),
890            "glass.debug.step" => {
891                let debugger = debugger(workspace, string("session")?)?;
892                let thread = integer(call, "threadId")?;
893                match string("kind")? {
894                    "over" => map_debug(debugger.next(thread)),
895                    "in" => map_debug(debugger.step_in(thread)),
896                    "out" => map_debug(debugger.step_out(thread)),
897                    _ => Err(DevelopmentError::InvalidInput(
898                        "debug step kind must be over, in, or out".into(),
899                    )),
900                }
901            }
902            "glass.debug.threads" => map_debug(debugger(workspace, string("session")?)?.threads()),
903            "glass.debug.stack" => map_debug(
904                debugger(workspace, string("session")?)?.stack_trace(integer(call, "threadId")?),
905            ),
906            "glass.debug.scopes" => map_debug(
907                debugger(workspace, string("session")?)?.scopes(integer(call, "frameId")?),
908            ),
909            "glass.debug.variables" => map_debug(
910                debugger(workspace, string("session")?)?
911                    .variables(integer(call, "variablesReference")?),
912            ),
913            "glass.debug.evaluate" => map_debug(debugger(workspace, string("session")?)?.evaluate(
914                string("expression")?,
915                call.arguments.get("frameId").and_then(Value::as_i64),
916                optional_string(call, "context").unwrap_or("repl"),
917            )),
918            "glass.debug.events" => {
919                map_debug(debugger(workspace, string("session")?)?.poll_events())
920            }
921            "glass.debug.inspect" => {
922                map_debug(debugger(workspace, string("session")?)?.snapshot())
923            }
924            "glass.debug.processes" => map_debug(
925                debugger(workspace, string("session")?)?.debuggee_processes(),
926            ),
927            "glass.debug.disconnect" => map_debug(
928                debugger(workspace, string("session")?)?
929                    .disconnect(boolean(call, "terminateDebuggee", false)),
930            ),
931            "glass.debug.terminate" => map_debug(
932                debugger(workspace, string("session")?)?
933                    .terminate(boolean(call, "restart", false)),
934            ),
935            "glass.debug.stop" => {
936                map_debug(workspace.stop_debugger(string("session")?))?;
937                Ok(serde_json::json!({"stopped":string("session")?}))
938            }
939            "glass.agent.list" => map_service(workspace.agents().list()),
940            "glass.agent.setup" => map_service(crate::pi_runtime::setup_pi_runtime(
941                None,
942                None,
943                boolean(call, "update", false),
944                boolean(call, "login", false),
945            )),
946            "glass.agent.spawn" => {
947                let spec: AgentSpec =
948                    serde_json::from_value(call.arguments.get("spec").cloned().ok_or_else(
949                        || DevelopmentError::InvalidInput("agent spawn requires spec".into()),
950                    )?)?;
951                map_service(workspace.agents().create(spec))
952            }
953            "glass.agent.prompt" => {
954                let id = agent_id(workspace, string("agentId")?)?;
955                let text = string("text")?;
956                map_service(workspace.agents().prompt_with_context(
957                    &id,
958                    text,
959                    call.arguments.get("context").cloned(),
960                ))?;
961                Ok(serde_json::json!({"queued":true}))
962            }
963            "glass.agent.send" => {
964                let text = string("text")?;
965                let context = call.arguments.get("context").cloned();
966                let mode = optional_string(call, "mode").unwrap_or("follow-up");
967                let selected = optional_string(call, "agentId")
968                    .map(|value| agent_id(workspace, value))
969                    .transpose()?;
970                let agent = selected.or_else(|| {
971                    workspace
972                        .agents()
973                        .list()
974                        .ok()?
975                        .into_iter()
976                        .find(|item| {
977                            !matches!(
978                                item.status,
979                                crate::AgentStatus::Completed
980                                    | crate::AgentStatus::Failed
981                                    | crate::AgentStatus::Cancelled
982                            )
983                        })
984                        .map(|item| item.id)
985                });
986                let agent = match agent {
987                    Some(agent) => agent,
988                    None => {
989                        let readiness = crate::pi_runtime::pi_readiness()?;
990                        if !readiness.ready {
991                            return Err(DevelopmentError::Conflict(
992                                "Pi is not ready; use Agent [s] to install the runtime and [l] to sign in"
993                                    .into(),
994                            ));
995                        }
996                        let id = workspace
997                            .agents()
998                            .create(AgentSpec::new(
999                                "assistant",
1000                                "interactive Glass Agent session",
1001                            ))?;
1002                        map_service(workspace.agents().prompt_with_context(&id, text, context))?;
1003                        return Ok(serde_json::json!({"queued":true,"agentId":id}));
1004                    }
1005                };
1006                let mut status = workspace.agents().snapshot(&agent)?.status;
1007                let restarted = matches!(
1008                    status,
1009                    crate::AgentStatus::Failed | crate::AgentStatus::Cancelled
1010                );
1011                if restarted {
1012                    workspace.agents().restart(&agent)?;
1013                    status = workspace.agents().snapshot(&agent)?.status;
1014                }
1015                if mode == "steer" && status == crate::AgentStatus::Working {
1016                    map_service(workspace.agents().steer_with_context(&agent, text, context.clone()))?;
1017                } else if mode == "follow-up" && status == crate::AgentStatus::Working {
1018                    map_service(workspace.agents().follow_up_with_context(&agent, text, context.clone()))?;
1019                } else {
1020                    map_service(workspace.agents().prompt_with_context(&agent, text, context))?;
1021                }
1022                let mut response = serde_json::json!({"queued":true,"agentId":agent});
1023                if restarted {
1024                    response["restarted"] = Value::Bool(true);
1025                }
1026                Ok(response)
1027            }
1028            "glass.agent.steer" => {
1029                let id = agent_id(workspace, string("agentId")?)?;
1030                let text = string("text")?;
1031                map_service(workspace.agents().steer_with_context(
1032                    &id,
1033                    text,
1034                    call.arguments.get("context").cloned(),
1035                ))?;
1036                Ok(serde_json::json!({"queued":true}))
1037            }
1038            "glass.agent.follow-up" => {
1039                let id = agent_id(workspace, string("agentId")?)?;
1040                let text = string("text")?;
1041                map_service(workspace.agents().follow_up_with_context(
1042                    &id,
1043                    text,
1044                    call.arguments.get("context").cloned(),
1045                ))?;
1046                Ok(serde_json::json!({"queued":true}))
1047            }
1048            "glass.agent.approve" => {
1049                let id = agent_id(workspace, string("agentId")?)?;
1050                map_service(workspace.agents().approve_tool(
1051                    &id,
1052                    string("frameId")?,
1053                    boolean(call, "approved", false),
1054                ))?;
1055                Ok(serde_json::json!({"queued":true}))
1056            }
1057            "glass.agent.abort" => {
1058                let id = agent_id(workspace, string("agentId")?)?;
1059                map_service(workspace.agents().cancel(&id))?;
1060                Ok(serde_json::json!({"cancelled":true}))
1061            }
1062            "glass.agent.compact" => {
1063                let id = agent_id(workspace, string("agentId")?)?;
1064                map_service(workspace.agents().request(
1065                    &id,
1066                    PiSessionRequest::Compact {
1067                        instructions: optional_string(call, "instructions").map(str::to_string),
1068                    },
1069                ))?;
1070                Ok(serde_json::json!({"queued":true}))
1071            }
1072            "glass.agent.model" => {
1073                let id = agent_id(workspace, string("agentId")?)?;
1074                map_service(workspace.agents().request(
1075                    &id,
1076                    PiSessionRequest::SetModel {
1077                        provider: string("provider")?.into(),
1078                        model_id: string("modelId")?.into(),
1079                    },
1080                ))?;
1081                Ok(serde_json::json!({"queued":true}))
1082            }
1083            "glass.agent.thinking" => {
1084                let id = agent_id(workspace, string("agentId")?)?;
1085                map_service(workspace.agents().request(
1086                    &id,
1087                    PiSessionRequest::SetThinking {
1088                        level: string("level")?.into(),
1089                    },
1090                ))?;
1091                Ok(serde_json::json!({"queued":true}))
1092            }
1093            "glass.agent.new-session" => {
1094                agent_request(workspace, call, PiSessionRequest::NewSession)
1095            }
1096            "glass.agent.clone-session" => {
1097                agent_request(workspace, call, PiSessionRequest::CloneSession)
1098            }
1099            "glass.agent.fork" => agent_request(
1100                workspace,
1101                call,
1102                PiSessionRequest::Fork {
1103                    entry_id: string("entryId")?.into(),
1104                },
1105            ),
1106            "glass.agent.switch-session" => agent_request(
1107                workspace,
1108                call,
1109                PiSessionRequest::SwitchSession {
1110                    path: string("path")?.into(),
1111                },
1112            ),
1113            "glass.agent.messages" => agent_request(workspace, call, PiSessionRequest::Messages),
1114            "glass.agent.entries" => agent_request(
1115                workspace,
1116                call,
1117                PiSessionRequest::Entries {
1118                    since: optional_string(call, "since").map(str::to_string),
1119                },
1120            ),
1121            "glass.agent.stats" => agent_request(workspace, call, PiSessionRequest::SessionStats),
1122            "glass.agent.name" => agent_request(
1123                workspace,
1124                call,
1125                PiSessionRequest::SetSessionName {
1126                    name: string("name")?.into(),
1127                },
1128            ),
1129            "glass.task.create" => {
1130                let spec = serde_json::from_value::<TaskSpec>(call.arguments.clone())?;
1131                Ok(serde_json::to_value(workspace.create_task(spec)?)?)
1132            }
1133            "glass.task.list" => Ok(serde_json::to_value(workspace.tasks()?)?),
1134            "glass.task.get" | "glass.task.inspect" => {
1135                let id = TaskId::parse(string("taskId")?)?;
1136                Ok(serde_json::to_value(workspace.task(&id)?)?)
1137            }
1138            "glass.task.pause" => task_action(workspace, call, |workspace, id| {
1139                workspace.pause_task(id)
1140            }),
1141            "glass.task.resume" => task_action(workspace, call, |workspace, id| {
1142                workspace.resume_task(id)
1143            }),
1144            "glass.task.cancel" => task_action(workspace, call, |workspace, id| {
1145                workspace.cancel_task(id)
1146            }),
1147            "glass.task.retry" => task_action(workspace, call, |workspace, id| {
1148                workspace.retry_task(id)
1149            }),
1150            "glass.task.override-blocked" => task_action(workspace, call, |workspace, id| {
1151                workspace.override_blocked_task(id)
1152            }),
1153            "glass.task.reassign" => {
1154                let id = TaskId::parse(string("taskId")?)?;
1155                workspace.reassign_task(
1156                    &id,
1157                    string("role")?.into(),
1158                    optional_string(call, "model").map(str::to_string),
1159                    optional_string(call, "thinking").map(str::to_string),
1160                )?;
1161                Ok(serde_json::json!({"reassigned":true}))
1162            }
1163            "glass.task.evidence" | "glass.task.verify" => {
1164                let id = TaskId::parse(string("taskId")?)?;
1165                workspace.submit_task_evidence(
1166                    &id,
1167                    string("kind")?.into(),
1168                    context.authorization.actor.id.clone(),
1169                    boolean(call, "passed", false),
1170                    call.arguments
1171                        .get("details")
1172                        .cloned()
1173                        .unwrap_or(Value::Null),
1174                )?;
1175                Ok(serde_json::json!({"recorded":true}))
1176            }
1177            "glass.experiment.create" => {
1178                let port = call
1179                    .arguments
1180                    .get("port")
1181                    .and_then(Value::as_u64)
1182                    .map(u16::try_from)
1183                    .transpose()
1184                    .map_err(|_| DevelopmentError::InvalidInput("invalid experiment port".into()))?;
1185                Ok(serde_json::to_value(workspace.experiments()?.create(
1186                    string("id")?,
1187                    string("branch")?,
1188                    port,
1189                )?)?)
1190            }
1191            "glass.experiment.collect" => Ok(serde_json::to_value(
1192                workspace
1193                    .experiments()?
1194                    .collect_automatic(string("id")?)?,
1195            )?),
1196            "glass.experiment.list" => Ok(serde_json::to_value(
1197                workspace.experiments()?.snapshots(),
1198            )?),
1199            "glass.experiment.compare" => Ok(serde_json::to_value(
1200                workspace.experiments()?.compare(),
1201            )?),
1202            "glass.experiment.select" => Ok(serde_json::to_value(
1203                workspace.experiments()?.select(string("id")?)?,
1204            )?),
1205            "glass.experiment.remove" => {
1206                workspace
1207                    .experiments()?
1208                    .remove(string("id")?, boolean(call, "force", false))?;
1209                Ok(serde_json::json!({"removed":true}))
1210            }
1211            "glass.graph.query" => Ok(serde_json::to_value(
1212                workspace.intelligence().node(string("id")?),
1213            )?),
1214            "glass.graph.source" => {
1215                let line = call
1216                    .arguments
1217                    .get("line")
1218                    .and_then(Value::as_u64)
1219                    .map(u32::try_from)
1220                    .transpose()
1221                    .map_err(|_| DevelopmentError::InvalidInput("invalid graph line".into()))?;
1222                Ok(serde_json::to_value(
1223                    workspace
1224                        .project()
1225                        .graph()
1226                        .entities_for_source(string("path")?, line),
1227                )?)
1228            }
1229            "glass.graph.path" | "glass.graph.explain" => Ok(serde_json::to_value(
1230                workspace
1231                    .intelligence()
1232                    .path(string("from")?, string("to")?)?,
1233            )?),
1234            "glass.graph.link" => {
1235                let revision = workspace.project().revision();
1236                let edge = workspace.intelligence_mut().link(
1237                    string("from")?,
1238                    string("to")?,
1239                    string("relation")?,
1240                    revision,
1241                    &actor,
1242                    call.arguments
1243                        .get("evidence")
1244                        .cloned()
1245                        .unwrap_or(Value::Null),
1246                )?;
1247                workspace.intelligence_mut().record(ObservableEventInput {
1248                    actor: &actor,
1249                    subsystem: "graph",
1250                    kind: "linked",
1251                    resource: None,
1252                    workspace_revision: revision,
1253                    evidence: serde_json::json!({"edgeId":edge,"from":string("from")?,"to":string("to")?,"relation":string("relation")?}),
1254                    rationale: None,
1255                })?;
1256                Ok(serde_json::json!({"edgeId":edge}))
1257            }
1258            "glass.replay.list" | "glass.replay.inspect" => {
1259                Ok(serde_json::to_value(workspace.intelligence().replay(
1260                    unsigned(call, "since", 0)?,
1261                    usize::try_from(unsigned(call, "limit", 128)?).unwrap_or(4096),
1262                )?)?)
1263            }
1264            "glass.replay.diff" => Ok(serde_json::to_value(
1265                workspace
1266                    .intelligence()
1267                    .replay_diff(unsigned(call, "from", 0)?, unsigned(call, "to", 1)?)?,
1268            )?),
1269            "glass.workspace.list" => {
1270                let store = WorkspaceStore::open_default()
1271                    .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1272                Ok(serde_json::to_value(store.list().map_err(|error| {
1273                    DevelopmentError::Process(error.to_string())
1274                })?)?)
1275            }
1276            "glass.workspace.inspect" => {
1277                let id = WorkspaceId::new(string("id")?)
1278                    .map_err(|error| DevelopmentError::InvalidInput(error.to_string()))?;
1279                let store = WorkspaceStore::open_default()
1280                    .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1281                Ok(serde_json::to_value(
1282                    store
1283                        .open(&id)
1284                        .map_err(|error| DevelopmentError::Process(error.to_string()))?,
1285                )?)
1286            }
1287            "glass.workspace.suspend" | "glass.workspace.resume" => {
1288                let id = WorkspaceId::new(string("id")?)
1289                    .map_err(|error| DevelopmentError::InvalidInput(error.to_string()))?;
1290                let store = WorkspaceStore::open_default()
1291                    .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1292                let workspace = if call.name.ends_with("suspend") {
1293                    store.suspend(&id)
1294                } else {
1295                    store.resume(&id)
1296                }
1297                .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1298                Ok(serde_json::to_value(workspace)?)
1299            }
1300            "glass.workspace.delete" => {
1301                let id = WorkspaceId::new(string("id")?)
1302                    .map_err(|error| DevelopmentError::InvalidInput(error.to_string()))?;
1303                let store = WorkspaceStore::open_default()
1304                    .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1305                store
1306                    .delete(&id)
1307                    .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1308                Ok(serde_json::json!({"id":id,"deleted":true}))
1309            }
1310            "glass.daemon.start" => {
1311                let runtime = tokio::runtime::Builder::new_current_thread()
1312                    .enable_all()
1313                    .build()
1314                    .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1315                map_service(runtime.block_on(crate::daemon::start(None, None)))
1316            }
1317            "glass.daemon.status" | "glass.daemon.doctor" => map_service(
1318                crate::daemon::read_status_checked(None, None)
1319                    .map_err(|error| DevelopmentError::Process(error.to_string())),
1320            ),
1321            "glass.daemon.stop" => map_service(
1322                crate::daemon::stop(None, None)
1323                    .map(|_| serde_json::json!({"status":"stopped"}))
1324                    .map_err(|error| DevelopmentError::Process(error.to_string())),
1325            ),
1326            "glass.daemon.logs" => map_service(
1327                crate::daemon::log_tail(None)
1328                    .map_err(|error| DevelopmentError::Process(error.to_string())),
1329            ),
1330            "glass.agent.hello" | "glass.agent.models" => {
1331                let id = optional_string(call, "agentId")
1332                    .map(|value| agent_id(workspace, value))
1333                    .transpose()?
1334                    .or_else(|| active_agent_id(workspace))
1335                    .ok_or_else(|| {
1336                        DevelopmentError::Conflict(
1337                            "start an interactive agent session before requesting Pi state"
1338                                .into(),
1339                        )
1340                    })?;
1341                let request = if call.name.ends_with("hello") {
1342                    PiSessionRequest::Hello
1343                } else {
1344                    PiSessionRequest::Models
1345                };
1346                map_service(workspace.agents().request(&id, request))?;
1347                Ok(serde_json::json!({"queued":true,"agentId":id.as_str()}))
1348            }
1349            "glass.project.attach" => {
1350                let actor = crate::development::Actor::external(string("actor")?);
1351                workspace.project_mut().attach_actor(actor.clone())?;
1352                Ok(serde_json::to_value(actor)?)
1353            }
1354            "glass.workspace.trust.status" => Ok(serde_json::json!({
1355                "trust":workspace.trust(),
1356                "identity":workspace.trust_identity(),
1357                "store":workspace.trust_store_path(),
1358                "localDecisionRequired":true
1359            })),
1360            "glass.workspace.trust.inspect" => Ok(serde_json::json!({
1361                "trust":workspace.trust(),
1362                "items":workspace.trust_inspection(),
1363                "localDecisionRequired":true
1364            })),
1365            _ => Err(DevelopmentError::NotFound(format!("tool {}", call.name))),
1366        }
1367    }
1368}
1369
1370fn service_descriptors() -> Vec<ToolDescriptor> {
1371    const READ: &[&str] = &[
1372        "glass.process.list",
1373        "glass.process.logs",
1374        "glass.git.status",
1375        "glass.git.diff",
1376        "glass.git.branches",
1377        "glass.git.blame",
1378        "glass.git.conflicts",
1379        "glass.git.stash.list",
1380        "glass.git.worktree.list",
1381        "glass.test.discover",
1382        "glass.test.results",
1383        "glass.eval.list",
1384        "glass.lsp.diagnostics",
1385        "glass.workspace.list",
1386        "glass.workspace.inspect",
1387        "glass.daemon.status",
1388        "glass.daemon.doctor",
1389        "glass.daemon.logs",
1390        "glass.agent.hello",
1391        "glass.agent.models",
1392        "glass.workspace.trust.status",
1393        "glass.workspace.trust.inspect",
1394        "glass.lsp.list",
1395        "glass.lsp.events",
1396        "glass.lsp.raw",
1397        "glass.lsp.hover",
1398        "glass.lsp.completion",
1399        "glass.lsp.definition",
1400        "glass.lsp.declaration",
1401        "glass.lsp.implementation",
1402        "glass.lsp.references",
1403        "glass.lsp.document_symbols",
1404        "glass.lsp.workspace_symbols",
1405        "glass.lsp.signature_help",
1406        "glass.lsp.code_actions",
1407        "glass.lsp.formatting",
1408        "glass.lsp.range_formatting",
1409        "glass.lsp.semantic_tokens",
1410        "glass.lsp.rename",
1411        "glass.debug.stack",
1412        "glass.debug.threads",
1413        "glass.debug.scopes",
1414        "glass.debug.variables",
1415        "glass.debug.evaluate",
1416        "glass.debug.events",
1417        "glass.debug.inspect",
1418        "glass.debug.processes",
1419        "glass.graph.source",
1420        "glass.agent.list",
1421        "glass.agent.messages",
1422        "glass.agent.entries",
1423        "glass.agent.stats",
1424        "glass.task.list",
1425        "glass.task.get",
1426        "glass.task.inspect",
1427        "glass.experiment.list",
1428        "glass.experiment.compare",
1429        "glass.graph.query",
1430        "glass.graph.path",
1431        "glass.graph.explain",
1432        "glass.replay.list",
1433        "glass.replay.inspect",
1434        "glass.replay.diff",
1435        "glass.editor.selection",
1436        "glass.editor.diff",
1437        "glass.editor.buffers",
1438        "glass.process.health",
1439        "glass.process.ports",
1440        "glass.browser.state",
1441        "glass.browser.observe",
1442        "glass.browser.snapshot",
1443        "glass.browser.semantic",
1444        "glass.browser.diff",
1445        "glass.browser.targets",
1446        "glass.browser.screenshot",
1447        "glass.browser.remote-view.status",
1448        "glass.workflow.list",
1449        "glass.workflow.verify",
1450        "glass.workflow.record",
1451        "glass.memory.retrieve",
1452        "glass.memory.explain",
1453        "glass.semantic.inspect",
1454        "glass.semantic.diff",
1455        "glass.semantic.links",
1456    ];
1457    const MUTATE: &[&str] = &[
1458        "glass.workspace.suspend",
1459        "glass.workspace.resume",
1460        "glass.workspace.delete",
1461        "glass.daemon.start",
1462        "glass.daemon.stop",
1463        "glass.project.attach",
1464        "glass.git.stage",
1465        "glass.git.unstage",
1466        "glass.git.discard",
1467        "glass.git.push",
1468        "glass.git.commit",
1469        "glass.git.branch.create",
1470        "glass.git.branch.switch",
1471        "glass.git.stash.push",
1472        "glass.git.stash.pop",
1473        "glass.git.worktree.create",
1474        "glass.git.worktree.remove",
1475        "glass.graph.link",
1476        "glass.test.run",
1477        "glass.test.run-affected",
1478        "glass.test.cancel",
1479        "glass.test.watch",
1480        "glass.eval.start",
1481        "glass.eval.execute",
1482        "glass.eval.cancel",
1483        "glass.eval.reset",
1484        "glass.eval.stop",
1485        "glass.debug.start",
1486        "glass.lsp.start",
1487        "glass.lsp.stop",
1488        "glass.debug.launch",
1489        "glass.debug.attach",
1490        "glass.debug.configuration_done",
1491        "glass.debug.restart",
1492        "glass.debug.breakpoint.set",
1493        "glass.debug.breakpoint.remove",
1494        "glass.debug.exception.set",
1495        "glass.debug.continue",
1496        "glass.debug.pause",
1497        "glass.debug.step",
1498        "glass.debug.disconnect",
1499        "glass.debug.terminate",
1500        "glass.debug.stop",
1501        "glass.agent.spawn",
1502        "glass.agent.setup",
1503        "glass.agent.prompt",
1504        "glass.agent.send",
1505        "glass.agent.steer",
1506        "glass.agent.follow-up",
1507        "glass.agent.approve",
1508        "glass.agent.abort",
1509        "glass.agent.compact",
1510        "glass.agent.model",
1511        "glass.agent.thinking",
1512        "glass.agent.new-session",
1513        "glass.agent.clone-session",
1514        "glass.agent.fork",
1515        "glass.agent.switch-session",
1516        "glass.agent.name",
1517        "glass.task.create",
1518        "glass.task.pause",
1519        "glass.task.resume",
1520        "glass.task.cancel",
1521        "glass.task.retry",
1522        "glass.task.reassign",
1523        "glass.task.override-blocked",
1524        "glass.task.evidence",
1525        "glass.task.verify",
1526        "glass.experiment.create",
1527        "glass.experiment.collect",
1528        "glass.experiment.select",
1529        "glass.experiment.remove",
1530        "glass.editor.open",
1531        "glass.editor.replace",
1532        "glass.editor.save",
1533        "glass.process.start",
1534        "glass.process.stop",
1535        "glass.process.restart",
1536        "glass.process.input",
1537        "glass.process.resize",
1538        "glass.browser.start",
1539        "glass.browser.attach",
1540        "glass.browser.reconnect",
1541        "glass.browser.stop",
1542        "glass.browser.target.select",
1543        "glass.browser.navigate",
1544        "glass.browser.act",
1545        "glass.browser.remote-view.open",
1546        "glass.browser.remote-view.revoke",
1547        "glass.workflow.run",
1548        "glass.workflow.pause",
1549        "glass.workflow.resume",
1550        "glass.workflow.cancel",
1551        "glass.memory.forget",
1552    ];
1553    READ.iter()
1554        .map(|name| service_descriptor(name, false))
1555        .chain(MUTATE.iter().map(|name| service_descriptor(name, true)))
1556        .collect()
1557}
1558
1559pub(crate) fn tool_requires_mutation(name: &str) -> bool {
1560    static MUTATING: std::sync::LazyLock<Vec<String>> = std::sync::LazyLock::new(|| {
1561        service_descriptors()
1562            .into_iter()
1563            .filter(|descriptor| descriptor.mutating)
1564            .map(|descriptor| descriptor.name)
1565            .collect()
1566    });
1567    MUTATING.iter().any(|candidate| candidate == name)
1568}
1569
1570fn untrusted_tool_allowed(name: &str) -> bool {
1571    matches!(
1572        name,
1573        "glass.file.read"
1574            | "glass.file.list"
1575            | "glass.file.search"
1576            | "glass.file.grep"
1577            | "glass.file.find"
1578            | "glass.git.status"
1579            | "glass.git.diff"
1580            | "glass.git.branches"
1581            | "glass.git.blame"
1582            | "glass.git.conflicts"
1583            | "glass.git.stash.list"
1584            | "glass.git.worktree.list"
1585            | "glass.browser.start"
1586            | "glass.browser.attach"
1587            | "glass.browser.reconnect"
1588            | "glass.browser.stop"
1589            | "glass.browser.state"
1590            | "glass.browser.observe"
1591            | "glass.browser.snapshot"
1592            | "glass.browser.semantic"
1593            | "glass.browser.diff"
1594            | "glass.browser.targets"
1595            | "glass.browser.target.select"
1596            | "glass.browser.navigate"
1597            | "glass.browser.act"
1598            | "glass.browser.screenshot"
1599            | "glass.browser.remote-view.open"
1600            | "glass.browser.remote-view.status"
1601            | "glass.browser.remote-view.revoke"
1602            | "glass.agent.setup"
1603            | "glass.graph.source"
1604            | "glass.agent.hello"
1605            | "glass.agent.models"
1606            | "glass.workspace.list"
1607            | "glass.workspace.inspect"
1608            | "glass.daemon.status"
1609            | "glass.daemon.doctor"
1610            | "glass.daemon.logs"
1611            | "glass.neovim.probe"
1612            | "glass.memory.retrieve"
1613            | "glass.memory.explain"
1614            | "glass.semantic.inspect"
1615            | "glass.semantic.diff"
1616            | "glass.semantic.links"
1617            | "glass.graph.query"
1618            | "glass.graph.path"
1619            | "glass.graph.explain"
1620            | "glass.replay.list"
1621            | "glass.replay.inspect"
1622            | "glass.replay.diff"
1623            | "glass.editor.open"
1624            | "glass.editor.selection"
1625            | "glass.editor.diff"
1626            | "glass.editor.buffers"
1627            | "glass.process.logs"
1628            | "glass.process.list"
1629            | "glass.process.health"
1630            | "glass.process.ports"
1631            | "glass.workspace.trust.status"
1632            | "glass.workspace.trust.inspect"
1633            | "glass.task.list"
1634            | "glass.task.get"
1635            | "glass.task.inspect"
1636    )
1637}
1638
1639fn service_descriptor(name: &str, mutating: bool) -> ToolDescriptor {
1640    ToolDescriptor {
1641        name: name.into(),
1642        description: format!("Resident Glass Dev operation {name}"),
1643        input_schema: serde_json::json!({"type":"object"}),
1644        mutating,
1645        available: true,
1646        unavailable_reason: None,
1647    }
1648}
1649
1650fn required_string<'a>(call: &'a ToolCall, name: &str) -> DevelopmentResult<&'a str> {
1651    call.arguments
1652        .get(name)
1653        .and_then(Value::as_str)
1654        .filter(|value| !value.is_empty() && value.len() <= 64 * 1024 && !value.contains('\0'))
1655        .ok_or_else(|| {
1656            DevelopmentError::InvalidInput(format!("{} requires bounded string {name}", call.name))
1657        })
1658}
1659
1660fn optional_string<'a>(call: &'a ToolCall, name: &str) -> Option<&'a str> {
1661    call.arguments.get(name).and_then(Value::as_str)
1662}
1663
1664fn required_value<'a>(call: &'a ToolCall, name: &str) -> DevelopmentResult<&'a Value> {
1665    call.arguments
1666        .get(name)
1667        .ok_or_else(|| DevelopmentError::InvalidInput(format!("{} requires {name}", call.name)))
1668}
1669
1670fn value_map(
1671    call: &ToolCall,
1672    name: &str,
1673) -> DevelopmentResult<std::collections::BTreeMap<String, Value>> {
1674    match call.arguments.get(name) {
1675        None => Ok(std::collections::BTreeMap::new()),
1676        Some(value) => serde_json::from_value(value.clone()).map_err(DevelopmentError::from),
1677    }
1678}
1679
1680fn boolean(call: &ToolCall, name: &str, default: bool) -> bool {
1681    call.arguments
1682        .get(name)
1683        .and_then(Value::as_bool)
1684        .unwrap_or(default)
1685}
1686
1687fn unsigned(call: &ToolCall, name: &str, default: u64) -> DevelopmentResult<u64> {
1688    let value = call
1689        .arguments
1690        .get(name)
1691        .and_then(Value::as_u64)
1692        .unwrap_or(default);
1693    (value <= i64::MAX as u64).then_some(value).ok_or_else(|| {
1694        DevelopmentError::InvalidInput(format!("{}.{} is out of range", call.name, name))
1695    })
1696}
1697
1698fn integer(call: &ToolCall, name: &str) -> DevelopmentResult<i64> {
1699    call.arguments
1700        .get(name)
1701        .and_then(Value::as_i64)
1702        .ok_or_else(|| DevelopmentError::InvalidInput(format!("{} requires {name}", call.name)))
1703}
1704
1705fn u32_value(call: &ToolCall, name: &str) -> DevelopmentResult<u32> {
1706    u32::try_from(unsigned(call, name, 0)?).map_err(|_| {
1707        DevelopmentError::InvalidInput(format!("{}.{} is out of range", call.name, name))
1708    })
1709}
1710
1711fn u16_value(call: &ToolCall, name: &str) -> DevelopmentResult<u16> {
1712    let value = u16::try_from(unsigned(call, name, 0)?).map_err(|_| {
1713        DevelopmentError::InvalidInput(format!("{}.{} is out of range", call.name, name))
1714    })?;
1715    (value > 0).then_some(value).ok_or_else(|| {
1716        DevelopmentError::InvalidInput(format!("{}.{} must be non-zero", call.name, name))
1717    })
1718}
1719
1720fn position(
1721    call: &ToolCall,
1722    name: &str,
1723) -> DevelopmentResult<crate::development::DiagnosticPosition> {
1724    serde_json::from_value(required_value(call, name)?.clone()).map_err(DevelopmentError::from)
1725}
1726
1727fn value_array_or_empty(call: &ToolCall, name: &str) -> DevelopmentResult<Vec<Value>> {
1728    match call.arguments.get(name) {
1729        None => Ok(Vec::new()),
1730        Some(Value::Array(values)) if values.len() <= 512 => Ok(values.clone()),
1731        Some(_) => Err(DevelopmentError::InvalidInput(format!(
1732            "{}.{} must be an array of at most 512 values",
1733            call.name, name
1734        ))),
1735    }
1736}
1737
1738fn number(call: &ToolCall, name: &str, default: f64) -> DevelopmentResult<f64> {
1739    let value = call
1740        .arguments
1741        .get(name)
1742        .and_then(Value::as_f64)
1743        .unwrap_or(default);
1744    value.is_finite().then_some(value).ok_or_else(|| {
1745        DevelopmentError::InvalidInput(format!("{}.{} must be finite", call.name, name))
1746    })
1747}
1748
1749fn string_array(call: &ToolCall, name: &str) -> DevelopmentResult<Vec<String>> {
1750    let values = call
1751        .arguments
1752        .get(name)
1753        .and_then(Value::as_array)
1754        .filter(|values| !values.is_empty() && values.len() <= 256)
1755        .ok_or_else(|| DevelopmentError::InvalidInput(format!("{} requires {name}", call.name)))?;
1756    values
1757        .iter()
1758        .map(|value| {
1759            value
1760                .as_str()
1761                .filter(|value| !value.is_empty() && value.len() <= 4096 && !value.contains('\0'))
1762                .map(str::to_string)
1763                .ok_or_else(|| DevelopmentError::InvalidInput(format!("invalid {name} item")))
1764        })
1765        .collect()
1766}
1767
1768fn string_array_or_empty(call: &ToolCall, name: &str) -> DevelopmentResult<Vec<String>> {
1769    if call.arguments.get(name).is_none() {
1770        Ok(Vec::new())
1771    } else {
1772        string_array(call, name)
1773    }
1774}
1775
1776fn unsigned_array(call: &ToolCall, name: &str) -> DevelopmentResult<Vec<u64>> {
1777    call.arguments
1778        .get(name)
1779        .and_then(Value::as_array)
1780        .filter(|values| !values.is_empty() && values.len() <= 512)
1781        .ok_or_else(|| DevelopmentError::InvalidInput(format!("{} requires {name}", call.name)))?
1782        .iter()
1783        .map(|value| {
1784            value
1785                .as_u64()
1786                .filter(|value| *value > 0)
1787                .ok_or_else(|| DevelopmentError::InvalidInput(format!("invalid {name} item")))
1788        })
1789        .collect()
1790}
1791
1792fn timeout(call: &ToolCall, maximum_seconds: u64) -> DevelopmentResult<Option<Duration>> {
1793    call.arguments
1794        .get("timeoutSeconds")
1795        .map(|_| unsigned(call, "timeoutSeconds", maximum_seconds))
1796        .transpose()?
1797        .map(|seconds| {
1798            if seconds == 0 || seconds > maximum_seconds {
1799                Err(DevelopmentError::InvalidInput(format!(
1800                    "timeoutSeconds must be 1..={maximum_seconds}"
1801                )))
1802            } else {
1803                Ok(Duration::from_secs(seconds))
1804            }
1805        })
1806        .transpose()
1807}
1808
1809fn parse_kernel_kind(value: &str) -> DevelopmentResult<KernelKind> {
1810    match value {
1811        "python" => Ok(KernelKind::Python),
1812        "javascript" => Ok(KernelKind::JavaScript),
1813        "shell" => Ok(KernelKind::Shell),
1814        "sql" => Ok(KernelKind::Sql),
1815        _ => Err(DevelopmentError::InvalidInput(
1816            "kernel kind must be python, javascript, shell, or sql".into(),
1817        )),
1818    }
1819}
1820
1821fn normalized_actor_id(value: &str) -> String {
1822    let normalized: String = value
1823        .chars()
1824        .filter(|character| character.is_ascii_alphanumeric() || "-_.".contains(*character))
1825        .take(128)
1826        .collect();
1827    if normalized.is_empty() {
1828        "actor".into()
1829    } else {
1830        normalized
1831    }
1832}
1833
1834fn agent_id(
1835    workspace: &mut DevelopmentWorkspace,
1836    value: &str,
1837) -> DevelopmentResult<crate::agents::AgentId> {
1838    workspace
1839        .agents()
1840        .list()?
1841        .into_iter()
1842        .find(|snapshot| snapshot.id.as_str() == value)
1843        .map(|snapshot| snapshot.id)
1844        .ok_or_else(|| DevelopmentError::NotFound(format!("agent {value}")))
1845}
1846fn active_agent_id(workspace: &mut DevelopmentWorkspace) -> Option<crate::agents::AgentId> {
1847    workspace
1848        .agents()
1849        .list()
1850        .ok()?
1851        .into_iter()
1852        .find(|snapshot| {
1853            !matches!(
1854                snapshot.status,
1855                crate::agents::AgentStatus::Completed
1856                    | crate::agents::AgentStatus::Failed
1857                    | crate::agents::AgentStatus::Cancelled
1858            )
1859        })
1860        .map(|snapshot| snapshot.id)
1861}
1862
1863fn agent_request(
1864    workspace: &mut DevelopmentWorkspace,
1865    call: &ToolCall,
1866    request: PiSessionRequest,
1867) -> DevelopmentResult<Value> {
1868    let id = agent_id(workspace, required_string(call, "agentId")?)?;
1869    map_service(workspace.agents().request(&id, request))?;
1870    Ok(serde_json::json!({"queued":true}))
1871}
1872
1873fn task_action(
1874    workspace: &mut DevelopmentWorkspace,
1875    call: &ToolCall,
1876    action: impl FnOnce(&mut DevelopmentWorkspace, &TaskId) -> DevelopmentResult<()>,
1877) -> DevelopmentResult<Value> {
1878    let id = TaskId::parse(required_string(call, "taskId")?)?;
1879    action(workspace, &id)?;
1880    Ok(serde_json::json!({"updated":true}))
1881}
1882
1883fn map_service<T: serde::Serialize, E: std::fmt::Display>(
1884    result: Result<T, E>,
1885) -> DevelopmentResult<Value> {
1886    result
1887        .map_err(|error| DevelopmentError::Process(error.to_string()))
1888        .and_then(|value| serde_json::to_value(value).map_err(DevelopmentError::from))
1889}
1890
1891fn map_debug<T: serde::Serialize>(
1892    result: crate::debugger::DebugResult<T>,
1893) -> DevelopmentResult<Value> {
1894    map_service(result)
1895}
1896
1897fn debugger<'a>(
1898    workspace: &'a mut DevelopmentWorkspace,
1899    name: &str,
1900) -> DevelopmentResult<&'a mut crate::debugger::DebuggerSession> {
1901    workspace
1902        .debugger_mut(name)
1903        .map_err(|error| DevelopmentError::Process(error.to_string()))
1904}
1905
1906fn git_value<T: serde::Serialize>(
1907    git: Option<&crate::git::GitService>,
1908    operation: impl FnOnce(&crate::git::GitService) -> crate::git::GitResult<T>,
1909) -> DevelopmentResult<Value> {
1910    map_service(operation(git.ok_or_else(|| {
1911        DevelopmentError::NotFound("Git repository".into())
1912    })?))
1913}
1914
1915fn git_mutation(
1916    git: Option<&crate::git::GitService>,
1917    operation: impl FnOnce(&crate::git::GitService) -> crate::git::GitResult<()>,
1918) -> DevelopmentResult<()> {
1919    operation(git.ok_or_else(|| DevelopmentError::NotFound("Git repository".into()))?)
1920        .map_err(|error| DevelopmentError::Process(error.to_string()))
1921}
1922
1923fn project_observable_result(
1924    workspace: &mut DevelopmentWorkspace,
1925    call: &ToolCall,
1926    actor: &str,
1927    before_revision: u64,
1928    after_revision: u64,
1929    result: &Value,
1930) -> DevelopmentResult<()> {
1931    let tool_node = format!("tool:{}", call.id);
1932    let result_bytes = serde_json::to_vec(result)?.len();
1933    let summary = serde_json::json!({
1934        "tool":call.name,
1935        "callId":call.id,
1936        "beforeRevision":before_revision,
1937        "afterRevision":after_revision,
1938        "resultBytes":result_bytes,
1939    });
1940    let argument = |name: &str| {
1941        call.arguments.get(name).and_then(|value| {
1942            value
1943                .as_str()
1944                .map(str::to_string)
1945                .or_else(|| value.as_u64().map(|value| value.to_string()))
1946                .or_else(|| value.as_i64().map(|value| value.to_string()))
1947        })
1948    };
1949    let resource_name = |preferred: &[&str], fallback: &str| {
1950        preferred
1951            .iter()
1952            .find_map(|name| argument(name))
1953            .unwrap_or_else(|| fallback.to_string())
1954    };
1955    let mut observed = Vec::<(String, DevelopmentNodeKind, String, String)>::new();
1956
1957    if call.name.starts_with("glass.file.") || call.name.starts_with("glass.editor.") {
1958        let path = resource_name(&["path", "from", "to"], &call.id);
1959        let file = format!("file:{}", id_component(&path));
1960        observed.push((
1961            file.clone(),
1962            DevelopmentNodeKind::File,
1963            path,
1964            "referencesFile".into(),
1965        ));
1966        if call.name.starts_with("glass.editor.") {
1967            observed.push((
1968                format!("editorRevision:{}", id_component(&call.id)),
1969                DevelopmentNodeKind::EditorRevision,
1970                format!("editor revision {after_revision}"),
1971                "producedEditorRevision".into(),
1972            ));
1973        }
1974    }
1975    if call.name.starts_with("glass.lsp.") {
1976        let path = resource_name(&["path"], &call.id);
1977        if call.name == "glass.lsp.diagnostics" || call.name == "glass.diagnostics.run" {
1978            observed.push((
1979                format!("diagnostic:{}", id_component(&call.id)),
1980                DevelopmentNodeKind::Diagnostic,
1981                path,
1982                "reportedDiagnostic".into(),
1983            ));
1984        } else if !matches!(
1985            call.name.as_str(),
1986            "glass.lsp.start" | "glass.lsp.stop" | "glass.lsp.list" | "glass.lsp.events"
1987        ) {
1988            observed.push((
1989                format!("symbol:{}", id_component(&call.id)),
1990                DevelopmentNodeKind::Symbol,
1991                path,
1992                "resolvedSymbol".into(),
1993            ));
1994        }
1995    }
1996    if call.name.starts_with("glass.git.") {
1997        let kind = if call.name == "glass.git.commit" {
1998            DevelopmentNodeKind::GitCommit
1999        } else {
2000            DevelopmentNodeKind::GitChange
2001        };
2002        observed.push((
2003            format!("gitChange:{}", id_component(&call.id)),
2004            kind,
2005            call.name.clone(),
2006            "observedGitChange".into(),
2007        ));
2008    }
2009    if call.name.starts_with("glass.process.") {
2010        let name = resource_name(&["name"], &call.id);
2011        observed.push((
2012            format!("process:{}", id_component(&name)),
2013            DevelopmentNodeKind::Process,
2014            name,
2015            "observedProcess".into(),
2016        ));
2017        if let Some(port) = find_scalar(result, &["port", "debugPort", "assignedPort"], 0) {
2018            observed.push((
2019                format!("port:{}", id_component(&port)),
2020                DevelopmentNodeKind::Port,
2021                port,
2022                "observedPort".into(),
2023            ));
2024        }
2025    }
2026    if call.name.starts_with("glass.debug.") {
2027        let session = resource_name(&["session"], &call.id);
2028        observed.push((
2029            format!("debugger:{}", id_component(&session)),
2030            DevelopmentNodeKind::Debugger,
2031            session.clone(),
2032            "observedDebugSession".into(),
2033        ));
2034        if call.name.contains("breakpoint") {
2035            observed.push((
2036                format!("breakpoint:{}", id_component(&call.id)),
2037                DevelopmentNodeKind::Breakpoint,
2038                resource_name(&["path"], &call.id),
2039                "configuredBreakpoint".into(),
2040            ));
2041        }
2042        if let Some(thread) = argument("threadId").or_else(|| find_scalar(result, &["threadId"], 0))
2043        {
2044            observed.push((
2045                format!(
2046                    "thread:{}:{}",
2047                    id_component(&session),
2048                    id_component(&thread)
2049                ),
2050                DevelopmentNodeKind::Thread,
2051                thread,
2052                "observedThread".into(),
2053            ));
2054        }
2055        if let Some(frame) =
2056            argument("frameId").or_else(|| find_scalar(result, &["frameId", "id"], 0))
2057        {
2058            observed.push((
2059                format!(
2060                    "stackFrame:{}:{}",
2061                    id_component(&session),
2062                    id_component(&frame)
2063                ),
2064                DevelopmentNodeKind::StackFrame,
2065                frame,
2066                "observedStackFrame".into(),
2067            ));
2068        }
2069    }
2070    if call.name.starts_with("glass.browser.") {
2071        let target = argument("targetId")
2072            .or_else(|| find_scalar(result, &["targetId", "id"], 0))
2073            .unwrap_or_else(|| "active".into());
2074        observed.push((
2075            format!("browserTarget:{}", id_component(&target)),
2076            DevelopmentNodeKind::BrowserTarget,
2077            target,
2078            "observedBrowserTarget".into(),
2079        ));
2080        if let Some(revision) = find_scalar(result, &["revision", "browserRevision"], 0) {
2081            observed.push((
2082                format!("browserRevision:{}", id_component(&revision)),
2083                DevelopmentNodeKind::BrowserRevision,
2084                revision,
2085                "observedBrowserRevision".into(),
2086            ));
2087        }
2088    }
2089    if call.name.starts_with("glass.semantic.") || call.name.starts_with("glass.web_ir.") {
2090        observed.push((
2091            format!("webIr:{}", id_component(&call.id)),
2092            DevelopmentNodeKind::WebIrEntity,
2093            call.name.clone(),
2094            "observedWebIr".into(),
2095        ));
2096    }
2097    if call.name.starts_with("glass.workflow.") {
2098        let run = resource_name(&["runId", "id", "name"], &call.id);
2099        observed.push((
2100            format!("workflow:{}", id_component(&run)),
2101            DevelopmentNodeKind::Workflow,
2102            run,
2103            "observedWorkflow".into(),
2104        ));
2105    }
2106    if call.name.starts_with("glass.test.") {
2107        let run = resource_name(&["runId", "suiteId"], &call.id);
2108        observed.push((
2109            format!("test:{}", id_component(&run)),
2110            DevelopmentNodeKind::Test,
2111            run,
2112            "observedTest".into(),
2113        ));
2114    }
2115    if call.name.starts_with("glass.eval.") {
2116        let name = resource_name(&["name"], &call.id);
2117        observed.push((
2118            format!("kernel:{}", id_component(&name)),
2119            DevelopmentNodeKind::Kernel,
2120            name,
2121            "observedKernel".into(),
2122        ));
2123    }
2124    if call.name.starts_with("glass.agent.") {
2125        let agent = argument("agentId")
2126            .or_else(|| find_scalar(result, &["agentId", "id"], 0))
2127            .unwrap_or_else(|| call.id.clone());
2128        observed.push((
2129            format!("agent:{}", id_component(&agent)),
2130            DevelopmentNodeKind::Agent,
2131            agent,
2132            "observedAgent".into(),
2133        ));
2134    }
2135    if call.name.starts_with("glass.task.") {
2136        let task = resource_name(&["taskId", "id"], &call.id);
2137        observed.push((
2138            format!("task:{}", id_component(&task)),
2139            DevelopmentNodeKind::Task,
2140            task,
2141            "observedTask".into(),
2142        ));
2143    }
2144    if call.name.starts_with("glass.experiment.") {
2145        let experiment = resource_name(&["id"], &call.id);
2146        observed.push((
2147            format!("experiment:{}", id_component(&experiment)),
2148            DevelopmentNodeKind::Experiment,
2149            experiment,
2150            "observedExperiment".into(),
2151        ));
2152    }
2153
2154    let mut previous: Option<String> = None;
2155    for (id, kind, label, relation) in observed {
2156        workspace.intelligence_mut().upsert_node(DevelopmentNode {
2157            id: id.clone(),
2158            kind,
2159            label,
2160            revision: after_revision,
2161            stale: false,
2162            evidence: summary.clone(),
2163        })?;
2164        workspace.intelligence_mut().link(
2165            previous.as_deref().unwrap_or(&tool_node),
2166            &id,
2167            &relation,
2168            after_revision,
2169            actor,
2170            summary.clone(),
2171        )?;
2172        workspace.intelligence_mut().record(ObservableEventInput {
2173            actor,
2174            subsystem: subsystem_for_tool(&call.name),
2175            kind: "observed",
2176            resource: Some(&id),
2177            workspace_revision: after_revision,
2178            evidence: summary.clone(),
2179            rationale: None,
2180        })?;
2181        previous = Some(id);
2182    }
2183    Ok(())
2184}
2185
2186fn subsystem_for_tool(tool: &str) -> &str {
2187    tool.strip_prefix("glass.")
2188        .and_then(|value| value.split('.').next())
2189        .unwrap_or("project")
2190}
2191
2192fn id_component(value: &str) -> String {
2193    value
2194        .chars()
2195        .map(|character| {
2196            if character.is_control() {
2197                '_'
2198            } else {
2199                character
2200            }
2201        })
2202        .take(240)
2203        .collect()
2204}
2205
2206fn find_scalar(value: &Value, keys: &[&str], depth: usize) -> Option<String> {
2207    if depth > 6 {
2208        return None;
2209    }
2210    match value {
2211        Value::Object(values) => {
2212            for key in keys {
2213                if let Some(value) = values.get(*key) {
2214                    if let Some(value) = value.as_str() {
2215                        return Some(value.to_string());
2216                    }
2217                    if let Some(value) = value.as_u64() {
2218                        return Some(value.to_string());
2219                    }
2220                }
2221            }
2222            values
2223                .values()
2224                .find_map(|value| find_scalar(value, keys, depth + 1))
2225        }
2226        Value::Array(values) => values
2227            .iter()
2228            .find_map(|value| find_scalar(value, keys, depth + 1)),
2229        _ => None,
2230    }
2231}
2232
2233#[cfg(test)]
2234mod tests {
2235    use super::*;
2236    use crate::development::Actor;
2237    use serde_json::json;
2238    use std::sync::atomic::{AtomicU64, Ordering};
2239
2240    static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
2241
2242    fn workspace() -> DevelopmentWorkspace {
2243        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2244        let root = std::env::temp_dir().join(format!(
2245            "glass-tool-router-{}-{sequence}",
2246            std::process::id()
2247        ));
2248        std::fs::create_dir_all(&root).unwrap();
2249        std::fs::write(
2250            root.join("Cargo.toml"),
2251            "[package]\nname='x'\nversion='0.1.0'\n",
2252        )
2253        .unwrap();
2254        let mut workspace = DevelopmentWorkspace::open(root).unwrap();
2255        workspace
2256            .apply_local_trust_decision(crate::LocalTrustDecision::TrustOnce)
2257            .unwrap();
2258        workspace
2259    }
2260
2261    fn context(workspace: &DevelopmentWorkspace, mutate: bool) -> DevelopmentToolContext {
2262        DevelopmentToolContext {
2263            authorization: ToolAuthorization {
2264                actor: Actor::embedded(),
2265                allow_mutation: mutate,
2266                confirmed: mutate,
2267            },
2268            initiator: None,
2269            expected_generation: workspace.generation(),
2270            expected_project_revision: workspace.project().revision(),
2271        }
2272    }
2273
2274    #[test]
2275    fn router_rejects_stale_or_unauthorized_mutations() {
2276        let mut workspace = workspace();
2277        let router = DevelopmentToolRouter::default();
2278        let call = ToolCall {
2279            id: "write-1".into(),
2280            name: "glass.file.write".into(),
2281            arguments: serde_json::json!({"path":"src/lib.rs","content":"pub fn ok() {}\n"}),
2282        };
2283        let read_only = context(&workspace, false);
2284        assert!(router.execute(&mut workspace, &call, &read_only).is_err());
2285        let mut stale = context(&workspace, true);
2286        stale.expected_project_revision = stale.expected_project_revision.saturating_add(1);
2287        assert!(router.execute(&mut workspace, &call, &stale).is_err());
2288        let valid = context(&workspace, true);
2289        workspace.execute_tool(&call, &valid).unwrap();
2290        assert!(workspace.root().join("src/lib.rs").exists());
2291        let replay = workspace.intelligence().replay(0, 16).unwrap();
2292        assert_eq!(
2293            replay
2294                .iter()
2295                .map(|event| event.kind.as_str())
2296                .collect::<Vec<_>>(),
2297            vec!["called", "observed", "completed"]
2298        );
2299        assert!(
2300            workspace
2301                .intelligence()
2302                .path("repository:root", "tool:write-1")
2303                .is_ok()
2304        );
2305    }
2306
2307    #[test]
2308    fn router_uses_resident_kernel_and_test_services() {
2309        let mut workspace = workspace();
2310        let router = DevelopmentToolRouter::default();
2311        let start = ToolCall {
2312            id: "kernel-1".into(),
2313            name: "glass.eval.start".into(),
2314            arguments: serde_json::json!({"name":"analysis","kind":"sql"}),
2315        };
2316        let mutation = context(&workspace, true);
2317        router.execute(&mut workspace, &start, &mutation).unwrap();
2318        let execute = ToolCall {
2319            id: "kernel-2".into(),
2320            name: "glass.eval.execute".into(),
2321            arguments: serde_json::json!({"name":"analysis","code":"SELECT 40 + 2 AS answer"}),
2322        };
2323        let result = router.execute(&mut workspace, &execute, &mutation).unwrap();
2324        assert_eq!(result["value"][0]["answer"], 42);
2325        assert!(
2326            router
2327                .descriptors()
2328                .iter()
2329                .any(|descriptor| descriptor.name == "glass.debug.launch")
2330        );
2331    }
2332
2333    #[test]
2334    fn kernel_bindings_reenter_the_same_router_with_dual_provenance() {
2335        let mut workspace = workspace();
2336        std::fs::write(workspace.root().join("evidence.txt"), "governed\n").unwrap();
2337        let router = DevelopmentToolRouter::default();
2338        let mutation = context(&workspace, true);
2339        router
2340            .execute(
2341                &mut workspace,
2342                &ToolCall {
2343                    id: "kernel-binding-start".into(),
2344                    name: "glass.eval.start".into(),
2345                    arguments: serde_json::json!({
2346                        "name":"analysis",
2347                        "kind":"sql",
2348                        "capabilities":["glass.file.read","glass.file.write"]
2349                    }),
2350                },
2351                &mutation,
2352            )
2353            .unwrap();
2354        let result = router
2355            .execute(
2356                &mut workspace,
2357                &ToolCall {
2358                    id: "kernel-binding-execute".into(),
2359                    name: "glass.eval.execute".into(),
2360                    arguments: serde_json::json!({
2361                        "name":"analysis",
2362                        "code":r#"GLASS CALL {"id":"sql-1","tool":"glass.file.read","arguments":{"path":"evidence.txt"}}"#
2363                    }),
2364                },
2365                &mutation,
2366            )
2367            .unwrap();
2368        assert_eq!(result["value"]["content"], "governed\n");
2369        assert_eq!(result["initiatorId"], "embedded:glass-agent");
2370        assert_eq!(result["executorId"], "kernel:analysis");
2371        let replay = workspace.intelligence().replay(0, 32).unwrap();
2372        let nested = replay
2373            .iter()
2374            .find(|event| event.resource.as_deref() == Some("tool:kernel-analysis-sql-1"))
2375            .unwrap();
2376        assert_eq!(nested.actor, "kernel:analysis");
2377        assert_eq!(nested.evidence["initiator"], "embedded:glass-agent");
2378        assert_eq!(nested.evidence["executor"], "kernel:analysis");
2379
2380        let denied = router.execute(
2381            &mut workspace,
2382            &ToolCall {
2383                id: "kernel-binding-denied".into(),
2384                name: "glass.eval.execute".into(),
2385                arguments: serde_json::json!({
2386                    "name":"analysis",
2387                    "code":r#"GLASS CALL {"id":"sql-2","tool":"glass.file.write","arguments":{"path":"denied.txt","content":"no"}}"#
2388                }),
2389            },
2390            &mutation,
2391        );
2392        assert!(denied.unwrap_err().to_string().contains("mutation"));
2393        assert!(!workspace.root().join("denied.txt").exists());
2394    }
2395
2396    #[test]
2397    fn governed_python_queries_browser_tests_and_graph_before_approved_mutation() {
2398        let mut workspace = workspace();
2399        let router = DevelopmentToolRouter::default();
2400        let mutation = context(&workspace, true);
2401        router
2402            .execute(
2403                &mut workspace,
2404                &ToolCall {
2405                    id: "governed-python-start".into(),
2406                    name: "glass.eval.start".into(),
2407                    arguments: serde_json::json!({
2408                        "name":"analysis",
2409                        "kind":"python",
2410                        "capabilities":[
2411                            "glass.browser.state",
2412                            "glass.test.results",
2413                            "glass.graph.path",
2414                            "glass.file.write"
2415                        ]
2416                    }),
2417                },
2418                &mutation,
2419            )
2420            .unwrap();
2421
2422        for (id, code, expected) in [
2423            (
2424                "governed-python-browser",
2425                "glass.call('glass.browser.state')",
2426                "'connected': False",
2427            ),
2428            (
2429                "governed-python-tests",
2430                "glass.call('glass.test.results')",
2431                "results",
2432            ),
2433            (
2434                "governed-python-graph",
2435                "glass.call('glass.graph.path', {'from': 'repository:root', 'to': 'tool:kernel-analysis-python-1'})",
2436                "repository:root",
2437            ),
2438        ] {
2439            let result = router
2440                .execute(
2441                    &mut workspace,
2442                    &ToolCall {
2443                        id: id.into(),
2444                        name: "glass.eval.execute".into(),
2445                        arguments: serde_json::json!({"name":"analysis","code":code}),
2446                    },
2447                    &mutation,
2448                )
2449                .unwrap();
2450            assert!(
2451                result["value"].as_str().unwrap().contains(expected),
2452                "{id} must return governed {expected} evidence: {result}"
2453            );
2454            assert_eq!(result["initiatorId"], "embedded:glass-agent");
2455            assert_eq!(result["executorId"], "kernel:analysis");
2456        }
2457
2458        let denied = router.execute(
2459            &mut workspace,
2460            &ToolCall {
2461                id: "governed-python-denied".into(),
2462                name: "glass.eval.execute".into(),
2463                arguments: serde_json::json!({
2464                    "name":"analysis",
2465                    "code":"glass.call('glass.file.write', {'path': 'denied.py', 'content': 'no'})"
2466                }),
2467            },
2468            &mutation,
2469        );
2470        assert!(denied.unwrap_err().to_string().contains("mutation"));
2471        assert!(!workspace.root().join("denied.py").exists());
2472
2473        router
2474            .execute(
2475                &mut workspace,
2476                &ToolCall {
2477                    id: "approved-python-start".into(),
2478                    name: "glass.eval.start".into(),
2479                    arguments: serde_json::json!({
2480                        "name":"approved",
2481                        "kind":"python",
2482                        "capabilities":["glass.file.write"],
2483                        "mutationAuthority":true
2484                    }),
2485                },
2486                &mutation,
2487            )
2488            .unwrap();
2489        let approved = router
2490            .execute(
2491                &mut workspace,
2492                &ToolCall {
2493                    id: "approved-python-write".into(),
2494                    name: "glass.eval.execute".into(),
2495                    arguments: serde_json::json!({
2496                        "name":"approved",
2497                        "code":"glass.call('glass.file.write', {'path': 'approved.py', 'content': 'approved\\n'})"
2498                    }),
2499                },
2500                &mutation,
2501            )
2502            .unwrap();
2503        assert_eq!(approved["initiatorId"], "embedded:glass-agent");
2504        assert_eq!(approved["executorId"], "kernel:approved");
2505        assert_eq!(
2506            std::fs::read_to_string(workspace.root().join("approved.py")).unwrap(),
2507            "approved\n"
2508        );
2509
2510        let replay = workspace.intelligence().replay(0, 128).unwrap();
2511        for resource in [
2512            "tool:kernel-analysis-python-1",
2513            "tool:kernel-analysis-python-2",
2514            "tool:kernel-analysis-python-3",
2515            "tool:kernel-approved-python-1",
2516        ] {
2517            let nested = replay
2518                .iter()
2519                .find(|event| event.resource.as_deref() == Some(resource))
2520                .unwrap_or_else(|| panic!("missing provenance for {resource}"));
2521            assert_eq!(nested.evidence["initiator"], "embedded:glass-agent");
2522            assert!(
2523                nested.evidence["executor"]
2524                    .as_str()
2525                    .unwrap()
2526                    .starts_with("kernel:")
2527            );
2528        }
2529    }
2530
2531    #[test]
2532    fn router_exposes_shared_editor_process_browser_and_complete_lsp_tools() {
2533        let mut workspace = workspace();
2534        std::fs::create_dir_all(workspace.root().join("src")).unwrap();
2535        std::fs::write(workspace.root().join("src/lib.rs"), "pub fn old() {}\n").unwrap();
2536        let router = DevelopmentToolRouter::default();
2537        let descriptors = router.descriptors();
2538        for name in [
2539            "glass.editor.open",
2540            "glass.editor.replace",
2541            "glass.editor.save",
2542            "glass.process.list",
2543            "glass.process.logs",
2544            "glass.process.start",
2545            "glass.process.stop",
2546            "glass.process.restart",
2547            "glass.browser.observe",
2548            "glass.browser.snapshot",
2549            "glass.browser.attach",
2550            "glass.browser.reconnect",
2551            "glass.browser.semantic",
2552            "glass.browser.diff",
2553            "glass.browser.navigate",
2554            "glass.browser.act",
2555            "glass.workflow.list",
2556            "glass.workflow.run",
2557            "glass.workflow.pause",
2558            "glass.workflow.resume",
2559            "glass.workflow.cancel",
2560            "glass.workflow.verify",
2561            "glass.workflow.record",
2562            "glass.memory.retrieve",
2563            "glass.memory.explain",
2564            "glass.memory.forget",
2565            "glass.semantic.inspect",
2566            "glass.semantic.diff",
2567            "glass.semantic.links",
2568            "glass.lsp.start",
2569            "glass.lsp.stop",
2570            "glass.lsp.list",
2571            "glass.lsp.events",
2572            "glass.lsp.definition",
2573            "glass.lsp.declaration",
2574            "glass.lsp.implementation",
2575            "glass.lsp.references",
2576            "glass.lsp.document_symbols",
2577            "glass.lsp.workspace_symbols",
2578            "glass.lsp.signature_help",
2579            "glass.lsp.code_actions",
2580            "glass.lsp.formatting",
2581            "glass.lsp.range_formatting",
2582            "glass.lsp.semantic_tokens",
2583            "glass.lsp.rename",
2584            "glass.lsp.raw",
2585            "glass.debug.configuration_done",
2586            "glass.debug.restart",
2587            "glass.debug.breakpoint.remove",
2588            "glass.debug.exception.set",
2589            "glass.debug.threads",
2590            "glass.debug.disconnect",
2591            "glass.debug.terminate",
2592            "glass.agent.model",
2593            "glass.agent.thinking",
2594            "glass.agent.new-session",
2595            "glass.agent.clone-session",
2596            "glass.agent.fork",
2597            "glass.agent.switch-session",
2598            "glass.agent.messages",
2599            "glass.agent.entries",
2600            "glass.agent.stats",
2601            "glass.agent.name",
2602            "glass.task.create",
2603            "glass.task.list",
2604            "glass.task.get",
2605            "glass.task.inspect",
2606            "glass.task.pause",
2607            "glass.task.resume",
2608            "glass.task.cancel",
2609            "glass.task.retry",
2610            "glass.task.reassign",
2611            "glass.task.override-blocked",
2612            "glass.task.evidence",
2613            "glass.task.verify",
2614            "glass.experiment.create",
2615            "glass.experiment.collect",
2616            "glass.experiment.list",
2617            "glass.experiment.compare",
2618            "glass.experiment.select",
2619            "glass.experiment.remove",
2620        ] {
2621            let descriptor = descriptors
2622                .iter()
2623                .find(|descriptor| descriptor.name == name)
2624                .unwrap_or_else(|| panic!("missing {name}"));
2625            assert!(
2626                descriptor.available,
2627                "{name} must execute, not be a placeholder"
2628            );
2629        }
2630
2631        for (id, name, arguments) in [
2632            (
2633                "open",
2634                "glass.editor.open",
2635                serde_json::json!({"path":"src/lib.rs"}),
2636            ),
2637            (
2638                "replace",
2639                "glass.editor.replace",
2640                serde_json::json!({"path":"src/lib.rs","oldText":"old","newText":"resident"}),
2641            ),
2642            (
2643                "save",
2644                "glass.editor.save",
2645                serde_json::json!({"path":"src/lib.rs"}),
2646            ),
2647        ] {
2648            let call = ToolCall {
2649                id: id.into(),
2650                name: name.into(),
2651                arguments,
2652            };
2653            let authorized = context(&workspace, true);
2654            router.execute(&mut workspace, &call, &authorized).unwrap();
2655        }
2656        assert_eq!(
2657            std::fs::read_to_string(workspace.root().join("src/lib.rs")).unwrap(),
2658            "pub fn resident() {}\n"
2659        );
2660    }
2661
2662    #[test]
2663    fn observable_projection_populates_every_issue_35_graph_resource_kind() {
2664        let mut workspace = workspace();
2665        let samples = vec![
2666            ("glass.editor.save", json!({"path":"src/lib.rs"}), json!({})),
2667            ("glass.lsp.hover", json!({"path":"src/lib.rs"}), json!({})),
2668            (
2669                "glass.lsp.diagnostics",
2670                json!({"path":"src/lib.rs"}),
2671                json!([]),
2672            ),
2673            ("glass.git.diff", json!({}), json!({"changed":true})),
2674            (
2675                "glass.process.ports",
2676                json!({"name":"web"}),
2677                json!({"port":8080}),
2678            ),
2679            (
2680                "glass.debug.stack",
2681                json!({"session":"rust","threadId":3}),
2682                json!({"stackFrames":[{"id":9}]}),
2683            ),
2684            (
2685                "glass.browser.state",
2686                json!({}),
2687                json!({"targetId":"page-1","revision":12}),
2688            ),
2689            ("glass.web_ir.inspect", json!({}), json!({"entities":[]})),
2690            (
2691                "glass.workflow.verify",
2692                json!({"runId":"checkout"}),
2693                json!({"passed":false}),
2694            ),
2695            (
2696                "glass.test.results",
2697                json!({"runId":"unit"}),
2698                json!({"passed":true}),
2699            ),
2700            (
2701                "glass.eval.execute",
2702                json!({"name":"analysis"}),
2703                json!({"value":42}),
2704            ),
2705            ("glass.agent.list", json!({}), json!({"agentId":"agent-1"})),
2706            (
2707                "glass.task.get",
2708                json!({"taskId":"task-1"}),
2709                json!({"state":"failed"}),
2710            ),
2711            (
2712                "glass.experiment.collect",
2713                json!({"id":"approach-a"}),
2714                json!({"measured":true}),
2715            ),
2716        ];
2717        for (index, (name, arguments, result)) in samples.into_iter().enumerate() {
2718            let call = ToolCall {
2719                id: format!("projection-{index}"),
2720                name: name.into(),
2721                arguments,
2722            };
2723            let tool_node = format!("tool:{}", call.id);
2724            workspace
2725                .intelligence_mut()
2726                .upsert_node(DevelopmentNode {
2727                    id: tool_node.clone(),
2728                    kind: DevelopmentNodeKind::ToolCall,
2729                    label: call.name.clone(),
2730                    revision: 1,
2731                    stale: false,
2732                    evidence: Value::Null,
2733                })
2734                .unwrap();
2735            workspace
2736                .intelligence_mut()
2737                .link(
2738                    "repository:root",
2739                    &tool_node,
2740                    "receivedToolCall",
2741                    1,
2742                    "test",
2743                    Value::Null,
2744                )
2745                .unwrap();
2746            project_observable_result(&mut workspace, &call, "test", 1, 1, &result).unwrap();
2747        }
2748        for kind in [
2749            DevelopmentNodeKind::Repository,
2750            DevelopmentNodeKind::File,
2751            DevelopmentNodeKind::Symbol,
2752            DevelopmentNodeKind::EditorRevision,
2753            DevelopmentNodeKind::GitChange,
2754            DevelopmentNodeKind::Process,
2755            DevelopmentNodeKind::Port,
2756            DevelopmentNodeKind::Diagnostic,
2757            DevelopmentNodeKind::Debugger,
2758            DevelopmentNodeKind::Thread,
2759            DevelopmentNodeKind::StackFrame,
2760            DevelopmentNodeKind::BrowserTarget,
2761            DevelopmentNodeKind::BrowserRevision,
2762            DevelopmentNodeKind::WebIrEntity,
2763            DevelopmentNodeKind::Workflow,
2764            DevelopmentNodeKind::Test,
2765            DevelopmentNodeKind::Kernel,
2766            DevelopmentNodeKind::Agent,
2767            DevelopmentNodeKind::Task,
2768            DevelopmentNodeKind::Experiment,
2769            DevelopmentNodeKind::ToolCall,
2770        ] {
2771            assert!(
2772                !workspace.intelligence().query_kind(kind).is_empty(),
2773                "missing {kind:?}"
2774            );
2775        }
2776        let router = DevelopmentToolRouter::default();
2777        for (index, (from, to, relation)) in [
2778            ("file:src/lib.rs", "gitChange:projection-3", "changedBy"),
2779            ("gitChange:projection-3", "test:unit", "verifiedBy"),
2780            ("test:unit", "webIr:projection-7", "observedRegression"),
2781        ]
2782        .into_iter()
2783        .enumerate()
2784        {
2785            let context = context(&workspace, true);
2786            router
2787                .execute(
2788                    &mut workspace,
2789                    &ToolCall {
2790                        id: format!("causal-link-{index}"),
2791                        name: "glass.graph.link".into(),
2792                        arguments: json!({
2793                            "from":from,
2794                            "to":to,
2795                            "relation":relation,
2796                            "evidence":{"source":"resident-verification"}
2797                        }),
2798                    },
2799                    &context,
2800                )
2801                .unwrap();
2802        }
2803        let path = workspace
2804            .intelligence()
2805            .path("file:src/lib.rs", "webIr:projection-7")
2806            .unwrap();
2807        assert_eq!(
2808            path.edges
2809                .iter()
2810                .map(|edge| edge.relation.as_str())
2811                .collect::<Vec<_>>(),
2812            vec!["changedBy", "verifiedBy", "observedRegression"]
2813        );
2814        assert!(path.edges.iter().all(|edge| !edge.provenance.is_empty()));
2815        let replay = workspace.intelligence().replay(0, 128).unwrap();
2816        assert!(replay.iter().any(|event| event.subsystem == "task"));
2817        assert!(replay.iter().all(|event| event.rationale.is_none()));
2818    }
2819}