This prompt is designed for platform engineers and CLI maintainers who need to document deep, nested subcommand hierarchies that are difficult to trace manually. The primary job-to-be-done is producing a complete, machine-readable map of every command path, including parent-child relationships, aliases, and deprecation markers. The ideal user is someone building a documentation pipeline where this structured output will feed directly into reference pages, shell completion scripts, or automated testing harnesses. Required context includes access to the source code or the ability to run binary introspection commands (like --help on every subcommand) to provide the model with the raw material it needs to analyze.
Prompt
Subcommand Tree Generation Prompt from Source Code

When to Use This Prompt
Identify the right scenarios for generating a complete, machine-readable subcommand tree from source code or binary introspection.
Use this prompt when you need a single source of truth for your CLI's command structure. It is particularly valuable for tools with multiple levels of subcommands, where manually maintaining a command tree is error-prone and time-consuming. The output is intended to be a JSON schema representing the tree, which can then be programmatically validated against the actual binary. This prompt is not a replacement for hand-written usage examples, conceptual overviews, or tutorials. It is a structural analysis tool. You should avoid using it for simple, flat CLI tools with only a few flags, as the overhead of the prompt and validation harness may outweigh the benefit of a simple manual list.
Before using this prompt, ensure you have a reliable method for extracting the raw command structure. This could be a script that iterates through all discovered subcommands and captures their --help output, or it could be the source code files themselves. The prompt's effectiveness depends on the completeness of this input. After generating the tree, your next step should be to run an automated validation that parses the output and checks for orphaned commands, missing leaf nodes, and incorrect nesting depth against the actual binary. Do not publish the generated tree without this validation step, as even minor source code changes can introduce drift.
Use Case Fit
Where the Subcommand Tree Generation Prompt delivers reliable structure and where it introduces risk. Use these cards to decide if this prompt fits your CLI documentation pipeline.
Good Fit: Deeply Nested CLI Tools
Use when: your CLI has three or more levels of subcommands (e.g., tool cluster node pool create). The prompt excels at extracting parent-child relationships, aliases, and hidden commands that manual documentation often misses. Guardrail: always validate the generated tree against [CLI_BINARY] --help output for every leaf node to catch orphaned commands.
Good Fit: Source-Annotated Command Definitions
Use when: subcommands are defined with structured annotations, decorators, or command builders in source code (e.g., @click.group, cobra.Command, clap::Subcommand). The prompt can parse these patterns reliably. Guardrail: provide the prompt with the exact annotation library and version so it recognizes the correct AST patterns.
Bad Fit: Dynamic or Plugin-Based Commands
Avoid when: subcommands are registered at runtime through plugins, dynamic imports, or external configuration files. The prompt cannot see commands that do not exist in static source analysis. Guardrail: use binary introspection ([CLI_BINARY] __complete or --list-commands) as the primary input for dynamic CLIs, not source code.
Bad Fit: Commands with Identical Names Across Packages
Avoid when: multiple packages or modules define subcommands with the same name under different parent groups. The prompt may merge or confuse these commands. Guardrail: pre-process source files to include fully qualified module paths as context, and add a deduplication check in the harness that flags ambiguous command names.
Required Inputs
You must provide: (1) the root CLI source directory or binary path, (2) the command framework and language (e.g., Python Click, Go Cobra, Rust Clap), (3) the maximum expected nesting depth, and (4) any commands or directories to exclude. Guardrail: missing any of these inputs causes the prompt to hallucinate command structure or miss entire subtrees.
Operational Risk: Stale Trees in CI/CD
Risk: the generated command tree becomes stale when new subcommands are added, deprecated, or renamed in subsequent releases. Documentation drifts silently. Guardrail: run the prompt in CI on every merge to main, compare the output against the previous version, and fail the build if the tree structure changes without a corresponding documentation update.
Copy-Ready Prompt Template
A reusable prompt template with square-bracket placeholders for generating a complete subcommand tree from source code or binary introspection.
This section provides the core prompt you will adapt and integrate into your documentation pipeline. The template is designed to analyze a CLI tool's source code, help text, or runtime introspection output and produce a structured, hierarchical representation of every command, subcommand, alias, and deprecation marker. The output is intended to be machine-readable so it can be ingested by downstream documentation generators, validated against the actual binary, and diffed for drift detection.
textYou are a CLI architecture analyzer. Your task is to generate a complete, hierarchical subcommand tree from the provided source material. ## INPUT [SOURCE_CODE_OR_INTROSPECTION_OUTPUT] ## CONSTRAINTS - Output ONLY the command tree in the specified [OUTPUT_SCHEMA]. Do not add commentary. - Capture the full parent-child relationship for every command, subcommand, and nested subcommand. - For each node, include: the command name, all known aliases, a brief description derived from help text or comments, and a boolean `deprecated` flag. - Mark any command flagged as deprecated, hidden, or experimental in the source with the appropriate status. - Preserve the exact nesting depth. A subcommand of `tool` is distinct from a subcommand of `tool component`. - If the source material is ambiguous about a command's parent, infer the relationship from usage strings, command registration code, or help text indentation. - If a command has no subcommands, it is a leaf node. Ensure leaf nodes are not omitted. ## OUTPUT_SCHEMA ```json { "cli_name": "string", "version": "string or null", "command_tree": [ { "name": "string", "aliases": ["string"], "description": "string", "deprecated": boolean, "status": "active | deprecated | hidden | experimental", "subcommands": [ // Recursive self-reference ] } ] }
EXAMPLES
Input (Go cobra):
govar rootCmd = &cobra.Command{Use: "mycli", Short: "Root command"} var getCmd = &cobra.Command{Use: "get [resource]", Aliases: []string{"g"}, Short: "Get a resource"} var getUsersCmd = &cobra.Command{Use: "users", Short: "Get users"} getCmd.AddCommand(getUsersCmd) rootCmd.AddCommand(getCmd)
Output:
json{ "cli_name": "mycli", "command_tree": [ { "name": "mycli", "aliases": [], "description": "Root command", "deprecated": false, "status": "active", "subcommands": [ { "name": "get", "aliases": ["g"], "description": "Get a resource", "deprecated": false, "status": "active", "subcommands": [ { "name": "users", "aliases": [], "description": "Get users", "deprecated": false, "status": "active", "subcommands": [] } ] } ] } ] }
FAILURE MODES TO AVOID
- Do not flatten the tree into a list of commands.
- Do not invent commands not present in the source.
- Do not omit leaf nodes.
- Do not treat aliases as separate commands.
To adapt this template, replace [SOURCE_CODE_OR_INTROSPECTION_OUTPUT] with the actual text you are analyzing—this could be a concatenation of source files, the output of mycli --help run recursively, or a structured introspection dump. Replace [OUTPUT_SCHEMA] if your downstream system expects a different format, such as YAML or a custom JSON schema. For high-risk documentation pipelines where accuracy is critical, always pair this prompt with a validation harness that executes the actual binary to confirm the generated tree matches reality. If the source material exceeds the model's context window, chunk it by top-level command and run the prompt once per chunk, then merge the results programmatically.
Prompt Variables
Required inputs for the Subcommand Tree Generation Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to verify the input is well-formed before generation begins.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[SOURCE_CODE] | Root directory path or file listing containing the CLI source code to analyze | /home/user/projects/my-cli/src/commands/ | Must resolve to an existing directory or file tree. Check path exists before prompt assembly. Reject empty directories. |
[ENTRY_POINT] | The main CLI entry file or module where command registration begins | src/main.rs or cli.py:main() | Must be a valid file path within [SOURCE_CODE]. Parse check: verify the file exists and is non-empty. If the entry point is a function, include the module path. |
[LANGUAGE] | Programming language of the source code for parser selection | Python, Rust, Go, TypeScript | Must be one of the supported languages in the harness config. Use exact casing from the allowed list. Reject unsupported languages with a clear error before generation. |
[CLI_FRAMEWORK] | The CLI parsing library or framework used in the source code | Click, Clap, Cobra, Commander.js | If null, the prompt attempts auto-detection. If provided, must match a known framework in the parser registry. Mismatch causes incorrect tree extraction. |
[MAX_DEPTH] | Maximum nesting depth for the subcommand tree | 3 | Must be a positive integer. Defaults to 10 if null. Depths greater than 15 risk token overflow. Validate as integer and clamp to 1-20 before prompt assembly. |
[INCLUDE_HIDDEN] | Whether to include hidden or internal commands in the output tree | Must be a boolean. When true, the prompt includes commands marked as hidden, private, or internal. When false, these are excluded. Validate as strict boolean before injection. | |
[INCLUDE_DEPRECATED] | Whether to include deprecated commands with deprecation markers | Must be a boolean. When true, deprecated commands appear with a deprecation flag and optional replacement note. When false, they are omitted entirely. Validate as strict boolean. | |
[OUTPUT_FORMAT] | Desired output structure for the command tree | JSON, YAML, or Mermaid | Must be one of the enumerated values. JSON and YAML produce structured trees with parent-child arrays. Mermaid produces a diagram-ready markdown string. Validate against the allowed set before generation. |
Implementation Harness Notes
How to wire the subcommand tree generation prompt into a reliable documentation pipeline with validation, retries, and human review gates.
Wiring this prompt into an application requires treating the generated command tree as a structured artifact that must pass validation before it reaches documentation. The prompt produces a JSON tree of parent-child relationships, aliases, and deprecation markers, but the harness is responsible for verifying that the tree matches the actual binary's behavior. Start by extracting ground truth from the CLI tool itself: run [TOOL_NAME] --help recursively for every discovered subcommand, capture the raw help text, and build a reference tree of expected commands, flags, and nesting depth. This reference tree becomes your validation source of truth, not the model's output.
The implementation loop follows a clear pattern: extract → prompt → validate → repair or escalate. First, run binary introspection to collect all subcommand paths and their help text. Feed this context into the prompt template along with the expected output schema. Parse the model's JSON response and run three validation passes: (1) completeness check — every command in the reference tree must appear in the generated tree with correct parent-child relationships; (2) orphan detection — no command in the generated tree should lack a valid parent path that traces back to the root; (3) nesting depth verification — the maximum depth in the generated tree must match the reference tree, flagging any missing leaf nodes or incorrectly nested intermediate commands. If validation fails, construct a repair prompt that includes the specific errors, the offending subtree, and the correct parent path from the reference tree. Retry up to two times before escalating to a human reviewer with a structured diff showing what the model got wrong.
Model choice matters here. Use a model with strong JSON schema adherence and long-context handling, since large CLI tools can produce help text that spans tens of thousands of tokens. For tools with more than 50 subcommands, consider chunking the help text by top-level command group and running the prompt once per group, then merging the trees with a reconciliation step that checks for cross-group references and duplicate leaf nodes. Log every prompt invocation, the raw model output, validation results, and any repair attempts. Store these logs alongside the generated tree so that documentation reviewers can trace how each node was produced. The final output should only be committed to documentation after passing all validation checks and, for high-risk or security-sensitive CLI tools, after a human has reviewed the complete tree diff against the previous version.
Expected Output Contract
Each field the Subcommand Tree Generation Prompt must return, with its expected type, whether it is required, and the validation rule to apply before accepting the output.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
command_tree | JSON Object | Top-level key must be present and parseable as a valid JSON object. Schema check: root is an object, not an array or scalar. | |
command_tree.root | String | Must match the CLI binary name exactly (e.g., 'kubectl', 'gh'). Regex check against [A-Za-z0-9_-]+. No empty string allowed. | |
command_tree.subcommands | Array of Objects | Must be an array. If the root command has no subcommands, use an empty array []. Null is not allowed. | |
command_tree.subcommands[].name | String | Must be a non-empty string matching the subcommand name from source. Regex: [A-Za-z0-9_-]+. Duplicate names at the same nesting level fail validation. | |
command_tree.subcommands[].aliases | Array of Strings | If present, each alias must be a non-empty string. If the command has no aliases, the field should be omitted or an empty array. Null is not allowed. | |
command_tree.subcommands[].deprecated | Boolean | Must be true or false. If the source marks the subcommand as deprecated, this must be true. Missing field fails validation. | |
command_tree.subcommands[].subcommands | Array of Objects | Recursive structure matching the parent subcommands schema. Leaf commands must use an empty array []. Null is not allowed. Nesting depth must not exceed 10 levels; deeper nesting triggers a manual review flag. | |
command_tree.subcommands[].description | String | If present, must be a single-sentence summary extracted from source doc comments or help text. Max 200 characters. If absent, validation passes but logs a completeness warning for manual review. |
Common Failure Modes
When generating subcommand trees from source code, these are the most common failure patterns that cause incomplete, incorrect, or misleading documentation. Each card identifies a specific risk and the guardrail that catches it before users encounter broken references.
Orphaned Commands Missing from Tree
Risk: The parser misses subcommands registered dynamically, through plugin systems, or behind conditional compilation flags. Users discover commands exist only when they fail to find documentation. Guardrail: Cross-reference the generated tree against a runtime --help --all dump or binary introspection output. Flag any command present in runtime output but absent from the generated tree as a critical gap before publication.
Incorrect Nesting Depth and Parent-Child Relationships
Risk: The prompt flattens nested subcommands or attaches a leaf command to the wrong parent, producing a tree where app cluster node list appears as a sibling of cluster rather than a child. Guardrail: Validate that every generated path matches an actual invocation path from the source. For each node, assert that its depth equals the number of segments in its fully qualified name and that its parent matches the immediate ancestor in the command hierarchy.
Deprecated Commands and Aliases Omitted or Mislabeled
Risk: The prompt treats deprecated commands as active or silently drops aliases, leaving users unaware of supported shortcuts or about-to-be-removed surfaces. Guardrail: Require the output schema to include status (active/deprecated/removed) and aliases fields for every node. Validate against deprecation annotations in source and ensure deprecated commands render with visible warnings, not as if they were fully supported.
Leaf Nodes Truncated in Deep Hierarchies
Risk: For CLIs with deep nesting (4+ levels), the model stops enumerating leaf commands after a certain depth or collapses subtrees into placeholder text like "...and 12 more commands." Guardrail: Set an explicit recursion depth requirement in the prompt constraints. Post-process the output to count leaf nodes per branch and compare against source. If any branch terminates without reaching actual leaves, flag for regeneration with that branch's source context isolated.
Source Parsing Misses Hidden or Internal Commands
Risk: Commands marked as hidden, internal, or debug-only in source are either included (cluttering user-facing docs) or excluded (breaking internal tooling that depends on them). Guardrail: Define an explicit inclusion policy in the prompt: document hidden commands in a separate "Internal Commands" section or mark them with a visibility: hidden field. Validate that every hidden command in source has a deliberate disposition in the output rather than being silently dropped or leaked.
Stale Output After Source Changes
Risk: The generated tree is correct at generation time but drifts as new subcommands are added, removed, or reorganized. Users trust outdated documentation and run commands that no longer exist. Guardrail: Embed a generation timestamp and source commit hash in the output metadata. Pair this prompt with a scheduled drift detection check that diffs the stored tree against a fresh runtime introspection and flags any additions, removals, or re-parenting events for review.
Evaluation Rubric
Use this rubric to test the quality of a generated subcommand tree before shipping it to documentation or integrating it into a CLI reference pipeline. Each criterion targets a specific failure mode common in tree generation from source code or binary introspection.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Command Coverage | Every public subcommand and leaf command found in source is present in the tree | Orphaned commands missing from the tree; commands present in source but absent in output | Diff the set of generated command paths against a ground-truth list extracted via AST walk or |
Parent-Child Nesting | Each command appears at the correct depth with the correct parent; nesting matches the source-defined command group hierarchy | Command placed under wrong parent; depth off by one or more levels; flat list instead of tree | Validate each path segment against the command registration chain in source; check that |
Alias Resolution | All defined aliases are listed under their canonical command with a clear alias marker; no alias is presented as a standalone command | Alias appears as a separate top-level or nested command; alias missing entirely; alias points to wrong canonical command | Cross-reference the alias map from source decorators or config against the generated tree's alias annotations |
Deprecation Markers | Every deprecated command, alias, or subcommand is flagged with a deprecation notice and, where available, a replacement suggestion | Deprecated command shown without warning; deprecation marker present on non-deprecated command; replacement suggestion missing or incorrect | Parse deprecation decorators, warnings, or |
Leaf Node Completeness | Every leaf command (no further subcommands) is present; no leaf is incorrectly shown as a parent group | Leaf command missing; leaf command incorrectly shown as having subcommands; empty group node with no children | Recursively walk the tree and flag any node marked as a group that has zero children; compare leaf set against source command registration |
Depth Accuracy | Maximum nesting depth in the tree matches the deepest command chain in the source; no artificially truncated or inflated depth | Tree truncated at a fixed depth, omitting deeper subcommands; extra nesting levels invented beyond source structure | Measure max depth of generated tree and compare to max depth from source command registration; flag any depth mismatch greater than zero |
Hidden Command Handling | Commands marked as hidden or internal in source are either excluded (if policy requires) or clearly labeled as hidden with a visibility flag | Hidden command exposed without label; hidden command missing when policy requires inclusion with label; visibility flag inconsistent | Parse visibility annotations from source; assert each hidden command in the tree has |
Cross-Reference Integrity | Every see-also or related-command reference points to a command that actually exists in the tree | Broken cross-reference pointing to a non-existent command path; circular reference; missing related-command link where source implies one | Resolve every cross-reference path against the generated command path set; flag any reference that does not resolve to a valid node |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single source file or --help dump. Accept a looser output schema—allow the tree as indented text or a simple nested JSON without strict depth validation. Skip deprecation marker extraction and alias resolution for the first pass.
Prompt modification
Replace [OUTPUT_SCHEMA] with: Return a nested JSON object where keys are command names and values are objects with "subcommands" arrays. Include a "description" field pulled from help text or doc comments.
Watch for
- Commands that share a name but live at different nesting levels (e.g.,
app configvscluster config) - Leaf commands missing their parent relationship
- Hidden or undocumented subcommands that appear in source but not in help output

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us