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
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
use std::path::{Path, PathBuf};

use crate::account::{get_accounts_path, AccountStore};
use crate::project::Project;

const IDENTITY: &str = "\
You are Procyon, a terminal development harness for Stellar and Soroban smart contracts. You \
work inside the user's workspace through the tools you are given.";

const WORKING_RULES: &str = "\
## Working rules

- Locate code with `glob` and `grep` before reading it. Do not guess file paths.
- When the answer depends on how Stellar or Soroban actually behaves — storage and TTL, auth, \
SEPs, CLI flags, fees, XDR — or on explaining a contract or host error, look it up with a \
connected MCP tool and cite what you found. Prefer looking it up over recalling from memory, \
and say so plainly when no source is available rather than guessing.
- Every file tool is confined to the workspace; paths outside it are rejected, so do not try \
absolute paths elsewhere.
- `write_file` and `edit_file` change the user's files immediately and are not undoable by you. \
Read a file before editing it, and prefer `edit_file` over rewriting a whole file.
- In a project that has `caatinga.config.ts`, use the `caatinga_*` tools for build, deploy and \
invoke rather than raw `stellar` CLI commands. They take contract *names* from that config, never \
a wasm path or a contract id: Caatinga resolves those from `caatinga.artifacts.json`, deploys in \
dependency order, and regenerates bindings afterwards. Do not copy a contract id out of a deploy \
log — read it from the artifacts, or let the tool report it. In a project without that config the \
`caatinga_*` tools will refuse, and the `stellar` CLI is the right path.
- Signing is always by Stellar CLI identity alias, such as `alice`. Never pass a secret key, seed \
phrase or raw address as `source`: it would reach the process list and the session log.
- Any tool that signs and submits requires the network as an explicit argument; there is no \
default. State the network you are about to act on before calling it.
- Mainnet is refused unless the operator enabled it in the config or the environment. You cannot \
enable it — if a mainnet operation is wanted, say what the user has to set and stop. Prefer \
`caatinga_read` over `caatinga_invoke` whenever you only need to read a value: it simulates, so it \
signs nothing and costs nothing.
- When a tool fails, read its error before retrying. Do not repeat an identical failing call.";

/// How many operations the ledger keeps.
///
/// Enough to cover a build → deploy → invoke sequence and the failure that stopped it, and no more:
/// this text is prepended to every turn, so its cost is paid on each one.
const RECENT_OPERATIONS: usize = 8;

/// One tool call and how it ended.
#[derive(Debug, Clone, PartialEq)]
pub struct Operation {
    pub tool: String,
    pub ok: bool,
    /// Why it failed, in one line. `None` when it succeeded — a list of successes is context, and
    /// their output is already in the conversation.
    pub reason: Option<String>,
}

/// The last few tool calls of this session, whatever else has happened to the conversation.
///
/// The model does see tool results in its own history, but only for as long as that history
/// survives: compaction drops the head of the conversation, and `--resume` folds a log back into
/// messages. What went wrong ten minutes ago is exactly what stops being visible first, and it is
/// exactly what "why did that fail?" needs. Quick actions have the same problem from the other
/// direction — Ctrl+B runs outside any turn, so nothing recorded it for the next one.
///
/// Bounded, and holds a one-line reason rather than the tool's output: this is a ledger of what
/// happened, not a second transcript.
#[derive(Debug, Default)]
pub struct OperationLog {
    entries: std::collections::VecDeque<Operation>,
}

impl OperationLog {
    /// Records an outcome. `Err` carries the failure as the model was told it.
    pub fn record(&mut self, tool: &str, outcome: Result<(), &str>) {
        if self.entries.len() == RECENT_OPERATIONS {
            self.entries.pop_front();
        }
        self.entries.push_back(Operation {
            tool: tool.to_string(),
            ok: outcome.is_ok(),
            reason: outcome.err().map(first_line),
        });
    }

    pub fn recent(&self) -> Vec<Operation> {
        self.entries.iter().cloned().collect()
    }
}

/// The first line of an error, short enough to sit in a prompt.
///
/// A tool result can be a whole compiler run; the ledger's job is to say which call failed and
/// roughly why, and the model can read the rest with the tool that produced it.
fn first_line(text: &str) -> String {
    let line = text.lines().find(|l| !l.trim().is_empty()).unwrap_or(text);
    let line = line.trim();
    match line.char_indices().nth(160) {
        Some((cut, _)) => format!("{}", &line[..cut]),
        None => line.to_string(),
    }
}

// Rebuilt every turn so the model sees the workspace as it is now, not as it was at boot.
pub struct WorkspaceContext {
    pub cwd: PathBuf,
    pub project: Option<Project>,
    pub accounts: Vec<String>,
    pub stellar_cli: Option<String>,
    pub npx: bool,
    pub mcp_servers: Vec<String>,
    /// Named so the model knows they exist. It has `list_skills`, but a tool nobody knows to call
    /// is the same as no tool — it would answer from memory instead.
    pub skills: Vec<String>,
    /// Oldest first, from [`OperationLog`].
    pub operations: Vec<Operation>,
    /// Source files written since the last successful build, from `crate::verify`.
    pub unverified: Vec<String>,
}

impl WorkspaceContext {
    pub async fn gather(cwd: &Path, mcp_servers: &[String]) -> Self {
        let discovered = Project::discover(cwd).await;
        let project_dir = discovered.as_ref().map(|d| d.dir.clone());
        let project = discovered.map(|d| d.project);

        let accounts = match &project_dir {
            Some(dir) => AccountStore::load(&get_accounts_path(dir))
                .await
                .map(|store| {
                    store
                        .list()
                        .iter()
                        .map(|a| format!("{} ({}) [{}]", a.name, a.address, a.network))
                        .collect()
                })
                .unwrap_or_default(),
            None => Vec::new(),
        };

        Self {
            cwd: cwd.to_path_buf(),
            project,
            accounts,
            stellar_cli: stellar_cli_version().await,
            npx: which::which("npx").is_ok(),
            mcp_servers: mcp_servers.to_vec(),
            skills: Vec::new(),
            operations: Vec::new(),
            unverified: Vec::new(),
        }
    }

    /// Adds what the session knows that the filesystem does not.
    ///
    /// Separate from `gather` because neither can be discovered from `cwd`: the skill registry is
    /// process-wide and the ledger belongs to the running session.
    pub fn with_session(mut self, skills: Vec<String>, operations: Vec<Operation>) -> Self {
        self.skills = skills;
        self.operations = operations;
        self
    }

    /// Names the writes no build has covered yet. See `crate::verify`.
    pub fn with_unverified(mut self, unverified: Vec<String>) -> Self {
        self.unverified = unverified;
        self
    }

    pub fn system_prompt(&self) -> String {
        let mut out = String::from(IDENTITY);
        out.push_str("\n\n## Environment\n\n");
        out.push_str(&format!("- Workspace: {}\n", self.cwd.display()));

        match &self.project {
            Some(project) => {
                out.push_str(&format!(
                    "- Project: {} v{}\n- Default network: {}\n",
                    project.name, project.version, project.default_network
                ));
                if project.contracts.is_empty() {
                    out.push_str("- Contracts: none registered yet\n");
                } else {
                    out.push_str("- Contracts:\n");
                    for contract in &project.contracts {
                        out.push_str(&format!(
                            "  - {} ({})\n",
                            contract.name,
                            contract.address.as_deref().unwrap_or("not deployed")
                        ));
                    }
                }
                // The model must not conclude from a named project that project state exists:
                // accounts and `project_init`-backed tools still need `.procyon/`.
                if project.is_inferred() {
                    out.push_str(
                        "- Project state: read from the repository itself; there is no \
                         `.procyon/project.toml`. Tools that need project state will say so — run \
                         `project_init` only if the user asks for it.\n",
                    );
                }
            }
            None => out.push_str(
                "- Project: no .procyon/project.toml found. Use `project_init` before tools that \
                 need project state.\n",
            ),
        }

        if self.accounts.is_empty() {
            out.push_str("- Accounts: none configured\n");
        } else {
            out.push_str("- Accounts:\n");
            for account in &self.accounts {
                out.push_str(&format!("  - {}\n", account));
            }
        }

        // Stated explicitly so the model does not propose a toolchain that is not installed.
        out.push_str(&format!(
            "- stellar CLI: {}\n- npx: {}\n",
            self.stellar_cli.as_deref().unwrap_or("not installed"),
            if self.npx {
                "available"
            } else {
                "not installed"
            }
        ));
        if self.mcp_servers.is_empty() {
            out.push_str(
                "- MCP servers: none connected, so you have no way to look up Stellar facts\n",
            );
        } else {
            out.push_str("- MCP servers:\n");
            for server in &self.mcp_servers {
                out.push_str(&format!("  - {}\n", server));
            }
        }

        if self.skills.is_empty() {
            out.push_str("- Skills: none installed\n");
        } else {
            out.push_str(&format!(
                "- Skills (load with `run_skill`): {}\n",
                self.skills.join(", ")
            ));
        }

        // Named so delegation is a real option rather than something the model has to already know
        // to try. Each has its own tool list and a ceiling on what it may do — `talk_to` hands it a
        // registry cut to that ceiling, so routing to the wrong one costs nothing it can undo.
        out.push_str(
            "- Specialists (reach with `talk_to`): SorobanArchitect (contract and project \
             design, read-only), ContractDebugger (build/simulation/auth failures, may build and \
             test), StellarTransactionExpert (XDR, fees, signatures, networks, read-only), \
             SecurityAuditor (contract and permission review, read-only), FrontendIntegrator \
             (bindings, wallets, client SDKs, may write files), DeploymentEngineer (build, deploy, \
             invoke — the only one that may sign). Prefer delegating to the specialist whose \
             description matches the question over answering it yourself, especially for a \
             security review or a transaction-level question.\n",
        );

        // Writing a file always succeeds, so nothing else in this prompt distinguishes code that
        // compiles from code that was merely produced. Named per file rather than as a flag: "run
        // a build" is advice, and a list is a thing the model can see it has not done.
        if !self.unverified.is_empty() {
            out.push_str("\n## Written but never compiled\n\n");
            for path in &self.unverified {
                out.push_str(&format!("- {}\n", path));
            }
            out.push_str(
                "\nNo build or test run has covered these changes. Run `caatinga_build` (or \
                 `run_tests`) and read the result before describing this work as done. \
                 `caatinga_deploy` will refuse until then: it ships the wasm from the last build, \
                 so deploying now would put the previous version of the contract on chain.\n",
            );
        }

        // Last, and as its own section: it is the only part of the prompt that says what has
        // already been tried, and a failure buried in a list of environment facts reads as one.
        if !self.operations.is_empty() {
            out.push_str("\n## Recent operations, oldest first\n\n");
            for operation in &self.operations {
                match (&operation.reason, operation.ok) {
                    (Some(reason), _) => {
                        out.push_str(&format!("- {} — failed: {}\n", operation.tool, reason))
                    }
                    (None, true) => out.push_str(&format!("- {} — ok\n", operation.tool)),
                    (None, false) => out.push_str(&format!("- {} — failed\n", operation.tool)),
                }
            }
            out.push_str(
                "\nThese ran earlier in this session and may predate the conversation you can \
                 see. A call listed as failed failed; do not present it as done, and do not repeat \
                 it unchanged.\n",
            );
        }

        out.push('\n');
        out.push_str(WORKING_RULES);
        out
    }
}

async fn stellar_cli_version() -> Option<String> {
    if which::which("stellar").is_err() {
        return None;
    }
    let output = tokio::process::Command::new("stellar")
        .arg("--version")
        .output()
        .await
        .ok()?;
    if !output.status.success() {
        return None;
    }
    String::from_utf8_lossy(&output.stdout)
        .lines()
        .next()
        .map(|line| line.trim().to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::project::{Contract, Network};

    fn context() -> WorkspaceContext {
        WorkspaceContext {
            cwd: PathBuf::from("/w/demo"),
            project: None,
            accounts: Vec::new(),
            stellar_cli: None,
            npx: false,
            mcp_servers: Vec::new(),
            skills: Vec::new(),
            operations: Vec::new(),
            unverified: Vec::new(),
        }
    }

    #[test]
    fn states_the_identity_and_the_workspace() {
        let prompt = context().system_prompt();
        assert!(prompt.contains("Stellar and Soroban"));
        assert!(prompt.contains("/w/demo"));
    }

    #[test]
    fn says_plainly_when_there_is_no_project() {
        let prompt = context().system_prompt();
        assert!(prompt.contains("no .procyon/project.toml found"));
        assert!(prompt.contains("Accounts: none configured"));
    }

    #[test]
    fn reports_missing_tooling_instead_of_staying_silent() {
        let prompt = context().system_prompt();
        assert!(prompt.contains("stellar CLI: not installed"));
        assert!(prompt.contains("npx: not installed"));
    }

    #[test]
    fn includes_project_network_and_contract_addresses() {
        let mut ctx = context();
        ctx.project = Some(Project {
            name: "demo".to_string(),
            version: "0.2.0".to_string(),
            default_network: Network::Testnet,
            contracts: vec![
                Contract {
                    name: "token".to_string(),
                    address: Some("CDLZ".to_string()),
                    wasm_path: None,
                },
                Contract {
                    name: "pending".to_string(),
                    address: None,
                    wasm_path: None,
                },
            ],
            ..Project::new("demo")
        });
        ctx.accounts = vec!["alice (GALICE) [testnet]".to_string()];

        let prompt = ctx.system_prompt();
        assert!(prompt.contains("demo v0.2.0"));
        assert!(prompt.contains("Default network: testnet"));
        assert!(prompt.contains("token (CDLZ)"));
        assert!(prompt.contains("pending (not deployed)"));
        assert!(prompt.contains("alice (GALICE) [testnet]"));
    }

    #[test]
    fn names_the_installed_skills_so_the_model_knows_they_exist() {
        let mut ctx = context();
        ctx.skills = vec!["soroban".to_string(), "caatinga".to_string()];
        let prompt = ctx.system_prompt();
        assert!(prompt.contains("run_skill"), "got {}", prompt);
        assert!(prompt.contains("soroban, caatinga"), "got {}", prompt);
    }

    #[test]
    fn says_plainly_when_no_skill_is_installed() {
        assert!(context().system_prompt().contains("Skills: none installed"));
    }

    // The point of the ledger: a failure has to survive the conversation it happened in, because
    // compaction drops the head of that conversation and `--resume` rebuilds it.
    #[test]
    fn a_failed_operation_is_carried_with_its_reason() {
        let mut ctx = context();
        ctx.operations = vec![
            Operation {
                tool: "caatinga_build".to_string(),
                ok: true,
                reason: None,
            },
            Operation {
                tool: "caatinga_deploy".to_string(),
                ok: false,
                reason: Some("no identity named 'alice'".to_string()),
            },
        ];

        let prompt = ctx.system_prompt();
        assert!(prompt.contains("Recent operations"), "got {}", prompt);
        assert!(prompt.contains("caatinga_build — ok"), "got {}", prompt);
        assert!(
            prompt.contains("caatinga_deploy — failed: no identity named 'alice'"),
            "got {}",
            prompt
        );
        // Without this the model reads the list as history it already handled and reports the
        // deploy as done.
        assert!(
            prompt.contains("do not present it as done"),
            "got {}",
            prompt
        );
    }

    // Writing a file always succeeds, so without this nothing in the prompt tells code that
    // compiles apart from code that was merely produced.
    #[test]
    fn code_written_and_never_compiled_is_named_as_such() {
        let mut ctx = context();
        ctx.unverified = vec!["contracts/counter/src/lib.rs".to_string()];

        let prompt = ctx.system_prompt();
        assert!(
            prompt.contains("Written but never compiled"),
            "got {}",
            prompt
        );
        assert!(
            prompt.contains("contracts/counter/src/lib.rs"),
            "got {}",
            prompt
        );
        assert!(prompt.contains("caatinga_build"), "got {}", prompt);
        // Saying the deploy will refuse is what keeps the refusal from reading as a bug when the
        // model hits it.
        assert!(prompt.contains("will refuse"), "got {}", prompt);
    }

    #[test]
    fn a_workspace_with_nothing_unbuilt_carries_no_such_section() {
        assert!(!context()
            .system_prompt()
            .contains("Written but never compiled"));
    }

    #[test]
    fn a_session_with_nothing_behind_it_carries_no_empty_section() {
        assert!(!context().system_prompt().contains("Recent operations"));
    }

    #[test]
    fn the_ledger_keeps_the_most_recent_operations() {
        let mut log = OperationLog::default();
        for index in 0..RECENT_OPERATIONS + 3 {
            log.record(&format!("tool{}", index), Ok(()));
        }

        let recent = log.recent();
        assert_eq!(recent.len(), RECENT_OPERATIONS);
        assert_eq!(
            recent.first().unwrap().tool,
            "tool3",
            "oldest dropped first"
        );
        assert_eq!(recent.last().unwrap().tool, "tool10");
    }

    // A tool result can be an entire compiler run. The ledger is prepended to every later turn, so
    // it keeps a line, not a transcript.
    #[test]
    fn a_recorded_failure_is_reduced_to_one_line() {
        let mut log = OperationLog::default();
        log.record(
            "run_tests",
            Err("error[E0308]: mismatched types\n  --> src/lib.rs:12\nand 300 more lines"),
        );

        let reason = log.recent()[0].reason.clone().unwrap();
        assert_eq!(reason, "error[E0308]: mismatched types");
    }

    #[test]
    fn a_long_single_line_failure_is_cut_rather_than_carried_whole() {
        let mut log = OperationLog::default();
        log.record("stellar_invoke", Err(&"x".repeat(500)));

        let reason = log.recent()[0].reason.clone().unwrap();
        assert!(
            reason.chars().count() <= 161,
            "got {} chars",
            reason.chars().count()
        );
        assert!(reason.ends_with(''));
    }

    #[test]
    fn says_plainly_when_no_mcp_server_is_connected() {
        let prompt = context().system_prompt();
        assert!(prompt.contains("none connected"), "got {}", prompt);
    }

    #[test]
    fn lists_connected_mcp_servers_and_their_tools() {
        let mut ctx = context();
        ctx.mcp_servers = vec!["raven (https://raven.stellar.org/mcp): raven__search".to_string()];
        let prompt = ctx.system_prompt();
        assert!(prompt.contains("raven__search"), "got {}", prompt);
        assert!(prompt.contains("https://raven.stellar.org/mcp"));
    }

    #[test]
    fn directs_the_model_to_look_up_rather_than_recall() {
        let prompt = context().system_prompt();
        assert!(prompt.contains("Prefer looking it up over recalling from memory"));
        assert!(prompt.contains("host error"));
    }

    #[test]
    fn tells_the_model_to_search_before_reading() {
        let prompt = context().system_prompt();
        assert!(prompt.contains("`glob`"));
        assert!(prompt.contains("`grep`"));
        assert!(prompt.contains("Do not guess file paths"));
    }

    #[test]
    fn warns_about_mainnet_and_unrecoverable_writes() {
        let prompt = context().system_prompt();
        assert!(prompt.contains("mainnet"));
        assert!(prompt.contains("not undoable"));
    }

    #[test]
    fn an_inferred_project_is_described_but_flagged_as_having_no_state() {
        let mut ctx = context();
        ctx.project = Some(Project {
            name: "my-app".to_string(),
            source: crate::project::ProjectSource::Inferred,
            ..Project::new("my-app")
        });

        let prompt = ctx.system_prompt();
        assert!(prompt.contains("my-app v0.1.0"));
        // Naming the project must not imply `.procyon/` exists — accounts and the tools that need
        // project state still do not.
        assert!(
            prompt.contains("read from the repository itself"),
            "{}",
            prompt
        );
        assert!(prompt.contains("`project_init` only if the user asks"));
    }

    #[test]
    fn a_manifest_project_carries_no_inference_caveat() {
        let mut ctx = context();
        ctx.project = Some(Project::new("demo"));
        assert!(!ctx
            .system_prompt()
            .contains("read from the repository itself"));
    }

    #[tokio::test]
    async fn a_soroban_repo_without_procyon_state_is_still_a_project() {
        let temp = tempfile::tempdir().unwrap();
        let contract = temp.path().join("contracts").join("counter");
        tokio::fs::create_dir_all(&contract).await.unwrap();
        tokio::fs::write(
            contract.join("Cargo.toml"),
            "[package]\nname = \"counter\"\nversion = \"0.1.0\"\n\n[dependencies]\nsoroban-sdk = \"22.0.1\"\n",
        )
        .await
        .unwrap();

        let ctx = WorkspaceContext::gather(temp.path(), &[]).await;
        let project = ctx
            .project
            .as_ref()
            .expect("contracts/counter is a project");
        assert_eq!(project.contracts[0].name, "counter");
        assert!(!ctx
            .system_prompt()
            .contains("no .procyon/project.toml found"));
    }

    #[tokio::test]
    async fn gathering_in_a_directory_without_a_project_does_not_fail() {
        let temp = tempfile::tempdir().unwrap();
        let ctx = WorkspaceContext::gather(temp.path(), &[]).await;
        assert!(ctx.project.is_none());
        assert!(ctx.accounts.is_empty());
        assert!(ctx.system_prompt().contains("no .procyon/project.toml"));
    }
}

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

    // Exercises the real gather() path against the actual working directory, including the MCP
    // servers from the user's config, so this is the prompt the model actually receives.
    // cargo test dump_real_prompt -- --ignored --nocapture
    #[tokio::test]
    #[ignore]
    async fn dump_real_prompt() {
        let cwd = std::env::current_dir().unwrap();

        // Boot-time input in the real app, so a prompt printed without it would be misleading.
        let servers = match crate::config::AppConfig::load() {
            Ok(cfg) => crate::mcp::load_servers(&cfg.mcp_servers).await.1,
            Err(_) => Vec::new(),
        };

        let prompt = WorkspaceContext::gather(&cwd, &servers)
            .await
            .system_prompt();
        println!("{}", prompt);

        assert!(
            prompt.contains(&cwd.display().to_string()),
            "the prompt must name the real workspace"
        );
        assert!(prompt.contains("## Environment"));
        assert!(prompt.contains("## Working rules"));
    }
}