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
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
use super::ExecutorPluginProvider;
use super::ExecutorPluginProviderError;
use super::resolve_plugin_root;
use crate::manifest::parse_plugin_manifest_uri;
use codex_exec_server::CopyOptions;
use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::EnvironmentManager;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::ExecutorFileSystemFuture;
use codex_exec_server::FileMetadata;
use codex_exec_server::FileSystemReadStream;
use codex_exec_server::FileSystemResult;
use codex_exec_server::FileSystemSandboxContext;
use codex_exec_server::GetMetadataOptions;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_exec_server::ReadDirectoryEntry;
use codex_exec_server::ReadFileOptions;
use codex_exec_server::RemoveOptions;
use codex_exec_server::WalkOptions;
use codex_exec_server::WalkOutcome;
use codex_exec_server::WriteFileOptions;
use codex_exec_server_test_support::environment_manager_without_environments;
use codex_plugin::PluginProvider;
use codex_plugin::ResolvedPlugin;
use codex_protocol::capabilities::CapabilityRootLocation;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use std::fs;
use std::io;
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;
use tempfile::tempdir;

const MANIFEST_CONTENTS: &str = r#"{
  "name": "demo-plugin",
  "version": " 1.2.3 ",
  "description": "Demo plugin",
  "skills": "./skills",
  "mcpServers": "./.mcp.json",
  "apps": "./.app.json",
  "interface": {
    "displayName": "Demo Plugin",
    "composerIcon": "./assets/icon.svg"
  }
}"#;

#[derive(Debug, PartialEq, Eq)]
enum FileSystemCall {
    Metadata(PathUri),
    Read(PathUri),
}

struct SyntheticPluginFileSystem {
    plugin_root: PathUri,
    manifest_path: PathUri,
    calls: Mutex<Vec<FileSystemCall>>,
}

impl SyntheticPluginFileSystem {
    fn unsupported<T>() -> FileSystemResult<T> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "operation is not used by plugin resolution",
        ))
    }
}

impl ExecutorFileSystem for SyntheticPluginFileSystem {
    fn canonicalize<'a>(
        &'a self,
        _path: &'a PathUri,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, PathUri> {
        Box::pin(async { Self::unsupported() })
    }

    fn read_file<'a>(
        &'a self,
        path: &'a PathUri,
        _options: ReadFileOptions,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
        Box::pin(async move {
            self.calls
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(FileSystemCall::Read(path.clone()));
            if path == &self.manifest_path {
                Ok(MANIFEST_CONTENTS.as_bytes().to_vec())
            } else {
                Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
            }
        })
    }

    fn read_file_stream<'a>(
        &'a self,
        _path: &'a PathUri,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, FileSystemReadStream> {
        Box::pin(async { Self::unsupported() })
    }

    fn write_file<'a>(
        &'a self,
        _path: &'a PathUri,
        _contents: Vec<u8>,
        _options: WriteFileOptions,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, ()> {
        Box::pin(async { Self::unsupported() })
    }

    fn create_directory<'a>(
        &'a self,
        _path: &'a PathUri,
        _options: CreateDirectoryOptions,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, ()> {
        Box::pin(async { Self::unsupported() })
    }

    fn get_metadata<'a>(
        &'a self,
        path: &'a PathUri,
        _options: GetMetadataOptions,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, FileMetadata> {
        Box::pin(async move {
            self.calls
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(FileSystemCall::Metadata(path.clone()));
            let (is_directory, is_file) = if path == &self.plugin_root {
                (true, false)
            } else if path == &self.manifest_path {
                (false, true)
            } else {
                return Err(io::Error::new(io::ErrorKind::NotFound, "not found"));
            };
            Ok(FileMetadata {
                is_directory,
                is_file,
                is_symlink: false,
                size: 0,
                created_at_ms: 0,
                modified_at_ms: 0,
            })
        })
    }

    fn read_directory<'a>(
        &'a self,
        _path: &'a PathUri,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, Vec<ReadDirectoryEntry>> {
        Box::pin(async { Self::unsupported() })
    }

    fn walk<'a>(
        &'a self,
        _path: &'a PathUri,
        _options: WalkOptions,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, WalkOutcome> {
        Box::pin(async { Self::unsupported() })
    }

    fn remove<'a>(
        &'a self,
        _path: &'a PathUri,
        _options: RemoveOptions,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, ()> {
        Box::pin(async { Self::unsupported() })
    }

    fn copy<'a>(
        &'a self,
        _source_path: &'a PathUri,
        _destination_path: &'a PathUri,
        _options: CopyOptions,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, ()> {
        Box::pin(async { Self::unsupported() })
    }
}

fn write_manifest(plugin_root: &Path, relative_path: &str, contents: &str) {
    let manifest_path = plugin_root.join(relative_path);
    fs::create_dir_all(manifest_path.parent().expect("manifest parent"))
        .expect("create manifest parent");
    fs::write(manifest_path, contents).expect("write manifest");
}

fn selected_root(id: &str, environment_id: &str, path: &Path) -> SelectedCapabilityRoot {
    SelectedCapabilityRoot {
        id: id.to_string(),
        location: CapabilityRootLocation::Environment {
            environment_id: environment_id.to_string(),
            path: PathUri::from_host_native_path(path).expect("path URI"),
        },
    }
}

fn selected_root_uri(id: &str, environment_id: &str, path: PathUri) -> SelectedCapabilityRoot {
    SelectedCapabilityRoot {
        id: id.to_string(),
        location: CapabilityRootLocation::Environment {
            environment_id: environment_id.to_string(),
            path,
        },
    }
}

#[tokio::test]
async fn plugin_root_resolution_uses_supplied_executor_file_system() {
    let temp_dir = tempdir().expect("tempdir");
    let plugin_root = temp_dir.path().join("executor-only-plugin");
    assert!(!plugin_root.exists());
    let plugin_root = PathUri::from_host_native_path(&plugin_root).expect("plugin root URI");
    let manifest_path = plugin_root
        .join(".codex-plugin/plugin.json")
        .expect("manifest URI");
    let parsed_manifest =
        parse_plugin_manifest_uri(&plugin_root, &manifest_path, MANIFEST_CONTENTS)
            .expect("parse manifest");
    let file_system = SyntheticPluginFileSystem {
        plugin_root: plugin_root.clone(),
        manifest_path: manifest_path.clone(),
        calls: Mutex::new(Vec::new()),
    };
    let resolved = resolve_plugin_root(
        &selected_root_uri("selected-demo", "executor-test", plugin_root.clone()),
        plugin_root.clone(),
        &file_system,
    )
    .await
    .expect("resolve executor plugin");

    assert_eq!(
        resolved,
        Some(
            ResolvedPlugin::from_environment(
                "selected-demo".to_string(),
                "executor-test".to_string(),
                plugin_root.clone(),
                manifest_path.clone(),
                parsed_manifest,
            )
            .expect("valid expected descriptor")
        )
    );
    assert_eq!(
        *file_system
            .calls
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner),
        vec![
            FileSystemCall::Metadata(plugin_root),
            FileSystemCall::Metadata(manifest_path.clone()),
            FileSystemCall::Read(manifest_path),
        ]
    );
}

#[tokio::test]
async fn plugin_root_resolution_accepts_foreign_executor_file_uri() {
    let plugin_root = PathUri::parse("file:///C:/plugins/foo").expect("Windows plugin root URI");
    let manifest_path = plugin_root
        .join(".codex-plugin/plugin.json")
        .expect("manifest URI");
    let parsed_manifest =
        parse_plugin_manifest_uri(&plugin_root, &manifest_path, MANIFEST_CONTENTS)
            .expect("parse manifest");
    let file_system = SyntheticPluginFileSystem {
        plugin_root: plugin_root.clone(),
        manifest_path: manifest_path.clone(),
        calls: Mutex::new(Vec::new()),
    };
    let selected_root = selected_root_uri("selected-demo", "executor-test", plugin_root.clone());
    let resolved = resolve_plugin_root(&selected_root, plugin_root.clone(), &file_system)
        .await
        .expect("resolve executor plugin");

    assert_eq!(
        resolved,
        Some(
            ResolvedPlugin::from_environment(
                "selected-demo".to_string(),
                "executor-test".to_string(),
                plugin_root.clone(),
                manifest_path.clone(),
                parsed_manifest,
            )
            .expect("valid expected descriptor")
        )
    );
    assert_eq!(
        *file_system
            .calls
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner),
        vec![
            FileSystemCall::Metadata(plugin_root),
            FileSystemCall::Metadata(manifest_path.clone()),
            FileSystemCall::Read(manifest_path),
        ]
    );
}

#[tokio::test]
async fn standalone_capability_root_is_not_a_plugin() {
    let temp_dir = tempdir().expect("tempdir");
    let standalone_root = temp_dir.path().join("standalone-skill");
    fs::create_dir_all(&standalone_root).expect("create standalone root");
    let provider = ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));

    let resolved = provider
        .resolve(&selected_root(
            "standalone",
            LOCAL_ENVIRONMENT_ID,
            &standalone_root,
        ))
        .await
        .expect("resolve standalone root");

    assert_eq!(resolved, None);
}

#[tokio::test]
async fn root_agent_plugin_manifest_is_not_an_executor_plugin() {
    let temp_dir = tempdir().expect("tempdir");
    let plugin_root = temp_dir.path().join("agent-plugin");
    write_manifest(
        &plugin_root,
        "plugin.json",
        r#"{
          "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
          "name": "agent-plugin",
          "version": "1.0.0"
        }"#,
    );
    let provider = ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));

    let resolved = provider
        .resolve(&selected_root(
            "agent-plugin",
            LOCAL_ENVIRONMENT_ID,
            &plugin_root,
        ))
        .await
        .expect("resolve selected root");

    assert_eq!(resolved, None);
}

#[tokio::test]
async fn unavailable_environment_does_not_fall_back_to_host_filesystem() {
    let temp_dir = tempdir().expect("tempdir");
    let plugin_root = temp_dir.path().join("host-plugin");
    write_manifest(&plugin_root, ".codex-plugin/plugin.json", MANIFEST_CONTENTS);
    let provider =
        ExecutorPluginProvider::new(Arc::new(environment_manager_without_environments()));

    let err = provider
        .resolve(&selected_root("host-plugin", "missing", &plugin_root))
        .await
        .expect_err("missing environment should fail");

    assert_eq!(
        err.to_string(),
        "selected capability root `host-plugin` references unavailable environment `missing`"
    );
}

#[tokio::test]
async fn malformed_preferred_manifest_does_not_fall_through_to_alternate() {
    let temp_dir = tempdir().expect("tempdir");
    let plugin_root = temp_dir.path().join("demo-plugin");
    write_manifest(&plugin_root, ".codex-plugin/plugin.json", "{not-json");
    write_manifest(
        &plugin_root,
        ".claude-plugin/plugin.json",
        MANIFEST_CONTENTS,
    );
    let expected_path =
        PathUri::from_host_native_path(plugin_root.join(".codex-plugin/plugin.json"))
            .expect("manifest URI");
    let provider = ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));

    let err = provider
        .resolve(&selected_root(
            "selected-demo",
            LOCAL_ENVIRONMENT_ID,
            &plugin_root,
        ))
        .await
        .expect_err("malformed preferred manifest should fail");

    let ExecutorPluginProviderError::ParseManifest {
        root_id,
        path,
        source: _,
    } = err
    else {
        panic!("expected parse error");
    };
    assert_eq!(
        (root_id, path),
        ("selected-demo".to_string(), expected_path)
    );
}