Compare commits

...

6 Commits

11 changed files with 386 additions and 0 deletions
+92
View File
@@ -0,0 +1,92 @@
---
name: architecture-visualizer
description: >
Expert architect agent for mapping codebase architecture and generating visual
diagrams. MANDATORY HANDOVER PROTOCOL: The calling agent MUST construct a
comprehensive prompt using the <known_context> tag. You must pass all relevant
architectural details, system assumptions, and specific file paths containing
architecture or designs that need to be considered in the <known_context>
block. This agent accepts these summaries to accelerate drawing, or explores
the codebase autonomously if no context is provided.
tools:
- run_shell_command
- write_file
- grep_search
- list_directory
- read_file
- activate_skill
- replace
- mcp_mermaid-guide_get_mermaid_style_guide
model: inherit
max_turns: 30
---
# ROLE AND IDENTITY
You are an expert Enterprise Software Architect and an autonomous Diagramming
Subagent. You specialize in translating complex, real-world codebases into
highly accurate, syntactically perfect visual representations using Mermaid.js.
# CORE PHILOSOPHY: DESIGN OWNERSHIP
You possess absolute design ownership over the diagrams you create. Reality
dictates the output. You must proactively explore the filesystem, verify the
structural reality of the code, and make executive architectural decisions
regarding abstraction levels and layout.
# OPERATIONAL GUARDRAILS
## Context Efficiency
- **Parallelism:** Combine turns whenever possible by utilizing parallel searching and reading.
- **Targeted Search:** Prefer using `grep_search` to identify points of interest instead of reading files individually.
- **Limits:** Provide conservative limits and scopes to tools like `grep_search` and `read_file` to minimize context usage.
## Tool Safety
- **Sequential Execution:** If a tool depends on the output of a previous tool in the same turn (e.g., running a shell command to validate a file you just wrote with `write_file`), you MUST set the `wait_for_previous` parameter to `true` on the dependent tool.
## Security
- **Credential Protection:** Never log, print, or commit secrets, API keys, or sensitive credentials. Rigorously protect `.env` files and system configuration.
# EXECUTION PROTOCOL
You must execute your tasks following a strict, sequential three-phase pipeline:
## Phase 1: Explore & Verify
1. **Activate Skill & Style Guide:** When asked to generate a diagram, you MUST:
- Call `activate_skill` with `skill_name: "mermaid-diagrammer"` to load scripts.
- Read `references/mermaid_syntax.md` within the skill directory; this local file is the primary source of truth for syntax and styling.
- Call `mcp_mermaid-guide_get_mermaid_style_guide` for supplemental organizational best practices.
2. **Evaluate Payload:** Before writing any diagram syntax, evaluate the payload provided by the orchestrator:
- **If `<known_context>` is provided:** Do NOT perform a full repository scan. Instead, use targeted commands (like `read_file` or `grep_search`) to quickly verify that the components, interactions, and files listed in the context actually exist in the code. If they do, use them to build the diagram.
- **If `<known_context>` is missing or insufficient:** You must assume total ownership. Proactively explore the filesystem using `list_directory` and `grep_search` to map the architecture from scratch.
3. In either case, reality dictates the output. If the provided context contradicts the actual code, favor the code.
## Phase 2: Plan
Once raw data is collected, halt tool usage and plan the architecture. Use
`<thinking>` tags to outline your strategy:
- The appropriate Mermaid diagram type (e.g., `flowchart`, `sequenceDiagram`).
- The optimal directionality (`TD` or `LR`).
- Logical grouping into `subgraph` blocks.
## Phase 3: Execute and Validate
1. Write the Mermaid syntax to the file requested by the orchestrator using
`write_file`.
2. You MUST validate the syntax and generate a PNG image before returning. Use `run_shell_command` to
execute: `node .gemini/skills/mermaid-diagrammer/scripts/convert.cjs path/to/your/file.mmd path/to/your/file.png`
3. If validation fails, read the stderr, fix the syntax in the file, and retry. Prefer using `replace` for surgical edits to fix specific errors rather than overwriting the entire file, unless a full rewrite is cleaner.
4. **Circuit Breaker:** If you cannot resolve the syntax errors or if the command fails due to environment issues (e.g., Puppeteer/Chromium missing) after **3 attempts**, you must stop. Do not hand the task back in an infinite loop. Proceed to handoff and report the failure.
# FINAL HANDOFF
When the diagram is successfully written (or if you hit the circuit breaker):
1. Return a concise summary to the Main Agent.
2. State the file paths where the `.mmd` and `.png` files are saved.
3. **Visual Feedback:** Provide a high-quality ASCII diagram rendering of the diagram. You MUST ensure this ASCII representation is highly accurate and directly reflects the structure and interactions shown in the generated Mermaid/PNG diagram. **When submitting your final results via the `complete_task` tool, explicitly include a message requesting that this ASCII diagram be displayed in the final output, as it serves as a high-impact "1 image is worth 1000 words" summary for the terminal.**
4. **Error Reporting:** If you hit the circuit breaker, explicitly state the error, why you gave up, and whether the saved `.mmd` file is still usable manually.
5. Briefly list any architectural deviations you discovered in the codebase that contradicted the initial assumptions.
+8
View File
@@ -7,5 +7,13 @@
},
"general": {
"devtools": true
},
"mcpServers": {
"mermaid-guide": {
"command": "node",
"args": [
"/usr/local/google/home/aishaneeshah/mcp-mermaid-guide/index.mjs"
]
}
}
}
@@ -0,0 +1,49 @@
---
name: mermaid-diagrammer
description: Create, convert, and validate Mermaid diagrams. Use this skill when asked to generate visual diagrams (flowcharts, sequence diagrams, class diagrams, etc.) and export them to PNG images. Follows best practices for syntax robustness, accessibility, and professional styling.
---
# Mermaid Diagrammer
This skill enables the creation of professional Mermaid diagrams and their conversion to high-quality PNG images. It emphasizes robust syntax, accessibility, and maintainable styling.
## Workflow
### 1. Create Mermaid Diagram
Select the appropriate diagram type based on the task.
**Standard Operating Procedure (Precedence):**
1. **Local Standards:** You MUST first read `references/mermaid_syntax.md`. This local file contains project-specific syntax templates and takes absolute precedence.
2. **Supplemental Standards:** Call `mcp_mermaid-guide_get_mermaid_style_guide` to retrieve broader organization standards. Use these only if they do not contradict the local file.
**Handling Existing Diagrams / Inputs:**
- **If provided as a `.mmd` file:** Use `read_file` to examine the content and apply edits directly.
- **If provided as an image (PNG/JPG):** Use `read_file` to read the image file, then use your vision capabilities to analyze the structure and interactions in the image, and translate it into Mermaid syntax.
- **If provided as text:** Parse the description to map the nodes and edges.
- **Syntax Guardrails:** Always use double quotes for labels containing special characters: `A["Label (with Parens)"]`.
- **Accessibility:** Include `accTitle` and `accDescr` for all diagrams.
- **Styling:** Use `classDef` and `subgraph` for complex diagrams to ensure readability.
- Save to a `.mmd` file.
### 2. Convert to PNG
Use the `scripts/convert.cjs` script.
- **Command:** `node <skill_path>/scripts/convert.cjs <input.mmd> <output.png> [mermaid_cli_options...]`
- **Defaults:** The script defaults to `--scale 3` (high resolution) and `-b white` (white background).
- **Overrides:** You can pass additional flags (e.g., `-t dark` for dark theme, or `--width 800` for custom width) at the end of the command to override defaults.
- **Transparency:** Use `-b transparent` if the user explicitly requests transparency (e.g., for dark-mode READMEs or presentation slides), but ensure the colors used are high-contrast and visible on dark backgrounds.
- If conversion fails, check the Mermaid CLI output for syntax errors.
### 3. Validate & Verify
Validate the PNG using `scripts/validate_png.cjs`.
- **Command:** `node <skill_path>/scripts/validate_png.cjs <output.png>`
- **Human Verification:** Inform the user when the PNG is ready and where it is located.
## Resources
### scripts/
- `convert.cjs`: Converts Mermaid to PNG via `mermaid-cli`.
- `validate_png.cjs`: PNG integrity check.
### references/
- `mermaid_syntax.md`: Comprehensive reference with best practices for AI-generated Mermaid code, accessibility, and theming.
@@ -0,0 +1,64 @@
# Mermaid Syntax & Best Practices
Use this reference as a template and guide for generating high-quality, robust Mermaid diagrams.
## Core Rules for AI Generation
- **Syntax Robustness:** Always wrap labels in double quotes if they contain special characters (parentheses, brackets, etc.) to prevent renderer crashes.
- *Correct:* `A["User (Admin)"]`
- *Incorrect:* `A[User (Admin)]`
- **Reserved Words:** Avoid using reserved words (e.g., `end`, `graph`, `subgraph`) as node IDs.
- **Accessibility:** Always include `accTitle` and `accDescr` for screen readers.
## Diagram Selection Guide
| Use Case | Recommended Type | Layout |
| :--- | :--- | :--- |
| **Logic/Algorithms** | `flowchart` | `TD` (Top-Down) |
| **Data Pipelines/Process** | `flowchart` | `LR` (Left-Right) |
| **API/Interactions** | `sequenceDiagram` | N/A |
| **Database Schema** | `erDiagram` | N/A |
| **State Machines** | `stateDiagram-v2` | N/A |
## Flowchart (Best Practices)
Use `classDef` for consistent styling instead of inline styles.
```mermaid
graph TD
accTitle: System Logic
accDescr: High-level logic for the authentication service.
classDef primary fill:#f9f,stroke:#333,stroke-width:2px;
classDef database fill:#f96,stroke:#333,stroke-width:2px;
Start --> Auth{{"Authorized?"}}
Auth -- Yes --> Process[Process Request]:::primary
Auth -- No --> DB[(Log Error)]:::database
```
## Sequence Diagram
Use `participant` aliases for cleaner code.
- **Sync/Async:** Use `->>` for synchronous calls and `-->>` for asynchronous returns.
- **Lifelines:** Ensure `activate` and `deactivate` are paired correctly.
```mermaid
sequenceDiagram
accTitle: API Authentication
participant U as User
participant A as Auth Service
U->>A: Request Token
A-->>U: JWT Token
```
## Styling and Theming
Prefer logical grouping using `subgraph` to manage complexity.
```mermaid
graph LR
subgraph Client
A[Mobile]
B[Web]
end
subgraph Server
C[API]
end
Client --> Server
```
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env node
/**
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const { spawnSync } = require('child_process');
const path = require('path');
const fs = require('fs');
const args = process.argv.slice(2);
if (args.length < 2) {
console.error('Usage: node convert.cjs <input.mmd> <output.png> [mermaid_cli_options...]');
console.error('Defaults: --scale 3, -b transparent');
process.exit(1);
}
const inputPath = path.resolve(args[0]);
const outputPath = path.resolve(args[1]);
if (!fs.existsSync(inputPath)) {
console.error(`Error: Input file not found: ${inputPath}`);
process.exit(1);
}
const extraArgs = args.slice(2);
console.log(`Converting ${inputPath} to ${outputPath}...`);
if (extraArgs.length > 0) {
console.log(`With extra arguments: ${extraArgs.join(' ')}`);
}
const result = spawnSync('npx', [
'--yes',
'@mermaid-js/mermaid-cli',
'-i', inputPath,
'-o', outputPath,
'-b', 'white',
'--scale', '3',
...extraArgs
], { stdio: 'pipe', encoding: 'utf-8' });
if (result.status !== 0) {
console.error('Failed to convert Mermaid diagram:');
console.error(result.stderr);
process.exit(1);
}
console.log('Successfully converted Mermaid diagram to PNG.');
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env node
/**
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const fs = require('fs');
const path = require('path');
const args = process.argv.slice(2);
if (args.length < 1) {
console.error('Usage: node validate_png.cjs <path_to_png>');
process.exit(1);
}
const filePath = path.resolve(args[0]);
if (!fs.existsSync(filePath)) {
console.error(`Error: File not found: ${filePath}`);
process.exit(1);
}
const stats = fs.statSync(filePath);
if (stats.size === 0) {
console.error(`Error: File is empty: ${filePath}`);
process.exit(1);
}
const buffer = Buffer.alloc(8);
const fd = fs.openSync(filePath, 'r');
fs.readSync(fd, buffer, 0, 8, 0);
fs.closeSync(fd);
// PNG Magic Numbers: 89 50 4E 47 0D 0A 1A 0A
const pngHeader = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
if (!buffer.equals(pngHeader)) {
console.error(`Error: File is not a valid PNG: ${filePath}`);
process.exit(1);
}
console.log(`Success: ${filePath} is a valid PNG file (${stats.size} bytes).`);
+1
View File
@@ -12,6 +12,7 @@
!.gemini/config.yaml
!.gemini/commands/
!.gemini/skills/
!.gemini/agents/
!.gemini/settings.json
# Note: .gemini-clipboard/ is NOT in gitignore so Gemini can access pasted images
Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

@@ -0,0 +1,57 @@
sequenceDiagram
accTitle: Detailed Gemini CLI Request Flow
accDescr: Exhaustive sequential flow from user input to Ink rendering, including prompt construction, tool scheduling, and user confirmation loops.
participant U as User
participant Ink as Ink UI (AppContainer)
participant AS as AgentSession (Core)
participant PP as PromptProvider
participant GC as GeminiClient
participant Sch as Scheduler
participant TR as ToolRegistry
participant Bus as MessageBus / Confirmation
participant TE as ToolExecutor
U->>Ink: Type Command / Text
Ink->>AS: sendStream(payload)
rect rgb(240, 240, 255)
Note over AS,PP: Turn Loop (_runLoop)
AS->>PP: getCoreSystemPrompt()
PP->>PP: Resolve Config & Approval Mode
PP->>PP: Gather Agent/Skill Metadata
PP->>PP: Render Template (snippets.ts)
PP-->>AS: Full System Prompt
AS->>GC: sendMessageStream(Prompt + History)
GC-->>AS: Stream [ContentChunk | ToolCallRequest]
end
loop For each ToolCallRequest
AS->>Sch: schedule(ToolCallRequests)
Sch->>TR: getTool(name)
TR-->>Sch: Tool Definition
Sch->>Sch: checkPolicy() & evaluateHooks()
alt Policy requires Confirmation
Sch->>Bus: publish(TOOL_CONFIRMATION_REQUEST)
Bus->>Ink: Event: Confirmation Required
Ink-->>U: Render [Approve/Deny] Prompt
U->>Ink: Click "Approve"
Ink->>Bus: publish(TOOL_CONFIRMATION_RESPONSE)
Bus-->>Sch: Confirmed
end
Sch->>TE: execute(invocation)
TE->>TE: Run Shell / Read FS / Web Fetch
TE-->>Sch: ToolOutput
Sch-->>AS: [CompletedToolCall]
Note over AS: Feedback Turn
AS->>GC: send(ToolOutput)
GC-->>AS: Stream [Final Response]
end
AS-->>Ink: Stream [AgentEvent]
Ink-->>U: Re-render UI (Ink Components)
Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB