robloxstudio-worktree 0.1.0

Own an isolated Rojo, Roblox Studio, and MCP runtime for each Git worktree
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result, bail};
use fs2::FileExt;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use sha2::{Digest, Sha256};
use uuid::Uuid;

use crate::config::{ProjectConfig, ServeMode};
use crate::mcp::McpClient;

const SCHEMA_VERSION: u32 = 2;
const ROJO_PORT_MIN: u16 = 40_000;
const ROJO_PORT_COUNT: u16 = 10_000;

#[derive(Clone, Debug)]
pub struct GeneratedPaths {
    pub state: PathBuf,
    pub lock: PathBuf,
    pub build_project: PathBuf,
    pub serve_project: PathBuf,
    pub artifact: PathBuf,
    pub rojo_log: PathBuf,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct SessionState {
    pub schema_version: Option<u32>,
    pub worktree_id: Option<String>,
    pub worktree_root: Option<String>,
    pub updated_at: Option<f64>,
    pub session_token: Option<String>,
    pub port: Option<u16>,
    pub project_name: Option<String>,
    pub project_source_digest: Option<String>,
    pub artifact_digest: Option<String>,
    pub artifact_built_at: Option<f64>,
    pub rojo_pid: Option<u32>,
    pub rojo_birth: Option<String>,
    pub rojo_start_ticks: Option<u64>,
    pub rojo_started_at: Option<f64>,
    pub instance_id: Option<String>,
    pub studio_started_at: Option<f64>,
    pub studio_process_pid: Option<u32>,
    pub studio_process_started: Option<u64>,
    pub validated_at: Option<f64>,
    pub manifest_verified_at: Option<f64>,
}

pub struct OperationLock(File);

impl Drop for OperationLock {
    fn drop(&mut self) {
        let _ = FileExt::unlock(&self.0);
    }
}

pub struct StudioSession {
    pub config: ProjectConfig,
    pub mcp: McpClient,
    pub paths: GeneratedPaths,
}

fn now() -> f64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs_f64()
}

pub fn worktree_identity(root: &Path) -> String {
    let resolved = root.to_string_lossy();
    let raw = root
        .file_name()
        .and_then(|value| value.to_str())
        .unwrap_or("worktree")
        .to_lowercase();
    let mut readable = String::new();
    let mut separating = false;
    for character in raw.chars() {
        if character.is_ascii_alphanumeric() || character == '_' || character == '-' {
            readable.push(character);
            separating = false;
        } else if !separating && !readable.is_empty() {
            readable.push('-');
            separating = true;
        }
    }
    let readable = readable.trim_matches('-');
    let readable = if readable.is_empty() {
        "worktree"
    } else {
        readable
    };
    let digest = Sha256::digest(resolved.as_bytes());
    format!("{readable}-{:x}", digest)[..readable.len() + 11].to_owned()
}

fn sha256(path: &Path) -> Result<String> {
    let mut file =
        File::open(path).with_context(|| format!("Could not open {}", path.display()))?;
    let mut digest = Sha256::new();
    std::io::copy(&mut file, &mut digest)
        .with_context(|| format!("Could not hash {}", path.display()))?;
    Ok(format!("{:x}", digest.finalize()))
}

fn replace_file(temporary: &Path, target: &Path) -> Result<()> {
    #[cfg(windows)]
    if target.exists() {
        fs::remove_file(target)
            .with_context(|| format!("Could not replace {}", target.display()))?;
    }
    fs::rename(temporary, target).with_context(|| {
        format!(
            "Could not move {} to {}",
            temporary.display(),
            target.display()
        )
    })
}

fn atomic_json<T: Serialize>(path: &Path, value: &T) -> Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("Could not create {}", parent.display()))?;
    }
    let temporary = path.with_extension(format!(
        "{}.next",
        path.extension()
            .and_then(|value| value.to_str())
            .unwrap_or("json")
    ));
    let mut bytes = serde_json::to_vec_pretty(value).context("Could not encode JSON")?;
    bytes.push(b'\n');
    fs::write(&temporary, bytes)
        .with_context(|| format!("Could not write {}", temporary.display()))?;
    replace_file(&temporary, path)
}

fn rebase_project_paths(value: &mut Value, project_dir: &Path, generated_dir: &Path) {
    match value {
        Value::Array(values) => {
            for value in values {
                rebase_project_paths(value, project_dir, generated_dir);
            }
        }
        Value::Object(object) => {
            if let Some(Value::String(path)) = object.get_mut("$path") {
                let original = Path::new(path);
                if !original.is_absolute() {
                    if let Some(relative) =
                        pathdiff::diff_paths(project_dir.join(original), generated_dir)
                    {
                        *path = relative.to_string_lossy().into_owned();
                    }
                }
            }
            for (key, value) in object.iter_mut() {
                if key != "$path" {
                    rebase_project_paths(value, project_dir, generated_dir);
                }
            }
        }
        _ => {}
    }
}

fn is_port_free(port: u16) -> bool {
    TcpListener::bind(("127.0.0.1", port)).is_ok()
}

pub fn choose_port(identity: &str, unavailable: &BTreeSet<u16>) -> Result<u16> {
    let digest = Sha256::digest(identity.as_bytes());
    let seed = u32::from_be_bytes([digest[0], digest[1], digest[2], digest[3]]);
    let start = ROJO_PORT_MIN + (seed % u32::from(ROJO_PORT_COUNT)) as u16;
    for offset in 0..ROJO_PORT_COUNT {
        let port = ROJO_PORT_MIN + ((start - ROJO_PORT_MIN + offset) % ROJO_PORT_COUNT);
        if !unavailable.contains(&port) && is_port_free(port) {
            return Ok(port);
        }
    }
    bail!("No free loopback port is available for this worktree's Rojo server")
}

impl StudioSession {
    pub fn new(config: ProjectConfig, mcp: McpClient) -> Self {
        let state_dir = &config.state_dir;
        Self {
            paths: GeneratedPaths {
                state: state_dir.join("session.json"),
                lock: state_dir.join("operation.lock"),
                build_project: state_dir.join("build.project.json"),
                serve_project: state_dir.join("serve.project.json"),
                artifact: state_dir.join("place.rbxl"),
                rojo_log: state_dir.join("rojo.log"),
            },
            config,
            mcp,
        }
    }

    pub fn identity(&self) -> String {
        worktree_identity(&self.config.root)
    }

    pub fn project_name(&self) -> String {
        format!("{}@{}", self.config.project_name, self.identity())
    }

    pub fn operation_lock(&self) -> Result<OperationLock> {
        fs::create_dir_all(&self.config.state_dir)
            .with_context(|| format!("Could not create {}", self.config.state_dir.display()))?;
        let file = OpenOptions::new()
            .create(true)
            .read(true)
            .write(true)
            .truncate(false)
            .open(&self.paths.lock)
            .with_context(|| format!("Could not open {}", self.paths.lock.display()))?;
        file.lock_exclusive()
            .with_context(|| format!("Could not lock {}", self.paths.lock.display()))?;
        Ok(OperationLock(file))
    }

    pub fn load_state(&self) -> Result<SessionState> {
        let bytes = match fs::read(&self.paths.state) {
            Ok(bytes) => bytes,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                return Ok(SessionState::default());
            }
            Err(error) => {
                return Err(error)
                    .with_context(|| format!("Could not read {}", self.paths.state.display()));
            }
        };
        serde_json::from_slice(&bytes)
            .with_context(|| format!("Invalid session state in {}", self.paths.state.display()))
    }

    pub fn save_state(&self, state: &mut SessionState) -> Result<()> {
        state.schema_version = Some(SCHEMA_VERSION);
        state.worktree_id = Some(self.identity());
        state.worktree_root = Some(self.config.root.to_string_lossy().into_owned());
        state.updated_at = Some(now());
        atomic_json(&self.paths.state, state)
    }

    fn ensure_session_token(state: &mut SessionState) -> String {
        match state
            .session_token
            .clone()
            .filter(|value| !value.is_empty())
        {
            Some(token) => token,
            None => {
                let token = Uuid::new_v4().simple().to_string();
                state.session_token = Some(token.clone());
                token
            }
        }
    }

    fn contract_attributes(&self, port: u16, session_token: &str) -> BTreeMap<String, String> {
        BTreeMap::from([
            (
                self.config.contract.endpoint_attribute.clone(),
                format!("http://127.0.0.1:{port}"),
            ),
            (
                self.config.contract.project_attribute.clone(),
                self.project_name(),
            ),
            (
                self.config.contract.session_attribute.clone(),
                session_token.to_owned(),
            ),
            (
                self.config.contract.identity_attribute.clone(),
                self.identity(),
            ),
        ])
    }

    pub fn generate_projects(
        &self,
        port: u16,
        session_token: &str,
    ) -> Result<(Value, Value, String)> {
        let bytes = fs::read(&self.config.project_path)
            .with_context(|| format!("Could not read {}", self.config.project_path.display()))?;
        let mut build: Value = serde_json::from_slice(&bytes).with_context(|| {
            format!(
                "Invalid Rojo project {}",
                self.config.project_path.display()
            )
        })?;
        rebase_project_paths(
            &mut build,
            self.config
                .project_path
                .parent()
                .context("Rojo project path has no parent")?,
            &self.config.state_dir,
        );
        let build_object = build
            .as_object_mut()
            .context("Rojo project root must be an object")?;
        build_object.insert("name".into(), Value::String(self.project_name()));
        let tree = build_object
            .get_mut("tree")
            .and_then(Value::as_object_mut)
            .context("Rojo project must define tree")?;
        let workspace = tree
            .get_mut("Workspace")
            .and_then(Value::as_object_mut)
            .context("Rojo project must define tree.Workspace")?;
        let attributes = workspace
            .entry("$attributes")
            .or_insert_with(|| Value::Object(Map::new()))
            .as_object_mut()
            .context("tree.Workspace.$attributes must be an object")?;
        for (name, value) in self.contract_attributes(port, session_token) {
            attributes.insert(name, Value::String(value));
        }

        let mut serve = build.clone();
        if self.config.serve.mode == ServeMode::SourceOverlay {
            let serve_tree = serve
                .get_mut("tree")
                .and_then(Value::as_object_mut)
                .expect("validated tree");
            serve_tree.insert("$ignoreUnknownInstances".into(), Value::Bool(true));
            for (service_name, children) in &self.config.serve.preserve {
                let service = serve_tree
                    .get_mut(service_name)
                    .and_then(Value::as_object_mut)
                    .with_context(|| format!("Rojo project must define tree.{service_name}"))?;
                for child in children {
                    service.remove(child);
                }
                service.insert("$ignoreUnknownInstances".into(), Value::Bool(true));
            }
            for service in serve_tree.values_mut() {
                if let Some(service) = service.as_object_mut() {
                    if service.contains_key("$className") {
                        service
                            .entry("$ignoreUnknownInstances")
                            .or_insert(Value::Bool(true));
                    }
                }
            }
        }
        atomic_json(&self.paths.build_project, &build)?;
        atomic_json(&self.paths.serve_project, &serve)?;
        Ok((build, serve, self.project_name()))
    }

    pub fn expand_command(
        &self,
        template: &[String],
        instance_id: Option<&str>,
        extra_args: &[String],
    ) -> Result<Vec<String>> {
        let values = BTreeMap::from([
            ("root", self.config.root.to_string_lossy().into_owned()),
            (
                "project",
                self.config.project_path.to_string_lossy().into_owned(),
            ),
            (
                "state_dir",
                self.config.state_dir.to_string_lossy().into_owned(),
            ),
            (
                "artifact",
                self.paths.artifact.to_string_lossy().into_owned(),
            ),
            ("instance_id", instance_id.unwrap_or_default().to_owned()),
            ("mcp_url", self.mcp.base_url().to_owned()),
            ("worktree_id", self.identity()),
        ]);
        let mut command = Vec::new();
        let mut used_args = false;
        for token in template {
            if token == "{args}" {
                command.extend(extra_args.iter().cloned());
                used_args = true;
                continue;
            }
            let mut expanded = token.clone();
            for (name, value) in &values {
                expanded = expanded.replace(&format!("{{{name}}}"), value);
            }
            if let Some(start) = expanded.find('{') {
                if expanded[start..].contains('}') {
                    bail!("Unknown command placeholder in {token:?}");
                }
            }
            command.push(expanded);
        }
        if !used_args {
            command.extend(extra_args.iter().cloned());
        }
        Ok(command)
    }

    fn run_checked(&self, command: &[String]) -> Result<()> {
        let (program, args) = command.split_first().context("Command must not be empty")?;
        let status = Command::new(program)
            .args(args)
            .current_dir(&self.config.root)
            .status()
            .with_context(|| format!("Required command is not installed: {program}"))?;
        if !status.success() {
            bail!(
                "Command failed with exit code {}: {}",
                status.code().unwrap_or(-1),
                command.join(" ")
            );
        }
        Ok(())
    }

    pub fn build_artifact(&self, state: &mut SessionState, port: u16) -> Result<()> {
        let token = Self::ensure_session_token(state);
        self.generate_projects(port, &token)?;
        let temporary = self.paths.artifact.with_extension("next.rbxl");
        if temporary.exists() {
            fs::remove_file(&temporary)
                .with_context(|| format!("Could not remove {}", temporary.display()))?;
        }
        self.run_checked(&[
            "rojo".into(),
            "build".into(),
            self.paths.build_project.to_string_lossy().into_owned(),
            "-o".into(),
            temporary.to_string_lossy().into_owned(),
        ])?;
        replace_file(&temporary, &self.paths.artifact)?;
        state.port = Some(port);
        state.project_name = Some(self.project_name());
        state.project_source_digest = Some(sha256(&self.config.project_path)?);
        state.artifact_digest = Some(sha256(&self.paths.artifact)?);
        state.artifact_built_at = Some(now());
        self.save_state(state)
    }
}

fn process_birth(pid: u32) -> Option<String> {
    if let Ok(stat) = fs::read_to_string(format!("/proc/{pid}/stat")) {
        let fields: Vec<_> = stat.split_whitespace().collect();
        if let Some(start) = fields.get(21) {
            return Some(format!("proc:{start}"));
        }
    }
    #[cfg(windows)]
    {
        let script = format!(
            "$p = Get-CimInstance Win32_Process -Filter \"ProcessId = {pid}\" -ErrorAction SilentlyContinue; \
             if ($p) {{ $p.CreationDate.ToUniversalTime().ToFileTimeUtc() }}"
        );
        let output = Command::new("powershell.exe")
            .args(["-NoProfile", "-Command", &script])
            .output()
            .ok()?;
        let value = String::from_utf8_lossy(&output.stdout).trim().to_owned();
        return (!value.is_empty()).then(|| format!("win:{value}"));
    }
    #[cfg(not(windows))]
    {
        let output = Command::new("ps")
            .args(["-o", "lstart=", "-p", &pid.to_string()])
            .output()
            .ok()?;
        let value = String::from_utf8_lossy(&output.stdout).trim().to_owned();
        (!value.is_empty()).then(|| format!("ps:{value}"))
    }
}

fn process_command(pid: u32) -> String {
    if let Ok(bytes) = fs::read(format!("/proc/{pid}/cmdline")) {
        return String::from_utf8_lossy(&bytes).replace('\0', " ");
    }
    #[cfg(windows)]
    {
        let script = format!(
            "$p = Get-CimInstance Win32_Process -Filter \"ProcessId = {pid}\" -ErrorAction SilentlyContinue; \
             if ($p) {{ $p.CommandLine }}"
        );
        return Command::new("powershell.exe")
            .args(["-NoProfile", "-Command", &script])
            .output()
            .ok()
            .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
            .unwrap_or_default();
    }
    #[cfg(not(windows))]
    {
        Command::new("ps")
            .args(["-o", "command=", "-p", &pid.to_string()])
            .output()
            .ok()
            .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
            .unwrap_or_default()
    }
}

impl StudioSession {
    fn owns_rojo_process(&self, state: &SessionState) -> bool {
        let Some(pid) = state.rojo_pid else {
            return false;
        };
        let birth = state
            .rojo_birth
            .clone()
            .or_else(|| state.rojo_start_ticks.map(|ticks| format!("proc:{ticks}")));
        let Some(birth) = birth else {
            return false;
        };
        if process_birth(pid).as_deref() != Some(&birth) {
            return false;
        }
        let command = process_command(pid);
        command.contains("rojo")
            && command.contains("serve")
            && command.contains(&self.paths.serve_project.to_string_lossy().to_string())
    }

    fn wait_for_port(&self, port: u16, child: &mut std::process::Child) -> Result<()> {
        let deadline = Instant::now() + Duration::from_secs(15);
        while Instant::now() < deadline {
            if let Some(status) = child.try_wait().context("Could not poll Rojo process")? {
                bail!(
                    "Rojo server exited with {}; see {}",
                    status.code().unwrap_or(-1),
                    self.paths.rojo_log.display()
                );
            }
            if TcpStream::connect_timeout(
                &(std::net::Ipv4Addr::LOCALHOST, port).into(),
                Duration::from_millis(200),
            )
            .is_ok()
            {
                return Ok(());
            }
            thread::sleep(Duration::from_millis(100));
        }
        bail!(
            "Rojo server did not listen on port {port}; see {}",
            self.paths.rojo_log.display()
        )
    }

    fn start_rojo(&self, state: &mut SessionState) -> Result<()> {
        if self.owns_rojo_process(state) {
            return Ok(());
        }
        let port = match state.port {
            Some(port) if is_port_free(port) => {
                let token = Self::ensure_session_token(state);
                self.generate_projects(port, &token)?;
                state.project_name = Some(self.project_name());
                port
            }
            _ => {
                let port = choose_port(&self.identity(), &BTreeSet::new())?;
                self.build_artifact(state, port)?;
                port
            }
        };
        fs::create_dir_all(&self.config.state_dir)
            .with_context(|| format!("Could not create {}", self.config.state_dir.display()))?;
        let log = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.paths.rojo_log)
            .with_context(|| format!("Could not open {}", self.paths.rojo_log.display()))?;
        let error_log = log.try_clone().context("Could not clone Rojo log handle")?;
        let mut command = Command::new("rojo");
        command
            .args([
                "serve",
                &self.paths.serve_project.to_string_lossy(),
                "--port",
                &port.to_string(),
                "--color",
                "never",
            ])
            .current_dir(&self.config.root)
            .stdin(Stdio::null())
            .stdout(Stdio::from(log))
            .stderr(Stdio::from(error_log));
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt;
            command.process_group(0);
        }
        #[cfg(windows)]
        {
            use std::os::windows::process::CommandExt;
            command.creation_flags(0x0000_0200);
        }
        let mut child = command
            .spawn()
            .context("Required command is not installed: rojo")?;
        self.wait_for_port(port, &mut child)?;
        state.rojo_pid = Some(child.id());
        state.rojo_birth = process_birth(child.id());
        state.rojo_start_ticks = None;
        state.rojo_started_at = Some(now());
        self.save_state(state)
    }

    fn stop_rojo(&self, state: &mut SessionState) {
        if !self.owns_rojo_process(state) {
            state.rojo_pid = None;
            state.rojo_birth = None;
            state.rojo_start_ticks = None;
            return;
        }
        let pid = state.rojo_pid.expect("owned process has pid");
        #[cfg(unix)]
        {
            // The PID was revalidated with its birth token and exact command before targeting its group.
            unsafe {
                libc::kill(-(pid as i32), libc::SIGTERM);
            }
            let deadline = Instant::now() + Duration::from_secs(5);
            while Instant::now() < deadline && process_birth(pid).is_some() {
                thread::sleep(Duration::from_millis(100));
            }
            if process_birth(pid).is_some() && self.owns_rojo_process(state) {
                unsafe {
                    libc::kill(-(pid as i32), libc::SIGKILL);
                }
            }
        }
        #[cfg(windows)]
        {
            let _ = Command::new("taskkill")
                .args(["/PID", &pid.to_string(), "/T", "/F"])
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status();
        }
        state.rojo_pid = None;
        state.rojo_birth = None;
        state.rojo_start_ticks = None;
        state.rojo_started_at = None;
    }
}

#[derive(Clone, Debug, Deserialize)]
struct WindowsStudioProcess {
    pid: u32,
    started: u64,
    title: String,
}

impl StudioSession {
    fn studio_status(&self, instance_id: &str) -> Option<Value> {
        self.mcp.manage_status(instance_id).ok()
    }

    fn rojo_marker(&self, instance_id: &str) -> Option<String> {
        let marker = serde_json::to_string(&self.config.contract.connection_marker).ok()?;
        let code = format!(
            "local marker = game:GetService(\"ServerStorage\"):FindFirstChild({marker})\n\
             return if marker and marker:IsA(\"StringValue\") then marker.Value else \"\""
        );
        self.mcp
            .tool(
                "execute_luau",
                json!({"instance_id": instance_id, "target": "edit", "code": code}),
                Duration::from_secs(30),
            )
            .ok()?
            .get("returnValue")?
            .as_str()
            .filter(|value| !value.is_empty())
            .map(str::to_owned)
    }

    fn nudge_rojo_autoconnect(&self, instance_id: &str, state: &mut SessionState) -> Result<()> {
        let port = state.port.context("Session is missing Rojo port")?;
        let token = Self::ensure_session_token(state);
        let endpoint_name = serde_json::to_string(&self.config.contract.endpoint_attribute)?;
        self.mcp.tool(
            "execute_luau",
            json!({
                "instance_id": instance_id,
                "target": "edit",
                "code": format!("workspace:SetAttribute({endpoint_name}, nil)"),
            }),
            Duration::from_secs(60),
        )?;
        let mut lines = Vec::new();
        for (name, value) in self.contract_attributes(port, &token) {
            lines.push(format!(
                "workspace:SetAttribute({}, {})",
                serde_json::to_string(&name)?,
                serde_json::to_string(&value)?
            ));
        }
        self.mcp.tool(
            "execute_luau",
            json!({
                "instance_id": instance_id,
                "target": "edit",
                "code": lines.join("\n"),
            }),
            Duration::from_secs(60),
        )?;
        Ok(())
    }

    fn studio_contract(&self, instance_id: &str) -> Option<Value> {
        let names = &self.config.contract;
        let code = format!(
            "local HttpService = game:GetService(\"HttpService\")\n\
             return HttpService:JSONEncode({{\n\
             endpoint = workspace:GetAttribute({}),\n\
             project = workspace:GetAttribute({}),\n\
             session = workspace:GetAttribute({}),\n\
             worktree = workspace:GetAttribute({}),\n\
             }})",
            serde_json::to_string(&names.endpoint_attribute).ok()?,
            serde_json::to_string(&names.project_attribute).ok()?,
            serde_json::to_string(&names.session_attribute).ok()?,
            serde_json::to_string(&names.identity_attribute).ok()?,
        );
        let result = self
            .mcp
            .tool(
                "execute_luau",
                json!({"instance_id": instance_id, "target": "edit", "code": code}),
                Duration::from_secs(10),
            )
            .ok()?;
        serde_json::from_str(result.get("returnValue")?.as_str()?).ok()
    }

    fn expected_studio_contract(&self, state: &mut SessionState) -> Result<Value> {
        Ok(json!({
            "endpoint": format!("http://127.0.0.1:{}", state.port.context("Session is missing Rojo port")?),
            "project": self.project_name(),
            "session": Self::ensure_session_token(state),
            "worktree": self.identity(),
        }))
    }

    fn windows_studio_processes(&self) -> Vec<WindowsStudioProcess> {
        let script = "Get-Process RobloxStudioBeta -ErrorAction SilentlyContinue | \
            ForEach-Object { [PSCustomObject]@{ pid = $_.Id; started = $_.StartTime.ToFileTimeUtc(); \
            title = $_.MainWindowTitle } } | ConvertTo-Json -Compress";
        let output = match Command::new("powershell.exe")
            .args(["-NoProfile", "-Command", script])
            .output()
        {
            Ok(output) if output.status.success() => output.stdout,
            _ => return Vec::new(),
        };
        let value: Value = match serde_json::from_slice(&output) {
            Ok(value) => value,
            Err(_) => return Vec::new(),
        };
        if value.is_array() {
            serde_json::from_value(value).unwrap_or_default()
        } else if value.is_object() {
            serde_json::from_value(value)
                .map(|entry| vec![entry])
                .unwrap_or_default()
        } else {
            Vec::new()
        }
    }

    fn windows_artifact_path(&self) -> Option<String> {
        if Path::new("/mnt/c").is_dir() {
            let output = Command::new("wslpath")
                .args(["-w", &self.paths.artifact.to_string_lossy()])
                .output()
                .ok()?;
            let value = String::from_utf8_lossy(&output.stdout).trim().to_owned();
            return (!value.is_empty()).then_some(value);
        }
        #[cfg(windows)]
        {
            Some(self.paths.artifact.to_string_lossy().into_owned())
        }
        #[cfg(not(windows))]
        {
            None
        }
    }

    fn record_owned_studio_process(
        &self,
        state: &mut SessionState,
        before_pids: Option<&BTreeSet<u32>>,
    ) -> bool {
        let Some(artifact) = self.windows_artifact_path() else {
            return false;
        };
        let artifact = artifact.to_lowercase();
        let matches: Vec<_> = self
            .windows_studio_processes()
            .into_iter()
            .filter(|entry| {
                !before_pids.is_some_and(|pids| pids.contains(&entry.pid))
                    && entry.title.to_lowercase().contains(&artifact)
            })
            .collect();
        if matches.len() != 1 {
            return false;
        }
        state.studio_process_pid = Some(matches[0].pid);
        state.studio_process_started = Some(matches[0].started);
        true
    }

    fn owns_windows_studio_process(&self, state: &SessionState) -> bool {
        let (Some(pid), Some(started)) = (state.studio_process_pid, state.studio_process_started)
        else {
            return false;
        };
        self.windows_studio_processes()
            .iter()
            .any(|entry| entry.pid == pid && entry.started == started)
    }

    fn stop_owned_windows_studio_process(&self, state: &mut SessionState) -> bool {
        if !self.owns_windows_studio_process(state)
            && !self.record_owned_studio_process(state, None)
        {
            return false;
        }
        let pid = state
            .studio_process_pid
            .expect("owned Studio process has pid");
        let status = Command::new("powershell.exe")
            .args([
                "-NoProfile",
                "-Command",
                &format!("Stop-Process -Id {pid} -ErrorAction Stop"),
            ])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
        if !status.is_ok_and(|status| status.success()) {
            return false;
        }
        state.studio_process_pid = None;
        state.studio_process_started = None;
        true
    }

    fn wait_for_launched_studio(&self, state: &mut SessionState) -> Result<String> {
        let expected = self.expected_studio_contract(state)?;
        let deadline = Instant::now() + Duration::from_secs(120);
        while Instant::now() < deadline {
            let listing = self.mcp.tool(
                "get_connected_instances",
                json!({}),
                Duration::from_secs(10),
            )?;
            let mut matches = Vec::new();
            if let Some(instances) = listing.get("instances").and_then(Value::as_array) {
                for candidate in instances {
                    if candidate.get("role").and_then(Value::as_str) != Some("edit") {
                        continue;
                    }
                    let project_matches = ["dataModelName", "placeName"].iter().any(|field| {
                        candidate.get(field).and_then(Value::as_str) == Some(&self.project_name())
                    });
                    if !project_matches {
                        continue;
                    }
                    let Some(instance_id) = candidate.get("instanceId").and_then(Value::as_str)
                    else {
                        continue;
                    };
                    if self.studio_contract(instance_id).as_ref() == Some(&expected) {
                        matches.push(instance_id.to_owned());
                    }
                }
            }
            match matches.len() {
                1 => return Ok(matches.remove(0)),
                2.. => bail!(
                    "More than one Studio process presented this session's exact worktree token; close the duplicates manually"
                ),
                _ => thread::sleep(Duration::from_millis(500)),
            }
        }
        bail!(
            "Studio launched but did not present this worktree's exact source contract before timeout"
        )
    }

    fn wait_for_rojo_connection(
        &self,
        instance_id: &str,
        expected: &str,
        timeout: Duration,
    ) -> Result<()> {
        let deadline = Instant::now() + timeout;
        while Instant::now() < deadline {
            if self.rojo_marker(instance_id).as_deref() == Some(expected) {
                return Ok(());
            }
            thread::sleep(Duration::from_millis(500));
        }
        bail!(
            "Studio did not auto-connect to {expected}. Run robloxstudio-worktree bootstrap, restart Studio, and inspect {}.",
            self.paths.rojo_log.display()
        )
    }

    fn run_validation_hook(&self, instance_id: &str) -> Result<()> {
        let Some(template) = &self.config.hooks.validate else {
            return Ok(());
        };
        let command = self.expand_command(template, Some(instance_id), &[])?;
        let (program, args) = command.split_first().context("Validation hook is empty")?;
        let output = Command::new(program)
            .args(args)
            .current_dir(&self.config.root)
            .output()
            .with_context(|| format!("Could not run project validation hook: {program}"))?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();
            let stdout = String::from_utf8_lossy(&output.stdout).trim().to_owned();
            let detail = if !stderr.is_empty() {
                stderr
            } else if !stdout.is_empty() {
                stdout
            } else {
                format!("exit code {}", output.status.code().unwrap_or(-1))
            };
            bail!("Project validation hook failed: {detail}");
        }
        Ok(())
    }
}

impl StudioSession {
    pub fn ensure_up(&self, fresh: bool) -> Result<SessionState> {
        let mut state = self.load_state()?;
        if let Some(owner) = &state.worktree_id {
            if owner != &self.identity() {
                bail!("Session state belongs to a different worktree: {owner}");
            }
        }
        if fresh {
            self.down_state(&mut state)?;
            state = self.load_state()?;
            state.session_token = Some(Uuid::new_v4().simple().to_string());
        }

        if let Some(instance_id) = state.instance_id.clone() {
            let status = self.studio_status(&instance_id);
            let is_edit = status
                .as_ref()
                .and_then(|value| value.get("roles"))
                .and_then(Value::as_array)
                .is_some_and(|roles| roles.iter().any(|role| role.as_str() == Some("edit")));
            if is_edit {
                let port = match state.port {
                    Some(port) => port,
                    None => choose_port(&self.identity(), &BTreeSet::new())?,
                };
                let token = Self::ensure_session_token(&mut state);
                self.generate_projects(port, &token)?;
                state.port = Some(port);
                state.project_name = Some(self.project_name());
                self.start_rojo(&mut state)?;
                if self.rojo_marker(&instance_id).as_deref() != Some(&self.project_name()) {
                    self.nudge_rojo_autoconnect(&instance_id, &mut state)?;
                    self.wait_for_rojo_connection(
                        &instance_id,
                        &self.project_name(),
                        Duration::from_secs(30),
                    )?;
                }
                self.run_validation_hook(&instance_id)?;
                if !self.owns_windows_studio_process(&state) {
                    self.record_owned_studio_process(&mut state, None);
                }
                state.validated_at = Some(now());
                self.save_state(&mut state)?;
                return Ok(state);
            }
            state.instance_id = None;
        }

        let port = match state.port {
            Some(port) if self.owns_rojo_process(&state) || is_port_free(port) => port,
            _ => choose_port(&self.identity(), &BTreeSet::new())?,
        };
        self.build_artifact(&mut state, port)?;
        self.start_rojo(&mut state)?;

        let before_pids: BTreeSet<u32> = self
            .windows_studio_processes()
            .into_iter()
            .map(|entry| entry.pid)
            .collect();
        self.mcp.tool(
            "manage_instance",
            json!({
                "action": "launch",
                "source": "local_file",
                "local_place_file": self.paths.artifact.to_string_lossy(),
                "wait_for_connection": false,
                "timeout_ms": 120000,
            }),
            Duration::from_secs(30),
        )?;
        let instance_id = self.wait_for_launched_studio(&mut state)?;
        self.record_owned_studio_process(&mut state, Some(&before_pids));
        state.instance_id = Some(instance_id.clone());
        state.studio_started_at = Some(now());
        self.save_state(&mut state)?;
        self.wait_for_rojo_connection(&instance_id, &self.project_name(), Duration::from_secs(45))?;
        self.run_validation_hook(&instance_id)?;
        state.validated_at = Some(now());
        self.save_state(&mut state)?;
        Ok(state)
    }

    fn down_state(&self, state: &mut SessionState) -> Result<()> {
        if let Some(instance_id) = state.instance_id.clone() {
            let _ = self.mcp.tool(
                "solo_playtest",
                json!({"action": "stop", "instance_id": instance_id, "timeout": 30}),
                Duration::from_secs(60),
            );
            let mut closed = false;
            if self.owns_windows_studio_process(state) {
                let expected = self.expected_studio_contract(state)?;
                if self.studio_contract(&instance_id).as_ref() != Some(&expected) {
                    bail!(
                        "Refusing native Studio teardown: Studio no longer presents this session contract"
                    );
                }
                if !self.stop_owned_windows_studio_process(state) {
                    bail!("Could not stop this session's exact recorded Studio process");
                }
                closed = true;
            }
            if !closed {
                let close = self.mcp.tool(
                    "manage_instance",
                    json!({"action": "close", "instance_id": instance_id}),
                    Duration::from_secs(45),
                );
                if let Err(close_error) = close {
                    if self.studio_status(&instance_id).is_some() {
                        let expected = self.expected_studio_contract(state)?;
                        if self.studio_contract(&instance_id).as_ref() != Some(&expected) {
                            bail!(
                                "Refusing process fallback: Studio no longer presents this session contract"
                            );
                        }
                        if !self.stop_owned_windows_studio_process(state) {
                            return Err(close_error);
                        }
                    }
                }
            }
            state.instance_id = None;
            state.studio_started_at = None;
            state.studio_process_pid = None;
            state.studio_process_started = None;
        }
        self.stop_rojo(state);
        self.save_state(state)
    }

    pub fn down(&self) -> Result<SessionState> {
        let mut state = self.load_state()?;
        self.down_state(&mut state)?;
        Ok(state)
    }

    pub fn status(&self) -> Result<Value> {
        let state = self.load_state()?;
        let studio = state
            .instance_id
            .as_deref()
            .and_then(|instance_id| self.studio_status(instance_id));
        Ok(json!({
            "worktree_id": self.identity(),
            "worktree_root": self.config.root.to_string_lossy(),
            "project_name": state.project_name,
            "rojo_port": state.port,
            "rojo_running": self.owns_rojo_process(&state),
            "studio_instance_id": state.instance_id,
            "studio_connected": studio.is_some(),
            "studio_roles": studio.as_ref().and_then(|value| value.get("roles")).cloned().unwrap_or_else(|| json!([])),
            "rojo_connected_project": match (studio.is_some(), state.instance_id.as_deref()) {
                (true, Some(instance_id)) => self.rojo_marker(instance_id),
                _ => None,
            },
            "artifact": self.paths.artifact.exists().then(|| self.paths.artifact.to_string_lossy().into_owned()),
            "artifact_digest": state.artifact_digest,
        }))
    }

    pub fn build(&self) -> Result<SessionState> {
        let mut state = self.load_state()?;
        if state.instance_id.is_some() {
            bail!("Studio is active; use robloxstudio-worktree up --fresh to rebuild safely");
        }
        let port = match state.port {
            Some(port) if self.owns_rojo_process(&state) || is_port_free(port) => port,
            _ => choose_port(&self.identity(), &BTreeSet::new())?,
        };
        self.build_artifact(&mut state, port)?;
        Ok(state)
    }

    pub fn run_test_hook(&self, state: &SessionState, extra_args: &[String]) -> Result<i32> {
        let template = self
            .config
            .hooks
            .test
            .as_ref()
            .context("This project does not define hooks.test in robloxstudio-worktree.json")?;
        let instance_id = state
            .instance_id
            .as_deref()
            .context("Session is missing Studio instance ID")?;
        let command = self.expand_command(template, Some(instance_id), extra_args)?;
        let (program, args) = command.split_first().context("Test hook is empty")?;
        let status = Command::new(program)
            .args(args)
            .current_dir(&self.config.root)
            .status()
            .with_context(|| format!("Could not run project test hook: {program}"))?;
        Ok(status.code().unwrap_or(1))
    }

    pub fn remove_generated_state(&self) -> Result<()> {
        match fs::remove_dir_all(&self.config.state_dir) {
            Ok(()) => Ok(()),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(error) => Err(error)
                .with_context(|| format!("Could not remove {}", self.config.state_dir.display())),
        }
    }

    pub fn bootstrap(&self) -> Result<()> {
        for template in &self.config.bootstrap.commands {
            let command = self.expand_command(template, None, &[])?;
            println!("+ {}", command.join(" "));
            self.run_checked(&command)?;
        }
        let mut missing = Vec::new();
        for pattern in &self.config.bootstrap.required_globs {
            let absolute = self
                .config
                .root
                .join(pattern)
                .to_string_lossy()
                .into_owned();
            let found = glob::glob(&absolute)
                .with_context(|| format!("Invalid bootstrap glob: {pattern}"))?
                .any(|entry| entry.is_ok());
            if !found {
                missing.push(pattern.clone());
            }
        }
        if !missing.is_empty() {
            bail!(
                "Bootstrap did not produce required paths: {}",
                missing.join(", ")
            );
        }
        if let Some(plugin) = &self.config.bootstrap.plugin {
            let bytes = if plugin == "bundled" {
                self.config.bundled_plugin_bytes().to_vec()
            } else {
                let path = self.config.root.join(plugin);
                fs::read(&path).with_context(|| {
                    format!("Managed Rojo plugin is missing: {}", path.display())
                })?
            };
            self.install_rojo_plugin(&bytes)?;
        }
        Ok(())
    }

    fn studio_plugin_dir(&self) -> Result<PathBuf> {
        #[cfg(windows)]
        if let Some(local) = std::env::var_os("LOCALAPPDATA") {
            return Ok(PathBuf::from(local).join("Roblox/Plugins"));
        }
        let is_wsl = fs::read_to_string("/proc/sys/kernel/osrelease")
            .is_ok_and(|release| release.to_lowercase().contains("microsoft"));
        if is_wsl {
            let windows = Command::new("cmd.exe")
                .args(["/d", "/c", "echo", "%LOCALAPPDATA%"])
                .output()
                .context("Could not locate Windows LOCALAPPDATA from WSL")?;
            let windows = String::from_utf8_lossy(&windows.stdout).trim().to_owned();
            let wsl = Command::new("wslpath")
                .args(["-u", &windows])
                .output()
                .context("Could not convert Windows LOCALAPPDATA for WSL")?;
            let wsl = String::from_utf8_lossy(&wsl.stdout).trim().to_owned();
            return Ok(PathBuf::from(wsl).join("Roblox/Plugins"));
        }
        #[cfg(target_os = "macos")]
        if let Some(home) = std::env::var_os("HOME") {
            return Ok(PathBuf::from(home).join("Documents/Roblox/Plugins"));
        }
        bail!("Managed Rojo plugin installation supports Windows, WSL, and macOS")
    }

    fn install_rojo_plugin(&self, bytes: &[u8]) -> Result<()> {
        let plugin_dir = self.studio_plugin_dir()?;
        fs::create_dir_all(&plugin_dir)
            .with_context(|| format!("Could not create {}", plugin_dir.display()))?;
        let target = plugin_dir.join("Rojo.rbxm");
        let backup = plugin_dir.join("Rojo.upstream.rbxm.disabled");
        let source_hash = format!("{:x}", Sha256::digest(bytes));
        if target.is_file() && sha256(&target).ok().as_deref() == Some(&source_hash) {
            println!(
                "Managed Rojo plugin already installed: {}",
                target.display()
            );
            return Ok(());
        }
        if target.is_file() && !backup.exists() {
            fs::copy(&target, &backup).with_context(|| {
                format!(
                    "Could not back up {} to {}",
                    target.display(),
                    backup.display()
                )
            })?;
            println!("Backed up the previous Rojo plugin to {}", backup.display());
        }
        let temporary = plugin_dir.join("Rojo.rbxm.next");
        let mut file = File::create(&temporary)
            .with_context(|| format!("Could not create {}", temporary.display()))?;
        file.write_all(bytes)
            .with_context(|| format!("Could not write {}", temporary.display()))?;
        file.sync_all().ok();
        replace_file(&temporary, &target)?;
        println!(
            "Installed managed Rojo plugin: {} ({})",
            target.display(),
            &source_hash[..12]
        );
        Ok(())
    }
}