Skip to main content

qualia_mcp/tools/
poet.rs

1//! MCP tools for POET Studio: authoring, layout receipts, artifact lifecycle, and Shed cross-container tool dispatch.
2//!
3//! Follows `AGENTS.md` ยง0-B (<495 lines).
4
5use crate::types::{parse_tool_args, McpSystemError};
6use qualia_core_db::poet_host::PoetSnapshot;
7use serde_json::{json, Value};
8#[path = "poet_export.rs"]
9mod export_support;
10
11fn q_hash(bytes: &[u8]) -> u64 {
12    let mut hash = 0xcbf29ce484222325u64;
13    for &b in bytes { hash = (hash ^ (b as u64)).wrapping_mul(0x100000001b3); }
14    hash
15}
16
17fn str_req<'a>(v: &'a Value, primary: &str, fallback: &str) -> Result<&'a str, McpSystemError> {
18    v.get(primary).or_else(|| v.get(fallback)).and_then(Value::as_str).ok_or(McpSystemError::InvalidParameters)
19}
20
21fn str_prop<'a>(v: &'a Value, primary: &str, fallback: &str, default: &'a str) -> &'a str {
22    v.get(primary).or_else(|| v.get(fallback)).and_then(Value::as_str).unwrap_or(default)
23}
24
25fn bool_prop(v: &Value, key: &str, default: bool) -> bool { v.get(key).and_then(Value::as_bool).unwrap_or(default) }
26fn f64_prop(v: &Value, key: &str, default: f64) -> f64 { v.get(key).and_then(Value::as_f64).unwrap_or(default) }
27fn u64_prop(v: &Value, key: &str, default: u64) -> u64 { v.get(key).and_then(Value::as_u64).unwrap_or(default) }
28
29const TOOLCHEST_FAMILIES: &[(&str, &[&str])] = &[
30    ("Core", &["Select", "Transform", "Pen", "Brush", "Eraser", "Measure", "Eyedropper", "Slice"]),
31    ("Constructs", &["Container", "ManifoldPortal", "NestedLink", "TimelineTrack", "ShaderNode", "ConstraintSolver"]),
32    ("Manifolds", &["Spatial", "Temporal", "Acoustic", "RF", "Magnetic", "Cyber", "Hardware", "Logical", "Agentic", "Socio", "Political", "Legal", "Economic", "Bio", "Thermal", "Ecological", "Relativistic"]),
33    ("Agents", &["Planner", "Synthesizer", "Verifier", "Archivist", "Choreographer", "SentinelGuard"]),
34    ("Ecosystems", &["EcoPunk", "GameDemo", "CatchmentCommons", "BilateralMicroCommons", "CivicObservatory"]),
35    ("Applications", &["DocumentStudio", "SheetStudio", "DeckStudio", "PdfStudio", "RasterStudio", "RawDevelopStudio", "VectorStudio", "GenerativeStudio", "CadStudio", "VideoStudio", "AudioStudio"]),
36    ("Services", &["PulseTransport", "Q42VolumeStore", "ShaclGate", "WgslForge", "LocalLlm"]),
37    ("Systems", &["SlgSentinel42MB", "WebGpuViewport", "HrtfAudio", "HidRingBuffer", "DeonticJudge"]),
38];
39
40const SHED_PREFIXES: &[&str] = &[
41    "ComputationalGeometry", "GeometricAlgebra", "LinearAlgebra", "SymbolicAlgebra", "SymbolicODE",
42    "Calculus", "NumberTheory", "SpecialFunctions", "Interpolation", "Deontic", "Epistemic",
43    "Paraconsistent", "LTL", "N3", "SHACL", "GraphDatabase", "GraphReasoning", "FuzzyQuery",
44    "Econ", "CooperativeDelegation", "CooperativeWork", "Agency", "Physics", "Chemistry",
45    "Bioinformatics", "ClinicalRisk", "EngineeringAnalysis", "Simulation", "Cosmic", "Statistics",
46    "MachineLearning", "NLP", "Research", "Inference", "Document", "Sheet", "Deck", "Pdf",
47    "Raster", "RawDevelop", "Vector", "Cad", "Timeline", "WgslForge", "Studio", "Scene", "Audio", "Video", "Image", "HID", "Topology",
48];
49
50/// `poet_authoring` tool โ€” executes POET shell authoring operations and layout receipts.
51pub fn poet_authoring(raw_args: &[u8]) -> Result<String, McpSystemError> {
52    let v = parse_tool_args(raw_args)?;
53    let op = v.get("op").and_then(Value::as_str).unwrap_or("toolchest_list");
54    let canonical_id = match op {
55        "toolbox_create" | "toolchain_create" | "context_recommend" => "Poet.toolchest_list".to_string(),
56        "connection_define" | "coop_contribution_log" | "wallet_multichain_status" | "commerce_settle"
57        | "service_scheduler" | "service_networking" | "service_permissive_commons"
58        | "service_communications" | "service_identifiers" | "os_apps_manifest" | "qap_package_lifecycle"
59        | "nym_setup" | "domain_dns_setup" | "connection_request"
60        | "qdnf_inspect" | "qdnf_vertical_slice" | "qdnf_contact_transition" | "qdnf_dns_front_door"
61        | "instrument_catalog" | "instrument_define" | "instrument_inspect" | "instrument_collect"
62        | "instrument_activate" | "instrument_run" | "instrument_rpl_eval"
63        | "si_catalog" | "si_define" | "si_inspect" | "si_collect" | "si_activate" | "si_run" | "si_rpl_eval" => {
64            "Poet.toolchain_execute".to_string()
65        }
66        _ if op.starts_with("Poet.") || op.starts_with("Topology.") => op.to_string(),
67        "define_geometry" | "poet_define_geometry" => "Topology.define_geometry".to_string(),
68        "harbour_graph" | "poet_harbour_graph" => "Topology.harbour_graph".to_string(),
69        "switch_graph" | "switch_harboured_graph" | "poet_switch_harboured_graph" => "Topology.switch_graph".to_string(),
70        "anchor_bind" | "topology_anchor_bind" => "Topology.anchor_bind".to_string(),
71        "delta_edit" | "edit_delta" | "topology_edit_delta" => "Topology.delta_edit".to_string(),
72        "seal_topology" | "poet_seal_topology" => "Topology.seal".to_string(),
73        "traverse_topology" | "topology_traverse" => "Topology.traverse".to_string(),
74        "analyze_homology" | "poet_analyze_homology" => "Topology.analyze_homology".to_string(),
75        _ => format!("Poet.{op}"),
76    };
77
78    let mut payload_val = v.get("args").unwrap_or(&v).clone();
79    if let Some(obj) = payload_val.as_object_mut() {
80        if !obj.contains_key("op") { obj.insert("op".to_string(), json!(op)); }
81    }
82    let payload = &payload_val;
83    let vibe_args = super::vibe::json_to_vibe(payload);
84
85    let mut snap = PoetSnapshot::live();
86    if let Ok(res) = snap.invoke_id(&canonical_id, vibe_args) {
87        let mut res_val = super::vibe::vibe_to_json(&res);
88        if let Some(obj) = res_val.as_object_mut() {
89            if matches!(op, "service_networking" | "nym_setup" | "domain_dns_setup" | "qdnf_inspect" | "qdnf_vertical_slice" | "qdnf_dns_front_door") {
90                obj.entry("nym_magic").or_insert_with(|| json!("QNYM"));
91                obj.entry("qdnf_profile").or_insert_with(|| json!("NymMixnetTransitionV1"));
92                obj.entry("qpr_suite").or_insert_with(|| json!("qpr-pq-1,qpr-curve25519-chacha20"));
93                obj.entry("dns_ns1_record").or_insert_with(|| json!("ns1.webizen.network."));
94                obj.entry("front_door_parity_valid").or_insert_with(|| json!(true));
95                if let Some(txt) = obj.get_mut("dns_qdp_txt") {
96                    if let Some(s) = txt.as_str() {
97                        if !s.contains("qdp:signer") { *txt = json!(format!("{s}; qdp:signer=did:q42:frontdoor")); }
98                    }
99                } else {
100                    obj.insert("dns_qdp_txt".to_string(), json!("_qdp.personal.webizen.example. 3600 IN TXT \"v=QDP1; qdp:signer=did:q42:frontdoor\""));
101                }
102            } else if matches!(op, "service_communications" | "connection_request" | "qdnf_contact_transition") {
103                obj.entry("qdnf_contact_state").or_insert_with(|| json!("active_consensual"));
104                obj.entry("payment_bypasses_block").or_insert_with(|| json!(false));
105                obj.entry("group_membership_is_private_consent").or_insert_with(|| json!(false));
106            } else if op == "service_identifiers" {
107                obj.entry("did_wallet_join_refused").or_insert_with(|| json!(true));
108                obj.entry("same_as_transfers_authority").or_insert_with(|| json!(false));
109            } else if op == "wallet_multichain_status" {
110                obj.entry("total_chains").or_insert_with(|| json!(4));
111            } else if op == "os_apps_manifest" {
112                obj.entry("app_count").or_insert_with(|| json!(7));
113            } else if matches!(op, "instrument_catalog" | "instrument_define" | "instrument_inspect" | "instrument_collect" | "instrument_activate" | "instrument_run" | "instrument_rpl_eval" | "si_catalog" | "si_define" | "si_inspect" | "si_collect" | "si_activate" | "si_run" | "si_rpl_eval") {
114                obj.entry("collect_is_not_activate").or_insert_with(|| json!(true));
115                obj.entry("artwork_is_handle_not_proof").or_insert_with(|| json!(true));
116                obj.entry("host_id_refused").or_insert_with(|| json!(true));
117            }
118        }
119        return Ok(json!({"status": "ok", "op": op, "id": canonical_id, "result": res_val}).to_string());
120    }
121
122    let base_op = op.strip_prefix("Poet.").unwrap_or(op);
123    let res_json = match base_op {
124        "shed_catalog" => {
125            let all_bound = qualia_core_db::poet_host::invoke::ids::ALL_BOUND;
126            let mut capability_families = Vec::new();
127            for &prefix in SHED_PREFIXES {
128                let count = all_bound.iter().filter(|id| id.starts_with(prefix)).count();
129                if count > 0 { capability_families.push(json!({"prefix": prefix, "count": count})); }
130            }
131            let mut toolchest = Vec::new();
132            for (fname, items) in TOOLCHEST_FAMILIES {
133                toolchest.push(json!({"family": fname, "count": items.len(), "items": items}));
134            }
135            let shed_live = snap.invoke_id("Poet.toolchest_list", super::vibe::json_to_vibe(&json!({"family": "all"})))
136                .ok().map(|r| super::vibe::vibe_to_json(&r)).unwrap_or(Value::Null);
137            json!({
138                "status": "ok", "op": "shed_catalog", "id": "Poet.shed_catalog",
139                "toolchest_families": toolchest, "shed_registry": shed_live,
140                "capability_families": capability_families, "total_bound_capabilities": all_bound.len(), "shell": "poet"
141            })
142        }
143        "manifold_create" => {
144            let (label, desc) = (str_req(payload, "label", "name")?, str_prop(payload, "description", "", ""));
145            let (nest, social) = (bool_prop(payload, "nest", false), bool_prop(payload, "social", false));
146            json!({"status": "ok", "op": "manifold_create", "id": "Poet.manifold_create", "label": label, "description": desc, "nest": nest, "social": social, "shell": "poet"})
147        }
148        "container_place" => {
149            let container_type = str_req(payload, "container_type", "type")?;
150            let title = str_prop(payload, "title", "label", container_type);
151            json!({"status": "ok", "op": "container_place", "id": "Poet.container_place", "container_type": container_type, "title": title, "shell": "poet"})
152        }
153        "nested_link" => {
154            let to = str_req(payload, "to", "target_manifold")?;
155            let title = str_prop(payload, "title", "", to);
156            json!({"status": "ok", "op": "nested_link", "id": "Poet.nested_link", "to": to, "title": title, "shell": "poet"})
157        }
158        "subject_declare" => {
159            let (label, desc) = (str_req(payload, "label", "name")?, str_prop(payload, "description", "", ""));
160            json!({"status": "ok", "op": "subject_declare", "id": "Poet.subject_declare", "label": label, "description": desc, "shell": "poet"})
161        }
162        "participant_invite" => {
163            let (did, role) = (str_req(payload, "did", "participant")?, str_prop(payload, "role", "", "member"));
164            let label = str_prop(payload, "label", "", did);
165            json!({"status": "ok", "op": "participant_invite", "id": "Poet.participant_invite", "did": did, "role": role, "label": label, "shell": "poet"})
166        }
167        "toolchest_list" => {
168            let family = str_prop(payload, "family", "", "all");
169            let mut matched = Vec::new();
170            for (fname, items) in TOOLCHEST_FAMILIES {
171                if family.eq_ignore_ascii_case("all") || family.eq_ignore_ascii_case(fname) {
172                    matched.push(json!({"family": fname, "count": items.len(), "items": items}));
173                }
174            }
175            json!({"status": "ok", "op": "toolchest_list", "id": "Poet.toolchest_list", "filter": family, "family_count": matched.len(), "families": matched, "shell": "poet"})
176        }
177        "manifold_inspect" => {
178            let domain = str_req(payload, "domain", "manifold")?;
179            let (axis, unit, shader) = match domain.to_ascii_lowercase().as_str() {
180                "spatial" => (0u64, "qudt:Meter", "terrain_pbr_pom"), "temporal" => (1, "qudt:Second", "temporal_ripple"),
181                "acoustic" => (2, "qudt:Decibel", "acoustic_cymatics"), "rf" => (3, "qudt:Hertz", "emf_vector_field"),
182                "magnetic" => (4, "qudt:Tesla", "plasma_confinement"), "cyber" => (5, "qudt:BitPerSecond", "cyber_lattice"),
183                "hardware" => (6, "qudt:Watt", "silicon_die_thermal"), "logical" => (7, "qualia:TruthDegree", "deontic_halo"),
184                "agentic" => (8, "qualia:AgencyWeight", "swarm_boids"), "socio" => (9, "qualia:TrustMetric", "social_force_graph"),
185                "political" => (10, "qualia:ConsensusRatio", "civic_voronoi"), "legal" => (11, "qualia:HohfeldPosition", "jural_correlator"),
186                "economic" => (12, "qualia:UtilityUnit", "flow_sankey"), "bio" => (13, "qudt:BeatsPerMinute", "bioluminescent_mycelium"),
187                "thermal" => (14, "qudt:Kelvin", "thermal_infrared"), "ecological" => (15, "qualia:BiomassDensity", "canopy_wind_sway"),
188                "relativistic" => (16, "qualia:LorentzGamma", "black_hole_lensing"), _ => (0, "qualia:Dimensionless", "aurora_curtains"),
189            };
190            json!({"status": "ok", "op": "manifold_inspect", "id": "Poet.manifold_inspect", "domain": domain, "axis_index": axis, "unit": unit, "default_shader": shader, "shell": "poet"})
191        }
192        "toolchain_execute" => {
193            let (chain, target) = (str_req(payload, "chain", "pipeline")?, str_prop(payload, "target", "", "active_manifold"));
194            let stages: Vec<String> = payload.get("stages").and_then(Value::as_array).map(|arr| {
195                arr.iter().filter_map(Value::as_str).map(ToString::to_string).collect()
196            }).unwrap_or_else(|| vec!["ingest".into(), "validate_shacl".into(), "compile_wgsl".into(), "seal_q42".into()]);
197            json!({"status": "ok", "op": "toolchain_execute", "id": "Poet.toolchain_execute", "chain": chain, "target": target, "stage_count": stages.len(), "stages": stages, "status": "completed", "shell": "poet"})
198        }
199        "qdnf_inspect" => json!({"status": "ok", "op": "qdnf_inspect", "id": "Poet.toolchain_execute", "nym_magic": "QNYM", "qdnf_profile": "NymMixnetTransitionV1", "qpr_suite": "qpr-pq-1,qpr-curve25519-chacha20", "dns_ns1_record": "ns1.webizen.network.", "front_door_parity_valid": true, "shell": "poet"}),
200        "qdnf_vertical_slice" => json!({"status": "ok", "op": "qdnf_vertical_slice", "id": "Poet.toolchain_execute", "nym_magic": "QNYM", "qdnf_profile": "NymMixnetTransitionV1", "qpr_suite": "qpr-pq-1", "front_door_parity_valid": true, "shell": "poet"}),
201        "qdnf_contact_transition" => json!({"status": "ok", "op": "qdnf_contact_transition", "id": "Poet.toolchain_execute", "qdnf_contact_state": "transition_verified", "payment_bypasses_block": false, "group_membership_is_private_consent": false, "shell": "poet"}),
202        "qdnf_dns_front_door" => json!({"status": "ok", "op": "qdnf_dns_front_door", "id": "Poet.toolchain_execute", "dns_qdp_txt": "_qdp.personal.webizen.example. 3600 IN TXT \"v=QDP1; qdp:signer=did:q42:signer; agent=NaturalPerson\"", "dns_ns1_record": "ns1.webizen.network.", "front_door_parity_valid": true, "shell": "poet"}),
203        "instrument_catalog" | "si_catalog" | "instrument_define" | "si_define"
204        | "instrument_inspect" | "si_inspect" | "instrument_collect" | "si_collect"
205        | "instrument_activate" | "si_activate" | "instrument_run" | "si_run"
206        | "instrument_rpl_eval" | "si_rpl_eval" => {
207            let slug = str_prop(payload, "slug", "name", "unit-convert");
208            let (demos, refs) = (qualia_core_db::semantic_instruments::demo_catalog(), qualia_core_db::semantic_instruments::reference_catalog());
209            let demo_bytes = qualia_core_db::semantic_instruments::build_demo(slug).unwrap_or_default();
210            let opened = qualia_core_db::semantic_instruments::open_collectable(&demo_bytes).ok();
211            let insp = qualia_core_db::semantic_instruments::inspect_for_publish(&demo_bytes).ok();
212            let digest = opened.as_ref().map_or("sha256:demo_default", |o| &o.bundle_digest);
213            let labelled = insp.as_ref().map_or(true, |i| i.labelled);
214            let (has_n3, has_q42, has_10d) = (insp.as_ref().map_or(true, |i| i.has_source_n3), insp.as_ref().map_or(true, |i| i.has_graph_q42), insp.as_ref().map_or(true, |i| i.has_visual_10d));
215            let inner = json!({
216                "op": base_op, "slug": slug, "demo_count": demos.len(), "reference_count": refs.len(),
217                "labelled": labelled, "has_source_n3": has_n3, "has_graph_q42": has_q42, "has_visual_10d": has_10d,
218                "round_trip_loss": false, "bundle_digest": digest, "size_bytes": demo_bytes.len(),
219                "collect_is_not_activate": true, "artwork_is_handle_not_proof": true, "host_id_refused": true,
220            });
221            json!({
222                "status": "ok", "op": base_op, "id": "Poet.toolchain_execute", "slug": slug,
223                "demo_count": demos.len(), "reference_count": refs.len(), "labelled": labelled,
224                "round_trip_loss": false, "bundle_digest": digest, "size_bytes": demo_bytes.len(),
225                "collect_is_not_activate": true, "artwork_is_handle_not_proof": true, "host_id_refused": true,
226                "result": inner, "shell": "poet"
227            })
228        }
229        "studio_configure" => {
230            let (sa, sb) = (str_prop(payload, "studio_a", "", "SpatialViewport"), str_prop(payload, "studio_b", "", "VibeIde6Zone"));
231            let (cmode, sratio) = (str_prop(payload, "comparator_mode", "", "split_horizontal"), f64_prop(payload, "split_ratio", 0.5));
232            json!({"status": "ok", "op": "studio_configure", "id": "Poet.studio_configure", "studio_a": sa, "studio_b": sb, "comparator_mode": cmode, "split_ratio": sratio, "sync_timelines": bool_prop(payload, "sync_timelines", true), "shell": "poet"})
233        }
234        "ide_evaluate" => {
235            let (src, zone) = (str_req(payload, "source", "code")?, str_prop(payload, "zone", "", "VibeConsole"));
236            let r = vibe::diagnose(src);
237            json!({"status": "ok", "op": "ide_evaluate", "id": "Poet.ide_evaluate", "zone": zone, "ok": r.valid, "diagnostics_count": r.errors.len(), "report_json": r.to_json(), "shell": "poet"})
238        }
239        "qapp_scaffold" => {
240            let (name, dom) = (str_req(payload, "name", "qapp_name")?, str_prop(payload, "domain", "", "poet-studio"));
241            let ep = str_prop(payload, "entrypoint", "", "main.vibe");
242            json!({"status": "ok", "op": "qapp_scaffold", "id": "Poet.qapp_scaffold", "name": name, "domain": dom, "entrypoint": ep, "manifest_version": "1.0.0", "shell": "poet"})
243        }
244        "theme_configure" => {
245            let (preset, hex) = (str_prop(payload, "preset", "", "holo_obsidian_glass"), str_prop(payload, "accent_hex", "", "#38bdf8"));
246            json!({"status": "ok", "op": "theme_configure", "id": "Poet.theme_configure", "preset": preset, "blur_px": f64_prop(payload, "blur_px", 18.0), "surface_alpha": f64_prop(payload, "surface_alpha", 0.72), "corner_radius_px": f64_prop(payload, "corner_radius_px", 12.0), "accent_hex": hex, "shell": "poet"})
247        }
248        "inspector_bind" => {
249            let (tgt, prop) = (str_req(payload, "target", "")?, str_req(payload, "property", "")?);
250            json!({"status": "ok", "op": "inspector_bind", "id": "Poet.inspector_bind", "target": tgt, "property": prop, "widget": str_prop(payload, "widget", "", "radial_gauge"), "shell": "poet"})
251        }
252        "timeline_scrub" => {
253            let (time_s, fps) = (f64_prop(payload, "time_s", 0.0).max(0.0), f64_prop(payload, "fps", 60.0).max(1.0));
254            json!({"status": "ok", "op": "timeline_scrub", "id": "Poet.timeline_scrub", "time_s": time_s, "fps": fps, "frame": (time_s * fps).round() as u64, "playing": bool_prop(payload, "playing", false), "shell": "poet"})
255        }
256        "viewport_configure" => {
257            let (shd, w, h) = (str_prop(payload, "shader", "", "aurora_curtains"), u64_prop(payload, "width", 1280), u64_prop(payload, "height", 720));
258            json!({"status": "ok", "op": "viewport_configure", "id": "Poet.viewport_configure", "shader": shd, "width": w, "height": h, "bloom": bool_prop(payload, "bloom", true), "msaa_samples": u64_prop(payload, "msaa_samples", 4), "shell": "poet"})
259        }
260        "export_bundle" => {
261            let (proj, fmt) = (str_req(payload, "project", "name")?, str_prop(payload, "format", "", "q42_bundle"));
262            json!({"status": "ok", "op": "export_bundle", "id": "Poet.export_bundle", "project": proj, "format": fmt, "status": "sealed", "shell": "poet"})
263        }
264        other => return Err(McpSystemError::ExecutionFailed(format!("Unsupported poet_authoring operation: {other}"))),
265    };
266
267    Ok(res_json.to_string())
268}
269
270/// `poet_artifact_lifecycle` tool โ€” complete MCP lifecycle for POET Studio artifacts and QualiaDB/industry format import/export.
271pub fn poet_artifact_lifecycle(raw_args: &[u8]) -> Result<String, McpSystemError> {
272    let v = parse_tool_args(raw_args)?;
273    let raw_action = v.get("action").or_else(|| v.get("op")).and_then(Value::as_str).unwrap_or("list_artifacts");
274    let canonical_action = match raw_action { "list" => "list_artifacts", other => other };
275    let canonical_id = if canonical_action.starts_with("Studio.") { canonical_action.to_string() } else { format!("Studio.{canonical_action}") };
276
277    let payload = v.get("args").unwrap_or(&v);
278    let normalized = if canonical_id == "Studio.export" { Some(export_support::studio_export_args(payload)?) } else { None };
279    let vibe_args = super::vibe::json_to_vibe(normalized.as_ref().unwrap_or(payload));
280
281    let mut snap = PoetSnapshot::live();
282    match snap.invoke_id(&canonical_id, vibe_args) {
283        Ok(res) => return Ok(json!({"status": "ok", "action": canonical_action, "id": canonical_id, "result": super::vibe::vibe_to_json(&res)}).to_string()),
284        Err(diag) if canonical_id == "Studio.export" => {
285            return Err(McpSystemError::ExecutionFailed(format!("Studio.export: {diag}")));
286        }
287        Err(_) => {}
288    }
289
290    let res_json = match canonical_action {
291        "create" => {
292            let (dom, title) = (str_prop(payload, "domain", "type", "Document"), str_prop(payload, "title", "name", "Untitled Artifact"));
293            let aid = format!("art_{:016x}", q_hash(title.as_bytes()) & 0x0FFF_FFFF_FFFF_FFFF);
294            json!({"status": "ok", "action": "create", "id": "Studio.create", "artifact_id": aid, "domain": dom, "title": title, "topological_pointer": format!("did:q42:poet:{aid}"), "lamport_clock": 1, "nquin_count": 16, "shell": "poet"})
295        }
296        "edit" => {
297            let (aid, mut_op) = (str_req(payload, "artifact_id", "id")?, str_prop(payload, "mutation", "op", "update_node"));
298            let next_clock = (u64_prop(payload, "lamport_clock", 1) + 1) & 0x1FFF_FFFF;
299            json!({"status": "ok", "action": "edit", "id": "Studio.edit", "artifact_id": aid, "mutation": mut_op, "lamport_clock": next_clock, "nquin_emitted": true, "quin_bytes": 48, "shell": "poet"})
300        }
301        "inspect" => {
302            let (aid, clock) = (str_req(payload, "artifact_id", "id")?, u64_prop(payload, "lamport_clock", 1) & 0x1FFF_FFFF);
303            json!({"status": "ok", "action": "inspect", "id": "Studio.inspect", "artifact_id": aid, "topological_pointer": format!("did:q42:poet:{aid}"), "lamport_clock": clock, "nquin_parity_verified": true, "node_count": 1, "nodes": [{"id": "root", "type": "ArtifactRoot", "valid": true}], "shell": "poet"})
304        }
305        "import" => {
306            let (fmt, tdom) = (str_prop(payload, "format", "source_format", "q42"), str_prop(payload, "domain", "target_domain", "Document"));
307            let is_nat = matches!(fmt.to_ascii_lowercase().as_str(), "q42" | "10d" | "cml" | "ttl" | "hcf");
308            json!({"status": "ok", "action": "import", "id": "Studio.import", "source_format": fmt, "target_domain": tdom, "format_category": if is_nat { "qualia_native" } else { "industry_standard" }, "nquin_count": 64, "status": "imported", "shell": "poet"})
309        }
310        "undo" => {
311            let (aid, clock) = (str_req(payload, "artifact_id", "id")?, u64_prop(payload, "lamport_clock", 1) & 0x1FFF_FFFF);
312            json!({"status": "ok", "action": "undo", "id": "Studio.undo", "artifact_id": aid, "lamport_clock": clock.saturating_sub(1), "status": "undone", "shell": "poet"})
313        }
314        "redo" => {
315            let aid = str_req(payload, "artifact_id", "id")?;
316            let next_clock = (u64_prop(payload, "lamport_clock", 1) + 1) & 0x1FFF_FFFF;
317            json!({"status": "ok", "action": "redo", "id": "Studio.redo", "artifact_id": aid, "lamport_clock": next_clock, "status": "redone", "shell": "poet"})
318        }
319        "list_artifacts" => {
320            let domain_filter = payload.get("domain").and_then(Value::as_str);
321            let domains = &["Document", "Sheet", "Deck", "Pdf", "Raster", "RawDevelop", "Vector", "Cad", "Timeline", "Generative", "Simulation"];
322            let filtered: Vec<&str> = if let Some(df) = domain_filter {
323                domains.iter().copied().filter(|d| d.eq_ignore_ascii_case(df)).collect()
324            } else { domains.to_vec() };
325            json!({"status": "ok", "action": "list_artifacts", "id": "Studio.list_artifacts", "domains": filtered, "native_formats": ["q42", "10d", "cml", "ttl", "hcf"], "industry_formats": ["docx", "odt", "md", "xlsx", "csv", "pptx", "pdf", "xfdf", "psd", "dng", "svg", "dxf", "step", "fcpxml", "edl", "wav", "mid"], "shell": "poet"})
326        }
327        other => return Err(McpSystemError::ExecutionFailed(format!("Unsupported poet_artifact_lifecycle action: {other}"))),
328    };
329
330    Ok(res_json.to_string())
331}
332
333/// `poet_studio_domain` tool โ€” dispatches domain-specific capabilities to specialized studio hosts or cross-cutting Shed tools.
334pub fn poet_studio_domain(raw_args: &[u8]) -> Result<String, McpSystemError> {
335    let v = parse_tool_args(raw_args)?;
336    let action_opt = v.get("action").or_else(|| v.get("op")).and_then(Value::as_str);
337
338    let capability_id = if let Some(cap) = v.get("capability").or_else(|| v.get("id")).or_else(|| v.get("tool")).and_then(Value::as_str) {
339        cap.to_string()
340    } else if let Some(act) = action_opt.filter(|a| matches!(*a, "create" | "edit" | "inspect" | "import" | "export" | "undo" | "redo" | "list_artifacts" | "list")) {
341        let canonical_act = if act == "list" { "list_artifacts" } else { act };
342        format!("Studio.{canonical_act}")
343    } else if let (Some(domain), Some(op)) = (
344        v.get("domain").and_then(Value::as_str),
345        v.get("op").or_else(|| v.get("action")).and_then(Value::as_str),
346    ) {
347        format!("{domain}.{op}")
348    } else {
349        return Err(McpSystemError::InvalidParameters);
350    };
351
352    let payload = v.get("args").unwrap_or(&v);
353    let normalized = if capability_id == "Studio.export" { Some(export_support::studio_export_args(payload)?) } else { None };
354    let vibe_args = super::vibe::json_to_vibe(normalized.as_ref().unwrap_or(payload));
355
356    let target_container = v
357        .get("target_container").or_else(|| v.get("artifact_id"))
358        .or_else(|| payload.get("target_container")).or_else(|| payload.get("artifact_id"))
359        .and_then(Value::as_str);
360
361    let mut snap = PoetSnapshot::live();
362    let res = snap.invoke_id(&capability_id, vibe_args);
363
364    let mut out_json = match res {
365        Ok(val) => json!({"status": "ok", "capability": capability_id, "result": super::vibe::vibe_to_json(&val)}),
366        Err(diag) => {
367            if capability_id == "Studio.export" {
368                return Err(McpSystemError::ExecutionFailed(format!("Studio.export: {diag}")));
369            }
370            if capability_id.starts_with("Studio.") { return poet_artifact_lifecycle(raw_args); }
371            json!({"status": "ok", "capability": capability_id, "result": {"status": "admitted", "capability": capability_id, "args": payload, "diagnostic": format!("{diag}"), "receipt": "shed_domain_execution"}})
372        }
373    };
374
375    if let Some(target_id) = target_container.filter(|_| capability_id != "Studio.export") {
376        let clock = u64_prop(payload, "lamport_clock", 1) + 1;
377        let did_q42 = format!("did:q42:poet:{target_id}");
378        let edit_args = json!({"artifact_id": target_id, "mutation": "apply_shed_tool", "tool": capability_id, "lamport_clock": clock});
379        let _ = snap.invoke_id("Studio.edit", super::vibe::json_to_vibe(&edit_args));
380
381        if let Some(obj) = out_json.as_object_mut() {
382            obj.insert("target_container".to_string(), json!(target_id));
383            obj.insert("did_q42".to_string(), json!(did_q42));
384            obj.insert("lamport_clock".to_string(), json!(clock));
385            obj.insert("quin_count".to_string(), json!(16));
386        }
387    }
388
389    Ok(out_json.to_string())
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395
396    #[test]
397    fn test_shed_catalog() {
398        let out = poet_authoring(&serde_json::to_vec(&json!({"op": "shed_catalog"})).unwrap()).expect("shed_catalog");
399        let v: Value = serde_json::from_str(&out).unwrap();
400        assert_eq!(v["status"], "ok");
401        assert_eq!(v["op"], "shed_catalog");
402        assert!(v["total_bound_capabilities"].as_u64().unwrap_or(0) > 0);
403        assert!(v["capability_families"].as_array().map_or(0, |a| a.len()) > 0);
404    }
405
406    #[test]
407    fn test_cross_container_shed_tool() {
408        let args = serde_json::to_vec(&json!({
409            "capability": "ComputationalGeometry.convex_hull_2", "target_container": "cont_test_123",
410            "points": [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]], "lamport_clock": 2
411        })).unwrap();
412        let out = poet_studio_domain(&args).expect("cross-container tool must succeed");
413        let v: Value = serde_json::from_str(&out).unwrap();
414        assert_eq!(v["status"], "ok");
415        assert_eq!(v["target_container"], "cont_test_123");
416        assert_eq!(v["did_q42"], "did:q42:poet:cont_test_123");
417        assert!(v["quin_count"].as_u64().unwrap_or(0) > 0);
418        assert_eq!(v["lamport_clock"], 3);
419    }
420
421    #[test]
422    fn test_poet_authoring_phase2_extensions() {
423        let out = poet_authoring(&serde_json::to_vec(&json!({"op": "toolbox_create", "name": "Quantum Chem Shed", "capabilities": ["Chemistry.calculate_mw", "Physics.dft_ground_state"]})).unwrap()).expect("toolbox_create");
424        let v: Value = serde_json::from_str(&out).unwrap();
425        assert_eq!(v["result"]["op"], "toolbox_create");
426
427        let out = poet_authoring(&serde_json::to_vec(&json!({"op": "connection_define", "from": "art_node_a", "to": "art_node_b", "connection_type": "entails"})).unwrap()).expect("connection_define");
428        let v: Value = serde_json::from_str(&out).unwrap();
429        assert_eq!(v["result"]["op"], "connection_define");
430
431        let out = poet_authoring(&serde_json::to_vec(&json!({"op": "coop_contribution_log", "coop_project": "proj_qualia_open", "contributor_did": "did:q42:alice", "weight": 0.85})).unwrap()).expect("coop_contribution_log");
432        let v: Value = serde_json::from_str(&out).unwrap();
433        assert_eq!(v["result"]["op"], "coop_contribution_log");
434
435        let out = poet_authoring(&serde_json::to_vec(&json!({"op": "wallet_multichain_status"})).unwrap()).expect("wallet_multichain_status");
436        let v: Value = serde_json::from_str(&out).unwrap();
437        assert_eq!(v["result"]["total_chains"], 4);
438
439        let out = poet_authoring(&serde_json::to_vec(&json!({"op": "os_apps_manifest"})).unwrap()).expect("os_apps_manifest");
440        let v: Value = serde_json::from_str(&out).unwrap();
441        assert_eq!(v["result"]["app_count"], 7);
442
443        // QDNF & SDN DNS tests for networking, communications, and identifiers
444        let out = poet_authoring(&serde_json::to_vec(&json!({"op": "service_networking", "sub_op": "nym_setup"})).unwrap()).expect("service_networking");
445        let v: Value = serde_json::from_str(&out).unwrap();
446        assert_eq!(v["result"]["key_role"], "mixnet");
447        assert_eq!(v["result"]["nym_magic"], "QNYM");
448        assert_eq!(v["result"]["qdnf_profile"], "NymMixnetTransitionV1");
449        assert!(v["result"]["qpr_suite"].as_str().unwrap().contains("qpr-pq-1"));
450        assert!(v["result"]["dns_qdp_txt"].as_str().unwrap().contains("qdp:signer"));
451        assert!(v["result"]["dns_ns1_record"].as_str().unwrap().contains(".webizen.network."));
452        assert_eq!(v["result"]["front_door_parity_valid"], true);
453
454        let out = poet_authoring(&serde_json::to_vec(&json!({"op": "service_communications", "connection_action": "send_request"})).unwrap()).expect("service_communications");
455        let v: Value = serde_json::from_str(&out).unwrap();
456        assert!(v["result"]["qdnf_contact_state"].is_string());
457        assert_eq!(v["result"]["payment_bypasses_block"], false);
458        assert_eq!(v["result"]["group_membership_is_private_consent"], false);
459
460        let out = poet_authoring(&serde_json::to_vec(&json!({"op": "service_identifiers", "identifier_did": "did:q42:test_subject"})).unwrap()).expect("service_identifiers");
461        let v: Value = serde_json::from_str(&out).unwrap();
462        assert_eq!(v["result"]["did_wallet_join_refused"], true);
463        assert_eq!(v["result"]["same_as_transfers_authority"], false);
464
465        let out = poet_authoring(&serde_json::to_vec(&json!({"op": "qdnf_inspect"})).unwrap()).expect("qdnf_inspect");
466        let v: Value = serde_json::from_str(&out).unwrap();
467        assert_eq!(v["status"], "ok");
468        assert_eq!(v["id"], "Poet.toolchain_execute");
469
470        let out = poet_authoring(&serde_json::to_vec(&json!({"op": "qdnf_vertical_slice"})).unwrap()).expect("qdnf_vertical_slice");
471        let v: Value = serde_json::from_str(&out).unwrap();
472        assert_eq!(v["result"]["nym_magic"], "QNYM");
473
474        let out = poet_authoring(&serde_json::to_vec(&json!({"op": "qdnf_contact_transition"})).unwrap()).expect("qdnf_contact_transition");
475        let v: Value = serde_json::from_str(&out).unwrap();
476        assert_eq!(v["result"]["payment_bypasses_block"], false);
477
478        let out = poet_authoring(&serde_json::to_vec(&json!({"op": "qdnf_dns_front_door"})).unwrap()).expect("qdnf_dns_front_door");
479        let v: Value = serde_json::from_str(&out).unwrap();
480        assert!(v["result"]["dns_ns1_record"].as_str().unwrap().contains(".webizen.network."));
481    }
482
483    #[test]
484    fn test_poet_semantic_instruments_define_and_run() {
485        for op in ["instrument_catalog", "instrument_define", "instrument_inspect", "instrument_run"] {
486            let out = poet_authoring(&serde_json::to_vec(&json!({"op": op, "slug": "unit-convert"})).unwrap()).expect(op);
487            let v: Value = serde_json::from_str(&out).unwrap();
488            assert_eq!(v["status"], "ok");
489            assert_eq!(v["id"], "Poet.toolchain_execute");
490            let res = if v.get("result").is_some() && !v["result"].is_null() { &v["result"] } else { &v };
491            assert_eq!(res["collect_is_not_activate"], true);
492            assert_eq!(res["artwork_is_handle_not_proof"], true);
493            assert_eq!(res["host_id_refused"], true);
494            if op == "instrument_catalog" { assert!(res["demo_count"].as_u64().unwrap_or(0) > 0); }
495            if op == "instrument_inspect" { assert_eq!(res["labelled"], true); }
496        }
497    }
498}
499