winx-code-agent 0.2.352

Remote-first Rust MCP runtime with Streamable HTTP, durable PTYs, and guarded agent tools
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
//! Implementation of the Initialize tool.

use std::collections::VecDeque;
use std::fmt::Write as FmtWrite;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex as StdMutex, OnceLock};
use std::time::Instant;
use tokio::sync::Mutex;
use tracing::{info, instrument, warn};

use crate::errors::{Result, WinxError};
use crate::runtime::{EmbeddedShellRuntime, ShellRuntime, ShellSessionTransition};
use crate::state::bash_state::{generate_thread_id, BashState};
use crate::types::{
    normalize_thread_id, AllowedCommands, AllowedGlobs, BashCommandMode, BashMode,
    CodeWriterConfig, FileEditMode, Initialize, InitializeType, Modes, WriteIfEmptyMode,
};
use crate::utils::mmap::read_file_to_string;
use crate::utils::path::{ensure_directory_exists, expand_user, validate_path_in_workspace};

const POLICY_WARNING_CACHE_CAPACITY: usize = 128;
static WARNED_POLICY_CONFIGURATIONS: OnceLock<StdMutex<VecDeque<Vec<String>>>> = OnceLock::new();

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum InitializeTransition {
    Created,
    AttachedExisting,
    ModeChanged,
    ShellReset,
    ResetSkippedHealthy,
    WorkspaceChanged,
    /// Read-only `status` probe; nothing changed.
    Status,
}

impl InitializeTransition {
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Created => "created",
            Self::AttachedExisting => "attached_existing",
            Self::ModeChanged => "mode_changed",
            Self::ShellReset => "shell_reset",
            Self::ResetSkippedHealthy => "reset_skipped_healthy",
            Self::WorkspaceChanged => "workspace_changed",
            Self::Status => "status",
        }
    }

    pub(crate) const fn reused(self) -> bool {
        matches!(self, Self::AttachedExisting | Self::ResetSkippedHealthy)
    }
}

#[derive(Debug)]
pub(crate) struct InitializeOutcome {
    pub(crate) text: String,
    pub(crate) transition: InitializeTransition,
    pub(crate) recovered_missing_session: bool,
    pub(crate) context_bytes: usize,
    pub(crate) guidelines_bytes: usize,
    pub(crate) initial_files_count: usize,
    pub(crate) compact_response: bool,
    pub(crate) code_writer_policy_strength: Option<&'static str>,
    pub(crate) shell_spawners_present: bool,
    pub(crate) shell_reset_retry_after_seconds: Option<u64>,
    pub(crate) temporary_artifact_dir: PathBuf,
    pub(crate) temporary_artifact_ttl_seconds: u64,
    pub(crate) temporary_artifact_max_bytes: u64,
    pub(crate) temporary_artifact_max_session_bytes: u64,
    pub(crate) temporary_artifact_max_file_bytes: u64,
    pub(crate) temporary_artifact_max_files: usize,
    pub(crate) temporary_artifact_stale_pruned_files: usize,
    pub(crate) temporary_artifact_stale_pruned_bytes: u64,
    pub(crate) temporary_code_map_max_calls: usize,
    pub(crate) temporary_code_map_max_unique_files: usize,
    /// Present only for `type = "status"` probes.
    pub(crate) session_status: Option<crate::runtime::ShellSessionStatus>,
}

/// Create a unique scratch workspace under the system temp dir, used when the
/// caller initializes without a workspace path.
fn create_playground_dir(thread_id: &str) -> Result<PathBuf> {
    #[cfg(unix)]
    let owner = crate::os::unix::effective_uid().to_string();
    #[cfg(not(unix))]
    let owner = std::process::id().to_string();

    let dir = std::env::temp_dir().join(format!("winx-playground-{owner}-{thread_id}"));
    ensure_directory_exists(&dir)?;
    Ok(dir)
}

/// Whether `cmd` is on PATH (best-effort, used only for advisory hints).
fn command_exists(cmd: &str) -> bool {
    crate::utils::executable::is_available(cmd)
}

fn code_writer_state(
    config: &CodeWriterConfig,
    workspace_root: &Path,
) -> (BashCommandMode, FileEditMode, WriteIfEmptyMode) {
    let mut config = config.clone();
    // Forgive the common `["all"]` mistake before turning relative globs absolute.
    config.allowed_globs.normalize();
    config.allowed_commands.normalize();
    config.update_relative_globs(&workspace_root.to_string_lossy());

    (
        BashCommandMode {
            bash_mode: BashMode::NormalMode,
            allowed_commands: config.allowed_commands,
        },
        FileEditMode { allowed_globs: config.allowed_globs.clone() },
        WriteIfEmptyMode { allowed_globs: config.allowed_globs },
    )
}

fn mode_to_state(
    mode: Modes,
    config: Option<&CodeWriterConfig>,
    workspace_root: &Path,
) -> Result<(BashCommandMode, FileEditMode, WriteIfEmptyMode)> {
    match mode {
        Modes::Wcgw => Ok((
            BashCommandMode {
                bash_mode: BashMode::NormalMode,
                allowed_commands: AllowedCommands::All("all".to_string()),
            },
            FileEditMode { allowed_globs: AllowedGlobs::All("all".to_string()) },
            WriteIfEmptyMode { allowed_globs: AllowedGlobs::All("all".to_string()) },
        )),
        Modes::Architect => Ok((
            BashCommandMode {
                bash_mode: BashMode::RestrictedMode,
                allowed_commands: AllowedCommands::List(
                    crate::utils::bash_parser::architect_allowed_commands(),
                ),
            },
            FileEditMode { allowed_globs: AllowedGlobs::List(vec![]) },
            WriteIfEmptyMode { allowed_globs: AllowedGlobs::List(vec![]) },
        )),
        Modes::CodeWriter => {
            let config = config.ok_or_else(|| {
                WinxError::ArgumentParseError(
                    "code_writer_config is required when mode_name is code_writer.".to_string(),
                )
            })?;
            Ok(code_writer_state(config, workspace_root))
        }
    }
}

fn active_code_writer_config(state: &BashState) -> Option<CodeWriterConfig> {
    (state.mode == Modes::CodeWriter).then(|| CodeWriterConfig {
        allowed_globs: state.file_edit_mode.allowed_globs.clone(),
        allowed_commands: state.bash_command_mode.allowed_commands.clone(),
    })
}

fn active_code_writer_policy(state: &BashState) -> (Option<&'static str>, Vec<String>) {
    if state.mode != Modes::CodeWriter {
        return (None, Vec::new());
    }

    match &state.bash_command_mode.allowed_commands {
        AllowedCommands::All(value) if value == "all" => (Some("unrestricted"), Vec::new()),
        AllowedCommands::All(_) => (Some("restricted"), Vec::new()),
        AllowedCommands::List(commands) => {
            let bypass = crate::utils::bash_parser::detect_allowlist_bypass(commands);
            let strength = if bypass.is_empty() { "restricted" } else { "weak" };
            (Some(strength), bypass)
        }
    }
}

fn warn_code_writer_policy_once(state: &BashState, bypass: &[String]) {
    if bypass.is_empty() {
        return;
    }
    let AllowedCommands::List(commands) = &state.bash_command_mode.allowed_commands else {
        return;
    };

    let cache = WARNED_POLICY_CONFIGURATIONS
        .get_or_init(|| StdMutex::new(VecDeque::with_capacity(POLICY_WARNING_CACHE_CAPACITY)));
    let mut cache = cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
    if cache.iter().any(|seen| seen == commands) {
        return;
    }
    if cache.len() == POLICY_WARNING_CACHE_CAPACITY {
        cache.pop_front();
    }
    cache.push_back(commands.clone());
    drop(cache);

    warn!(
        commands = ?bypass,
        "code_writer allowlist includes shell-spawning commands; the command allowlist is \
         effectively bypassable and does not sandbox the agent"
    );
}

fn append_code_writer_policy_warning(response: &mut String, bypass: &[String]) {
    if bypass.is_empty() {
        return;
    }
    let _ = writeln!(
        response,
        "\n⚠️  SECURITY: code_writer allowlist includes shell/eval commands ({}). \
         They execute arbitrary code from string arguments (e.g. `bash -c …`, \
         `find -exec …`), so the command allowlist is effectively bypassable and \
         does NOT sandbox the agent. Drop them if you intended a hard restriction.",
        bypass.join(", ")
    );
}

fn read_initial_files_simple(files: &[String], workspace: &std::path::Path) -> String {
    let mut output = String::new();
    for file_path in files {
        let expanded = expand_user(file_path);
        let path = if std::path::Path::new(&expanded).is_absolute() {
            PathBuf::from(&expanded)
        } else {
            workspace.join(&expanded)
        };

        if let Ok(validated) = validate_path_in_workspace(&path, workspace) {
            if validated.exists() && validated.is_file() {
                if let Ok(content) = read_file_to_string(&validated, 10_000_000) {
                    let _ = write!(output, "\n{file_path}\n```\n{content}\n```\n");
                }
            }
        }
    }
    output
}

fn prepare_workspace(
    initialize: &Initialize,
    thread_id: &str,
    response: &mut String,
) -> Result<PathBuf> {
    let workspace_path_str = expand_user(&initialize.any_workspace_path);
    if workspace_path_str.is_empty() {
        // wcgw parity: no path given → spin up a scratch playground instead of
        // forcing the agent to always supply a workspace.
        let playground = create_playground_dir(thread_id)?;
        let _ = writeln!(
            response,
            "No workspace path provided; created a playground at {}",
            playground.display()
        );
        return Ok(playground);
    }

    let workspace_path = PathBuf::from(&workspace_path_str);
    let mut folder_to_start = workspace_path.clone();

    if workspace_path.exists() {
        if workspace_path.is_file() {
            folder_to_start = workspace_path.parent().unwrap_or(&workspace_path).to_path_buf();
            let _ =
                writeln!(response, "Using parent directory of file: {}", folder_to_start.display());
        } else if workspace_path.is_dir() {
            let _ = writeln!(response, "Using workspace directory: {}", folder_to_start.display());
        }
    } else if workspace_path.is_absolute() {
        ensure_directory_exists(&workspace_path).map_err(|e| {
            WinxError::WorkspacePathError(format!("Failed to create workspace: {e}"))
        })?;
        let _ = writeln!(response, "Created workspace directory: {}", workspace_path.display());
    }

    // Canonicalize so downstream comparisons (workspace checks, glob prefixes) match
    // paths that were canonicalized via fs::canonicalize — important on macOS where
    // /var, /tmp etc. are symlinks to /private/var, /private/tmp.
    if folder_to_start.exists() {
        if let Ok(canonical) = folder_to_start.canonicalize().map(crate::utils::path::simplified) {
            folder_to_start = canonical;
        }
    }

    Ok(folder_to_start)
}

fn initialize_thread_id(initialize: &Initialize) -> String {
    let thread_id = normalize_thread_id(&initialize.thread_id);
    if thread_id.is_empty() {
        generate_thread_id()
    } else {
        thread_id
    }
}

fn validate_thread_id(initialize: &Initialize) -> Result<()> {
    if initialize.init_type != InitializeType::FirstCall
        && normalize_thread_id(&initialize.thread_id).is_empty()
    {
        return Err(WinxError::ThreadIdMismatch(
            "Thread id should be provided if type != 'first_call', including when resetting."
                .to_string(),
        ));
    }

    Ok(())
}

fn load_guidelines(workspace: &Path) -> String {
    let mut output = String::new();
    let mut candidates = Vec::new();
    if let Some(home) = home::home_dir() {
        candidates.push(home.join(".winx").join("AGENTS.md"));
        candidates.push(home.join(".winx").join("CLAUDE.md"));
        candidates.push(home.join(".wcgw").join("AGENTS.md"));
        candidates.push(home.join(".wcgw").join("CLAUDE.md"));
    }
    candidates.push(workspace.join("AGENTS.md"));
    candidates.push(workspace.join("CLAUDE.md"));

    for path in candidates {
        if path.is_file() {
            if let Ok(content) = fs::read_to_string(&path) {
                let _ = writeln!(output, "\n## {}\n{}", path.display(), content);
            }
        }
    }
    output
}

pub async fn handle_tool_call(
    bash_state_arc: &Arc<Mutex<Option<BashState>>>,
    initialize: Initialize,
) -> Result<String> {
    handle_tool_call_with_runtime(&EmbeddedShellRuntime, bash_state_arc, initialize).await
}

pub async fn handle_tool_call_with_runtime(
    runtime: &dyn ShellRuntime,
    bash_state_arc: &Arc<Mutex<Option<BashState>>>,
    initialize: Initialize,
) -> Result<String> {
    Ok(handle_tool_call_with_runtime_detailed(runtime, bash_state_arc, initialize).await?.text)
}

#[instrument(level = "info", skip(runtime, bash_state_arc, initialize))]
#[allow(clippy::too_many_lines)]
pub(crate) async fn handle_tool_call_with_runtime_detailed(
    runtime: &dyn ShellRuntime,
    bash_state_arc: &Arc<Mutex<Option<BashState>>>,
    mut initialize: Initialize,
) -> Result<InitializeOutcome> {
    let mut response = String::new();
    let mut context_bytes = 0;
    let mut guidelines_bytes = 0;
    let initial_files_count = initialize.initial_files_to_read.len();

    info!("Initialize called for workspace: {}", initialize.any_workspace_path);

    validate_thread_id(&initialize)?;
    let thread_id = initialize_thread_id(&initialize);
    if initialize.init_type == InitializeType::Status {
        return describe_session_status(runtime, bash_state_arc, &thread_id).await;
    }
    let mut bash_state_guard = bash_state_arc.lock().await;
    let recovered_request = if bash_state_guard.is_none() {
        match initialize.init_type {
            InitializeType::UserAskedModeChange => Some("user_asked_mode_change"),
            InitializeType::ResetShell => Some("reset_shell"),
            InitializeType::FirstCall
            | InitializeType::UserAskedChangeWorkspace
            | InitializeType::Status => None,
        }
    } else {
        None
    };
    if let Some(requested_transition) = recovered_request {
        info!(requested_transition, "Initialize recovered a missing live session as first_call");
        initialize.init_type = InitializeType::FirstCall;
    }
    if initialize.init_type != InitializeType::FirstCall && bash_state_guard.is_none() {
        return Err(WinxError::BashStateNotInitialized);
    }
    let local_attach = initialize.init_type == InitializeType::FirstCall
        && bash_state_guard
            .as_ref()
            .is_some_and(|state| state.initialized && state.current_thread_id == thread_id);
    let folder_to_start = if local_attach {
        bash_state_guard
            .as_ref()
            .map_or_else(|| PathBuf::from("/tmp"), |state| state.workspace_root.clone())
    } else {
        prepare_workspace(&initialize, &thread_id, &mut response)?
    };
    let requested_mode = Modes::from(&initialize.mode_name);
    let preserve_active_mode =
        local_attach || initialize.init_type == InitializeType::UserAskedChangeWorkspace;
    let (mode, bash_command_mode, file_edit_mode, write_if_empty_mode) = if preserve_active_mode {
        let Some(state) = bash_state_guard.as_ref() else {
            return Err(WinxError::BashStateNotInitialized);
        };
        (
            state.mode,
            state.bash_command_mode.clone(),
            state.file_edit_mode.clone(),
            state.write_if_empty_mode.clone(),
        )
    } else {
        let (bash_command_mode, file_edit_mode, write_if_empty_mode) = mode_to_state(
            requested_mode,
            initialize.code_writer_config.as_ref(),
            &folder_to_start,
        )?;
        (requested_mode, bash_command_mode, file_edit_mode, write_if_empty_mode)
    };

    let transition;
    let mut compact_response = false;
    let mut shell_reset_retry_after_seconds = None;

    match initialize.init_type {
        InitializeType::Status => {
            return Err(WinxError::ArgumentParseError(
                "status probes are answered before any session transition".to_string(),
            ));
        }
        InitializeType::FirstCall => {
            let configured = if local_attach {
                let Some(state) = bash_state_guard.as_mut() else {
                    return Err(WinxError::BashStateNotInitialized);
                };
                // Refresh guardian activity without resetting the PTY or waiting
                // behind an unrelated long-running shell action.
                let mut configured = runtime.attach_session(state).await?;
                configured.attached_existing = true;
                configured
            } else {
                let mut new_bash_state = BashState::new();
                new_bash_state.current_thread_id.clone_from(&thread_id);
                new_bash_state.mode = mode;
                new_bash_state.bash_command_mode = bash_command_mode;
                new_bash_state.file_edit_mode = file_edit_mode;
                new_bash_state.write_if_empty_mode = write_if_empty_mode;
                new_bash_state.initialized = true;

                let resumed_context = if initialize.task_id_to_resume.trim().is_empty() {
                    None
                } else {
                    crate::tools::context_save::load_saved_context(&initialize.task_id_to_resume)?
                };

                if let Some((memory_data, snapshot)) = &resumed_context {
                    if let Some(snapshot) = snapshot {
                        new_bash_state.apply_snapshot(snapshot);
                        new_bash_state.current_thread_id.clone_from(&thread_id);
                    }
                    let _ = writeln!(
                        response,
                        "\n# Resumed task {}\nFollowing is the retrieved task context:\n{}",
                        initialize.task_id_to_resume, memory_data
                    );
                }

                // A bash snapshot already carries cwd/workspace. Without one, prefer
                // the project root recorded in the resumed memory (so the agent lands
                // back in the right repo), then fall back to the provided folder.
                if resumed_context.as_ref().and_then(|(_, snapshot)| snapshot.as_ref()).is_none() {
                    let resumed_root = resumed_context
                        .as_ref()
                        .and_then(|(memory, _)| {
                            crate::tools::context_save::extract_project_root(memory)
                        })
                        .filter(|root| root.exists());
                    let target = resumed_root.as_deref().unwrap_or(folder_to_start.as_path());
                    if target.exists() {
                        new_bash_state.update_cwd(target)?;
                        new_bash_state.update_workspace_root(target)?;
                    }
                }
                let configured = runtime
                    .configure_session(&mut new_bash_state, ShellSessionTransition::FirstCall)
                    .await?;
                *bash_state_guard = Some(new_bash_state);
                configured
            };

            transition = if configured.attached_existing {
                InitializeTransition::AttachedExisting
            } else {
                InitializeTransition::Created
            };
            compact_response = configured.attached_existing
                && initialize.initial_files_to_read.is_empty()
                && initialize.task_id_to_resume.is_empty();

            if compact_response {
                response.clear();
                let state = bash_state_guard.as_ref().ok_or(WinxError::BashStateNotInitialized)?;
                let _ = writeln!(
                    response,
                    "Attached to the existing durable Winx session; PTY, cwd, mode, and prior \
                     context were preserved.\ncwd={}\nmode={}",
                    state.cwd.display(),
                    state.mode
                );
                if let Some(attach_hint) = configured.attach_hint.as_deref() {
                    let _ = writeln!(response, "Attach terminal: {attach_hint}");
                }
                response.push_str(
                    "Context and instructions are unchanged. Continue with the existing thread; \
                     use an explicit mode/workspace change or reset only when intended.\n",
                );
            } else {
                if configured.attached_existing {
                    response.push_str(
                        "\nAttached to the existing durable session for this principal/workspace; \
                         the guardian-owned PTY and cwd were preserved. Use `reset_shell` or an \
                         explicit workspace/mode change when replacement is intended.\n",
                    );
                }

                let _ = write!(
                    response,
                    "\n# Environment\nSystem: {}\nMachine: {}\nInitialized in directory: {}\n",
                    std::env::consts::OS,
                    std::env::consts::ARCH,
                    bash_state_guard
                        .as_ref()
                        .map_or(folder_to_start.as_path(), |state| state.cwd.as_path())
                        .display()
                );

                if command_exists("rg") {
                    let _ = writeln!(
                        response,
                        "\n# Available commands\nUse ripgrep `rg` instead of `grep`/`find -name` — \
                         it's much faster and respects .gitignore."
                    );
                }

                if let Some(attach_hint) = configured.attach_hint.as_deref() {
                    let _ = writeln!(response, "\nAttach terminal: {attach_hint}");
                }

                // Explain the actual active policy. A daemon reattach can restore a
                // different mode than the model redundantly supplied.
                let active_config = bash_state_guard.as_ref().and_then(active_code_writer_config);
                let active_mode = bash_state_guard.as_ref().map_or(mode, |state| state.mode);
                let _ = writeln!(
                    response,
                    "\n{}",
                    crate::utils::mode_prompts::mode_prompt(active_mode, active_config.as_ref())
                );

                let active_workspace = bash_state_guard
                    .as_ref()
                    .map_or(folder_to_start.as_path(), |state| state.workspace_root.as_path());

                let guidelines = load_guidelines(active_workspace);
                guidelines_bytes = guidelines.len();
                if !guidelines.is_empty() {
                    let _ = writeln!(response, "\n# Agent guidelines\n{guidelines}");
                }

                if let Ok((repo_context, _)) =
                    crate::utils::repo::get_repo_context(active_workspace)
                {
                    context_bytes = repo_context.len();
                    let _ = writeln!(response, "\n# Workspace structure\n{repo_context}");
                }

                if !initialize.initial_files_to_read.is_empty() {
                    let content = read_initial_files_simple(
                        &initialize.initial_files_to_read,
                        active_workspace,
                    );
                    if !content.is_empty() {
                        let _ = writeln!(response, "\n# Requested files\n{content}");
                    }
                }
            }
            if let Some(requested_transition) = recovered_request {
                let _ = writeln!(
                    response,
                    "\nRecovered missing live session: `{requested_transition}` arrived after \
                     the adapter no longer had session state. Winx safely performed `first_call` \
                     with the same thread and intended workspace; continue with the returned \
                     thread_id/workspace_root pair."
                );
            }
        }
        InitializeType::UserAskedModeChange => {
            transition = InitializeTransition::ModeChanged;
            if let Some(state) = bash_state_guard.as_mut() {
                state.mode = mode;
                state.bash_command_mode = bash_command_mode;
                state.file_edit_mode = file_edit_mode;
                state.write_if_empty_mode = write_if_empty_mode;
                runtime.configure_session(state, ShellSessionTransition::ModeChange).await?;
                let _ = writeln!(response, "Changed mode to: {mode:?}");
                let active_config = active_code_writer_config(state);
                let _ = writeln!(
                    response,
                    "\n{}",
                    crate::utils::mode_prompts::mode_prompt(mode, active_config.as_ref())
                );
            } else {
                return Err(WinxError::BashStateNotInitialized);
            }
        }
        InitializeType::ResetShell => {
            if let Some(state) = bash_state_guard.as_mut() {
                if let Some(retry_after) = state.shell_reset_retry_after(Instant::now()) {
                    transition = InitializeTransition::ResetSkippedHealthy;
                    compact_response = true;
                    let retry_after_seconds = retry_after.as_secs().max(1);
                    shell_reset_retry_after_seconds = Some(retry_after_seconds);
                    let _ = writeln!(
                        response,
                        "Skipped redundant reset_shell: the PTY was replaced recently and no \
                         shell-runtime failure has occurred since. The existing PTY, cwd, mode, \
                         and context were preserved. Continue with BashCommand; retry reset_shell \
                         only after a shell-runtime failure or in {retry_after_seconds} seconds."
                    );
                } else {
                    state.mode = mode;
                    state.bash_command_mode = bash_command_mode;
                    state.file_edit_mode = file_edit_mode;
                    state.write_if_empty_mode = write_if_empty_mode;
                    if let Err(error) =
                        runtime.configure_session(state, ShellSessionTransition::Reset).await
                    {
                        state.record_shell_runtime_failure();
                        return Err(error);
                    }
                    state.record_shell_reset(Instant::now());
                    transition = InitializeTransition::ShellReset;
                    response.push_str("Reset shell (new PTY created)\n");
                }
            } else {
                return Err(WinxError::BashStateNotInitialized);
            }
        }
        InitializeType::UserAskedChangeWorkspace => {
            transition = InitializeTransition::WorkspaceChanged;
            if let Some(state) = bash_state_guard.as_mut() {
                if folder_to_start.exists() {
                    state.update_cwd(&folder_to_start)?;
                    state.update_workspace_root(&folder_to_start)?;
                    runtime
                        .configure_session(state, ShellSessionTransition::WorkspaceChange)
                        .await?;
                    let _ =
                        writeln!(response, "Changed workspace to: {}", folder_to_start.display());
                } else {
                    let _ = writeln!(
                        response,
                        "Warning: Workspace path {} does not exist",
                        folder_to_start.display()
                    );
                }
            } else {
                return Err(WinxError::BashStateNotInitialized);
            }
        }
    }

    let state = bash_state_guard.as_ref().ok_or(WinxError::BashStateNotInitialized)?;
    let temporary_artifact =
        crate::utils::agent_temp::prepare_session(&state.workspace_root, &state.current_thread_id);
    let temporary_artifact_instruction = if compact_response {
        format!(
            "Use temporary_artifact_dir={} for a small stable set of session-local derived \
             helpers; BashCommand exports the same path as WINX_TEMP_DIR. Reuse helpers instead \
             of creating CodeMap carriers; helper maps accept one existing file and are limited \
             to {} unique files / {} calls. Near its quota Winx reclaims only helpers inactive for \
             the advertised TTL; if it remains over budget, explicitly remove obsolete helpers \
             before running ordinary commands.",
            temporary_artifact.directory.display(),
            crate::utils::agent_temp::MAX_DERIVED_CODE_MAP_UNIQUE_FILES,
            crate::utils::agent_temp::MAX_DERIVED_CODE_MAP_CALLS,
        )
    } else {
        format!(
            "Use temporary_artifact_dir={} for session-local derived helpers only; keep names \
             short, reuse one stable file per purpose, preserve source-path/line provenance, and \
             treat helpers as non-canonical. Never create a carrier solely for CodeMap. The \
             directory is created on demand, limited to {} files / {} bytes for this session, and \
             expired after {} seconds of inactivity. Every BashCommand PTY exports the same path \
             as WINX_TEMP_DIR; shell-generated helpers must stay beneath it. Winx audits actual \
             usage after Bash. At a high-water mark it reclaims only helpers inactive for the full \
             TTL, never fresh artifacts; if the hard limit remains exceeded, explicitly inspect and \
             remove obsolete helpers before ordinary commands can continue. \
             Helper CodeMap accepts one existing file and is limited to {} unique files / {} calls \
             in this live session.",
            temporary_artifact.directory.display(),
            temporary_artifact.max_session_files,
            temporary_artifact.max_session_bytes,
            temporary_artifact.ttl_seconds,
            crate::utils::agent_temp::MAX_DERIVED_CODE_MAP_UNIQUE_FILES,
            crate::utils::agent_temp::MAX_DERIVED_CODE_MAP_CALLS,
        )
    };
    let _ = writeln!(
        response,
        "\nUse thread_id={thread_id} for all winx tool calls.\nUse workspace_root={} for all winx tool calls.\n{temporary_artifact_instruction}\nBefore every reuse, confirm workspace_root still matches the user's current project. Keep this exact pair together. workspace_root identifies this project session; it does not restrict target paths allowed by policy.",
        state.workspace_root.display(),
    );

    let (code_writer_policy_strength, bypass) =
        bash_state_guard.as_ref().map_or((None, Vec::new()), active_code_writer_policy);
    if let Some(state) = bash_state_guard.as_ref() {
        warn_code_writer_policy_once(state, &bypass);
    }
    if compact_response {
        if let Some(strength) = code_writer_policy_strength {
            let _ = writeln!(
                response,
                "code_writer_policy={strength} shell_spawners_present={}",
                !bypass.is_empty()
            );
        }
    } else {
        append_code_writer_policy_warning(&mut response, &bypass);
        crate::utils::orchestration::append_initialize_instructions(&mut response);
    }

    Ok(InitializeOutcome {
        text: response,
        transition,
        recovered_missing_session: recovered_request.is_some(),
        context_bytes,
        guidelines_bytes,
        initial_files_count,
        compact_response,
        code_writer_policy_strength,
        shell_spawners_present: !bypass.is_empty(),
        shell_reset_retry_after_seconds,
        temporary_artifact_dir: temporary_artifact.directory,
        temporary_artifact_ttl_seconds: temporary_artifact.ttl_seconds,
        temporary_artifact_max_bytes: temporary_artifact.max_total_bytes,
        temporary_artifact_max_session_bytes: temporary_artifact.max_session_bytes,
        temporary_artifact_max_file_bytes: temporary_artifact.max_file_bytes,
        temporary_artifact_max_files: temporary_artifact.max_session_files,
        temporary_artifact_stale_pruned_files: temporary_artifact.stale_pruned_files,
        temporary_artifact_stale_pruned_bytes: temporary_artifact.stale_pruned_bytes,
        temporary_code_map_max_calls: crate::utils::agent_temp::MAX_DERIVED_CODE_MAP_CALLS,
        temporary_code_map_max_unique_files:
            crate::utils::agent_temp::MAX_DERIVED_CODE_MAP_UNIQUE_FILES,
        session_status: None,
    })
}

/// `Initialize(type = "status")`: describe the live session for `thread_id`
/// without creating, resetting or reconfiguring anything.
async fn describe_session_status(
    runtime: &dyn ShellRuntime,
    bash_state_arc: &Arc<Mutex<Option<BashState>>>,
    thread_id: &str,
) -> Result<InitializeOutcome> {
    let (workspace_root, cwd, mode, bound_thread_id) = {
        let guard = bash_state_arc.lock().await;
        let state = guard.as_ref().ok_or(WinxError::BashStateNotInitialized)?;
        if !state.initialized {
            return Err(WinxError::BashStateNotInitialized);
        }
        if state.current_thread_id != thread_id {
            return Err(WinxError::ThreadIdMismatch(format!(
                "thread_id {thread_id} is not the session bound here ({})",
                state.current_thread_id
            )));
        }
        (
            state.workspace_root.clone(),
            state.cwd.clone(),
            state.mode,
            state.current_thread_id.clone(),
        )
    };
    let status = runtime.describe_session(bash_state_arc).await?;
    let temporary_artifact =
        crate::utils::agent_temp::session_info(&workspace_root, &bound_thread_id);
    let mut response = String::new();
    let _ = writeln!(response, "# Session status");
    let _ = writeln!(response, "thread_id={bound_thread_id}");
    let _ = writeln!(response, "workspace_root={}", workspace_root.display());
    let _ = writeln!(response, "cwd={}", cwd.display());
    let _ = writeln!(response, "mode={mode}");
    let _ = writeln!(response, "runtime={}", status.runtime);
    if let Some(pid) = status.guardian_pid {
        let _ = writeln!(
            response,
            "guardian_pid={pid} guardian_epoch={} guardian_build={}",
            status.guardian_epoch.as_deref().unwrap_or("?"),
            status.guardian_build.as_deref().unwrap_or("?")
        );
    }
    let _ = writeln!(response, "command_running={}", status.command_running);
    if !status.background_command_ids.is_empty() {
        let _ = writeln!(response, "background_command_ids={:?}", status.background_command_ids);
    }
    let _ = writeln!(
        response,
        "next: {}",
        if status.command_running {
            "poll BashCommand status_check for the running command"
        } else {
            "keep using this thread_id/workspace_root pair; nothing to re-initialize"
        }
    );
    Ok(InitializeOutcome {
        text: response,
        transition: InitializeTransition::Status,
        recovered_missing_session: false,
        context_bytes: 0,
        guidelines_bytes: 0,
        initial_files_count: 0,
        compact_response: true,
        code_writer_policy_strength: None,
        shell_spawners_present: false,
        shell_reset_retry_after_seconds: None,
        temporary_artifact_dir: temporary_artifact.directory,
        temporary_artifact_ttl_seconds: temporary_artifact.ttl_seconds,
        temporary_artifact_max_bytes: temporary_artifact.max_total_bytes,
        temporary_artifact_max_session_bytes: temporary_artifact.max_session_bytes,
        temporary_artifact_max_file_bytes: temporary_artifact.max_file_bytes,
        temporary_artifact_max_files: temporary_artifact.max_session_files,
        temporary_artifact_stale_pruned_files: temporary_artifact.stale_pruned_files,
        temporary_artifact_stale_pruned_bytes: temporary_artifact.stale_pruned_bytes,
        temporary_code_map_max_calls: crate::utils::agent_temp::MAX_DERIVED_CODE_MAP_CALLS,
        temporary_code_map_max_unique_files:
            crate::utils::agent_temp::MAX_DERIVED_CODE_MAP_UNIQUE_FILES,
        session_status: Some(status),
    })
}