A Practical Guide to Slash Commands for CLI AI Coding Assistants

    This article explains how slash commands in command-line AI coding assistants improve context ROI, enforce repeatable instructions, and convert individual workflows into shared team assets. It covers trigger rules, command sources, essential built-in commands, custom command design, workflow integration, enterprise adoption, measurement, common pitfalls, and interview-ready explanations.

    A Practical Guide to Slash Commands for CLI AI Coding Assistants

    1. Why Slash Commands Determine the Context ROI of AI Coding

    In command-line AI coding assistants, what flows between you and the model is not “code” but context: the current conversation history, files that have been read, retrieval results, and command output. Every turn consumes a limited context window, and every line of context participates in the model’s attention allocation.

    The first question to ask when judging whether an interaction is efficient is not “Did the AI write the right thing?” but “Did the model see the right information at the right time?”

    Based on this standard, daily usage can be divided into three layers:

    1. Manage context correctly. Clear irrelevant history when switching tasks, compact long conversations in time, and make the model read key files before it starts writing code.
    2. Make instructions repeatable. Constraints such as project conventions, review checklists, and testing requirements are often repeated in natural language. Doing this every time wastes tokens and makes the instruction fragile when the wording changes. Turning them into commands writes the “standard” into the workflow.
    3. Turn processes into team assets. Command files are plain text. They can be committed to version control with code, reviewed, iterated, and shared. New team members can immediately adopt the same working methods as existing members.

    Most complaints about “using AI badly” come from failing at the first layer: the context has already been polluted by irrelevant content, and the model never sees a clean problem, so the output naturally becomes unpredictable.

    The value of slash commands is that they turn these operations from “something you have to remember” into “something you do with muscle memory.”

    2. Trigger Rules and the Three Sources of Commands

    2.1 Three Hard Rules You Should Remember First

    • They are recognized only at the beginning of an input line. A command must start with / at the very beginning of the message. A / in the middle of a sentence is just a normal character and will not be parsed. After typing /, a candidate list appears. Using arrow keys and Tab completion is far more reliable than memorizing command names.
    • Text after the command name is passed in as arguments. This point is easy to miss: arguments are not comments for the AI to read casually. They are parsed or concatenated according to the command’s convention. If the format is incorrect, the arguments may be treated as ordinary text, or only the first word may be captured.
    • Session-level scope comes first. Most commands affect only the current session. Operations such as clearing or compacting do not rewrite source files on disk, but they do discard the current context. Therefore, before compacting or switching models, it is worth confirming that key conclusions have already been written to a file.

    2.2 Three Sources: The Same Menu, Different Mental Models

    The commands shown in the candidate list look like one type of thing, but they actually come from three sources with significantly different behavior:

    Type Behavior determined by Can it be invoked automatically? Typical uses
    Built-in commands Hard-coded inside the program No; manual invocation only Clear context, compact context, switch model, view changes, export session
    Preset workflow / skill-style commands A preset instruction text executed by the model Yes; the model may select it based on the description Code review, run tests, commit, generate documentation
    Custom commands Markdown files written by you Depends on whether descriptive information is provided Project conventions, team workflows, focused analysis

    This distinction has direct practical significance.

    Built-in commands must be invoked manually, because the program will not make context decisions for you. Preset workflows and custom commands can be triggered automatically, which is both convenient and risky. For example, a poorly described review command may be triggered when the user only wants to change one line of configuration, wasting a turn of context.

    When writing descriptions for custom commands, write them like function documentation: clearly state when to use it and when not to use it.

    2.3 What Should and Should Not Be Turned into Commands

    A practical rule of thumb is this: if you say almost the same thing for the third time, consider turning it into a command.

    However, repetition is not the only condition. The structure must also be stable.

    Good candidates for commands include:

    • Outputs with a fixed format, such as commit messages, changelogs, and API documentation;
    • Checks that must be executed, such as security review and dependency change review;
    • Scripts with fixed input sources, such as CI configuration and build scripts;
    • Specification constraints that need to be enforced consistently.

    Poor candidates for commands include:

    • One-off exploratory requests;
    • Architecture discussions that require repeated back-and-forth;
    • One-off troubleshooting that depends heavily on the current context.

    Turning these into command files will only create “zombie commands” that no one dares to modify and no one dares to delete. The value of a command comes from reuse frequency multiplied by benefit. Low-frequency commands usually cost more to maintain than they return.

    3. Built-in Commands You Really Need to Remember

    You do not need to memorize dozens of commands. Remembering the following groups by scenario covers most daily operations. Command names may vary across implementations. Focus on the capability category, then search the candidate list by keyword.

    3.1 Context and State Management — Highest Priority

    • Clear the current session. When switching to a completely unrelated task, clear the context first instead of continuing to ask questions in the old context. Bringing memory from the previous task into an unrelated module is a common source of “strange changes.”
    • Compact long sessions. When the context approaches its limit, summarize the current conversation and continue. After compaction, run a verification step immediately: ask the model to restate the current task goal, completed changes, and unresolved issues. Confirm that no key constraints were lost before continuing.
    • Export the session. Export the current conversation to a file for retrospectives, defect reports, or handing context over to a colleague. This is highly valuable in team collaboration but often overlooked.
    • Resume a historical session. Use this to continue after an interruption. Before resuming, confirm whether the workspace state matches the description at the end of the session. Otherwise, the model may make judgments based on a distorted memory.

    3.2 Code Changes and Output Management

    • View changes in the current round. After a long session, it becomes difficult to remember what was actually changed. This type of command shows file-level additions and deletions in a diff view. It should be a mandatory checkpoint at the end of every task.
    • Generate commit messages / changelogs. The model reads the diff and generates a commit message or changelog that follows team conventions. This removes the step where “writing the commit message is harder than changing the code.” The prerequisite is that the model reads the real diff, not the diff you described verbally.
    • Run checks and tasks. Let the model run tests, static checks, or builds. The output flows directly back into the context. This is far more reliable than manually copying and pasting error messages, because the model sees complete output rather than truncated fragments.

    3.3 Model and Configuration

    • Switch models. Different models make different trade-offs among reasoning depth, response speed, and context length. A common practice is to use stronger reasoning models for planning and complex refactoring, and faster, cheaper models for batch renaming, formatting, and simple scripts. Decide the model based on the task type, not on mood.
    • Permissions and execution modes. For scenarios involving file modifications or shell command execution, many implementations offer several modes, from “discussion only, no actions” to “automatic execution.” The rule is: never give fully automatic execution to write operations in production, deletion operations, or permission changes, even if it is slower.
    • Custom configuration items. Most configuration changes require restarting the session to take effect. After changing the configuration, verify the behavior change immediately to avoid assuming that the change worked when it did not.

    4. Build Your Own Commands: From Repetition to Assets

    The essence of a custom command is a Markdown file. The file name is the command name, and the file body is the instruction content. When placed in the agreed command directory, it can be recognized. There are usually two levels:

    • User-level directory — located in the configuration directory under the user’s home directory. It affects only yourself and is suitable for personal habits.
    • Project-level directory — located inside the project repository. It can be committed with code and shared with the team. It is suitable for conventions and workflows.

    File names should use lowercase words separated by hyphens, such as commit-message.md, api-doc.md, and perf-review.md. The description should be placed in the file header metadata. It will appear in the candidate list, so it should be written in the form of “condition + purpose.” For example:

    Use when documentation is needed for a new API in accordance with the team template.

    This is better than a simple description such as “generate documentation.”

    4.1 A Runnable Example

    Assume the team requires that API documentation must include an error code table, an idempotency statement, and a rate-limiting policy. It must also be derived from code and database migration scripts, and must not be invented.

    A command file could look like this:

    1. ---
    2. description: Generate API documentation for new or changed endpoints based on code and migration scripts, following the team template; do not speculate about fields
    3. allowed-tools: read files, search code, view diffs
    4. model: default
    5. ---
    6. Goal: Generate an API documentation draft for the endpoints changed in this update.
    7. Inputs:
    8. - Change scope: $ARGUMENTS (if empty, default to the current uncommitted changes)
    9. - Allowed directories to read: src/, migrations/
    10. Steps:
    11. 1. First review the uncommitted changes and list the routes and handler functions involved;
    12. 2. For each endpoint, extract: path, method, request parameters, response structure, error codes, and authentication method;
    13. 3. Derive field constraints and default values from the migration scripts;
    14. 4. Mark idempotency and rate-limiting requirements. If no evidence is found in the code, write “to be confirmed” instead of making it up.
    15. Output: One Markdown document and one “items to be confirmed” list, sorted by severity.

    This example intentionally reflects several design points that matter more than the syntax itself:

    • Single responsibility. It only generates documentation and does not modify code. If one command does three things, it becomes difficult to locate which step failed.
    • Explicit input conventions. When the argument is empty, a default behavior is defined. This avoids random behavior caused by missing arguments.
    • Give the model boundaries. Explicitly stating the allowed directories to read and forbidding speculation narrows uncertainty into a “to be confirmed” list instead of spreading guesses throughout the document.
    • Structured output contract. When the output format is fixed, it can enter downstream workflows, such as being pasted into a review system or imported into a documentation site.

    4.2 Arguments, File References, and Execution Inside Commands

    In addition to plain text instructions, many implementations support several common enhancement capabilities. The exact syntax depends on the tool documentation, but the ideas are broadly similar:

    • Argument placeholders. Text after the command name is passed in as arguments. It can be referenced in the instruction body. Some implementations support “take all arguments,” while others support “take the Nth argument in order.” Parameterization allows one command to cover a whole class of tasks, such as generate commit message <repository path>.
    • File references. You can reference a file path in the instruction body, and the file content will enter the context together with the command. This is suitable for long lists, such as review checklists, coding standards, and terminology lists. The benefit is that the list can evolve independently while the command body remains short.
    • Shell execution inside commands. You can embed command output directly into the context, such as making the real output of a build script the model’s input. This is one of the most effective ways to eliminate “hallucinated data.” If a fact can be verified by a real command, do not ask the model to recall it.
    • Script-based extensions. Some implementations allow commands to be implemented as executable scripts. This is suitable for complex workflows that need stable, testable logic. Pure instruction text is more suitable when the model’s judgment is needed. The choice depends on whether the step requires judgment or determinism.

    4.3 Make Commands Actually Get Used

    Writing a command does not automatically create value. Four things determine whether it survives:

    1. Put it under version control and review. Command files are carriers of team conventions. They should go through the same review process as code. Otherwise, they quickly become legacy baggage where “no one knows why it was written this way.”
    2. Control the number of commands. Too many commands pollute the candidate list and reduce discoverability. Periodically remove commands that have not been used for half a year and have no references.
    3. Write clearly when not to use it. Explicitly excluding scenarios can significantly reduce accidental triggers. The cost of an accidental trigger, in terms of both context and trust, is much higher than missing one command use.
    4. Tighten permissions. Use least privilege by default. For commands involving write operations, state in the instruction body: “Confirm with the user before execution.” Do not preset destructive operations as confirmation-free.

    5. Chain Commands into a Workflow

    A single command improves the efficiency of one operation. A workflow improves the stability of the entire chain.

    A common daily loop looks like this:

    1. Receive request → clear/compact context → use an /init-style command to generate project documentation
    2. → plan (read-only first) → implement step by step → run tests and static checks
    3. → view changes → generate commit message → run code review command → record follow-ups

    There are three habits that are easy to skip but have high value:

    • Separate planning from execution. First let the model read the code and output a plan and an impact list. After you confirm, let it start making changes. This step prevents a large amount of rework before code is written, and the cost is much lower than rolling back afterward.
    • Reset context in stages. The exploration stage can tolerate some context redundancy. The implementation stage should stay as clean as possible. Clearing the context when switching tasks is the cheapest way to prevent cross-task pollution.
    • Always review changes at the end. After a long session, the model’s self-awareness of what it did has already degraded. Only a real diff view can tell you which files it actually touched. This check can also expose two types of problems: files that should not have been changed, and changes that were claimed but never written.

    6. How to Scale in Enterprise Environments

    When personal techniques become team practices, several engineering-side items need to be completed. These are common capability categories, and the specific choices should follow the existing technology stack:

    • Store commands and configurations with code. Project-level commands, project documentation files, and coding standards should all be placed in the code repository, reviewed, and version-controlled. This ensures that “new members use the same methods as the team from day one.”
    • Define permission and compliance boundaries. Clearly state which environments allow tools to write directly and which require manual confirmation. Production changes should follow the existing approval and release process. The introduction of AI tools should not weaken it. Operations involving credentials and sensitive data should follow the principle of least privilege. Avoid writing secrets into context.
    • Add observability. Connect the tool’s invocation logs and task execution records to a unified logging service. Combine them with monitoring alerts to track task duration, failure rate, and rework count. Only with data can you answer the question that management always asks: “How much labor did this approach actually save?”
    • Plan compute and deployment shape. Team-level usage usually requires isolated execution environments on container platforms or cloud hosts. Object storage can be used for session exports and artifact archiving. Message queues and pipelines can connect task nodes. When making choices, prioritize integration cost with existing infrastructure rather than isolated feature points.

    7. How to Measure Whether You Are Really Faster

    Three observable metrics are more reliable than subjective feelings:

    • Turns per task. Compare the number of conversation turns required for the same type of task before and after making it command-based. A typical sign of effective command usage is a noticeable drop in the number of turns.
    • First-pass acceptance rate. The proportion of generated code, documentation, and commit messages that are accepted without manual modification.
    • Rework and unintended-change rate. The number of out-of-scope changes and factual errors found during the end-of-task review. If this metric rises, it usually means there is a context management problem, not a model capability problem.

    8. Common Pitfalls

    • Treating commands as a universal entry point. One-off exploratory requests are more flexible in natural language. Forcing them into commands only increases maintenance cost.
    • Putting multiple responsibilities into one command. When it fails, you cannot locate the problem, and the output is difficult to reuse.
    • Not defining an output contract. If the output format is random, it cannot be integrated into downstream workflows, and it is difficult to determine whether it succeeded.
    • Abusing automatic execution permissions. This is especially risky for three categories of operations: deletion, permission changes, and production writes.
    • Not versioning commands. If each team member has a different version, the specification becomes meaningless.
    • Ignoring the context budget. Stuffing every possibly relevant file into the context usually performs worse than selecting only the key files.

    9. How to Answer This Type of Question in an Interview

    If asked, “What are some practical techniques for slash commands?”, a structured answer with clear trade-offs is more convincing than simply listing command names. You can answer in four progressive layers:

    1. Explain the mechanism. Commands are triggered only at the beginning of a line, and the text after them is passed in as arguments. The candidate menu mixes three different sources of commands.
    2. Explain the classification. Built-in commands change session and configuration state. Preset workflows and custom commands change model behavior. The former must be invoked manually, while the latter may be triggered automatically.
    3. Explain the scenarios. Clearing and compacting manage context. Diff views and commit message generation manage output. Model switching should be based on task type. Separating planning from execution reduces rework.
    4. Explain engineering practices. Command files should be version-controlled, reviewed, and granted least privilege. They should be connected to logging and monitoring, and their benefits should be measured with real metrics.

    The first two layers show that you have used the tool. The third layer shows that you use it deeply. The fourth layer shows that you can turn it into a team capability. Most candidates stop at the first layer, and that is where the difference lies.