agentgear 0.1.1

Install and self-heal the plugin your Rust binary ships into Claude Code and 24 other coding agents, via a derive macro.
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
//! The qwen-code backend: a full translate into qwen-code's own config. qwen-code
//! is a Claude-Code-shaped fork, so translation is mostly a re-emit. MCP goes
//! through the shared json renderer (Plain `{command,args,env}`) into the
//! `mcpServers` key of `~/.qwen/settings.json`; CC hooks land in that same file
//! under a `hooks` key using CC's identical nested shape (qwen-code's event names —
//! `SessionStart`/`UserPromptSubmit`/`PreToolUse`/… — match CC 1:1); CC commands
//! copy through verbatim as markdown under `~/.qwen/commands/<plugin>/` (subdirs
//! preserved for qwen's `:` namespacing); CC agents become plugin-prefixed
//! `~/.qwen/agents/<plugin>-<name>.md` subagent files.
//!
//! Ownership: mcp servers are keyed by our server names; commands live in a
//! `commands/<plugin>/` subtree we own whole; agent files are plugin-prefixed. So
//! `remove` is exact and a second reconcile is a true `NoOp`. `~/.qwen` is honored
//! via `QWEN_HOME` first (so a test redirecting it redirects the backend), else
//! HOME-based. Skills land as bare `~/.qwen/skills/<name>/SKILL.md` (both scopes),
//! tagged for ownership so `remove` only deletes skills we wrote (see
//! `docs/harness/qwen-code.md`).
//!
//! One surface breaks that key-ownership pattern: qwen-code copied CC's status-line
//! object into its own `ui.statusLine`, which is a single-valued, last-writer-wins
//! SLOT. It runs through the shared [`super::statuslinejson`] lifecycle
//! (stash-before-write, restore-on-remove, and a `forget` that restores on every
//! teardown branch — the settings file outlives qwen-code itself).

use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};

use serde_json::Value;

use super::cchooks::{hook_is_portable, remove_hook_groups, render_hook_group};
use super::confedit::{json_edit, json_obj_at, json_prune_obj, json_remove, remove_file_idem, write_file_idem};
use super::mcpjson::{self, RemoteShape, ServerShape};
use super::report;
use super::skillsdir;
use super::statuslinejson::{self, SlotShape};
use super::{AgentBackend, BackendState};
use crate::components::{HookBinding, MarkdownDoc};
use crate::doctor::{CheckStatus, DoctorCheck, DoctorReport};
use crate::error::{Error, IoContext, Result};
use crate::host::{Capabilities, Desired, Outcome, Plugin, Scope, Source};

pub(crate) struct QwenCodeBackend;

/// qwen picks transport purely by key presence (`httpUrl` = http, `url` = sse;
/// `type` is never read), so a `url`-keyed http server would silently load over SSE.
const SHAPE: ServerShape = ServerShape::plain().with_remote(RemoteShape::HttpUrlKeyed);

/// qwen-code's status-line slot: CC's key, nested under its own `ui` block.
const STATUSLINE_SLOT: &[&str] = &["ui", "statusLine"];

/// The body is CC's, copied verbatim (`docs/harness/matrix.md` § status line).
///
/// qwen-code reads `type`/`command`/`refreshInterval`/`respectUserColors`/
/// `hideContextIndicator` into a fresh object and silently drops CC's `padding`, so a
/// declared padding lands in the file and does nothing there — deliberate, not an
/// oversight to "fix": qwen never rewrites the value on read, so convergence against
/// what we wrote still holds (`docs/research/statusline-survey.md` §1).
const STATUSLINE_SHAPE: SlotShape = SlotShape::typed_command();

impl AgentBackend for QwenCodeBackend {
    fn id(&self) -> &'static str {
        "qwen-code"
    }

    fn detect(&self) -> bool {
        // `QWEN_HOME` (the documented config-dir override) wins over `~/.qwen`, so a
        // test setting it redirects both detection and every write; the `qwen` binary
        // on PATH is the other signal. `QWEN_CODE` is only a per-tool-subprocess env
        // (not a whole-session marker like CC's `CLAUDECODE`), so it is not used here.
        which::which("qwen").is_ok() || user_qwen_base().is_ok_and(|b| b.is_dir())
    }

    fn capabilities(&self) -> Capabilities {
        // Claude-Code-shaped fork: mcp + hooks + commands + agents + skills all
        // translate, and it copied CC's status-line object into its own `ui` block.
        Capabilities {
            plugins: false,
            mcp: true,
            hooks: true,
            commands: true,
            agents: true,
            skills: true,
            instructions: false,
            statusline: true,
            scopes: &["user", "project"],
        }
    }

    fn probe(&self, plugin: &Plugin, scope: &Scope, source: &Source) -> Result<BackendState> {
        // Compose every surface we write (mcp + hooks + the status-line slot in
        // settings.json, command/agent/skill files), so a dropped hook group or missing
        // command behind healthy mcp keys reads NeedsRepair rather than Healthy.
        // `source` is the one self_heal resolved for this agent (rehydrated
        // `--path`, else the compile-time default), so probe and reconcile render
        // identical bytes.
        let comp = plugin.components(source)?.with_client(self.id());
        let base = qwen_dir(scope)?;
        let settings = settings_file(scope)?;
        let mcp = mcpjson::probe_surface(&settings, &["mcpServers"], &comp.mcp_servers, SHAPE)?;
        let hooks = report::probe_json_entries(&settings, &hook_entries(&comp.hooks))?;
        let cmd_root = base.join("commands").join(plugin.name);
        let commands = report::probe_files(
            &comp.commands.iter().map(|doc| (cmd_root.join(command_rel(doc)), doc.raw.clone())).collect::<Vec<_>>(),
            |_, _| true,
        )?;
        let agent_root = base.join("agents");
        let agents = report::probe_files(
            &comp
                .agents
                .iter()
                .map(|doc| (agent_root.join(agent_file(plugin.name, doc)), render_agent(plugin.name, doc).into_bytes()))
                .collect::<Vec<_>>(),
            |_, _| true,
        )?;
        let skills = skillsdir::probe(&base.join("skills"), plugin, &comp.skills)?;
        // The slot folds in beside the rest, but it is the one key we do NOT own, so
        // it can never carry presence on its own: a foreign line reads `Absent` (see
        // `statuslinejson::state`), which keeps an uninstalled plugin at `Absent`
        // instead of handing self_heal's adopt row a reason to reinstall the whole
        // translation over the user's own status line.
        let statusline = statuslinejson::state(&settings, STATUSLINE_SLOT, plugin, scope, self.id(), STATUSLINE_SHAPE)?;
        Ok(report::compose([mcp, hooks, commands, agents, skills, statusline].into_iter().flatten()))
    }

    fn reconcile(&self, plugin: &Plugin, desired: &Desired, scope: &Scope) -> Result<Outcome> {
        let comp = plugin.components(&desired.source)?.with_client(self.id());
        let base = qwen_dir(scope)?;
        let settings = settings_file(scope)?;

        let mut changed = false;
        changed |= mcpjson::reconcile(&settings, &["mcpServers"], &comp.mcp_servers, SHAPE)? != Outcome::NoOp;
        changed |= reconcile_hooks(&settings, &comp.hooks)?;

        // Commands copy through verbatim: qwen reads CC's own markdown+frontmatter
        // command shape, so the raw file bytes go straight under `commands/<plugin>/`.
        let cmd_root = base.join("commands").join(plugin.name);
        for doc in &comp.commands {
            changed |= write_file_idem(&cmd_root.join(command_rel(doc)), &doc.raw)?;
        }
        // Agents share `agents/` with the user's own, so we write plugin-prefixed
        // files (never a subtree we could confuse with theirs).
        let agent_root = base.join("agents");
        for doc in &comp.agents {
            changed |= write_file_idem(&agent_root.join(agent_file(plugin.name, doc)), render_agent(plugin.name, doc).as_bytes())?;
        }
        changed |= skillsdir::reconcile(&base.join("skills"), plugin, &comp.skills)?;
        changed |= statuslinejson::reconcile(&settings, STATUSLINE_SLOT, plugin, &desired.source, scope, self.id(), STATUSLINE_SHAPE)?;
        Ok(if changed { Outcome::Installed } else { Outcome::NoOp })
    }

    fn remove(&self, plugin: &Plugin, scope: &Scope, source: &Source) -> Result<Outcome> {
        let comp = plugin.components(source)?.with_client(self.id());
        let base = qwen_dir(scope)?;
        let settings = settings_file(scope)?;

        let mut changed = false;
        changed |= mcpjson::remove(&settings, &["mcpServers"], &comp.mcp_servers, SHAPE)? != Outcome::NoOp;
        changed |= remove_hooks(&settings, &comp.hooks)?;

        // We own the whole `commands/<plugin>/` subtree, so a recursive drop is exact
        // and never reaches a user's own commands.
        let cmd_root = base.join("commands").join(plugin.name);
        if cmd_root.exists() {
            fs::remove_dir_all(&cmd_root).io_ctx(|| format!("removing {}", cmd_root.display()))?;
            changed = true;
        }
        // Agent files are plugin-prefixed in a shared dir, so delete only ours by name.
        let agent_root = base.join("agents");
        for doc in &comp.agents {
            changed |= remove_file_idem(&agent_root.join(agent_file(plugin.name, doc)))?;
        }
        changed |= skillsdir::remove(&base.join("skills"), plugin, &comp.skills)?;
        // Exact-remove for a slot means RESTORE: put back what our write displaced,
        // or drop the key when the slot was empty before us.
        changed |= statuslinejson::remove(&settings, STATUSLINE_SLOT, plugin, scope, self.id(), STATUSLINE_SHAPE)?;
        Ok(if changed { Outcome::Removed } else { Outcome::NoOp })
    }

    /// The `ui.statusLine` slot lives in the user's own settings file, which outlives
    /// qwen-code's config tree and the `qwen` binary itself, so every teardown branch
    /// that reaches the marker clear — an undetected harness, an unsupported scope or
    /// source, a plugin the user removed by hand — must put their value back first.
    /// The marker is the only copy of it.
    fn forget(&self, plugin: &Plugin, scope: &Scope) -> Result<()> {
        let Some(settings) = statusline_target(plugin, scope)? else {
            return Ok(());
        };
        statuslinejson::remove(&settings, STATUSLINE_SLOT, plugin, scope, self.id(), STATUSLINE_SHAPE).map(|_| ())
    }

    fn report(&self, plugin: &Plugin, source: &Source) -> DoctorReport {
        DoctorReport::from_checks(report_checks(self, plugin, source))
    }
}

// --- paths -------------------------------------------------------------------

/// The user config base: `$QWEN_HOME` (the documented override, the config dir
/// itself) if set, else `~/.qwen`. Honoring the override first matches what qwen
/// reads and lets a test redirect the backend without touching HOME.
fn user_qwen_base() -> Result<PathBuf> {
    if let Some(dir) = std::env::var_os("QWEN_HOME").filter(|v| !v.is_empty()) {
        return Ok(PathBuf::from(dir));
    }
    dirs::home_dir()
        .map(|h| h.join(".qwen"))
        .ok_or_else(|| Error::Tree("no home directory (HOME unset) and QWEN_HOME unset; cannot locate ~/.qwen".into()))
}

/// The qwen config base for a scope: the user base (above) or `<cwd>/.qwen`
/// (project). User scope needs HOME or QWEN_HOME; a missing one is a clear error.
fn qwen_dir(scope: &Scope) -> Result<PathBuf> {
    match scope {
        Scope::User => user_qwen_base(),
        Scope::Project { path } => Ok(path.join(".qwen")),
    }
}

/// `<base>/settings.json` for `scope` — the one file both the slot lifecycle and the
/// doctor check must agree on, so it is resolved here once rather than joined
/// independently at each call site.
fn settings_file(scope: &Scope) -> Result<PathBuf> {
    Ok(qwen_dir(scope)?.join("settings.json"))
}

/// The settings file the slot lifecycle writes, or `None` when the host declares no
/// status line.
fn statusline_target(plugin: &Plugin, scope: &Scope) -> Result<Option<PathBuf>> {
    statuslinejson::target(plugin, QwenCodeBackend.id(), STATUSLINE_SHAPE, || settings_file(scope))
}

// --- hooks -------------------------------------------------------------------

/// Map a CC hook event to qwen-code's. qwen-code's event set is a superset of CC's
/// hook events (it adds `PostToolUseFailure`/`TodoCreated`/… of its own), so every
/// CC event maps identically. An unknown event is skipped rather than guessed.
fn map_event(cc_event: &str) -> Option<&'static str> {
    match cc_event {
        "PreToolUse" => Some("PreToolUse"),
        "PostToolUse" => Some("PostToolUse"),
        "UserPromptSubmit" => Some("UserPromptSubmit"),
        "SessionStart" => Some("SessionStart"),
        "SessionEnd" => Some("SessionEnd"),
        "Stop" => Some("Stop"),
        "SubagentStart" => Some("SubagentStart"),
        "SubagentStop" => Some("SubagentStop"),
        "PreCompact" => Some("PreCompact"),
        "Notification" => Some("Notification"),
        _ => None,
    }
}

/// The `(array key_path, rendered group)` pairs `probe` checks are present under
/// `hooks.<event>`, mirroring `reconcile_hooks`'s writable filter exactly.
fn hook_entries(hooks: &[HookBinding]) -> Vec<(Vec<String>, Value)> {
    hooks
        .iter()
        .filter(|h| hook_is_portable(h))
        .filter_map(|h| map_event(&h.event).map(|event| (vec!["hooks".to_string(), event.to_string()], render_hook_group(h))))
        .collect()
}

/// Add-if-absent our hook groups under each mapped event in `settings.json`'s
/// `hooks` key, leaving the user's own groups in place. Idempotent: a group already
/// present (deep-equal) is not re-added. Non-portable hooks and events with no qwen
/// analog are skipped, same as mcp servers. Skips the whole edit when nothing is
/// writable so no empty `"hooks": {}` key is created for zero writes.
fn reconcile_hooks(settings: &Path, hooks: &[HookBinding]) -> Result<bool> {
    let writable: Vec<(&'static str, &HookBinding)> =
        hooks.iter().filter(|h| hook_is_portable(h)).filter_map(|h| map_event(&h.event).map(|event| (event, h))).collect();
    if writable.is_empty() {
        return Ok(false);
    }
    json_edit(settings, |root| {
        let events = json_obj_at(root, &["hooks"]);
        for (event, hook) in &writable {
            let group = render_hook_group(hook);
            let entry = events.entry((*event).to_string()).or_insert_with(|| Value::Array(Vec::new()));
            if let Value::Array(list) = entry
                && !list.iter().any(|g| g == &group)
            {
                list.push(group);
            }
        }
        Ok(())
    })
}

/// Strip exactly our hook handlers (matched by command string) from every event in
/// the `hooks` key, dropping a group or event array we emptied. A user handler
/// sharing a group with ours (or a group of their own) survives. The ownership set
/// mirrors `reconcile_hooks`'s writable filter exactly (portable AND mapped) — a
/// command string from an unmapped/non-portable hook (never written here) must never
/// be treated as ours to remove.
fn remove_hooks(settings: &Path, hooks: &[HookBinding]) -> Result<bool> {
    if !settings.exists() {
        return Ok(false);
    }
    let ours: BTreeSet<&str> =
        hooks.iter().filter(|h| hook_is_portable(h) && map_event(&h.event).is_some()).map(|h| h.command.as_str()).collect();
    json_remove(settings, |root| {
        json_prune_obj(root, &["hooks"], |events| {
            remove_hook_groups(events, &ours);
            Ok(())
        })
        .map(|_| ())
    })
}

// --- commands / agents -------------------------------------------------------

/// `commands/hello.md` -> `hello.md`, preserving any subdir so qwen's `:`
/// namespacing (and our exact `commands/<plugin>/` removal) stays intact. Copy-
/// through: the CC command file's own bytes are what qwen reads, so no transform.
fn command_rel(doc: &MarkdownDoc) -> String {
    doc.rel.strip_prefix("commands/").unwrap_or(&doc.rel).to_string()
}

/// `agents/ez-helper.md` -> `<plugin>-ez-helper.md` (a nested path flattens). The
/// plugin prefix keeps the file identifiable as ours for an exact `remove` and clear
/// of a user's own agent of the same stem.
fn agent_file(plugin: &str, doc: &MarkdownDoc) -> String {
    format!("{plugin}-{}.md", flat_stem(&doc.rel, "agents/"))
}

fn flat_stem(rel: &str, prefix: &str) -> String {
    let stripped = rel.strip_prefix(prefix).unwrap_or(rel);
    let stem = stripped.strip_suffix(".md").unwrap_or(stripped);
    stem.replace(['/', '\\'], "-")
}

/// Render a CC agent def as a qwen subagent file. `name` is plugin-prefixed so two
/// plugins' agents never collide (qwen keys subagents by frontmatter `name`, not
/// filename); both `name` and `description` carry over JSON-quoted (a valid YAML flow
/// scalar) so a YAML-special char never breaks the frontmatter. The
/// CC `model` alias (`sonnet`/`opus`/`haiku`) is dropped — those are not qwen model
/// ids and qwen has no portable `inherit` sentinel, so the subagent falls back to
/// qwen's default model. The body (the system prompt) copies through verbatim.
/// Deterministic so a re-reconcile is byte-identical.
fn render_agent(plugin: &str, doc: &MarkdownDoc) -> String {
    let name = doc.frontmatter.get("name").and_then(Value::as_str).unwrap_or(doc.name.as_str());
    let mut out = String::from("---\n");
    // JSON-quote the full name (a valid YAML flow scalar) so a YAML-special char in
    // the plugin or agent name can't produce malformed frontmatter — same escaping
    // path as `description` below.
    out.push_str("name: ");
    out.push_str(&Value::String(format!("{plugin}-{name}")).to_string());
    out.push('\n');
    if let Some(desc) = doc.frontmatter.get("description").and_then(Value::as_str) {
        out.push_str("description: ");
        out.push_str(&Value::String(desc.to_string()).to_string());
        out.push('\n');
    }
    out.push_str("---\n\n");
    out.push_str(doc.body.trim());
    out.push('\n');
    out
}

// --- report ------------------------------------------------------------------

fn report_checks(backend: &QwenCodeBackend, plugin: &Plugin, source: &Source) -> Vec<DoctorCheck> {
    let mut checks = Vec::new();

    checks.push(if backend.detect() {
        DoctorCheck { name: "qwen-code detected", status: CheckStatus::Ok("`qwen` on PATH or ~/.qwen present".into()) }
    } else {
        DoctorCheck {
            name: "qwen-code detected",
            status: CheckStatus::Fail {
                problem: "qwen-code CLI not detected".into(),
                fix: "install it with `npm install -g @qwen-code/qwen-code`".into(),
            },
        }
    });

    let base = match qwen_dir(&Scope::User) {
        Ok(base) => base,
        Err(e) => {
            checks.push(DoctorCheck { name: "settings file", status: CheckStatus::Warn(e.to_string()) });
            return checks;
        }
    };
    let settings = match settings_file(&Scope::User) {
        Ok(settings) => settings,
        Err(e) => {
            checks.push(DoctorCheck { name: "settings file", status: CheckStatus::Warn(e.to_string()) });
            return checks;
        }
    };

    let root = report::read_json_config(&mut checks, "settings file", &settings);

    let Some(comp) = report::components(&mut checks, plugin, source).map(|c| c.with_client(backend.id())) else {
        return checks;
    };

    checks.push(report::check_mcp_registered(
        &comp.mcp_servers,
        root.as_ref(),
        &["mcpServers"],
        "not in settings.json",
        "run the host's `setup`",
    ));
    checks.push(report::check_mcp_command(&comp.mcp_servers));
    checks.push(check_commands_present(&comp.commands, &base.join("commands").join(plugin.name)));
    checks.push(check_agents_present(&comp.agents, &base.join("agents"), plugin.name));
    // Absent entirely for a host that declares no status line, rather than reporting
    // on a surface nobody asked for.
    checks.extend(statuslinejson::check(STATUSLINE_SLOT, plugin, &Scope::User, backend.id(), STATUSLINE_SHAPE, "qwen-code", settings_file));

    checks
}

fn check_commands_present(commands: &[MarkdownDoc], cmd_root: &Path) -> DoctorCheck {
    let name = "translated commands present";
    if commands.is_empty() {
        return DoctorCheck { name, status: CheckStatus::Ok("no commands to translate".into()) };
    }
    let missing: Vec<String> = commands.iter().map(command_rel).filter(|rel| !cmd_root.join(rel).exists()).collect();
    if missing.is_empty() {
        DoctorCheck { name, status: CheckStatus::Ok(format!("{} command file(s) present", commands.len())) }
    } else {
        DoctorCheck {
            name,
            status: CheckStatus::Fail {
                problem: format!("command file(s) missing: {}", missing.join(", ")),
                fix: "run the host's `setup`".into(),
            },
        }
    }
}

fn check_agents_present(agents: &[MarkdownDoc], agent_root: &Path, plugin: &str) -> DoctorCheck {
    let name = "translated agents present";
    if agents.is_empty() {
        return DoctorCheck { name, status: CheckStatus::Ok("no agents to translate".into()) };
    }
    let missing: Vec<String> = agents.iter().map(|d| agent_file(plugin, d)).filter(|f| !agent_root.join(f).exists()).collect();
    if missing.is_empty() {
        DoctorCheck { name, status: CheckStatus::Ok(format!("{} agent file(s) present", agents.len())) }
    } else {
        DoctorCheck {
            name,
            status: CheckStatus::Fail {
                problem: format!("agent file(s) missing: {}", missing.join(", ")),
                fix: "run the host's `setup`".into(),
            },
        }
    }
}

#[cfg(test)]
#[path = "../../tests/unit/qwen_code.rs"]
mod qwen_code_tests;