rvpm 3.26.0

Fast Neovim plugin manager with pre-compiled loader and merge optimization
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
// AI-assisted `rvpm add` (#93).
//
// このモジュールは静的 scan (#90, plugin_scan.rs) の代わりに外部 AI CLI
// (claude / gemini / codex) を呼んで `[[plugins]]` 全体 + 必要な hook ファイル
// を提案させる。設計トレードオフ:
//
//   - **CLI subprocess 経由**: API key 管理を user の `claude login` / `gemini auth`
//     に委ねる。SDK 直叩きより薄く保ち、3 ツール統一インターフェース。
//   - **構造化出力**: AI 出力は `<rvpm:plugin_entry>` 等の XML tag で囲ませ、
//     code fence や前置きが混ざっても robust に regex 抽出する。
//   - **Mode A (内蔵 chat loop)** がメイン路: rvpm が会話履歴を保持し毎ターン
//     `claude -p "..."` を一発投げ直す。長期会話は token 食うが TOML 抽出が
//     確実 + 3 ツール挙動統一。
//   - **Mode B (handoff)** は user に CLI を直接渡す逃げ道: prompt をテンポラリ
//     ファイルに保存してパスを announce、`claude` (interactive) を inherit-stdio
//     で spawn する。**stdin 事前注入はしない** (claude-code は EOF で即 exit する
//     ため interactive にならない)。user が CLI 内で prompt ファイルを読めば
//     refine 済み文脈が手に入る。CLI ツール側のファイル編集機能で config.toml /
//     hook 直接書かせる。**rvpm 側は結果を re-import しない** (README に明記)。

use anyhow::{Context, Result, anyhow};
use std::path::{Path, PathBuf};

mod chat;
mod prompt;

pub use chat::{ChatOutcome, run_ai_add};

/// 利用可能な AI CLI ツール。
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Backend {
    Claude,
    Gemini,
    Codex,
}

impl Backend {
    /// CLI 実行ファイル名 (PATH 上にあるべきもの)。
    pub fn cli_name(self) -> &'static str {
        match self {
            Backend::Claude => "claude",
            Backend::Gemini => "gemini",
            Backend::Codex => "codex",
        }
    }

    /// `cli_name()` が PATH 上に見つかるかを返す。Windows では `.ps1` 等の
    /// non-default PATHEXT も探すので、pnpm 等が `.ps1` wrapper のみ install した
    /// ケースでも検出できる。
    pub fn is_available(self) -> bool {
        resolve_cli(self.cli_name()).is_some()
    }

    /// バックエンド共通のラベル。
    pub fn label(self) -> &'static str {
        match self {
            Backend::Claude => "Claude",
            Backend::Gemini => "Gemini",
            Backend::Codex => "Codex",
        }
    }
}

/// 解決された CLI の起動情報。
#[derive(Debug, Clone)]
pub struct ResolvedCli {
    /// `Command::new` に渡すプログラム (`.exe` 直、もしくは `powershell.exe`)。
    pub program: PathBuf,
    /// プログラムの最初に付ける引数 (PowerShell 経由時は `-File <path>` 等)。
    pub prefix_args: Vec<String>,
}

/// `name` を PATH から解決する (Windows の `.ps1` 対応込み)。
///
/// 探索順:
///   1. `which(name)` — Unix なら直接、Windows なら PATHEXT デフォルト (`.exe`/`.cmd`/`.bat` 等)。
///      解決パスが `.ps1` だった場合は PowerShell 起動命令として包む。
///   2. (Windows のみ) `which("name.ps1")` — pnpm 等が `.ps1` のみ install した
///      ケースの fallback。PATHEXT に `.ps1` が無くても拾える。
///
/// `.ps1` を実行するには Windows の `CreateProcess` 単体では不可なので、
/// `powershell.exe -NoProfile -ExecutionPolicy Bypass -File <full path>` で wrap する。
pub fn resolve_cli(name: &str) -> Option<ResolvedCli> {
    if let Ok(p) = which::which(name) {
        return Some(wrap_if_powershell(p));
    }
    #[cfg(windows)]
    {
        for ext in ["ps1", "cmd", "bat", "exe"] {
            if let Ok(p) = which::which(format!("{name}.{ext}")) {
                return Some(wrap_if_powershell(p));
            }
        }
    }
    None
}

fn wrap_if_powershell(path: PathBuf) -> ResolvedCli {
    let is_ps1 = path
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| e.eq_ignore_ascii_case("ps1"))
        .unwrap_or(false);
    if is_ps1 {
        // PowerShell 7 (`pwsh.exe`) を優先、無ければ Windows PowerShell 5.1
        // (`powershell.exe`、Windows 標準同梱) に fallback。
        //   - pnpm 利用層は modern toolchain に偏るので PS7 入りが大多数。
        //   - pnpm の wrapper script は単純な PATH/exec 操作のみで、PS5.1 / 7
        //     どちらでも同じ挙動 (silent fallback の behavioral risk が無い)。
        //   - PS5.1 を primary にすると PS7 のみ user で odd ハマる可能性。
        //
        // `-NoProfile` で user の $PROFILE をスキップ (起動高速化 + side effect 排除)、
        // `-ExecutionPolicy Bypass` で署名要求と zone-prompt の両方を無効化
        // (Unrestricted は MOTW タグ付き script で interactive prompt を出すので、
        // subprocess 起動時に hang する可能性がある)。
        let ps_exe = if which::which("pwsh").is_ok() {
            "pwsh.exe"
        } else {
            "powershell.exe"
        };
        ResolvedCli {
            program: PathBuf::from(ps_exe),
            prefix_args: vec![
                "-NoProfile".to_string(),
                "-ExecutionPolicy".to_string(),
                "Bypass".to_string(),
                "-File".to_string(),
                path.to_string_lossy().into_owned(),
            ],
        }
    } else {
        ResolvedCli {
            program: path,
            prefix_args: Vec::new(),
        }
    }
}

/// AI が出力する 1 ターン分の提案。
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Proposal {
    /// `[[plugins]]` block (TOML として valid であることを呼び出し側で検証)。
    pub plugin_entry_toml: String,
    /// per-plugin init.lua 内容。`None` なら作らない。
    pub init_lua: Option<String>,
    pub before_lua: Option<String>,
    pub after_lua: Option<String>,
    /// 2-3 文の根拠説明 (preview 表示用)。
    pub explanation: String,
}

/// AI CLI が PATH に無いときのエラー (install hint 込み)。
pub fn ensure_cli_installed(backend: Backend) -> Result<()> {
    if backend.is_available() {
        return Ok(());
    }
    let cli = backend.cli_name();
    let hint = match backend {
        Backend::Claude => "https://docs.claude.com/claude-code",
        Backend::Gemini => "https://ai.google.dev/gemini-api/docs/cli",
        Backend::Codex => "https://github.com/openai/codex",
    };
    Err(anyhow!(
        "AI backend `{cli}` is not on PATH. Install it first ({hint}) or pass a different `--ai` flag."
    ))
}

/// CLI を一発呼び出しモードで起動して prompt を投げ、応答を文字列で返す。
/// stdin で prompt を渡す (shell escape & 長文対策)。
///
/// **timeout**: 5 分 (300 秒)。当初 90 秒だったが、chat 2 turn 目以降は
/// `build_followup_prompt` で `initial + prior_response + feedback` を全部
/// 再投入するので prompt が 50-100KB クラスに膨らみ、Gemini が 90 秒では
/// 収まらないケース報告あり。300 秒なら現実的に余裕がある。
/// `RVPM_AI_TIMEOUT_SECS` 環境変数で per-call 上書き可能 (ネットワーク遅延が
/// 強い環境向け)。
pub async fn invoke_oneshot(backend: Backend, prompt_text: &str) -> Result<String> {
    use tokio::io::AsyncWriteExt;
    use tokio::process::Command;
    use tokio::time::{Duration, timeout};

    ensure_cli_installed(backend)?;
    let resolved = resolve_cli(backend.cli_name())
        .ok_or_else(|| anyhow!("AI CLI `{}` is not on PATH", backend.cli_name()))?;

    // prompt サイズを表示 (timeout 原因の透明性 + sanity check)。
    eprintln!(
        "  (prompt size: {} bytes / {} lines)",
        prompt_text.len(),
        prompt_text.lines().count()
    );

    // 各 CLI のフラグは「stdin から prompt を読み、結果を stdout に」のモードを選ぶ:
    //   - claude: `claude -p` で one-shot non-interactive、stdin で prompt
    //   - gemini: `gemini -p` 同様
    //   - codex:  `codex exec`  (or `codex -p`、ver 依存)
    // どれも stdin 受け付けるはず。安全側に prompt を stdin で渡す。
    let mut cmd = Command::new(&resolved.program);
    cmd.args(&resolved.prefix_args);
    match backend {
        Backend::Claude | Backend::Gemini => {
            cmd.arg("-p").arg("-");
        }
        Backend::Codex => {
            cmd.arg("exec").arg("-");
        }
    }
    cmd.stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        // tokio Command の `kill_on_drop` は default false。timeout で future が
        // drop されたとき子プロセスを残さないように true にする (CodeRabbit Critical)。
        .kill_on_drop(true);

    let mut child = cmd.spawn().with_context(|| {
        format!(
            "failed to spawn AI CLI `{}` (is it installed and on PATH?)",
            backend.cli_name()
        )
    })?;

    // stdin に prompt を書き込んで close (EOF を AI に伝える)。
    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(prompt_text.as_bytes())
            .await
            .context("failed to write prompt to AI CLI stdin")?;
        // explicit drop → close stdin → AI が EOF 受け取って応答開始
    }

    // timeout は default 300 秒、`RVPM_AI_TIMEOUT_SECS` で上書き可能。
    let timeout_secs = std::env::var("RVPM_AI_TIMEOUT_SECS")
        .ok()
        .and_then(|s| s.parse::<u64>().ok())
        .unwrap_or(300);
    let output = timeout(Duration::from_secs(timeout_secs), child.wait_with_output())
        .await
        .map_err(|_| {
            anyhow!(
                "AI CLI `{}` timed out after {timeout_secs}s. \
                 The chat follow-up prompt grows with conversation history; \
                 set RVPM_AI_TIMEOUT_SECS=600 or longer if your network is slow.",
                backend.cli_name()
            )
        })?
        .with_context(|| format!("AI CLI `{}` failed to produce output", backend.cli_name()))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(anyhow!(
            "AI CLI `{}` exited with status {}: {}",
            backend.cli_name(),
            output.status,
            stderr.trim()
        ));
    }

    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

/// AI 応答から `<rvpm:plugin_entry>` 等の XML tag を抜き取る。
pub fn parse_proposal(response: &str) -> Result<Proposal> {
    let entry = extract_tag(response, "plugin_entry")
        .ok_or_else(|| anyhow!("AI response missing required <rvpm:plugin_entry> tag"))?;
    let init = extract_optional_lua(response, "init_lua");
    let before = extract_optional_lua(response, "before_lua");
    let after = extract_optional_lua(response, "after_lua");
    let explanation =
        extract_tag(response, "explanation").unwrap_or_else(|| "(no explanation given)".into());
    Ok(Proposal {
        plugin_entry_toml: entry.trim().to_string(),
        init_lua: init,
        before_lua: before,
        after_lua: after,
        explanation: explanation.trim().to_string(),
    })
}

/// `<rvpm:NAME>...</rvpm:NAME>` の中身を返す (前後 whitespace つき)。
/// 見つからなければ `None`。
///
/// AI の preamble に `<rvpm:plugin_entry>` という単語が混じる false positive を避けるため、
/// **最後の occurrence** を起点に matching する: 構造化出力は応答末尾に来るのが
/// 通常だし、preamble の言及で偶発的に block を切り出す事故が起きにくい。
fn extract_tag(text: &str, name: &str) -> Option<String> {
    let open = format!("<rvpm:{name}>");
    let close = format!("</rvpm:{name}>");
    let start_off = text.rfind(&open)? + open.len();
    let close_off = text[start_off..].find(&close)? + start_off;
    Some(text[start_off..close_off].to_string())
}

/// Lua 系 tag の中身を `Option<String>` で返す。`(none)` (大文字小文字無視) は `None`。
fn extract_optional_lua(text: &str, name: &str) -> Option<String> {
    let body = extract_tag(text, name)?;
    let trimmed = body.trim();
    if trimmed.eq_ignore_ascii_case("(none)") || trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// AI 提案 TOML が valid であることを軽く verify (parse できるか + `[[plugins]]`
/// が 1 件あるか)。
pub fn validate_proposal_toml(toml_src: &str) -> Result<()> {
    let value: toml::Value =
        toml::from_str(toml_src).context("AI-proposed TOML failed to parse")?;
    let plugins = value
        .get("plugins")
        .and_then(|v| v.as_array())
        .ok_or_else(|| anyhow!("AI proposal missing `[[plugins]]` array"))?;
    if plugins.is_empty() {
        return Err(anyhow!("AI proposal contains 0 plugin entries"));
    }
    if plugins.len() > 1 {
        return Err(anyhow!(
            "AI proposed {} plugin entries; expected exactly 1 for `rvpm add`",
            plugins.len()
        ));
    }
    Ok(())
}

/// Mode B のハンドオフ: prompt をテンポラリファイルに書き出し、CLI を
/// **interactive モードで** 起動する (stdin / stdout / stderr とも親 TTY を継承)。
/// rvpm は CLI 終了まで `wait` するだけで、それ以降の状態は CLI 側に委譲する。
///
/// **prompt の事前注入は意図的に行わない**: stdin pipe + drop すると claude-code
/// などは EOF を受けて即座に exit するため、interactive にならない (Gemini High)。
/// 代わりに prompt をテンポラリ MD ファイルに保存してパスを announce する。
/// user は CLI 内で `/file <path>` (claude-code) や `cat <path>` を使って
/// 読み込めばよい。
///
/// CLI 終了まで blocking wait するが、`spawn_blocking` で別 thread に逃がして
/// Tokio executor は塞がない。
pub async fn run_handoff(backend: Backend, prompt_text: &str) -> Result<()> {
    ensure_cli_installed(backend)?;
    let resolved = resolve_cli(backend.cli_name())
        .ok_or_else(|| anyhow!("AI CLI `{}` is not on PATH", backend.cli_name()))?;

    // prompt をテンポラリファイルに保存
    let mut tmp_path = std::env::temp_dir();
    let stamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    tmp_path.push(format!("rvpm-ai-prompt-{stamp}.md"));
    std::fs::write(&tmp_path, prompt_text)
        .with_context(|| format!("failed to write prompt to {}", tmp_path.display()))?;

    eprintln!();
    eprintln!(
        "\u{1f4dd} Prompt saved to: {}\n\
         Starting `{}` interactively. Paste the prompt or load it via your CLI's file-reading mechanism.\n",
        tmp_path.display(),
        backend.cli_name()
    );

    // 子プロセスを spawn_blocking 内で起動 + wait (std::process は async に乗らないため)。
    let label = backend.cli_name().to_string();
    tokio::task::spawn_blocking(move || -> Result<()> {
        let status = std::process::Command::new(&resolved.program)
            .args(&resolved.prefix_args)
            .stdin(std::process::Stdio::inherit())
            .stdout(std::process::Stdio::inherit())
            .stderr(std::process::Stdio::inherit())
            .status()
            .with_context(|| format!("failed to spawn AI CLI `{label}`"))?;
        let _ = status; // exit status は無視 (user 操作なのでエラーじゃない)
        Ok(())
    })
    .await
    .context("failed to join blocking handoff task")??;

    Ok(())
}

/// AI mode で生成された hook 内容を、呼び出し側で resolve 済みの per-plugin
/// config dir (`<config_root>/plugins/<host>/<owner>/<repo>/`) に書き込む。
///
/// `chezmoi_enabled` (`options.chezmoi`) が true のとき、書き込みは `chezmoi::write_path`
/// 経由で source state に行い、`chezmoi::apply` で target に反映する。
/// raw `fs::write` で target に直書きすると次の `chezmoi apply` で削除/drift 扱いになるため、
/// `rvpm edit` 等の他コマンドと同じ規約に揃える。
///
/// path 解決は呼び出し側 (`run_add`) が `resolve_plugin_config_dir` 経由で行う。
/// ここでホスト名や url 形式を再パースしないことで、GitLab / 他 host や
/// `Plugin::canonical_path` の形式変更にも自動追従する。
pub async fn write_hook_files(
    plugin_dir: &Path,
    proposal: &Proposal,
    chezmoi_enabled: bool,
) -> Result<Vec<PathBuf>> {
    std::fs::create_dir_all(plugin_dir).with_context(|| {
        format!(
            "failed to create plugin config dir {}",
            plugin_dir.display()
        )
    })?;

    let mut written = Vec::new();
    for (name, body) in [
        ("init.lua", proposal.init_lua.as_deref()),
        ("before.lua", proposal.before_lua.as_deref()),
        ("after.lua", proposal.after_lua.as_deref()),
    ] {
        let Some(body) = body else { continue };
        let target = plugin_dir.join(name);
        // 既存ファイルは上書きしない (user の手書き編集を尊重)。
        if target.exists() {
            eprintln!(
                "\u{26a0} {} already exists, skipping AI-generated content. Apply manually if desired.",
                target.display()
            );
            continue;
        }
        crate::chezmoi::write_routed(chezmoi_enabled, &target, format!("{}\n", body.trim_end()))
            .await
            .with_context(|| format!("failed to write {}", target.display()))?;
        written.push(target);
    }
    Ok(written)
}

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

    #[test]
    fn parse_proposal_extracts_required_tags() {
        let response = r#"
some preamble that should be ignored

<rvpm:plugin_entry>
[[plugins]]
url = "owner/repo"
on_cmd = ["Foo"]
</rvpm:plugin_entry>

<rvpm:init_lua>
vim.g.foo = 1
</rvpm:init_lua>

<rvpm:before_lua>(none)</rvpm:before_lua>
<rvpm:after_lua>
require('foo').setup({})
</rvpm:after_lua>

<rvpm:explanation>
README shows :Foo as the entry command.
</rvpm:explanation>
"#;
        let p = parse_proposal(response).unwrap();
        assert!(p.plugin_entry_toml.contains("[[plugins]]"));
        assert!(p.plugin_entry_toml.contains(r#"url = "owner/repo""#));
        assert_eq!(p.init_lua.as_deref(), Some("vim.g.foo = 1"));
        assert_eq!(p.before_lua, None, "(none) must collapse to None");
        assert_eq!(p.after_lua.as_deref(), Some("require('foo').setup({})"));
        assert!(p.explanation.contains("README shows"));
    }

    #[test]
    fn parse_proposal_missing_plugin_entry_errors() {
        let response = "<rvpm:explanation>nothing else</rvpm:explanation>";
        assert!(parse_proposal(response).is_err());
    }

    #[test]
    fn parse_proposal_ignores_tag_name_in_preamble() {
        // AI が "I will use the <rvpm:plugin_entry> tag below..." のように preamble で
        // tag 名を言及するケース。最後の occurrence を起点にすれば誤切り出しを回避できる。
        let response = r#"
I will populate the <rvpm:plugin_entry> tag below with the proposal.

<rvpm:plugin_entry>
[[plugins]]
url = "real/entry"
</rvpm:plugin_entry>
<rvpm:init_lua>(none)</rvpm:init_lua>
<rvpm:before_lua>(none)</rvpm:before_lua>
<rvpm:after_lua>(none)</rvpm:after_lua>
<rvpm:explanation>ok</rvpm:explanation>
"#;
        let p = parse_proposal(response).unwrap();
        assert!(p.plugin_entry_toml.contains("real/entry"));
        assert!(!p.plugin_entry_toml.contains("populate"));
    }

    #[test]
    fn parse_proposal_extracts_when_wrapped_in_markdown_fences() {
        // 一部 CLI は ``` fence を勝手に付ける可能性。tag 抽出は中身さえあれば OK。
        let response = r#"
```
<rvpm:plugin_entry>
[[plugins]]
url = "x/y"
</rvpm:plugin_entry>
<rvpm:init_lua>(none)</rvpm:init_lua>
<rvpm:before_lua>(none)</rvpm:before_lua>
<rvpm:after_lua>(none)</rvpm:after_lua>
<rvpm:explanation>ok</rvpm:explanation>
```
"#;
        let p = parse_proposal(response).unwrap();
        assert!(p.plugin_entry_toml.contains(r#"url = "x/y""#));
        assert_eq!(p.init_lua, None);
    }

    #[test]
    fn validate_proposal_toml_accepts_single_plugin_entry() {
        let toml_src = r#"
[[plugins]]
url = "owner/repo"
on_cmd = ["Foo"]
"#;
        validate_proposal_toml(toml_src).unwrap();
    }

    #[test]
    fn validate_proposal_toml_rejects_multiple_plugin_entries() {
        let toml_src = r#"
[[plugins]]
url = "a/b"

[[plugins]]
url = "c/d"
"#;
        assert!(validate_proposal_toml(toml_src).is_err());
    }

    #[test]
    fn validate_proposal_toml_rejects_invalid_syntax() {
        let toml_src = "[[plugins]\nurl = ";
        assert!(validate_proposal_toml(toml_src).is_err());
    }

    #[test]
    fn validate_proposal_toml_rejects_no_plugins_array() {
        let toml_src = r#"name = "ignored""#;
        assert!(validate_proposal_toml(toml_src).is_err());
    }

    #[test]
    fn wrap_if_powershell_wraps_ps1_path() {
        // .ps1 ファイルは pwsh.exe (PS7 入りなら) または powershell.exe で起動。
        // どちらが選ばれるかは test 実行環境に依存するので exact 比較しない。
        let p = std::path::PathBuf::from("C:/foo/gemini.ps1");
        let r = wrap_if_powershell(p);
        let prog = r.program.to_string_lossy().to_ascii_lowercase();
        assert!(
            prog == "pwsh.exe" || prog == "powershell.exe",
            "expected pwsh.exe or powershell.exe, got {prog}"
        );
        assert!(r.prefix_args.iter().any(|a| a == "-File"));
        assert!(r.prefix_args.iter().any(|a| a.contains("gemini.ps1")));
        // ExecutionPolicy Bypass で署名要求 + zone prompt を無効化する
        assert!(r.prefix_args.iter().any(|a| a == "Bypass"));
        // -NoProfile で user $PROFILE スキップ
        assert!(r.prefix_args.iter().any(|a| a == "-NoProfile"));
    }

    #[test]
    fn wrap_if_powershell_passes_exe_through() {
        // .exe は直接起動 (prefix_args 空)。
        let p = std::path::PathBuf::from("C:/foo/claude.exe");
        let r = wrap_if_powershell(p.clone());
        assert_eq!(r.program, p);
        assert!(r.prefix_args.is_empty());
    }

    #[test]
    fn wrap_if_powershell_passes_unix_path_through() {
        // 拡張子無し (Unix の典型的な executable) も直接起動。
        let p = std::path::PathBuf::from("/usr/local/bin/codex");
        let r = wrap_if_powershell(p.clone());
        assert_eq!(r.program, p);
        assert!(r.prefix_args.is_empty());
    }

    #[tokio::test]
    async fn write_hook_files_writes_only_present_lua_blocks() {
        // 呼び出し側 (`run_add`) が plugin_dir を resolve 済みで渡す前提を確認。
        // chezmoi_enabled=false で従来 path (raw fs::write 相当) と挙動一致するか。
        let tmp = tempfile::tempdir().unwrap();
        let plugin_dir = tmp
            .path()
            .join("plugins")
            .join("github.com")
            .join("o")
            .join("r");
        let p = Proposal {
            plugin_entry_toml: r#"[[plugins]]
url = "o/r""#
                .to_string(),
            init_lua: Some("vim.g.x = 1".to_string()),
            before_lua: None,
            after_lua: Some("require('o').setup({})".to_string()),
            explanation: "test".to_string(),
        };
        let written = write_hook_files(&plugin_dir, &p, false).await.unwrap();
        assert_eq!(written.len(), 2);
        assert!(plugin_dir.join("init.lua").exists());
        assert!(!plugin_dir.join("before.lua").exists());
        assert!(plugin_dir.join("after.lua").exists());
    }

    #[test]
    fn extract_optional_lua_collapses_none_marker() {
        let resp = "<rvpm:init_lua>  (none)  </rvpm:init_lua>";
        assert_eq!(extract_optional_lua(resp, "init_lua"), None);
    }

    #[test]
    fn extract_optional_lua_keeps_real_content() {
        let resp = "<rvpm:init_lua>vim.g.x = 1</rvpm:init_lua>";
        assert_eq!(
            extract_optional_lua(resp, "init_lua").as_deref(),
            Some("vim.g.x = 1")
        );
    }
}