vtcode-core 0.169.4

Core library for VT Code - a Rust-based terminal coding agent
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
//! Plan artifact I/O: persisting drafts, syncing the embedded tracker,
//! and detecting workspace validation commands.
//!
//! Depends on `artifacts` for pure content shaping and on `state` for the
//! plan-file location. Tool wiring lives in `start.rs` / `finish.rs`.

use anyhow::{Context, Result, bail};
use serde_json::Value;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use crate::tools::handlers::planning_workflow::artifacts::{
    PlanValidationReport, extract_embedded_tracker, generate_tracker_markdown_from_plan, render_plan_with_tracker,
    tracker_file_for_plan_file, tracker_has_progress_or_notes, validate_plan_content,
};
use crate::tools::handlers::planning_workflow::state::PlanningWorkflowState;
use crate::utils::file_utils::{
    ensure_dir_exists, read_file_with_context, write_file_atomic_with_context, write_file_with_context,
};

#[derive(Debug, Clone)]
pub struct PersistedPlanDraft {
    pub plan_file: PathBuf,
    pub tracker_file: Option<PathBuf>,
    pub validation: PlanValidationReport,
}

/// Allocate the workspace-local plan file when none exists.
///
/// Shared by `persist_plan_draft` (active-planning synthesis without a prior
/// `start_planning` call) and the execution-mode approval path, which must
/// persist a valid first draft without activating the planning workflow.
/// Sets the file pointer and baseline and ensures the parent directory.
/// Returns the existing path when one is already set.
pub async fn allocate_plan_file_if_missing(state: &PlanningWorkflowState) -> Result<PathBuf> {
    if let Some(existing) = state.get_plan_file().await {
        return Ok(existing);
    }
    // The dedicated plan agent can enter planning without invoking the
    // `start_planning` tool first. Plan synthesis must still have a
    // durable artifact before approval, so lazily allocate the same
    // workspace-local plan location used by `start_planning`.
    let plan_file = state
        .plans_dir()
        .join(format!("{}.md", vtcode_commons::slug::create_timestamped()));
    if let Some(parent) = plan_file.parent() {
        ensure_dir_exists(parent)
            .await
            .with_context(|| format!("Failed to create plans directory: {}", parent.display()))?;
    }
    state.set_plan_file(Some(plan_file.clone())).await;
    state.set_plan_baseline(Some(SystemTime::now())).await;
    tracing::info!(
        plan_file = %plan_file.display(),
        "Initialized missing plan file during plan synthesis"
    );
    Ok(plan_file)
}

async fn persist_global_tracker_if_missing(workspace_root: &Path, tracker_markdown: &str) -> Result<bool> {
    if workspace_root.as_os_str().is_empty() {
        return Ok(false);
    }
    let task_file = workspace_root.join(".vtcode").join("tasks").join("current_task.md");
    if tokio::fs::read_to_string(&task_file)
        .await
        .ok()
        .is_some_and(|content| !content.trim().is_empty())
    {
        return Ok(false);
    }
    if let Some(parent) = task_file.parent() {
        ensure_dir_exists(parent)
            .await
            .with_context(|| format!("Failed to create task tracker directory: {}", parent.display()))?;
    }
    write_file_atomic_with_context(&task_file, tracker_markdown, "task checklist")
        .await
        .with_context(|| format!("Failed to write task checklist: {}", task_file.display()))?;
    Ok(true)
}

async fn read_optional_file(path: &Path, context: &str) -> Result<Option<String>> {
    match tokio::fs::read_to_string(path).await {
        Ok(content) => Ok(Some(content)),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error).with_context(|| format!("Failed to read {context}: {}", path.display())),
    }
}

async fn restore_optional_file(path: &Path, content: Option<&str>, context: &str) -> Result<()> {
    if let Some(content) = content {
        return write_file_atomic_with_context(path, content, context).await;
    }

    match tokio::fs::remove_file(path).await {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error).with_context(|| format!("Failed to remove {context}: {}", path.display())),
    }
}

pub async fn sync_tracker_into_plan_file(plan_file: &Path, tracker_markdown: &str) -> Result<()> {
    let plan_content = read_file_with_context(plan_file, "plan file")
        .await
        .with_context(|| format!("Failed to read plan file: {}", plan_file.display()))?;
    let updated = render_plan_with_tracker(&plan_content, Some(tracker_markdown));
    write_file_with_context(plan_file, &updated, "plan file")
        .await
        .with_context(|| format!("Failed to write plan file: {}", plan_file.display()))?;
    Ok(())
}

pub async fn persist_plan_draft(state: &PlanningWorkflowState, plan_markdown: &str) -> Result<PersistedPlanDraft> {
    let validation = validate_plan_content(plan_markdown);
    if !validation.is_ready() {
        bail!("plan draft is not ready for persistence: {}", validation.reasons().join("; "));
    }

    let plan_file = match state.get_plan_file().await {
        Some(path) => path,
        None if state.is_active() => allocate_plan_file_if_missing(state).await?,
        None => bail!("No active plan file. Call start_planning first."),
    };
    let existing_plan = read_optional_file(&plan_file, "plan file").await?;
    let tracker_file = tracker_file_for_plan_file(&plan_file);
    let (existing_tracker, tracker_from_sidecar, original_tracker_file) = if let Some(path) = tracker_file.as_ref() {
        let sidecar = read_optional_file(path, "plan tracker file").await?;
        if sidecar.is_some() {
            let existing_tracker = sidecar.clone().filter(|value| !value.trim().is_empty());
            (existing_tracker, true, sidecar)
        } else {
            (
                existing_plan
                    .as_deref()
                    .and_then(extract_embedded_tracker)
                    .filter(|content: &String| !content.trim().is_empty()),
                false,
                None,
            )
        }
    } else {
        (
            existing_plan
                .as_deref()
                .and_then(extract_embedded_tracker)
                .filter(|content: &String| !content.trim().is_empty()),
            false,
            None,
        )
    };
    let workspace_root = state.workspace_root().unwrap_or_default();
    let global_tracker_file = (!workspace_root.as_os_str().is_empty())
        .then(|| workspace_root.join(".vtcode").join("tasks").join("current_task.md"));
    let existing_global_tracker = match global_tracker_file.as_ref() {
        Some(path) => read_optional_file(path, "task checklist").await?,
        None => None,
    };

    let should_refresh_embedded = !tracker_from_sidecar
        && existing_tracker
            .as_deref()
            .is_some_and(|tracker| !tracker_has_progress_or_notes(tracker));
    let generated_tracker = generate_tracker_markdown_from_plan(plan_markdown);
    let tracker_to_persist = if should_refresh_embedded {
        generated_tracker.or(existing_tracker.clone())
    } else {
        existing_tracker.clone().or(generated_tracker)
    };
    let Some(tracker_markdown) = tracker_to_persist.as_deref().filter(|content| !content.trim().is_empty()) else {
        bail!("unable to generate a non-empty plan task tracker");
    };
    let Some(tracker_file_path) = tracker_file.as_ref() else {
        bail!("unable to derive a plan task tracker path");
    };

    let canonical_plan = render_plan_with_tracker(plan_markdown, Some(tracker_markdown));
    let mut tracker_published = false;
    let mut global_tracker_published = false;
    let mut plan_published = false;
    let publish_result: Result<()> = async {
        // Publish the tracker artifacts before replacing the plan. Each file
        // is written atomically so readers never observe a truncated artifact.
        if let Some(parent) = tracker_file_path.parent() {
            ensure_dir_exists(parent)
                .await
                .with_context(|| format!("Failed to create plan tracker directory: {}", parent.display()))?;
        }
        write_file_atomic_with_context(tracker_file_path, tracker_markdown, "plan tracker file")
            .await
            .with_context(|| format!("Failed to write plan tracker file: {}", tracker_file_path.display()))?;
        tracker_published = true;
        global_tracker_published = persist_global_tracker_if_missing(&workspace_root, tracker_markdown).await?;
        write_file_atomic_with_context(&plan_file, &canonical_plan, "plan file")
            .await
            .with_context(|| format!("Failed to write plan file: {}", plan_file.display()))?;
        plan_published = true;
        Ok(())
    }
    .await;

    if let Err(error) = publish_result {
        let mut rollback_error = None;
        if plan_published
            && let Err(rollback) =
                restore_optional_file(&plan_file, existing_plan.as_deref(), "plan file rollback").await
        {
            rollback_error = Some(rollback);
        }
        if tracker_published
            && let Err(rollback) =
                restore_optional_file(tracker_file_path, original_tracker_file.as_deref(), "plan tracker rollback")
                    .await
        {
            rollback_error.get_or_insert(rollback);
        }
        if global_tracker_published
            && let Some(global_tracker_file) = global_tracker_file.as_ref()
            && let Err(rollback) = restore_optional_file(
                global_tracker_file,
                existing_global_tracker.as_deref(),
                "task checklist rollback",
            )
            .await
        {
            rollback_error.get_or_insert(rollback);
        }
        if let Some(rollback_error) = rollback_error {
            return Err(error.context(format!("failed to roll back plan artifacts: {rollback_error}")));
        }
        return Err(error);
    }

    Ok(PersistedPlanDraft {
        plan_file,
        tracker_file: Some(tracker_file_path.clone()),
        validation,
    })
}

pub(super) fn resolve_plan_path(workspace_root: &Path, raw_path: &str) -> PathBuf {
    let trimmed = raw_path.trim();
    if Path::new(trimmed).is_absolute() {
        PathBuf::from(trimmed)
    } else {
        workspace_root.join(trimmed)
    }
}

pub(super) fn plan_title_seed(path: &Path, fallback_plan_name: &str) -> String {
    path.file_stem()
        .and_then(|stem| stem.to_str())
        .map(|stem| stem.to_string())
        .unwrap_or_else(|| fallback_plan_name.to_string())
}

pub(super) async fn initialize_plan_file(
    plan_file: &Path,
    plan_file_display: &str,
    plan_title: &str,
    description: Option<&str>,
    validation_hints: &ValidationCommandHints,
) -> Result<()> {
    let initial_content =
        render_initial_plan_file_content(plan_title, description, plan_file_display, validation_hints);
    write_file_with_context(plan_file, &initial_content, "plan file")
        .await
        .with_context(|| format!("Failed to create plan file: {}", plan_file.display()))
}

pub(super) async fn plan_file_baseline(plan_file: &Path) -> SystemTime {
    tokio::fs::metadata(plan_file)
        .await
        .and_then(|meta| meta.modified())
        .unwrap_or_else(|_| SystemTime::now())
}

fn render_initial_plan_file_content(
    plan_title: &str,
    description: Option<&str>,
    plan_file_display: &str,
    validation_hints: &ValidationCommandHints,
) -> String {
    let mut content = format!("# {plan_title}\n\n");
    content.push_str("Status: drafting\n");
    content.push_str(&format!("Created: {}\n", chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")));
    content.push_str(&format!("Plan file: `{plan_file_display}`\n"));
    if let Some(description) = description.map(str::trim).filter(|value| !value.is_empty()) {
        content.push_str(&format!("Description: {description}\n"));
    }
    content.push('\n');
    content.push_str("> Planning workflow is active. Research first, then materialize one compact `<proposed_plan>` spec here (fit ~1500 tokens; steps as `Action -> files: [path] -> verify: [command]`, prefer file:symbol refs over prose; add `## Expected Outcomes` and `## Dependencies and Prerequisites` when material).\n");
    content.push_str(&format!(
        "> Suggested validation defaults: build/lint {}; tests {}.\n",
        validation_hints.build_and_lint, validation_hints.tests
    ));
    content
}

#[derive(Debug, Clone)]
pub(super) struct ValidationCommandHints {
    pub(super) build_and_lint: String,
    pub(super) tests: String,
}

fn package_manager_for_workspace(workspace_root: &Path) -> &'static str {
    if workspace_root.join("pnpm-lock.yaml").exists() {
        "pnpm"
    } else if workspace_root.join("yarn.lock").exists() {
        "yarn"
    } else if workspace_root.join("bun.lockb").exists() || workspace_root.join("bun.lock").exists() {
        "bun"
    } else {
        "npm"
    }
}

fn node_script_command(pm: &str, script: &str) -> String {
    match pm {
        "yarn" => format!("yarn {script}"),
        "bun" => format!("bun run {script}"),
        _ => format!("{pm} run {script}"),
    }
}

fn package_json_has_script(workspace_root: &Path, script: &str) -> bool {
    let path = workspace_root.join("package.json");
    let Ok(content) = std::fs::read_to_string(path) else {
        return false;
    };
    let Ok(json) = serde_json::from_str::<Value>(&content) else {
        return false;
    };
    json.get("scripts")
        .and_then(Value::as_object)
        .is_some_and(|scripts| scripts.contains_key(script))
}

pub(super) fn detect_validation_command_hints(workspace_root: &Path) -> ValidationCommandHints {
    if workspace_root.join("Cargo.toml").exists() {
        return ValidationCommandHints {
            build_and_lint: "`cargo check`; `cargo clippy --workspace --all-targets -- -D warnings`".to_string(),
            tests: "`cargo test` (or `cargo nextest run` if nextest is configured)".to_string(),
        };
    }

    if workspace_root.join("package.json").exists() {
        let pm = package_manager_for_workspace(workspace_root);
        let has_build = package_json_has_script(workspace_root, "build");
        let has_lint = package_json_has_script(workspace_root, "lint");
        let has_test = package_json_has_script(workspace_root, "test");

        let build_and_lint = match (has_build, has_lint) {
            (true, true) => format!("`{}`; `{}`", node_script_command(pm, "build"), node_script_command(pm, "lint")),
            (true, false) => {
                format!("`{}`; plus configured lint command for the workspace", node_script_command(pm, "build"))
            }
            (false, true) => format!(
                "`{}`; plus configured build/typecheck command for the workspace",
                node_script_command(pm, "lint")
            ),
            (false, false) => {
                format!("Use configured {pm} build/lint (or typecheck) scripts for this workspace")
            }
        };
        let tests = if has_test {
            format!("`{}`", node_script_command(pm, "test"))
        } else {
            format!("Use configured {pm} test command for this workspace")
        };

        return ValidationCommandHints { build_and_lint, tests };
    }

    if workspace_root.join("pyproject.toml").exists()
        || workspace_root.join("requirements.txt").exists()
        || workspace_root.join("setup.py").exists()
    {
        return ValidationCommandHints {
            build_and_lint: "`python -m compileall .`; run configured linter (for example `ruff check .`)".to_string(),
            tests: "`pytest`".to_string(),
        };
    }

    if workspace_root.join("go.mod").exists() {
        return ValidationCommandHints {
            build_and_lint: "`go build ./...`; `go vet ./...`".to_string(),
            tests: "`go test ./...`".to_string(),
        };
    }

    if workspace_root.join("Makefile").exists() {
        return ValidationCommandHints {
            build_and_lint: "`make lint` (or `make build` if no lint target exists)".to_string(),
            tests: "`make test`".to_string(),
        };
    }

    ValidationCommandHints {
        build_and_lint: "[project build and lint command(s)]".to_string(),
        tests: "[project test command(s)]".to_string(),
    }
}