procyon 0.1.2

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
use async_trait::async_trait;
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
use tera::Tera;

use super::paths::resolve_in_workspace;
use super::Tool;
use crate::account::{get_accounts_path, AccountStore};
use crate::project::Project;

pub struct ProjectInitTool;

#[async_trait]
impl Tool for ProjectInitTool {
    fn name(&self) -> &str {
        "project_init"
    }

    fn capability(&self) -> crate::risk::Capability {
        crate::risk::Capability::Write
    }

    fn description(&self) -> &str {
        "Initialize a new Soroban project with scaffolded contracts"
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "Project name"
                },
                "template": {
                    "type": "string",
                    "enum": ["token", "empty"],
                    "description": "Project template (default: empty)"
                },
                "path": {
                    "type": "string",
                    "description": "Directory to create project in (default: current directory)"
                }
            },
            "required": ["name"]
        })
    }

    async fn execute(&self, input: Value) -> Result<String, String> {
        let name = input
            .get("name")
            .and_then(|v| v.as_str())
            .ok_or("Missing 'name' parameter")?;

        let template = input
            .get("template")
            .and_then(|v| v.as_str())
            .unwrap_or("empty");

        if name.is_empty() || name.contains('/') || name.contains('\\') || name.starts_with('.') {
            return Err(format!(
                "Invalid project name '{}': must not be empty, start with '.', or contain path separators",
                name
            ));
        }

        let base_path = input.get("path").and_then(|v| v.as_str()).unwrap_or(".");

        let project_dir = resolve_in_workspace(base_path)?.join(name);
        let procyon_dir = project_dir.join(".procyon");
        let contracts_dir = project_dir.join("contracts");

        tokio::fs::create_dir_all(&procyon_dir)
            .await
            .map_err(|e| format!("Failed to create .procyon dir: {}", e))?;
        tokio::fs::create_dir_all(&contracts_dir)
            .await
            .map_err(|e| format!("Failed to create contracts dir: {}", e))?;

        let project = Project::new(name);
        project
            .save(&procyon_dir.join("project.toml"))
            .await
            .map_err(|e| format!("Failed to save project config: {}", e))?;

        if template == "token" {
            let contract_name = format!("{}_token", name.replace('-', "_"));
            scaffold_token_contract(&contracts_dir, &contract_name).await?;
        }

        Ok(format!(
            "Project '{}' initialized at {}\nTemplate: {}\n\nCreated:\n- .procyon/project.toml\n- contracts/",
            name,
            project_dir.display(),
            template
        ))
    }
}

fn to_upper_camel(name: &str) -> String {
    name.split(['_', '-'])
        .filter(|word| !word.is_empty())
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect()
}

async fn scaffold_token_contract(contracts_dir: &Path, contract_name: &str) -> Result<(), String> {
    let contract_dir = contracts_dir.join(contract_name);
    let src_dir = contract_dir.join("src");

    tokio::fs::create_dir_all(&src_dir)
        .await
        .map_err(|e| format!("Failed to create contract src dir: {}", e))?;

    let mut tera = Tera::default();
    tera.add_raw_template(
        "contract.rs",
        include_str!("../../templates/token_contract.rs"),
    )
    .map_err(|e| format!("Failed to add template: {}", e))?;
    tera.add_raw_template(
        "Cargo.toml",
        include_str!("../../templates/contract_cargo.toml"),
    )
    .map_err(|e| format!("Failed to add template: {}", e))?;

    let mut context = tera::Context::new();
    context.insert("contract_name", contract_name);
    // Computed here because Tera has no upper-camel filter; the template used to reference a
    // nonexistent `upper_camel`, which failed rendering before anything was written.
    context.insert("contract_struct", &to_upper_camel(contract_name));

    let contract_code = tera
        .render("contract.rs", &context)
        .map_err(|e| format!("Failed to render contract template: {}", e))?;
    let cargo_toml = tera
        .render("Cargo.toml", &context)
        .map_err(|e| format!("Failed to render Cargo.toml template: {}", e))?;

    tokio::fs::write(src_dir.join("lib.rs"), contract_code)
        .await
        .map_err(|e| format!("Failed to write lib.rs: {}", e))?;
    tokio::fs::write(contract_dir.join("Cargo.toml"), cargo_toml)
        .await
        .map_err(|e| format!("Failed to write Cargo.toml: {}", e))?;

    Ok(())
}

/// Which of the two scaffolds this directory actually carries — and it can be both.
///
/// The confusion this exists to end: a Caatinga template with a Procyon project nested inside it
/// gave two tools two different answers about the same checkout, `project_info` reporting no
/// project and `caatinga_doctor` reporting one, with nothing on screen explaining that they were
/// looking for different files.
async fn scaffold_label(dir: &Path, inferred: bool) -> String {
    let has = |name: &str| {
        let path = dir.join(name);
        async move { tokio::fs::try_exists(&path).await.unwrap_or(false) }
    };

    let mut found = Vec::new();
    if !inferred {
        found.push("procyon (.procyon/project.toml)");
    }
    if has("caatinga.config.ts").await || has("caatinga.config.js").await {
        found.push("caatinga (caatinga.config.ts)");
    }

    if found.is_empty() {
        // Inferred with no Caatinga config: `Project::discover` got here from a contract manifest.
        return format!("cargo only, at {}", dir.display());
    }
    format!("{} at {}", found.join(" + "), dir.display())
}

/// What to say when there is no project here at all.
///
/// Names the nearest Caatinga config below this directory when there is one, because the case that
/// produced the original complaint was a template that nests its own app one level down: the answer
/// "no project" was true of the launch directory and useless, since the project was one `cd` away.
async fn no_project_message(start: &Path) -> String {
    let nested = nearest_caatinga_child(start).await;
    let mut msg = format!(
        "No Stellar project at {} or above it: no .procyon/project.toml, no caatinga.config.ts \
         and no contract manifest that depends on soroban-sdk.",
        start.display()
    );
    if let Some(child) = nested {
        msg.push_str(&format!(
            " There is a Caatinga project one level down, at {} — Procyon treats the directory it \
             was launched from as the workspace, so relaunch it there.",
            child.display()
        ));
    } else {
        msg.push_str(
            " Run project_init to create one, or `npx @caatinga/cli init` for a Caatinga project.",
        );
    }
    msg
}

/// A Caatinga config in an immediate subdirectory, if there is exactly somewhere obvious to point.
/// One level only: this is a hint in an error message, not a search.
async fn nearest_caatinga_child(start: &Path) -> Option<PathBuf> {
    let mut entries = tokio::fs::read_dir(start).await.ok()?;
    let mut found = Vec::new();
    while let Ok(Some(entry)) = entries.next_entry().await {
        let dir = entry.path();
        if !dir.is_dir() {
            continue;
        }
        for name in ["caatinga.config.ts", "caatinga.config.js"] {
            if tokio::fs::try_exists(dir.join(name)).await.unwrap_or(false) {
                found.push(dir.clone());
            }
        }
    }
    // Sorted so the hint does not depend on `read_dir` order, which is the filesystem's business.
    found.sort();
    found.into_iter().next()
}

pub struct ProjectInfoTool;

#[async_trait]
impl Tool for ProjectInfoTool {
    fn name(&self) -> &str {
        "project_info"
    }

    fn capability(&self) -> crate::risk::Capability {
        crate::risk::Capability::ReadOnly
    }

    fn description(&self) -> &str {
        "Report the current project: name, network, contracts and signing accounts. Works whether \
         the project was set up with project_init or is a plain Caatinga/Cargo checkout."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {},
            "required": []
        })
    }

    async fn execute(&self, _input: Value) -> Result<String, String> {
        let current_dir = std::env::current_dir()
            .map_err(|e| format!("Failed to get current directory: {}", e))?;

        // `discover`, not `find_project_dir`. The strict lookup answered "No .procyon/project.toml
        // found in parent directories" inside a checkout that plainly had a `caatinga.config.ts`
        // and contracts under it, which reads as "Procyon cannot see this project" — and the model
        // then fell back to listing directories by hand. The same discovery already backs the
        // workspace prompt, so `project_info` and `/status` now agree about what project this is.
        let Some(found) = Project::discover(&current_dir).await else {
            return Err(no_project_message(&current_dir).await);
        };
        let project_dir = found.dir;
        let project = found.project;

        let mut output = format!(
            "Project: {} v{}\nNetwork: {}\nScaffold: {}\n",
            project.name,
            project.version,
            project.default_network,
            scaffold_label(&project_dir, project.is_inferred()).await,
        );

        if !project.contracts.is_empty() {
            output.push_str("\nContracts:\n");
            for contract in &project.contracts {
                let addr = contract.address.as_deref().unwrap_or("not deployed");
                output.push_str(&format!("  - {} ({})\n", contract.name, addr));
            }
        }

        // Read from the account store rather than the project file: that is where account_create
        // writes, so anything else would report an empty list.
        let store = AccountStore::load(&get_accounts_path(&project_dir))
            .await
            .map_err(|e| format!("Failed to load accounts: {}", e))?;

        if !store.list().is_empty() {
            output.push_str("\nAccounts:\n");
            for account in store.list() {
                output.push_str(&format!(
                    "  - {} ({}) [{}]\n",
                    account.name, account.address, account.network
                ));
            }
        }

        Ok(output)
    }
}

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

    // The label is what tells a reader which of the two scaffolds they are actually in, which is
    // the question that produced two tools giving two answers about one checkout.
    #[tokio::test]
    async fn the_scaffold_label_names_a_caatinga_checkout_with_no_procyon_manifest() {
        let temp = tempfile::tempdir().unwrap();
        tokio::fs::write(temp.path().join("caatinga.config.ts"), "export default {}")
            .await
            .unwrap();

        let label = scaffold_label(temp.path(), true).await;
        assert!(label.contains("caatinga (caatinga.config.ts)"), "{}", label);
        assert!(!label.contains("procyon"), "{}", label);
    }

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

        let label = scaffold_label(temp.path(), false).await;
        assert!(label.contains("procyon"), "{}", label);
        assert!(label.contains("caatinga"), "{}", label);
    }

    // "No project" was true of the launch directory and useless: the project was one `cd` away,
    // and nothing said so.
    #[tokio::test]
    async fn no_project_points_at_a_nested_caatinga_app() {
        let temp = tempfile::tempdir().unwrap();
        let nested = temp.path().join("my-app");
        tokio::fs::create_dir(&nested).await.unwrap();
        tokio::fs::write(nested.join("caatinga.config.ts"), "export default {}")
            .await
            .unwrap();

        let msg = no_project_message(temp.path()).await;
        assert!(msg.contains("my-app"), "{}", msg);
        assert!(msg.contains("relaunch"), "{}", msg);
    }

    #[test]
    fn both_templates_render() {
        let mut tera = Tera::default();
        tera.add_raw_template(
            "contract.rs",
            include_str!("../../templates/token_contract.rs"),
        )
        .unwrap();
        tera.add_raw_template(
            "Cargo.toml",
            include_str!("../../templates/contract_cargo.toml"),
        )
        .unwrap();

        let mut context = tera::Context::new();
        context.insert("contract_name", "my_token");
        context.insert("contract_struct", "MyToken");

        let contract = tera
            .render("contract.rs", &context)
            .expect("contract template must render");
        let cargo = tera
            .render("Cargo.toml", &context)
            .expect("Cargo.toml template must render");

        assert!(contract.contains("MyToken"), "struct name not substituted");
        assert!(
            !contract.contains("{{"),
            "unrendered placeholder left behind"
        );
        assert!(cargo.contains("my_token"));
        assert!(!cargo.contains("{{"));
    }

    #[test]
    fn upper_camel_handles_separators_and_casing() {
        assert_eq!(to_upper_camel("my_token"), "MyToken");
        assert_eq!(to_upper_camel("my-cool-token"), "MyCoolToken");
        assert_eq!(to_upper_camel("token"), "Token");
        assert_eq!(to_upper_camel("my__token"), "MyToken");
        assert_eq!(to_upper_camel("MY_token"), "MYToken");
    }

    #[test]
    fn rendered_struct_name_is_a_valid_rust_identifier() {
        let mut tera = Tera::default();
        tera.add_raw_template(
            "contract.rs",
            include_str!("../../templates/token_contract.rs"),
        )
        .unwrap();

        let mut context = tera::Context::new();
        context.insert("contract_name", "my_cool_token");
        context.insert("contract_struct", &to_upper_camel("my_cool_token"));

        let contract = tera.render("contract.rs", &context).unwrap();
        assert!(contract.contains("pub struct MyCoolTokenContract;"));
        assert!(contract.contains("MyCoolTokenContractClient"));
    }

    // Drives the tool itself, not just the scaffold helper: name validation, workspace
    // confinement, project.toml, and the token contract, then builds the result for wasm.
    // Uses target/ as the base because it is inside the workspace and gitignored.
    // cargo test project_init_tool_end_to_end -- --ignored --nocapture
    #[tokio::test]
    #[ignore]
    async fn project_init_tool_end_to_end() {
        let base = "target/procyon-demo";
        let name = "token_demo";
        let root = std::path::Path::new(base).join(name);
        let _ = tokio::fs::remove_dir_all(&root).await;

        let report = ProjectInitTool
            .execute(json!({"name": name, "template": "token", "path": base}))
            .await
            .expect("project_init should succeed");
        println!("--- project_init ---\n{}", report);

        // Project state
        let project_file = root.join(".procyon/project.toml");
        assert!(project_file.exists(), "missing {}", project_file.display());
        let project = Project::load(&project_file)
            .await
            .expect("project.toml parses");
        assert_eq!(project.name, name);
        assert_eq!(project.default_network.to_string(), "testnet");

        // Scaffolded contract, with the struct name derived in Rust rather than by a Tera filter
        let crate_dir = root.join("contracts").join(format!("{}_token", name));
        let lib = tokio::fs::read_to_string(crate_dir.join("src/lib.rs"))
            .await
            .expect("lib.rs");
        assert!(
            lib.contains("pub struct TokenDemoTokenContract;"),
            "got a bad struct name"
        );
        assert!(!lib.contains("{{"), "unrendered placeholder survived");
        assert!(lib.contains("#[contracterror]"));

        // It has to actually build for the target Soroban accepts.
        let wasm = std::process::Command::new("cargo")
            .args(["build", "--release", "--target", "wasm32v1-none"])
            .current_dir(&crate_dir)
            .output()
            .expect("cargo runs");
        assert!(
            wasm.status.success(),
            "generated contract failed to build:\n{}",
            String::from_utf8_lossy(&wasm.stderr)
        );

        let artifact = crate_dir.join(format!("target/wasm32v1-none/release/{}_token.wasm", name));
        let size = tokio::fs::metadata(&artifact).await.expect("wasm").len();
        println!("wasm: {} ({} bytes)", artifact.display(), size);
        assert!(size > 0);
    }

    // Compiles the scaffolded contract for real: downloads soroban-sdk and builds wasm, so it is
    // a CI gate rather than part of the fast local suite.
    // Run with: cargo test scaffolded_contract_builds -- --ignored
    #[tokio::test]
    #[ignore]
    async fn scaffolded_contract_builds_and_passes_its_own_tests() {
        let temp = tempfile::tempdir().unwrap();
        let contracts_dir = temp.path().join("contracts");

        scaffold_token_contract(&contracts_dir, "my_token")
            .await
            .expect("scaffolding must succeed");

        let crate_dir = contracts_dir.join("my_token");
        assert!(crate_dir.join("src/lib.rs").exists());
        assert!(crate_dir.join("Cargo.toml").exists());

        let tests = std::process::Command::new("cargo")
            .args(["test"])
            .current_dir(&crate_dir)
            .output()
            .expect("cargo must be runnable");
        assert!(
            tests.status.success(),
            "generated contract failed its own tests:\n{}",
            String::from_utf8_lossy(&tests.stderr)
        );

        let wasm = std::process::Command::new("cargo")
            .args(["build", "--release", "--target", "wasm32v1-none"])
            .current_dir(&crate_dir)
            .output()
            .expect("cargo must be runnable");
        assert!(
            wasm.status.success(),
            "generated contract failed to build for wasm32v1-none:\n{}",
            String::from_utf8_lossy(&wasm.stderr)
        );

        assert!(
            crate_dir
                .join("target/wasm32v1-none/release/my_token.wasm")
                .exists(),
            "no wasm artifact produced"
        );
    }
}