starweaver-cli 0.1.0

Command-line interface for Starweaver
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
//! CLI environment provider resolution.

use std::{ffi::OsString, path::PathBuf, sync::Arc};

use starweaver_envd::LocalEnvd;
use starweaver_envd_client::EnvdRpcClient;
use starweaver_envd_core::DEFAULT_ENVIRONMENT_ID;
use starweaver_environment::{
    CompositeEnvironmentProvider, DynEnvironmentProvider, DynProcessShellProvider,
    EnvdEnvironmentProvider, EnvironmentMount, EnvironmentMountMode, EnvironmentPolicy, FilePolicy,
    LocalEnvironmentProvider, ShellPolicy, SwitchableEnvironmentProvider,
    SwitchableEnvironmentTarget, VirtualEnvironmentProvider,
};
use starweaver_rpc_core::{
    EnvironmentAttachmentAccessMode, EnvironmentAttachmentRef, LOCAL_ENVIRONMENT_ATTACHMENT_ID,
    LOCAL_ENVIRONMENT_ATTACHMENT_KIND,
};

use crate::{CliConfig, CliError, CliResult};

/// Resolved environment provider for one CLI run.
#[derive(Clone)]
pub struct ResolvedEnvironment {
    /// Provider handle attached to `AgentSession`.
    pub provider: DynEnvironmentProvider,
    /// Optional process-capable provider override for background shell tools.
    pub process_provider: Option<DynProcessShellProvider>,
    /// Switchable provider handle used by active-run host mutations.
    pub switchable: Option<Arc<SwitchableEnvironmentProvider>>,
    /// Effective run-local attachment refs backing this environment.
    pub attachments: Vec<EnvironmentAttachmentRef>,
}

/// Validate environment configuration before creating run/session records.
pub fn validate_environment_config(config: &CliConfig) -> CliResult<()> {
    let _policy = environment_policy(config)?;
    validate_environment_provider(config.environment_provider.as_str())
}

/// Build an environment provider from resolved CLI config.
#[cfg(test)]
pub fn resolve_environment(config: &CliConfig) -> CliResult<ResolvedEnvironment> {
    resolve_environment_with_tmp_namespace(config, None)
}

/// Build an environment provider with a session-scoped temporary file namespace.
pub fn resolve_environment_for_session(
    config: &CliConfig,
    session_id: &str,
) -> CliResult<ResolvedEnvironment> {
    resolve_environment_with_tmp_namespace(config, Some(session_id))
}

/// Build an environment provider for a session, optionally using host RPC attachments.
pub fn resolve_environment_for_session_with_attachments(
    config: &CliConfig,
    session_id: &str,
    attachments: &[EnvironmentAttachmentRef],
) -> CliResult<ResolvedEnvironment> {
    let target =
        resolve_environment_target_for_session_with_attachments(config, session_id, attachments)?;
    let switchable = Arc::new(SwitchableEnvironmentProvider::new(
        "cli-active-environment",
        SwitchableEnvironmentTarget::new(target.provider.clone(), target.process_provider.clone()),
    ));
    let provider: DynEnvironmentProvider = switchable.clone();
    let process_provider = target
        .process_provider
        .is_some()
        .then(|| switchable.clone() as DynProcessShellProvider);
    Ok(ResolvedEnvironment {
        provider,
        process_provider,
        switchable: Some(switchable),
        attachments: target.attachments,
    })
}

/// Build a non-switchable target for a session and attachment list.
pub fn resolve_environment_target_for_session_with_attachments(
    config: &CliConfig,
    session_id: &str,
    attachments: &[EnvironmentAttachmentRef],
) -> CliResult<ResolvedEnvironment> {
    if attachments.is_empty() {
        let mut resolved = resolve_environment_for_session(config, session_id)?;
        resolved.attachments = vec![default_local_attachment()];
        return Ok(resolved);
    }
    let default_id = default_attachment_id(attachments);
    let default_shell_id = default_shell_attachment_id(attachments, default_id);
    let mut effective_attachments = attachments.to_vec();
    for attachment in &mut effective_attachments {
        attachment.is_default = default_id == Some(attachment.id.as_str());
        attachment.is_default_for_shell = default_shell_id == Some(attachment.id.as_str());
    }
    let mut mounts = Vec::new();
    for attachment in &effective_attachments {
        let resolved = resolve_environment_attachment(config, Some(session_id), attachment)?;
        mounts.push(
            EnvironmentMount::new(&attachment.id, resolved.provider)
                .map_err(|error| CliError::Config(error.to_string()))?
                .with_mode(environment_mount_mode(attachment.resolved_mode()))
                .with_default(attachment.is_default)
                .with_default_for_shell(attachment.is_default_for_shell),
        );
    }
    let provider: DynEnvironmentProvider = Arc::new(
        CompositeEnvironmentProvider::new(mounts)
            .map_err(|error| CliError::Config(error.to_string()))?,
    );
    let process_provider = provider.clone().process_shell_provider();
    Ok(ResolvedEnvironment {
        provider,
        process_provider,
        switchable: None,
        attachments: effective_attachments,
    })
}

fn default_attachment_id(attachments: &[EnvironmentAttachmentRef]) -> Option<&str> {
    if attachments.len() == 1 {
        return Some(attachments[0].id.as_str());
    }
    attachments
        .iter()
        .find(|attachment| attachment.is_default)
        .map(|attachment| attachment.id.as_str())
}

fn default_shell_attachment_id<'a>(
    attachments: &'a [EnvironmentAttachmentRef],
    default_id: Option<&'a str>,
) -> Option<&'a str> {
    if let Some(explicit) = attachments
        .iter()
        .find(|attachment| attachment.is_default_for_shell)
        .map(|attachment| attachment.id.as_str())
    {
        return Some(explicit);
    }
    let default_id = default_id?;
    attachments
        .iter()
        .find(|attachment| attachment.id == default_id && attachment_supports_shell(attachment))
        .map(|attachment| attachment.id.as_str())
}

fn resolve_environment_with_tmp_namespace(
    config: &CliConfig,
    tmp_namespace: Option<&str>,
) -> CliResult<ResolvedEnvironment> {
    validate_environment_config(config)?;
    let policy = environment_policy(config)?;
    let provider: DynEnvironmentProvider = match config.environment_provider.as_str() {
        "local" => {
            let mut provider = LocalEnvironmentProvider::new(config.workspace_root.clone())
                .with_id("cli-local")
                .with_allowed_paths(local_allowed_paths(config))
                .with_context_file_tree_roots([config.workspace_root.clone()])
                .with_policy(policy);
            if let Some(namespace) = tmp_namespace {
                provider = provider.with_tmp_namespace(namespace);
            }
            envd_backed_provider(Arc::new(provider), "cli-local")
        }
        "virtual" => {
            let mut provider = VirtualEnvironmentProvider::new("cli-virtual")
                .with_policy(policy)
                .with_file("README.md", "Virtual Starweaver CLI workspace");
            if let Some(namespace) = tmp_namespace {
                provider = provider.with_tmp_namespace(namespace);
            }
            envd_backed_provider(Arc::new(provider), "cli-virtual")
        }
        other => {
            unreachable!("environment provider should be validated before resolution: {other}")
        }
    };
    let process_provider = provider.clone().process_shell_provider();
    Ok(ResolvedEnvironment {
        provider,
        process_provider,
        switchable: None,
        attachments: vec![default_local_attachment()],
    })
}

fn default_local_attachment() -> EnvironmentAttachmentRef {
    EnvironmentAttachmentRef {
        id: LOCAL_ENVIRONMENT_ATTACHMENT_ID.to_string(),
        kind: LOCAL_ENVIRONMENT_ATTACHMENT_KIND.to_string(),
        mode: Some(EnvironmentAttachmentAccessMode::ReadWrite),
        is_default: true,
        is_default_for_shell: true,
        attachment_lease_id: None,
        endpoint_ref: None,
        environment_id: None,
        auth_token: None,
        metadata: serde_json::Map::new(),
    }
}

fn resolve_environment_attachment(
    config: &CliConfig,
    tmp_namespace: Option<&str>,
    attachment: &EnvironmentAttachmentRef,
) -> CliResult<ResolvedEnvironment> {
    if attachment.id == LOCAL_ENVIRONMENT_ATTACHMENT_ID
        && attachment.kind != LOCAL_ENVIRONMENT_ATTACHMENT_KIND
    {
        return Err(CliError::Config(
            "reserved environment attachment id local requires kind local".to_string(),
        ));
    }
    match attachment.kind.as_str() {
        "local" => resolve_environment_with_tmp_namespace(config, tmp_namespace),
        "envd" => resolve_envd_attachment(attachment),
        other => Err(CliError::Config(format!(
            "unsupported environment attachment kind: {other}"
        ))),
    }
}

fn resolve_envd_attachment(
    attachment: &EnvironmentAttachmentRef,
) -> CliResult<ResolvedEnvironment> {
    let client = envd_client_for_attachment(attachment)
        .map_err(|error| CliError::Config(format!("invalid envd endpoint: {error}")))?;
    let environment_id = attachment
        .requested_environment_id()
        .unwrap_or(DEFAULT_ENVIRONMENT_ID)
        .to_string();
    let provider: DynEnvironmentProvider = Arc::new(
        EnvdEnvironmentProvider::new(Arc::new(client), environment_id).with_id(&attachment.id),
    );
    let process_provider = provider.clone().process_shell_provider();
    Ok(ResolvedEnvironment {
        provider,
        process_provider,
        switchable: None,
        attachments: vec![attachment.clone()],
    })
}

pub fn envd_client_for_attachment(
    attachment: &EnvironmentAttachmentRef,
) -> Result<EnvdRpcClient, String> {
    let endpoint = attachment
        .requested_endpoint_ref()
        .ok_or_else(|| "envd attachment requires endpointRef".to_string())?;
    if endpoint.starts_with("http://") {
        validate_envd_http_endpoint(endpoint)?;
        let auth_token = attachment
            .requested_auth_token()
            .ok_or_else(|| "envd HTTP attachment requires authToken".to_string())?;
        validate_envd_http_auth_token(Some(auth_token))?;
        return EnvdRpcClient::http_with_token(endpoint, auth_token)
            .map_err(|error| error.to_string());
    }
    if endpoint.starts_with("stdio://") {
        let (program, args) = parse_stdio_envd_endpoint(endpoint)?;
        return EnvdRpcClient::spawn_stdio(program, args).map_err(|error| error.to_string());
    }
    Err("envd attachment supports http:// and stdio:// endpoint refs".to_string())
}

pub fn validate_envd_attachment_transport(
    attachment: &EnvironmentAttachmentRef,
) -> Result<(), String> {
    let endpoint = attachment
        .requested_endpoint_ref()
        .ok_or_else(|| "envd environment attachment requires endpointRef".to_string())?;
    if endpoint.starts_with("http://") {
        validate_envd_http_endpoint(endpoint)?;
        validate_envd_http_auth_token(attachment.requested_auth_token())?;
        return Ok(());
    }
    if endpoint.starts_with("stdio://") {
        parse_stdio_envd_endpoint(endpoint).map(|_| ())?;
        return Ok(());
    }
    Err("envd environment attachment supports http:// and stdio:// endpoint refs".to_string())
}

pub fn redacted_envd_endpoint_ref(attachment: &EnvironmentAttachmentRef) -> Option<String> {
    let endpoint = attachment.requested_endpoint_ref()?;
    if endpoint.starts_with("stdio://") {
        return Some("stdio://<redacted>".to_string());
    }
    if endpoint.starts_with("http://") {
        return Some(endpoint.to_string());
    }
    None
}

fn validate_envd_http_endpoint(endpoint: &str) -> Result<(), String> {
    let rest = endpoint
        .strip_prefix("http://")
        .ok_or_else(|| "envd HTTP endpoint must start with http://".to_string())?;
    if rest.is_empty() {
        return Err("envd HTTP endpoint host cannot be empty".to_string());
    }
    if endpoint.contains('?') || endpoint.contains('#') {
        return Err("envd HTTP endpoint cannot contain query strings or fragments".to_string());
    }
    let authority = rest.split('/').next().unwrap_or(rest);
    if authority.contains('@') {
        return Err("envd HTTP endpoint cannot contain userinfo".to_string());
    }
    let host = http_authority_host(authority)?;
    if is_loopback_http_host(host) {
        Ok(())
    } else {
        Err(
            "envd HTTP endpoint must be loopback unless configured by a future host policy"
                .to_string(),
        )
    }
}

fn http_authority_host(authority: &str) -> Result<&str, String> {
    if authority.is_empty() {
        return Err("envd HTTP endpoint host cannot be empty".to_string());
    }
    if let Some(rest) = authority.strip_prefix('[') {
        let Some((host, _)) = rest.split_once(']') else {
            return Err("envd HTTP endpoint has invalid IPv6 host".to_string());
        };
        return Ok(host);
    }
    Ok(authority
        .split_once(':')
        .map_or(authority, |(host, _)| host))
}

fn is_loopback_http_host(host: &str) -> bool {
    host.eq_ignore_ascii_case("localhost") || host == "::1" || host.starts_with("127.")
}

fn validate_envd_http_auth_token(auth_token: Option<&str>) -> Result<(), String> {
    let Some(auth_token) = auth_token else {
        return Err("envd HTTP attachment requires authToken".to_string());
    };
    if auth_token.trim().is_empty() {
        return Err("envd HTTP attachment authToken cannot be empty".to_string());
    }
    if auth_token.bytes().any(|byte| matches!(byte, b'\r' | b'\n')) {
        return Err("envd HTTP attachment authToken cannot contain newlines".to_string());
    }
    Ok(())
}

fn parse_stdio_envd_endpoint(endpoint: &str) -> Result<(PathBuf, Vec<OsString>), String> {
    let rest = endpoint
        .strip_prefix("stdio://")
        .ok_or_else(|| "envd stdio endpoint must start with stdio://".to_string())?;
    let (program, query) = rest.split_once('?').unwrap_or((rest, ""));
    if program.trim().is_empty() {
        return Err("envd stdio endpoint program cannot be empty".to_string());
    }
    let mut args = Vec::new();
    if !query.is_empty() {
        for part in query.split('&').filter(|part| !part.is_empty()) {
            let Some(value) = part.strip_prefix("arg=") else {
                return Err(
                    "envd stdio endpoint query supports only repeated arg= values".to_string(),
                );
            };
            args.push(OsString::from(percent_decode_component(value)?));
        }
    }
    Ok((PathBuf::from(percent_decode_component(program)?), args))
}

fn percent_decode_component(value: &str) -> Result<String, String> {
    let bytes = value.as_bytes();
    let mut decoded = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        match bytes[index] {
            b'%' if index + 2 < bytes.len() => {
                let high = hex_value(bytes[index + 1])?;
                let low = hex_value(bytes[index + 2])?;
                decoded.push((high << 4) | low);
                index += 3;
            }
            b'%' => return Err("envd stdio endpoint has incomplete percent escape".to_string()),
            b'+' => {
                decoded.push(b' ');
                index += 1;
            }
            byte => {
                decoded.push(byte);
                index += 1;
            }
        }
    }
    String::from_utf8(decoded).map_err(|error| error.to_string())
}

fn hex_value(byte: u8) -> Result<u8, String> {
    match byte {
        b'0'..=b'9' => Ok(byte - b'0'),
        b'a'..=b'f' => Ok(byte - b'a' + 10),
        b'A'..=b'F' => Ok(byte - b'A' + 10),
        _ => Err("envd stdio endpoint has invalid percent escape".to_string()),
    }
}

const fn environment_mount_mode(mode: EnvironmentAttachmentAccessMode) -> EnvironmentMountMode {
    match mode {
        EnvironmentAttachmentAccessMode::ReadOnly => EnvironmentMountMode::ReadOnly,
        EnvironmentAttachmentAccessMode::ReadWrite => EnvironmentMountMode::ReadWrite,
    }
}

fn attachment_supports_shell(attachment: &EnvironmentAttachmentRef) -> bool {
    matches!(
        attachment.resolved_mode(),
        EnvironmentAttachmentAccessMode::ReadWrite
    )
}

fn envd_backed_provider(provider: DynEnvironmentProvider, id: &str) -> DynEnvironmentProvider {
    let shell_review_context = provider.shell_review_context();
    let envd = Arc::new(LocalEnvd::new(provider));
    let environment_id = envd.environment_id().to_string();
    Arc::new(
        EnvdEnvironmentProvider::new(envd, environment_id)
            .with_id(id)
            .with_shell_review_context(shell_review_context),
    )
}

fn local_allowed_paths(config: &CliConfig) -> Vec<PathBuf> {
    let mut paths = Vec::new();
    // Include the system temp dir so CLI/TUI agents can access user-specified
    // temporary files, while LocalEnvironmentProvider still appends its
    // provider-managed session temp dir separately.
    push_allowed_path(&mut paths, std::env::temp_dir());
    push_allowed_path(&mut paths, config.global_dir.clone());
    if let Some(home) = std::env::var_os("HOME") {
        push_allowed_path(&mut paths, PathBuf::from(home).join(".agents"));
    }
    push_allowed_path(&mut paths, config.workspace_root.clone());
    push_allowed_path(&mut paths, config.project_dir.clone());
    for dir in config.skill_dirs.iter().chain(config.subagent_dirs.iter()) {
        push_allowed_path(&mut paths, dir.clone());
    }
    paths
}

fn push_allowed_path(paths: &mut Vec<PathBuf>, path: PathBuf) {
    let path = path.canonicalize().unwrap_or(path);
    if !paths.iter().any(|existing| existing == &path) {
        paths.push(path);
    }
}

#[cfg(test)]
fn display_local_test_path(path: &std::path::Path) -> String {
    #[cfg(windows)]
    {
        let path = path.to_string_lossy();
        let normalized = path.replace('/', "\\");
        let stripped = if let Some(stripped) = normalized.strip_prefix(r"\\?\UNC\") {
            format!(r"\\{stripped}")
        } else if let Some(stripped) = normalized.strip_prefix(r"\\?\") {
            stripped.to_string()
        } else {
            normalized
        };
        stripped.replace('\\', "/")
    }
    #[cfg(not(windows))]
    {
        path.to_string_lossy().replace('\\', "/")
    }
}

fn validate_environment_provider(provider: &str) -> CliResult<()> {
    match provider {
        "local" | "virtual" => Ok(()),
        other => Err(CliError::Config(format!(
            "unknown environment provider: {other}"
        ))),
    }
}

fn environment_policy(config: &CliConfig) -> CliResult<EnvironmentPolicy> {
    let files = match config.files_policy.as_str() {
        "read_only" | "read-only" => FilePolicy::read_only(),
        "read_write" | "read-write" => FilePolicy::read_write(),
        "none" | "disabled" => FilePolicy::default(),
        other => return Err(CliError::Config(format!("unknown files policy: {other}"))),
    };
    let shell = if config.shell_enabled {
        ShellPolicy::allow_all()
    } else {
        ShellPolicy::default()
    };
    Ok(EnvironmentPolicy { files, shell })
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]

    use std::path::Path;

    use super::*;
    use crate::{args, profiles::list_skills, ConfigResolver};

    #[tokio::test]
    async fn cli_local_environment_can_read_configured_skill_package_paths() {
        let temp = tempfile::tempdir().unwrap();
        let global_dir = temp.path().join("global");
        std::fs::create_dir_all(&global_dir).unwrap();
        std::fs::write(
            global_dir.join("config.toml"),
            r#"
[skills]
additional_dirs = ["../custom-skills"]
"#,
        )
        .unwrap();

        let cli = args::parse(["starweaver-cli".to_string()]).unwrap();
        let config = ConfigResolver::for_tests(temp.path())
            .resolve(&cli)
            .unwrap();
        write_skill(
            &config.global_dir.join("skills/global-skill/SKILL.md"),
            "global-skill",
            "Global config skill",
        );
        write_skill(
            &temp
                .path()
                .join("shared-agents/skills/shared-skill/SKILL.md"),
            "shared-skill",
            "Shared agent skill",
        );
        write_skill(
            &config.project_dir.join("skills/project-skill/SKILL.md"),
            "project-skill",
            "Project config skill",
        );
        write_skill(
            &temp.path().join("custom-skills/custom-skill/SKILL.md"),
            "custom-skill",
            "Custom skill dir",
        );

        let packages = list_skills(&config);
        assert_eq!(packages.len(), 4);
        assert!(config
            .skill_dirs
            .iter()
            .any(|path| path.ends_with("shared-agents/skills")));

        let environment = resolve_environment(&config).unwrap();
        assert_eq!(environment.provider.id(), "cli-local");
        let state = environment.provider.export_state().await.unwrap();
        assert_eq!(
            state.metadata["envd_environment_id"],
            serde_json::json!("env_cli_default")
        );
        assert_eq!(state.metadata["envd_store"], serde_json::json!("ephemeral"));
        for package in packages {
            let content = environment.provider.read_text(&package.path).await.unwrap();
            assert!(content.contains(&format!("name: {}", package.name)));
        }
    }

    #[tokio::test]
    async fn cli_local_environment_tmp_outputs_and_system_tmp_are_readable() {
        let temp = tempfile::tempdir().unwrap();
        let cli = args::parse(["starweaver-cli".to_string()]).unwrap();
        let config = ConfigResolver::for_tests(temp.path())
            .resolve(&cli)
            .unwrap();
        let environment = resolve_environment_for_session(&config, "session_123").unwrap();

        let tmp_path = environment
            .provider
            .write_tmp_file("stdout.log", b"captured output")
            .await
            .unwrap();
        assert!(Path::new(&tmp_path).is_absolute());
        assert!(tmp_path.contains("session_123"));
        assert_eq!(
            Path::new(&tmp_path).file_name().unwrap().to_string_lossy(),
            "stdout.log"
        );
        assert_eq!(
            environment.provider.read_text(&tmp_path).await.unwrap(),
            "captured output"
        );
        let state = environment.provider.export_state().await.unwrap();
        assert_eq!(
            state.metadata["envd_operation_ids"]
                .as_array()
                .unwrap()
                .len(),
            1
        );

        let system_tmp_file = std::env::temp_dir().join(format!(
            "starweaver-cli-system-tmp-read-{}",
            std::process::id()
        ));
        let system_tmp_output = std::env::temp_dir().join(format!(
            "starweaver-cli-system-tmp-write-{}",
            std::process::id()
        ));
        std::fs::write(&system_tmp_file, "user temp").unwrap();
        assert_eq!(
            environment
                .provider
                .read_text(&system_tmp_file.display().to_string())
                .await
                .unwrap(),
            "user temp"
        );
        environment
            .provider
            .write_text(&system_tmp_output.display().to_string(), "agent temp")
            .await
            .unwrap();
        assert_eq!(
            std::fs::read_to_string(&system_tmp_output).unwrap(),
            "agent temp"
        );
        let _ = std::fs::remove_file(system_tmp_file);
        let _ = std::fs::remove_file(system_tmp_output);
    }

    #[tokio::test]
    async fn cli_local_environment_allows_system_tmp_before_config_paths() {
        let temp = tempfile::tempdir().unwrap();
        let cli = args::parse(["starweaver-cli".to_string()]).unwrap();
        let config = ConfigResolver::for_tests(temp.path())
            .resolve(&cli)
            .unwrap();

        let allowed_paths = local_allowed_paths(&config);
        let system_tmp_dir = std::env::temp_dir()
            .canonicalize()
            .unwrap_or_else(|_| std::env::temp_dir());

        assert_eq!(allowed_paths.first(), Some(&system_tmp_dir));
        assert!(allowed_paths.contains(
            &config
                .global_dir
                .canonicalize()
                .unwrap_or_else(|_| config.global_dir.clone())
        ));
        assert!(allowed_paths.contains(
            &config
                .workspace_root
                .canonicalize()
                .unwrap_or_else(|_| config.workspace_root.clone())
        ));
        assert!(allowed_paths.contains(
            &config
                .project_dir
                .canonicalize()
                .unwrap_or_else(|_| config.project_dir.clone())
        ));
    }

    #[tokio::test]
    async fn cli_local_environment_file_tree_context_uses_workspace_only() {
        let temp = tempfile::tempdir().unwrap();
        let cli = args::parse(["starweaver-cli".to_string()]).unwrap();
        let config = ConfigResolver::for_tests(temp.path())
            .resolve(&cli)
            .unwrap();
        std::fs::create_dir_all(&config.workspace_root).unwrap();
        std::fs::create_dir_all(&config.global_dir).unwrap();
        std::fs::write(config.workspace_root.join("app.rs"), "fn main() {}").unwrap();
        std::fs::write(config.global_dir.join("config-marker.txt"), "config").unwrap();

        let environment = resolve_environment_for_session(&config, "session_123").unwrap();
        let context = environment
            .provider
            .render_environment_context()
            .await
            .unwrap()
            .unwrap();

        assert_eq!(context.matches("<directory path=").count(), 1);
        assert!(context.contains(&format!(
            "<directory path=\"{}\">",
            display_local_test_path(
                &config
                    .workspace_root
                    .canonicalize()
                    .unwrap_or_else(|_| config.workspace_root.clone())
            )
        )));
        assert!(context.contains("app.rs"));
        assert!(!context.contains("config-marker.txt"));
        assert!(!context.contains(&format!(
            "<directory path=\"{}\">",
            display_local_test_path(
                &config
                    .global_dir
                    .canonicalize()
                    .unwrap_or_else(|_| config.global_dir.clone())
            )
        )));

        assert_eq!(
            environment
                .provider
                .read_text(
                    &config
                        .global_dir
                        .join("config-marker.txt")
                        .display()
                        .to_string(),
                )
                .await
                .unwrap(),
            "config"
        );
    }

    #[tokio::test]
    async fn cli_resolves_single_environment_attachment_as_composite_provider() {
        let temp = tempfile::tempdir().unwrap();
        let cli = args::parse(["starweaver-cli".to_string()]).unwrap();
        let config = ConfigResolver::for_tests(temp.path())
            .resolve(&cli)
            .unwrap();
        std::fs::create_dir_all(&config.workspace_root).unwrap();
        std::fs::write(config.workspace_root.join("README.md"), "local workspace").unwrap();
        let attachments = vec![EnvironmentAttachmentRef {
            id: "workspace".to_string(),
            kind: "local".to_string(),
            mode: Some(EnvironmentAttachmentAccessMode::ReadOnly),
            is_default: false,
            is_default_for_shell: false,
            attachment_lease_id: None,
            endpoint_ref: None,
            environment_id: None,
            auth_token: None,
            metadata: serde_json::Map::new(),
        }];

        let environment =
            resolve_environment_for_session_with_attachments(&config, "session_123", &attachments)
                .unwrap();

        assert_eq!(environment.provider.id(), "cli-active-environment");
        assert!(environment.switchable.is_some());
        assert_eq!(environment.attachments[0].id, "workspace");
        assert!(environment.attachments[0].is_default);
        assert!(!environment.attachments[0].is_default_for_shell);
        assert_eq!(
            environment.provider.read_text("README.md").await.unwrap(),
            "local workspace"
        );
        assert_eq!(
            environment
                .provider
                .read_text("/environment/workspace/README.md")
                .await
                .unwrap(),
            "local workspace"
        );
        assert!(matches!(
            environment.provider.write_text("new.txt", "blocked").await,
            Err(starweaver_environment::EnvironmentError::AccessDenied(_))
        ));
        assert!(matches!(
            environment
                .provider
                .write_text("/environment/workspace/new.txt", "blocked")
                .await,
            Err(starweaver_environment::EnvironmentError::AccessDenied(_))
        ));
    }

    #[tokio::test]
    async fn cli_resolves_multiple_environment_attachments_as_composite_provider() {
        let temp = tempfile::tempdir().unwrap();
        let cli = args::parse(["starweaver-cli".to_string()]).unwrap();
        let config = ConfigResolver::for_tests(temp.path())
            .resolve(&cli)
            .unwrap();
        std::fs::create_dir_all(&config.workspace_root).unwrap();
        std::fs::write(config.workspace_root.join("README.md"), "local workspace").unwrap();
        let attachments = vec![
            EnvironmentAttachmentRef {
                id: "workspace".to_string(),
                kind: "local".to_string(),
                mode: Some(EnvironmentAttachmentAccessMode::ReadWrite),
                is_default: true,
                is_default_for_shell: true,
                attachment_lease_id: None,
                endpoint_ref: None,
                environment_id: None,
                auth_token: None,
                metadata: serde_json::Map::new(),
            },
            EnvironmentAttachmentRef {
                id: "tools".to_string(),
                kind: "local".to_string(),
                mode: Some(EnvironmentAttachmentAccessMode::ReadOnly),
                is_default: false,
                is_default_for_shell: false,
                attachment_lease_id: None,
                endpoint_ref: None,
                environment_id: None,
                auth_token: None,
                metadata: serde_json::Map::new(),
            },
        ];

        let environment =
            resolve_environment_for_session_with_attachments(&config, "session_123", &attachments)
                .unwrap();

        assert_eq!(environment.provider.id(), "cli-active-environment");
        assert!(environment.switchable.is_some());
        assert!(environment.attachments[0].is_default);
        assert!(environment.attachments[0].is_default_for_shell);
        assert!(!environment.attachments[1].is_default);
        assert!(!environment.attachments[1].is_default_for_shell);
        assert_eq!(
            environment.provider.read_text("README.md").await.unwrap(),
            "local workspace"
        );
        assert_eq!(
            environment
                .provider
                .read_text("/environment/tools/README.md")
                .await
                .unwrap(),
            "local workspace"
        );
        assert!(matches!(
            environment
                .provider
                .write_text("/environment/tools/new.txt", "blocked")
                .await,
            Err(starweaver_environment::EnvironmentError::AccessDenied(_))
        ));
        assert!(environment.process_provider.is_some());
    }

    fn write_skill(path: &Path, name: &str, description: &str) {
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(
            path,
            format!(
                r"---
name: {name}
description: {description}
---
Use this skill.
"
            ),
        )
        .unwrap();
    }
}