Skip to main content

merry_coding/
workflow_commands.rs

1//! Built-in coding workflow slash commands owned by `merry-coding`.
2//!
3//! These workflows compile into ordinary user-turn prompts so interactive
4//! surfaces can trigger structured review flows without mutating the stable
5//! system prefix or provider tool catalog (preserving KV cache reuse).
6
7/// Built-in coding workflow command exposed to interactive surfaces.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub enum CodingWorkflowCommand {
10    /// Multi-angle skeptical code review with 3-state verification.
11    CodeReview,
12    /// High-confidence security audit with explicit false-positive filtering.
13    SecurityReview,
14}
15
16impl CodingWorkflowCommand {
17    /// Canonical slash command name (without leading `/`).
18    #[must_use]
19    pub const fn name(self) -> &'static str {
20        match self {
21            Self::CodeReview => "code-review",
22            Self::SecurityReview => "security-review",
23        }
24    }
25
26    /// Secondary slash aliases (without leading `/`).
27    #[must_use]
28    pub const fn aliases(self) -> &'static [&'static str] {
29        match self {
30            Self::CodeReview => &["review"],
31            Self::SecurityReview => &["sec-review"],
32        }
33    }
34
35    /// Short description for help and completion menus.
36    #[must_use]
37    pub const fn description(self) -> &'static str {
38        match self {
39            Self::CodeReview => "Review recent changes or a specified target",
40            Self::SecurityReview => "Audit recent changes or a target for security risks",
41        }
42    }
43
44    /// Human-readable optional argument hint.
45    #[must_use]
46    pub const fn argument_hint(self) -> &'static str {
47        "[scope or focus]"
48    }
49
50    /// Renders the user-turn prompt for this workflow command.
51    ///
52    /// Keeps the stable system prefix and tool definitions unchanged while
53    /// structuring multi-angle analysis, skeptical verification, and
54    /// context-aware delegation to Merry's built-in `review` subagent.
55    #[must_use]
56    pub fn build_prompt(self, scope_or_focus: Option<&str>) -> String {
57        let scope = scope_or_focus
58            .map(str::trim)
59            .filter(|value| !value.is_empty());
60        match self {
61            Self::CodeReview => build_code_review_prompt(scope),
62            Self::SecurityReview => build_security_review_prompt(scope),
63        }
64    }
65}
66
67fn build_code_review_prompt(scope: Option<&str>) -> String {
68    let phase_zero = match scope {
69        Some(target) => format!(
70            "## Phase 0 — Gather the scope\n\
71Target scope / focus requested by user:\n\
72{target}\n\n\
73Inspect the requested scope directly (files, commits, diff range, or subsystem) along with its enclosing functions, callers, and invariants."
74        ),
75        None => "## Phase 0 — Gather the diff\n\
76Inspect uncommitted workspace changes first (`git status --short`, `git diff`, `git diff --cached`, and any untracked files). \
77If the working tree is clean, inspect the current branch diff against the default branch (`git diff origin/HEAD...HEAD`, falling back to `git diff main...HEAD` or `git diff HEAD~1..HEAD`).".to_owned(),
78    };
79
80    format!(
81        "Perform a precision-focused, skeptical code review. Every finding you surface must be actionable and worth fixing.\n\n\
82{phase_zero}\n\n\
83## Delegation rule (context-aware)\n\
84- If you authored or edited code in this session, OR the diff spans multiple files / non-trivial logic, AND `spawn_subagents` is available, delegate independent discovery and/or Phase 2 verification to independent `review` subagent(s) (`role: \"review\"`) so they inspect the diff from an unanchored fresh context. Brief them strictly with the scope, diff/files, and known user constraints—never pass optimistic conclusions or self-justifications. Verify key `path:line` citations yourself before presenting the final report.\n\
85- If this is already a fresh session reviewing a narrow/single-file target, or subagents are disabled/unavailable, run all phases directly.\n\n\
86## Phase 1 — Multi-angle candidate discovery\n\
87Inspect the diff from all five angles:\n\
881. **Line-by-line & enclosing-function scan**: Read every hunk line by line and read the enclosing function (unchanged lines re-exposed by the diff are in scope). Ask what input, state, timing, or platform makes each line wrong: inverted conditions, off-by-one, empty/zero/null handling, missing `await`, swallowed errors, copy-paste variable mistakes, unescaped metacharacters.\n\
892. **Removed-behavior audit**: For every line deleted or replaced, name the invariant or guard it enforced and confirm where the new code re-establishes it (dropped guards, lost error paths, narrowed validation, removed test coverage).\n\
903. **Cross-file caller & callee tracing**: Search callers (`rg`) for changed functions/types/contracts and check call sites for broken preconditions, changed return shapes, new errors, or ordering/timing regressions.\n\
914. **Project rules & conventions (`AGENTS.md`)**: Check applicable `AGENTS.md` files (repo root and ancestor directories of changed files) for clear violations of stated project rules, quoting the exact rule and offending line.\n\
925. **Efficiency & hot-path regressions**: Flag concrete wasted work introduced by the diff (redundant I/O or computation in loops/hot paths, blocking work in async paths, avoidable serialization, long-lived closures retaining large scopes) and name the cheaper alternative.\n\n\
93## Phase 2 — Skeptical 3-state verification\n\
94Deduplicate overlapping candidates, then verify each remaining candidate against exact source lines (and targeted checks/tests when helpful). Classify each candidate as exactly one of:\n\
95- **CONFIRMED**: Can name exact inputs/state that trigger the bug and the wrong output or crash; quote the exact line.\n\
96- **PLAUSIBLE**: Real mechanism, trigger depends on timing, environment, or configuration; state exactly what would confirm it.\n\
97- **REFUTED**: Factually wrong or already guarded elsewhere — drop it and do not report it.\n\
98Keep only **CONFIRMED** and **PLAUSIBLE** findings.\n\n\
99## Review constraints\n\
100- Read-only review: do not modify production files or apply fixes inline unless the user asks afterward.\n\
101- Group repeated occurrences of the exact same mistake into one finding and list all affected `path:line` locations.\n\n\
102## Output format\n\
1031. **Verdict**: `PASS`, `FAIL`, or `BLOCKED` (naming the exact reviewed scope).\n\
1042. **Findings** ordered by severity (`Important` -> `Pre-existing` -> `Nit`), or explicitly state no material issues found:\n\
105   - `Important`: bug added or re-exposed by this change that should be fixed before merging (a rare trigger does not lower severity).\n\
106   - `Pre-existing`: real bug in unchanged code that this change did not introduce.\n\
107   - `Nit`: minor non-blocking issue worth fixing (e.g. a broken `AGENTS.md` rule or misleading diagnostic).\n\
108   - For each finding include: `[CONFIRMED|PLAUSIBLE]`, exact `path:line`, and 2-3 concise sentences (user-visible problem -> exact location and trigger -> `Fix:` concrete change).\n\
1093. **Verification**: exact commands/checks executed and their outcomes (or what was skipped and why)."
110    )
111}
112
113fn build_security_review_prompt(scope: Option<&str>) -> String {
114    let phase_zero = match scope {
115        Some(target) => format!(
116            "## Target scope\n\
117Target scope / focus requested by user:\n\
118{target}\n\n\
119Audit the requested scope and trace every trust boundary, untrusted input source, and privileged sink it touches."
120        ),
121        None => "## Target scope\n\
122Audit newly introduced security implications in the pending changes: inspect uncommitted changes first (`git status --short`, `git diff`, `git diff --cached`, and untracked files); if the working tree is clean, inspect the branch diff (`git diff origin/HEAD...HEAD`, falling back to `git diff main...HEAD` or `git diff HEAD~1..HEAD`). Focus on security risks introduced or worsened by these changes rather than unrelated legacy code.".to_owned(),
123    };
124
125    format!(
126        "Perform a high-confidence security review focused strictly on concrete, exploitable vulnerabilities. Better to report zero findings than flood the review with theoretical noise.\n\n\
127{phase_zero}\n\n\
128## Delegation rule (context-aware)\n\
129- Prefer delegating to independent `review` subagent(s) (`role: \"review\"`) whenever `spawn_subagents` is available and either you authored edits in this session OR the audit spans multiple files / trust boundaries: first identify candidate vulnerabilities from an unanchored context, then run a skeptical false-positive verification pass applying the Hard Exclusions and Confidence >= 8 gate below. Verify key `path:line` citations before presenting the final report.\n\
130- If this is already a fresh session auditing a narrow single-file target, or subagents are disabled/unavailable, execute Phases 1-3 directly while strictly enforcing the same false-positive filter.\n\n\
131## Phase 1 — Repository security context\n\
132Before judging the diff, inspect existing security boundaries, validation/sanitization helpers, permission/sandbox policy, and authentication/authorization patterns in the repository.\n\n\
133## Phase 2 — Comparative & dataflow vulnerability analysis\n\
134Compare the changed code against existing secure patterns and trace untrusted inputs (`Source -> Sink`) across trust boundaries:\n\
135- **Input validation & injection**: command/shell injection, SQL/NoSQL injection, template/XXE injection, XSS (reflected/stored/DOM, excluding auto-escaped framework views unless unsafe escape hatches are used), unsafe deserialization / code execution.\n\
136- **AuthN / AuthZ & boundary bypasses**: authentication or authorization bypasses, privilege escalation, session/token validation flaws, sandbox/permission bypasses, untrusted project config weakening global trust policy.\n\
137- **Filesystem & network safety**: path traversal, symlink/TOCTOU escapes, SSRF where an attacker controls the host or protocol, unsafe temp files.\n\
138- **Crypto, secrets & data exposure**: hardcoded credentials/API keys, weak crypto or broken certificate validation, plaintext logging or API leakage of high-value secrets or PII.\n\
139- **Memory safety**: only when actual `unsafe` blocks or FFI boundaries violate soundness invariants.\n\n\
140## Phase 3 — False-positive filtering & confidence gate\n\
141Read the code directly to verify exploitability; do not edit production files. Automatically exclude findings matching any of these **Hard Exclusions**:\n\
1421. Denial of Service (DoS), rate-limiting, CPU/memory exhaustion, or resource/FD leaks.\n\
1432. Missing defense-in-depth hardening or theoretical best practices without a concrete exploit path.\n\
1443. Theoretical race conditions or timing attacks without a concrete, practical trigger.\n\
1454. Outdated third-party dependency advisories (handled separately), test-only files, or Markdown documentation.\n\
1465. Memory-safety claims in safe Rust or other memory-safe languages without `unsafe`/FFI.\n\
1476. Log spoofing or logging non-secret, non-PII data (such as ordinary URLs); missing audit logs.\n\
1487. SSRF where the attacker controls only the URL path (not host or protocol); regex injection / ReDoS.\n\
1498. Missing permission checks in untrusted client-side code when enforced server-side.\n\
1509. Attacks assuming the attacker already controls trusted local CLI flags or host environment variables (unless the project's threat model explicitly treats them as untrusted).\n\n\
151Score every surviving finding from 1 to 10 for exploitability confidence:\n\
152- **8-10**: Clear, concrete exploit path verified in code -> **REPORT**.\n\
153- **Below 8**: Speculative or unverified -> **DROP**.\n\n\
154## Output format\n\
1551. **Verdict**: `PASS`, `FAIL`, or `BLOCKED` (naming the exact audited scope).\n\
1562. **Findings** (High and concrete Medium findings with confidence >= 8/10 only, ordered by severity; if none survive, explicitly state no high-confidence exploitable vulnerabilities were found):\n\
157   - Heading: `### Vuln N: <Category>: path:line`\n\
158   - `Severity`: `High` (directly exploitable RCE, auth bypass, sandbox escape, or data breach; local-network exploits still count) or `Medium` (concrete impact under specific conditions)\n\
159   - `Confidence`: `<8-10>/10`\n\
160   - `Description`: exact flaw and broken trust boundary\n\
161   - `Exploit Scenario`: concrete attacker model, input/trigger path, and resulting impact\n\
162   - `Recommendation`: minimal, concrete fix aligned with repository patterns\n\
1633. **Residual risks**: any trust boundaries in scope that could not be verified from the available code."
164    )
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    #[test]
172    fn workflow_command_metadata_and_prompts_are_well_formed() {
173        assert_eq!(CodingWorkflowCommand::CodeReview.name(), "code-review");
174        assert_eq!(CodingWorkflowCommand::CodeReview.aliases(), &["review"]);
175        assert_eq!(
176            CodingWorkflowCommand::SecurityReview.name(),
177            "security-review"
178        );
179        assert_eq!(
180            CodingWorkflowCommand::SecurityReview.aliases(),
181            &["sec-review"]
182        );
183
184        let default_code = CodingWorkflowCommand::CodeReview.build_prompt(None);
185        assert!(default_code.contains("git diff"));
186        assert!(default_code.contains("role: \"review\""));
187        assert!(default_code.contains("Removed-behavior audit"));
188        assert!(default_code.contains("Cross-file caller & callee tracing"));
189        assert!(default_code.contains("AGENTS.md"));
190        assert!(default_code.contains("CONFIRMED"));
191        assert!(default_code.contains("PLAUSIBLE"));
192        assert!(default_code.contains("REFUTED"));
193        assert!(default_code.contains("Read-only review"));
194
195        let scoped_code = CodingWorkflowCommand::CodeReview.build_prompt(Some("  main..HEAD  "));
196        assert!(scoped_code.contains("main..HEAD"));
197        assert!(!scoped_code.contains("If the working tree is clean"));
198
199        let blank_security = CodingWorkflowCommand::SecurityReview.build_prompt(Some("   "));
200        assert!(blank_security.contains("git diff"));
201        assert!(blank_security.contains("Hard Exclusions"));
202        assert!(blank_security.contains("Confidence >= 8"));
203        assert!(blank_security.contains("Exploit Scenario"));
204        assert!(blank_security.contains("path traversal"));
205
206        let scoped_security = CodingWorkflowCommand::SecurityReview
207            .build_prompt(Some("crates/merry-tools/src/ssrf.rs"));
208        assert!(scoped_security.contains("crates/merry-tools/src/ssrf.rs"));
209        assert!(scoped_security.contains("role: \"review\""));
210    }
211}