Skip to content

Commit 64c1fe1

Browse files
authored
Merge pull request #1564 from ksylvan/0701-code-review-pattern
Add code_review pattern and updates in Pattern_Descriptions
2 parents 5e0aaa1 + 1cea32a commit 64c1fe1

File tree

6 files changed

+289
-69
lines changed

6 files changed

+289
-69
lines changed

Pattern_Descriptions/README_Pattern_Descriptions_and_Tags_MGT.md

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ This document explains the complete workflow for managing pattern descriptions a
55
## System Overview
66

77
The pattern system follows this hierarchy:
8+
89
1. `~/.config/fabric/patterns/` directory: The source of truth for available patterns
910
2. `pattern_extracts.json`: Contains first 500 words of each pattern for reference
1011
3. `pattern_descriptions.json`: Stores pattern metadata (descriptions and tags)
@@ -13,26 +14,30 @@ The pattern system follows this hierarchy:
1314
## Pattern Processing Workflow
1415

1516
### 1. Adding New Patterns
17+
1618
- Add patterns to `~/.config/fabric/patterns/`
1719
- Run extract_patterns.py to process new additions:
20+
1821
```bash
1922
python extract_patterns.py
2023

2124
The Python Script automatically:
25+
2226
- Creates pattern extracts for reference
2327
- Adds placeholder entries in descriptions file
2428
- Syncs to web interface
2529

2630
### 2. Pattern Extract Creation
31+
2732
The script extracts first 500 words from each pattern's system.md file to:
2833
2934
- Provide context for writing descriptions
3035
- Maintain reference material
3136
- Aid in pattern categorization
3237
3338
### 3. Description and Tag Management
34-
Pattern descriptions and tags are managed in pattern_descriptions.json:
3539
40+
Pattern descriptions and tags are managed in pattern_descriptions.json:
3641
3742
{
3843
"patterns": [
@@ -44,20 +49,21 @@ Pattern descriptions and tags are managed in pattern_descriptions.json:
4449
]
4550
}
4651
47-
4852
## Completing Pattern Metadata
4953
5054
### Writing Descriptions
55+
5156
1. Check pattern_descriptions.json for "[Description pending]" entries
5257
2. Reference pattern_extracts.json for context
5358
54-
3. How to update Pattern short descriptions (one sentence).
59+
3. How to update Pattern short descriptions (one sentence).
5560
56-
You can update your descriptions in pattern_descriptions.json manually or using LLM assistance (preferred approach).
61+
You can update your descriptions in pattern_descriptions.json manually or using LLM assistance (preferred approach).
5762
58-
Tell AI to look for "Description pending" entries in this file and write a short description based on the extract info in the pattern_extracts.json file. You can also ask your LLM to add tags for those newly added patterns, using other patterns tag assignments as example.
63+
Tell AI to look for "Description pending" entries in this file and write a short description based on the extract info in the pattern_extracts.json file. You can also ask your LLM to add tags for those newly added patterns, using other patterns tag assignments as example.
5964
6065
### Managing Tags
66+
6167
1. Add appropriate tags to new patterns
6268
2. Update existing tags as needed
6369
3. Tags are stored as arrays: ["TAG1", "TAG2"]
@@ -67,6 +73,7 @@ Tell AI to look for "Description pending" entries in this file and write a short
6773
## File Synchronization
6874
6975
The script maintains synchronization between:
76+
7077
- Local pattern_descriptions.json
7178
- Web interface copy in static/data/
7279
- No manual file copying needed
@@ -91,6 +98,7 @@ The script maintains synchronization between:
9198
## Troubleshooting
9299
93100
If patterns are not showing in the web interface:
101+
94102
1. Verify pattern_descriptions.json format
95103
2. Check web static copy exists
96104
3. Ensure proper file permissions
@@ -108,17 +116,3 @@ fabric/
108116
└── static/
109117
└── data/
110118
└── pattern_descriptions.json # Web interface copy
111-
112-
113-
114-
115-
116-
117-
118-
119-
120-
121-
122-
123-
124-

Pattern_Descriptions/extract_patterns.py

100644100755
Lines changed: 61 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,81 +1,96 @@
1+
#!/usr/bin/env python3
2+
3+
"""Extracts pattern information from the ~/.config/fabric/patterns directory,
4+
creates JSON files for pattern extracts and descriptions, and updates web static files.
5+
"""
16
import os
27
import json
38
import shutil
49

10+
511
def load_existing_file(filepath):
612
"""Load existing JSON file or return default structure"""
713
if os.path.exists(filepath):
8-
with open(filepath, 'r', encoding='utf-8') as f:
9-
return json.load(f)
14+
try:
15+
with open(filepath, "r", encoding="utf-8") as f:
16+
return json.load(f)
17+
except json.JSONDecodeError:
18+
print(
19+
f"Warning: Malformed JSON in {filepath}. Starting with an empty list."
20+
)
21+
return {"patterns": []}
1022
return {"patterns": []}
1123

24+
1225
def get_pattern_extract(pattern_path):
1326
"""Extract first 500 words from pattern's system.md file"""
1427
system_md_path = os.path.join(pattern_path, "system.md")
15-
with open(system_md_path, 'r', encoding='utf-8') as f:
16-
content = ' '.join(f.read().split()[:500])
28+
with open(system_md_path, "r", encoding="utf-8") as f:
29+
content = " ".join(f.read().split()[:500])
1730
return content
1831

32+
1933
def extract_pattern_info():
34+
"""Extract pattern information from the patterns directory"""
2035
script_dir = os.path.dirname(os.path.abspath(__file__))
2136
patterns_dir = os.path.expanduser("~/.config/fabric/patterns")
2237
print(f"\nScanning patterns directory: {patterns_dir}")
23-
38+
2439
extracts_path = os.path.join(script_dir, "pattern_extracts.json")
2540
descriptions_path = os.path.join(script_dir, "pattern_descriptions.json")
26-
41+
2742
existing_extracts = load_existing_file(extracts_path)
2843
existing_descriptions = load_existing_file(descriptions_path)
29-
44+
3045
existing_extract_names = {p["patternName"] for p in existing_extracts["patterns"]}
31-
existing_description_names = {p["patternName"] for p in existing_descriptions["patterns"]}
46+
existing_description_names = {
47+
p["patternName"] for p in existing_descriptions["patterns"]
48+
}
3249
print(f"Found existing patterns: {len(existing_extract_names)}")
33-
50+
3451
new_extracts = []
3552
new_descriptions = []
36-
37-
53+
3854
for dirname in sorted(os.listdir(patterns_dir)):
39-
# Only log new pattern processing
40-
if dirname not in existing_extract_names:
41-
print(f"Processing new pattern: {dirname}")
42-
43-
4455
pattern_path = os.path.join(patterns_dir, dirname)
4556
system_md_path = os.path.join(pattern_path, "system.md")
46-
print(f"Checking system.md at: {system_md_path}")
47-
57+
4858
if os.path.isdir(pattern_path) and os.path.exists(system_md_path):
49-
print(f"Valid pattern directory found: {dirname}")
59+
if dirname not in existing_extract_names:
60+
print(f"Processing new pattern: {dirname}")
61+
5062
try:
5163
if dirname not in existing_extract_names:
5264
print(f"Creating new extract for: {dirname}")
53-
pattern_extract = get_pattern_extract(pattern_path) # Pass directory path
54-
new_extracts.append({
55-
"patternName": dirname,
56-
"pattern_extract": pattern_extract
57-
})
58-
65+
pattern_extract = get_pattern_extract(
66+
pattern_path
67+
) # Pass directory path
68+
new_extracts.append(
69+
{"patternName": dirname, "pattern_extract": pattern_extract}
70+
)
71+
5972
if dirname not in existing_description_names:
6073
print(f"Creating new description for: {dirname}")
61-
new_descriptions.append({
62-
"patternName": dirname,
63-
"description": "[Description pending]",
64-
"tags": []
65-
})
66-
67-
except Exception as e:
74+
new_descriptions.append(
75+
{
76+
"patternName": dirname,
77+
"description": "[Description pending]",
78+
"tags": [],
79+
}
80+
)
81+
82+
except OSError as e:
6883
print(f"Error processing {dirname}: {str(e)}")
6984
else:
7085
print(f"Invalid pattern directory or missing system.md: {dirname}")
71-
72-
print(f"\nProcessing summary:")
86+
87+
print("\nProcessing summary:")
7388
print(f"New extracts created: {len(new_extracts)}")
7489
print(f"New descriptions added: {len(new_descriptions)}")
75-
90+
7691
existing_extracts["patterns"].extend(new_extracts)
7792
existing_descriptions["patterns"].extend(new_descriptions)
78-
93+
7994
return existing_extracts, existing_descriptions, len(new_descriptions)
8095

8196

@@ -87,28 +102,29 @@ def update_web_static(descriptions_path):
87102
static_path = os.path.join(static_dir, "pattern_descriptions.json")
88103
shutil.copy2(descriptions_path, static_path)
89104

105+
90106
def save_pattern_files():
91107
"""Save both pattern files and sync to web"""
92108
script_dir = os.path.dirname(os.path.abspath(__file__))
93109
extracts_path = os.path.join(script_dir, "pattern_extracts.json")
94110
descriptions_path = os.path.join(script_dir, "pattern_descriptions.json")
95-
111+
96112
pattern_extracts, pattern_descriptions, new_count = extract_pattern_info()
97-
113+
98114
# Save files
99-
with open(extracts_path, 'w', encoding='utf-8') as f:
115+
with open(extracts_path, "w", encoding="utf-8") as f:
100116
json.dump(pattern_extracts, f, indent=2, ensure_ascii=False)
101-
102-
with open(descriptions_path, 'w', encoding='utf-8') as f:
117+
118+
with open(descriptions_path, "w", encoding="utf-8") as f:
103119
json.dump(pattern_descriptions, f, indent=2, ensure_ascii=False)
104-
120+
105121
# Update web static
106122
update_web_static(descriptions_path)
107-
108-
print(f"\nProcessing complete:")
123+
124+
print("\nProcessing complete:")
109125
print(f"Total patterns: {len(pattern_descriptions['patterns'])}")
110126
print(f"New patterns added: {new_count}")
111127

128+
112129
if __name__ == "__main__":
113130
save_pattern_files()
114-

Pattern_Descriptions/pattern_descriptions.json

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1710,7 +1710,7 @@
17101710
},
17111711
{
17121712
"patternName": "analyze_bill_short",
1713-
"description": "Consended - Analyze a legislative bill and implications.",
1713+
"description": "Condensed - Analyze a legislative bill and implications.",
17141714
"tags": [
17151715
"ANALYSIS",
17161716
"BILL"
@@ -1815,6 +1815,35 @@
18151815
"WRITING",
18161816
"CREATIVITY"
18171817
]
1818+
},
1819+
{
1820+
"patternName": "extract_alpha",
1821+
"description": "Extracts the most novel and surprising ideas (\"alpha\") from content, inspired by information theory.",
1822+
"tags": [
1823+
"EXTRACT",
1824+
"ANALYSIS",
1825+
"CR THINKING",
1826+
"WISDOM"
1827+
]
1828+
},
1829+
{
1830+
"patternName": "extract_mcp_servers",
1831+
"description": "Analyzes content to identify and extract detailed information about Model Context Protocol (MCP) servers.",
1832+
"tags": [
1833+
"ANALYSIS",
1834+
"EXTRACT",
1835+
"DEVELOPMENT",
1836+
"AI"
1837+
]
1838+
},
1839+
{
1840+
"patternName": "review_code",
1841+
"description": "Performs a comprehensive code review, providing detailed feedback on correctness, security, and performance.",
1842+
"tags": [
1843+
"DEVELOPMENT",
1844+
"REVIEW",
1845+
"SECURITY"
1846+
]
18181847
}
18191848
]
1820-
}
1849+
}

Pattern_Descriptions/pattern_extracts.json

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -883,6 +883,18 @@
883883
{
884884
"patternName": "write_essay",
885885
"pattern_extract": "# Identity and Purpose You are an expert on writing clear, and illuminating essays on the topic of the input provided. # Output Instructions - Write the essay in the style of {{author_name}}, embodying all the qualities that they are known for. - Look up some example Essays by {{author_name}} (Use web search if the tool is available) - Write the essay exactly like {{author_name}} would write it as seen in the examples you find. - Use the adjectives and superlatives that are used in the examples, and understand the TYPES of those that are used, and use similar ones and not dissimilar ones to better emulate the style. - Use the same style, vocabulary level, and sentence structure as {{author_name}}. # Output Format - Output a full, publish-ready essay about the content provided using the instructions above. - Write in {{author_name}}'s natural and clear style, without embellishment. - Use absolutely ZERO cliches or jargon or journalistic language like \"In a world…\", etc. - Do not use cliches or jargon. - Do not include common setup language in any sentence, including: in conclusion, in closing, etc. - Do not output warnings or notes—just the output requested. # INPUT: INPUT:"
886+
},
887+
{
888+
"patternName": "extract_alpha",
889+
"pattern_extract": "# IDENTITY You're an expert at finding Alpha in content. # PHILOSOPHY I love the idea of Claude Shannon's information theory where basically the only real information is the stuff that's different and anything that's the same as kind of background noise. I love that idea for novelty and surprise inside of content when I think about a presentation or a talk or a podcast or an essay or anything I'm looking for the net new ideas or the new presentation of ideas for the new frameworks of how to use ideas or combine ideas so I'm looking for a way to capture that inside of content. # INSTRUCTIONS I want you to extract the 24 highest alpha ideas and thoughts and insights and recommendations in this piece of content, and I want you to output them in unformatted marked down in 8-word bullets written in the approachable style of Paul Graham. # INPUT"
890+
},
891+
{
892+
"patternName": "extract_mcp_servers",
893+
"pattern_extract": "# IDENTITY and PURPOSE You are an expert at analyzing content related to MCP (Model Context Protocol) servers. You excel at identifying and extracting mentions of MCP servers, their features, capabilities, integrations, and usage patterns. Take a step back and think step-by-step about how to achieve the best results for extracting MCP server information. # STEPS - Read and analyze the entire content carefully - Identify all mentions of MCP servers, including: - Specific MCP server names - Server capabilities and features - Integration details - Configuration examples - Use cases and applications - Installation or setup instructions - API endpoints or methods exposed - Any limitations or requirements # OUTPUT SECTIONS - Output a summary of all MCP servers mentioned with the following sections: ## SERVERS FOUND - List each MCP server found with a 15-word description - Include the server name and its primary purpose - Use bullet points for each server ## SERVER DETAILS For each server found, provide: - **Server Name**: The official name - **Purpose**: Main functionality in 25 words or less - **Key Features**: Up to 5 main features as bullet points - **Integration**: How it integrates with systems (if mentioned) - **Configuration**: Any configuration details mentioned - **Requirements**: Dependencies or requirements (if specified) ## USAGE EXAMPLES - Extract any code snippets or usage examples - Include configuration files or setup instructions - Present each example with context ## INSIGHTS - Provide 3-5 insights about the MCP servers mentioned - Focus on patterns, trends, or notable characteristics - Each insight should be a 20-word bullet point # OUTPUT INSTRUCTIONS - Output in clean, readable Markdown - Use proper heading hierarchy - Include code blocks with appropriate language tags - Do not include warnings or notes about the content - If no MCP servers are found, simply state \"No MCP servers mentioned in the content\" - Ensure all server names are accurately captured - Preserve technical details and specifications # INPUT: INPUT:"
894+
},
895+
{
896+
"patternName": "review_code",
897+
"pattern_extract": "# Code Review Task ## ROLE AND GOAL You are a Principal Software Engineer, renowned for your meticulous attention to detail and your ability to provide clear, constructive, and educational code reviews. Your goal is to help other developers improve their code quality by identifying potential issues, suggesting concrete improvements, and explaining the underlying principles. ## TASK You will be given a snippet of code or a diff. Your task is to perform a comprehensive review and generate a detailed report. ## STEPS 1. **Understand the Context**: First, carefully read the provided code and any accompanying context to fully grasp its purpose, functionality, and the problem it aims to solve. 2. **Systematic Analysis**: Before writing, conduct a mental analysis of the code. Evaluate it against the following key aspects. Do not write this analysis in the output; use it to form your review. * **Correctness**: Are there bugs, logic errors, or race conditions? * **Security**: Are there any potential vulnerabilities (e.g., injection attacks, improper handling of sensitive data)? * **Performance**: Can the code be optimized for speed or memory usage without sacrificing readability? * **Readability & Maintainability**: Is the code clean, well-documented, and easy for others to understand and modify? * **Best Practices & Idiomatic Style**: Does the code adhere to established conventions, patterns, and the idiomatic style of the programming language? * **Error Handling & Edge Cases**: Are errors handled gracefully? Have all relevant edge cases been considered? 3. **Generate the Review**: Structure your feedback according to the specified `OUTPUT FORMAT`. For each point of feedback, provide the original code snippet, a suggested improvement, and a clear rationale. ## OUTPUT FORMAT Your review must be in Markdown and follow this exact structure: --- ### Overall Assessment A brief, high-level summary of the code's quality. Mention its strengths and the primary areas for improvement. ### **Prioritized Recommendations** A numbered list of the most important changes, ordered from most to least critical. 1. (Most critical change) 2. (Second most critical change) 3. ... ### **Detailed Feedback** For each issue you identified, provide a detailed breakdown in the following format. --- **[ISSUE TITLE]** - (e.g., `Security`, `Readability`, `Performance`) **Original Code:** ```[language] // The specific lines of code with the issue ``` **Suggested Improvement:** ```[language] // The revised, improved code ``` **Rationale:** A clear and concise explanation of why the change is recommended. Reference best practices, design patterns, or potential risks. If you use advanced concepts, briefly explain them. --- (Repeat this section for each issue) ## EXAMPLE Here is an example of a review for a simple Python function: --- ### **Overall Assessment** The function correctly fetches user data, but it can be made more robust and efficient. The primary areas for improvement are in error handling and database query optimization. ### **Prioritized Recommendations** 1. Avoid making database queries inside a loop to prevent performance issues (N+1 query problem). 2. Add specific error handling for when a user is not found. ### **Detailed Feedback** --- **[PERFORMANCE]** - N+1 Database Query **Original Code:**"
886898
}
887899
]
888-
}
900+
}

0 commit comments

Comments
 (0)