procyon 0.1.1

Terminal development harness for Stellar and Soroban smart contracts, driven by a language model
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
use color_eyre::{eyre::bail, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

// Must stay lowercase to match `Display`/`FromStr`, which is the spelling `project.toml` and the
// `/network` command use.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Network {
    Local,
    Testnet,
    Mainnet,
}

impl std::fmt::Display for Network {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Network::Local => write!(f, "local"),
            Network::Testnet => write!(f, "testnet"),
            Network::Mainnet => write!(f, "mainnet"),
        }
    }
}

impl std::str::FromStr for Network {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "local" => Ok(Network::Local),
            "testnet" => Ok(Network::Testnet),
            "mainnet" => Ok(Network::Mainnet),
            _ => Err(format!("Unknown network: {}", s)),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Contract {
    pub name: String,
    pub address: Option<String>,
    pub wasm_path: Option<String>,
}

// Where the project we are reporting came from. A project read off the filesystem is real enough
// to describe to the model, but nothing may write to it as if it were ours — `.procyon/` is the
// only thing we own, and it is created by `project_init`, not by looking at a directory.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ProjectSource {
    /// Loaded from `.procyon/project.toml`.
    #[default]
    Manifest,
    /// Inferred from `caatinga.config.ts` / `contracts/*/Cargo.toml`.
    Inferred,
}

// Accounts deliberately do not live here. They are owned by `AccountStore` in
// `.procyon/accounts.toml`, which is the only thing that writes them; a second list on Project
// was never written and so silently reported "no accounts" while accounts existed.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Project {
    pub name: String,
    pub version: String,
    pub default_network: Network,
    pub contracts: Vec<Contract>,
    // Never written to project.toml: it describes how *this* value was obtained, not the project.
    #[serde(skip)]
    pub source: ProjectSource,
}

/// A project found on disk, and the directory it is rooted at.
#[derive(Debug, Clone)]
pub struct Discovery {
    pub dir: PathBuf,
    pub project: Project,
}

impl Project {
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            version: "0.1.0".to_string(),
            default_network: Network::Testnet,
            contracts: Vec::new(),
            source: ProjectSource::Manifest,
        }
    }

    pub fn is_inferred(&self) -> bool {
        self.source == ProjectSource::Inferred
    }

    pub async fn save(&self, path: &Path) -> Result<()> {
        // Unlike AccountStore::save this used to assume the parent existed, which only held for
        // the one caller that had just created it.
        if let Some(parent) = path.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }
        let toml = toml::to_string_pretty(self)?;
        tokio::fs::write(path, toml).await?;
        Ok(())
    }

    pub async fn load(path: &Path) -> Result<Self> {
        let toml = tokio::fs::read_to_string(path).await?;
        let project: Self = toml::from_str(&toml)?;
        Ok(project)
    }

    pub async fn find_project_dir(start: &Path) -> Result<PathBuf> {
        let mut current = start.to_path_buf();
        loop {
            let project_file = current.join(".procyon").join("project.toml");
            if tokio::fs::try_exists(&project_file).await.unwrap_or(false) {
                return Ok(current);
            }
            if !current.pop() {
                bail!("No .procyon/project.toml found in parent directories");
            }
        }
    }

    /// Find the project `start` sits in, whether or not Procyon created it.
    ///
    /// `.procyon/project.toml` still wins wherever it exists — it is the only file we write, so a
    /// user who ran `project_init` gets exactly what they configured. Failing that we read the
    /// project off the filesystem, because requiring `project_init` inside a repo that already has
    /// `caatinga.config.ts` and `contracts/counter/Cargo.toml` meant reporting "No project" in the
    /// one place the harness is meant to be useful.
    pub async fn discover(start: &Path) -> Option<Discovery> {
        let mut current = start.to_path_buf();
        loop {
            let manifest = current.join(".procyon").join("project.toml");
            if tokio::fs::try_exists(&manifest).await.unwrap_or(false) {
                if let Ok(project) = Self::load(&manifest).await {
                    return Some(Discovery {
                        dir: current,
                        project,
                    });
                }
                // A corrupt manifest should not hide a project that is plainly there on disk.
            }
            if let Some(project) = infer_at(&current).await {
                return Some(Discovery {
                    dir: current,
                    project,
                });
            }
            if !current.pop() {
                return None;
            }
        }
    }
}

/// Read a project out of a directory's own files, or decide there is no Stellar project here.
///
/// The signal is `soroban-sdk` in a contract manifest, or a Caatinga config — not merely a
/// `Cargo.toml`, which would claim every Rust checkout on the machine.
async fn infer_at(dir: &Path) -> Option<Project> {
    let caatinga = tokio::fs::try_exists(dir.join("caatinga.config.ts"))
        .await
        .unwrap_or(false);
    let contracts = scan_contracts(dir).await;
    let root_contract = is_soroban_manifest(&dir.join("Cargo.toml")).await;

    if !caatinga && contracts.is_empty() && !root_contract {
        return None;
    }

    let (pkg_name, pkg_version) = package_json_identity(dir).await;
    let name = pkg_name
        .or(cargo_package_name(&dir.join("Cargo.toml")).await)
        .or_else(|| {
            dir.file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .filter(|n| !n.is_empty())
        })?;

    let mut contracts = contracts;
    if root_contract {
        if let Some(root) = cargo_package_name(&dir.join("Cargo.toml")).await {
            contracts.push(Contract {
                name: root,
                address: None,
                wasm_path: None,
            });
        }
    }
    apply_artifact_addresses(dir, &mut contracts).await;

    Some(Project {
        name,
        version: pkg_version.unwrap_or_else(|| "0.1.0".to_string()),
        // The filesystem does not record a preferred network. Testnet matches `Project::new` and
        // is the safe default; `allow_mainnet` gates anything that could act on it regardless.
        default_network: Network::Testnet,
        contracts,
        source: ProjectSource::Inferred,
    })
}

/// The directory Caatinga keeps contracts in — `contracts/` unless the template says otherwise.
async fn contracts_dir(dir: &Path) -> PathBuf {
    let template = tokio::fs::read_to_string(dir.join("caatinga.template.json"))
        .await
        .ok()
        .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
        .and_then(|json| {
            json.get("contracts")?
                .get("path")?
                .as_str()
                .map(str::to_string)
        });
    dir.join(template.as_deref().unwrap_or("contracts"))
}

async fn scan_contracts(dir: &Path) -> Vec<Contract> {
    let root = contracts_dir(dir).await;
    let Ok(mut entries) = tokio::fs::read_dir(&root).await else {
        return Vec::new();
    };

    let mut found = Vec::new();
    while let Ok(Some(entry)) = entries.next_entry().await {
        let manifest = entry.path().join("Cargo.toml");
        if !is_soroban_manifest(&manifest).await {
            continue;
        }
        // The crate name is what `caatinga build <name>` and the CLI take, so prefer it over the
        // directory name; they usually agree, and when they do not the manifest is the truth.
        let name = cargo_package_name(&manifest)
            .await
            .unwrap_or_else(|| entry.file_name().to_string_lossy().into_owned());
        found.push(Contract {
            name,
            address: None,
            wasm_path: None,
        });
    }
    found.sort_by(|a, b| a.name.cmp(&b.name));
    found
}

async fn is_soroban_manifest(path: &Path) -> bool {
    match tokio::fs::read_to_string(path).await {
        Ok(raw) => raw.contains("soroban-sdk"),
        Err(_) => false,
    }
}

async fn cargo_package_name(path: &Path) -> Option<String> {
    let raw = tokio::fs::read_to_string(path).await.ok()?;
    let parsed: toml::Value = toml::from_str(&raw).ok()?;
    parsed
        .get("package")?
        .get("name")?
        .as_str()
        .map(str::to_string)
}

async fn package_json_identity(dir: &Path) -> (Option<String>, Option<String>) {
    let Ok(raw) = tokio::fs::read_to_string(dir.join("package.json")).await else {
        return (None, None);
    };
    let Ok(json) = serde_json::from_str::<serde_json::Value>(&raw) else {
        return (None, None);
    };
    let field = |key: &str| {
        json.get(key)
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
            .map(str::to_string)
    };
    (field("name"), field("version"))
}

/// Fill in deployed addresses from `caatinga.artifacts.json`, which is where Caatinga records them.
///
/// The per-contract entry has been both a bare id and an object across template versions, so read
/// either shape and skip anything else rather than guessing.
async fn apply_artifact_addresses(dir: &Path, contracts: &mut [Contract]) {
    if contracts.is_empty() {
        return;
    }
    let Ok(raw) = tokio::fs::read_to_string(dir.join("caatinga.artifacts.json")).await else {
        return;
    };
    let Ok(json) = serde_json::from_str::<serde_json::Value>(&raw) else {
        return;
    };
    let Some(networks) = json.get("networks").and_then(|n| n.as_object()) else {
        return;
    };

    for contract in contracts.iter_mut() {
        // Without a project.toml there is no recorded default network, so take the first network
        // that actually has this contract deployed rather than inventing a preference.
        for network in networks.values() {
            let Some(entry) = network
                .get("contracts")
                .and_then(|c| c.as_object())
                .and_then(|c| c.get(&contract.name))
            else {
                continue;
            };
            let address = match entry {
                serde_json::Value::String(id) => Some(id.clone()),
                serde_json::Value::Object(_) => ["id", "contractId", "address"]
                    .iter()
                    .find_map(|key| entry.get(*key).and_then(|v| v.as_str()))
                    .map(str::to_string),
                _ => None,
            };
            if address.is_some() {
                contract.address = address;
                break;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::str::FromStr;

    #[test]
    fn deserializes_lowercase_network_from_project_file() {
        let toml_str = r#"
            name = "demo"
            version = "0.1.0"
            default_network = "testnet"
            contracts = []
            accounts = []
        "#;
        let project: Project = toml::from_str(toml_str).unwrap();
        assert_eq!(project.default_network.to_string(), "testnet");
    }

    #[test]
    fn a_project_file_written_before_accounts_moved_out_still_loads() {
        let legacy = r#"
            name = "demo"
            version = "0.1.0"
            default_network = "testnet"
            contracts = []

            [[accounts]]
            name = "alice"
            address = "GALICE"
            network = "testnet"
        "#;
        let project: Project = toml::from_str(legacy).expect("legacy file must still parse");
        assert_eq!(project.name, "demo");
    }

    #[test]
    fn accounts_are_not_serialized_into_the_project_file() {
        let written = toml::to_string(&Project::new("demo")).unwrap();
        assert!(
            !written.contains("accounts"),
            "accounts belong to AccountStore, not project.toml: {}",
            written
        );
    }

    #[test]
    fn serde_agrees_with_display() {
        for network in [Network::Local, Network::Testnet, Network::Mainnet] {
            let project = Project {
                default_network: network.clone(),
                ..Project::new("demo")
            };
            let written = toml::to_string(&project).unwrap();
            assert!(
                written.contains(&format!("default_network = \"{}\"", network)),
                "Display spelling of {:?} is not what serde wrote: {}",
                network,
                written
            );
        }
    }

    #[test]
    fn from_str_matches_serde() {
        for spelling in ["local", "testnet", "mainnet"] {
            let toml_str = format!(
                "name = \"d\"\nversion = \"0.1.0\"\ndefault_network = \"{}\"\ncontracts = []\naccounts = []\n",
                spelling
            );
            let project: Project = toml::from_str(&toml_str).unwrap();
            assert_eq!(
                Network::from_str(spelling).unwrap().to_string(),
                project.default_network.to_string()
            );
        }
    }

    // --- discovery -------------------------------------------------------------------------
    //
    // These build real directories rather than calling `infer_at` on a mock: the bug being fixed
    // was that a genuine on-disk layout reported "No project", so the layout is the thing to test.

    async fn write(path: &Path, body: &str) {
        tokio::fs::create_dir_all(path.parent().unwrap())
            .await
            .unwrap();
        tokio::fs::write(path, body).await.unwrap();
    }

    async fn soroban_contract(dir: &Path, crate_name: &str) {
        write(
            &dir.join("Cargo.toml"),
            &format!(
                "[package]\nname = \"{}\"\nversion = \"0.1.0\"\n\n[dependencies]\nsoroban-sdk = \"22.0.1\"\n",
                crate_name
            ),
        )
        .await;
    }

    #[tokio::test]
    async fn finds_a_caatinga_project_that_never_ran_project_init() {
        let temp = tempfile::tempdir().unwrap();
        write(&temp.path().join("caatinga.config.ts"), "export default {}").await;
        write(
            &temp.path().join("package.json"),
            r#"{"name":"my-app","version":"0.2.0"}"#,
        )
        .await;
        soroban_contract(&temp.path().join("contracts").join("counter"), "counter").await;

        let found = Project::discover(temp.path())
            .await
            .expect("a Caatinga project with a Soroban contract is a project");
        assert_eq!(found.project.name, "my-app");
        assert_eq!(found.project.version, "0.2.0");
        assert!(found.project.is_inferred());
        assert_eq!(found.project.contracts.len(), 1);
        assert_eq!(found.project.contracts[0].name, "counter");
    }

    #[tokio::test]
    async fn a_plain_rust_checkout_is_not_a_stellar_project() {
        let temp = tempfile::tempdir().unwrap();
        write(
            &temp.path().join("Cargo.toml"),
            "[package]\nname = \"cli\"\nversion = \"1.0.0\"\n\n[dependencies]\nserde = \"1\"\n",
        )
        .await;

        assert!(
            Project::discover(temp.path()).await.is_none(),
            "soroban-sdk is the signal; any Cargo.toml would claim every repo on the machine"
        );
    }

    #[tokio::test]
    async fn a_bare_contract_crate_is_a_project_on_its_own() {
        let temp = tempfile::tempdir().unwrap();
        soroban_contract(temp.path(), "token").await;

        let found = Project::discover(temp.path()).await.expect("soroban crate");
        assert_eq!(found.project.name, "token");
        assert_eq!(found.project.contracts[0].name, "token");
    }

    #[tokio::test]
    async fn the_manifest_wins_wherever_it_exists() {
        let temp = tempfile::tempdir().unwrap();
        write(&temp.path().join("caatinga.config.ts"), "export default {}").await;
        write(
            &temp.path().join("package.json"),
            r#"{"name":"from-package-json"}"#,
        )
        .await;
        Project::new("from-manifest")
            .save(&temp.path().join(".procyon").join("project.toml"))
            .await
            .unwrap();

        let found = Project::discover(temp.path()).await.unwrap();
        assert_eq!(found.project.name, "from-manifest");
        assert!(
            !found.project.is_inferred(),
            "what the user configured must not be second-guessed by the filesystem"
        );
    }

    #[tokio::test]
    async fn discovery_walks_up_from_a_subdirectory() {
        let temp = tempfile::tempdir().unwrap();
        write(&temp.path().join("caatinga.config.ts"), "export default {}").await;
        let nested = temp.path().join("src").join("components");
        tokio::fs::create_dir_all(&nested).await.unwrap();

        let found = Project::discover(&nested)
            .await
            .expect("working in src/ is still working in the project");
        assert_eq!(found.dir, temp.path());
    }

    #[tokio::test]
    async fn deployed_addresses_come_from_the_caatinga_artifacts() {
        let temp = tempfile::tempdir().unwrap();
        write(&temp.path().join("caatinga.config.ts"), "export default {}").await;
        soroban_contract(&temp.path().join("contracts").join("counter"), "counter").await;
        write(
            &temp.path().join("caatinga.artifacts.json"),
            r#"{"networks":{"testnet":{"contracts":{"counter":{"id":"CDLZ"}}}},"version":1}"#,
        )
        .await;

        let found = Project::discover(temp.path()).await.unwrap();
        assert_eq!(found.project.contracts[0].address.as_deref(), Some("CDLZ"));
    }

    #[tokio::test]
    async fn an_undeployed_contract_has_no_address_rather_than_a_wrong_one() {
        let temp = tempfile::tempdir().unwrap();
        write(&temp.path().join("caatinga.config.ts"), "export default {}").await;
        soroban_contract(&temp.path().join("contracts").join("counter"), "counter").await;
        // The shape `ctg init` actually writes: the network is there, with nothing deployed.
        write(
            &temp.path().join("caatinga.artifacts.json"),
            r#"{"project":"my-app","networks":{"testnet":{"contracts":{},"dependencyGraph":{}}},"version":1}"#,
        )
        .await;

        let found = Project::discover(temp.path()).await.unwrap();
        assert!(found.project.contracts[0].address.is_none());
    }

    #[tokio::test]
    async fn the_contracts_directory_follows_the_template() {
        let temp = tempfile::tempdir().unwrap();
        write(&temp.path().join("caatinga.config.ts"), "export default {}").await;
        write(
            &temp.path().join("caatinga.template.json"),
            r#"{"contracts":{"path":"soroban","default":"counter"}}"#,
        )
        .await;
        soroban_contract(&temp.path().join("soroban").join("counter"), "counter").await;

        let found = Project::discover(temp.path()).await.unwrap();
        assert_eq!(found.project.contracts.len(), 1);
    }

    #[tokio::test]
    async fn the_crate_name_beats_the_directory_name() {
        let temp = tempfile::tempdir().unwrap();
        // Caatinga takes the crate name, so a directory that disagrees must not win.
        soroban_contract(
            &temp.path().join("contracts").join("counter-contract"),
            "counter",
        )
        .await;

        let found = Project::discover(temp.path()).await.unwrap();
        assert_eq!(found.project.contracts[0].name, "counter");
    }

    #[tokio::test]
    async fn a_corrupt_manifest_falls_back_to_the_repository() {
        let temp = tempfile::tempdir().unwrap();
        write(&temp.path().join("caatinga.config.ts"), "export default {}").await;
        write(&temp.path().join("package.json"), r#"{"name":"my-app"}"#).await;
        write(
            &temp.path().join(".procyon").join("project.toml"),
            "this is not toml {{{",
        )
        .await;

        let found = Project::discover(temp.path())
            .await
            .expect("a broken manifest must not hide a project that is plainly there");
        assert_eq!(found.project.name, "my-app");
        assert!(found.project.is_inferred());
    }

    #[test]
    fn discovery_does_not_leak_into_the_project_file() {
        let inferred = Project {
            source: ProjectSource::Inferred,
            ..Project::new("demo")
        };
        let written = toml::to_string(&inferred).unwrap();
        assert!(
            !written.contains("source"),
            "how we found the project is not part of it: {}",
            written
        );
    }

    #[test]
    fn rejects_unknown_network() {
        let toml_str = "name = \"d\"\nversion = \"0.1.0\"\ndefault_network = \"futurenet\"\ncontracts = []\naccounts = []\n";
        assert!(toml::from_str::<Project>(toml_str).is_err());
    }
}