@moon791017/neo-skills 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/GEMINI.md +115 -0
  2. package/README.md +155 -0
  3. package/bin/install-claude-skills.js +72 -0
  4. package/commands/neo/cd-app-service.toml +20 -0
  5. package/commands/neo/cd-iis.toml +20 -0
  6. package/commands/neo/ci-dotnet.toml +21 -0
  7. package/commands/neo/clarification.toml +48 -0
  8. package/commands/neo/code-review.toml +33 -0
  9. package/commands/neo/dotnet-gen-interface.toml +31 -0
  10. package/commands/neo/explain.toml +44 -0
  11. package/commands/neo/git-commit.toml +49 -0
  12. package/dist/hooks/secret-guard.js +2 -0
  13. package/dist/server.js +220 -0
  14. package/gemini-extension.json +15 -0
  15. package/package.json +39 -0
  16. package/skills/azure-pipelines/SKILL.md +45 -0
  17. package/skills/azure-pipelines/templates/build/build-dotnet.yml +92 -0
  18. package/skills/azure-pipelines/templates/deploy/deploy-app-service.yml +71 -0
  19. package/skills/azure-pipelines/templates/deploy/deploy-iis.yml +189 -0
  20. package/skills/azure-pipelines/templates/util/clean-artifact.yml +40 -0
  21. package/skills/azure-pipelines/templates/util/extract-artifact.yml +57 -0
  22. package/skills/azure-pipelines/templates/util/iis/iis-backup.yml +92 -0
  23. package/skills/azure-pipelines/templates/util/iis/iis-deploy-files.yml +112 -0
  24. package/skills/azure-pipelines/templates/util/iis/iis-manage-website.yml +112 -0
  25. package/skills/azure-pipelines/templates/util/iis/iis-rollback.yml +98 -0
  26. package/skills/azure-pipelines/templates/util/iis/iis-start-website.yml +89 -0
  27. package/skills/azure-pipelines/templates/util/iis/iis-stop-website.yml +80 -0
  28. package/skills/azure-pipelines/templates/util/iis/iis-task.yml +157 -0
  29. package/skills/azure-pipelines/templates/util/set-aspnetcore-env.yml +77 -0
  30. package/skills/clarification/SKILL.md +22 -0
  31. package/skills/code-review/SKILL.md +72 -0
  32. package/skills/csharp/SKILL.md +87 -0
  33. package/skills/csharp/reference/anti-patterns.md +142 -0
  34. package/skills/csharp/reference/coding-style.md +86 -0
  35. package/skills/csharp/reference/patterns.md +142 -0
  36. package/skills/csharp-interface-generator/SKILL.md +40 -0
  37. package/skills/dotnet/SKILL.md +41 -0
  38. package/skills/dotnet-ef-core/SKILL.md +78 -0
  39. package/skills/dotnet-ef-core/reference/anti-patterns.md +51 -0
  40. package/skills/dotnet-ef-core/reference/coding-style.md +42 -0
  41. package/skills/dotnet-ef-core/reference/patterns.md +53 -0
  42. package/skills/dotnet-minimal-apis/SKILL.md +78 -0
  43. package/skills/dotnet-minimal-apis/reference/anti-patterns.md +59 -0
  44. package/skills/dotnet-minimal-apis/reference/coding-style.md +54 -0
  45. package/skills/dotnet-minimal-apis/reference/patterns.md +68 -0
  46. package/skills/dotnet-mvc/SKILL.md +78 -0
  47. package/skills/dotnet-mvc/reference/anti-patterns.md +49 -0
  48. package/skills/dotnet-mvc/reference/coding-style.md +43 -0
  49. package/skills/dotnet-mvc/reference/patterns.md +56 -0
  50. package/skills/dotnet-webapi/SKILL.md +78 -0
  51. package/skills/dotnet-webapi/reference/anti-patterns.md +48 -0
  52. package/skills/dotnet-webapi/reference/coding-style.md +47 -0
  53. package/skills/dotnet-webapi/reference/patterns.md +52 -0
  54. package/skills/explain/SKILL.md +27 -0
  55. package/skills/git-commit/SKILL.md +84 -0
  56. package/skills/python/SKILL.md +61 -0
  57. package/skills/python/reference/anti-patterns.md +177 -0
  58. package/skills/python/reference/coding-style.md +92 -0
  59. package/skills/python/reference/patterns.md +112 -0
  60. package/skills/python-manager/SKILL.md +61 -0
  61. package/skills/start-plan/SKILL.md +29 -0
  62. package/skills/swift/SKILL.md +78 -0
  63. package/skills/swift/reference/anti-patterns.md +75 -0
  64. package/skills/swift/reference/coding-style.md +56 -0
  65. package/skills/swift/reference/patterns.md +94 -0
  66. package/skills/swift-ui/SKILL.md +76 -0
  67. package/skills/swift-ui/reference/anti-patterns.md +52 -0
  68. package/skills/swift-ui/reference/coding-style.md +46 -0
  69. package/skills/swift-ui/reference/patterns.md +87 -0
@@ -0,0 +1,77 @@
1
+ # ==============================================================================
2
+ # Template Name: Set ASP.NET Core Environment (set-aspnetcore-env.yml)
3
+ # Description:
4
+ # Modify web.config before deployment to inject or update the ASPNETCORE_ENVIRONMENT environment variable.
5
+ # This ensures the application starts with the correct environment settings, avoiding a second restart.
6
+ # ==============================================================================
7
+
8
+ parameters:
9
+ - name: aspNetCoreEnvironment
10
+ type: string
11
+ - name: packagePath
12
+ type: string
13
+
14
+ # Execution Condition
15
+ - name: runCondition
16
+ type: string
17
+ default: 'succeeded()'
18
+
19
+ steps:
20
+ - powershell: |
21
+ $envValue = "${{ parameters.aspNetCoreEnvironment }}"
22
+ $packagePath = "${{ parameters.packagePath }}"
23
+
24
+ Write-Host "Target Package Path: $packagePath"
25
+
26
+ # Check if path exists and is a directory
27
+ if (Test-Path $packagePath -PathType Container) {
28
+ $webConfigPath = Get-ChildItem -Path $packagePath -Filter "web.config" -Recurse | Select-Object -First 1
29
+
30
+ if ($webConfigPath) {
31
+ Write-Host "Found web.config at: $($webConfigPath.FullName)"
32
+
33
+ # Read XML
34
+ $xml = [xml](Get-Content $webConfigPath.FullName)
35
+
36
+ # Use XPath to find aspNetCore node, ignoring structure differences (e.g. wrapped in <location>)
37
+ $aspNetCore = $xml.SelectSingleNode("//system.webServer/aspNetCore")
38
+
39
+ if ($aspNetCore) {
40
+ # Ensure environmentVariables node exists
41
+ if (-not $aspNetCore.SelectSingleNode("environmentVariables")) {
42
+ Write-Host "Creating environmentVariables node..."
43
+ $envVars = $xml.CreateElement("environmentVariables")
44
+ $aspNetCore.AppendChild($envVars) | Out-Null
45
+ }
46
+
47
+ # Get environmentVariables node (Use SelectSingleNode to ensure XmlElement)
48
+ $envVarsNode = $aspNetCore.SelectSingleNode("environmentVariables")
49
+
50
+ # Check if variable exists, remove old one if so
51
+ $existing = $envVarsNode.SelectSingleNode("environmentVariable[@name='ASPNETCORE_ENVIRONMENT']")
52
+ if ($existing) {
53
+ Write-Host "Removing existing ASPNETCORE_ENVIRONMENT setting..."
54
+ $envVarsNode.RemoveChild($existing) | Out-Null
55
+ }
56
+
57
+ # Create new environment variable node
58
+ Write-Host "Injecting ASPNETCORE_ENVIRONMENT='$envValue'..."
59
+ $newEnv = $xml.CreateElement("environmentVariable")
60
+ $newEnv.SetAttribute("name", "ASPNETCORE_ENVIRONMENT")
61
+ $newEnv.SetAttribute("value", $envValue)
62
+ $envVarsNode.AppendChild($newEnv) | Out-Null
63
+
64
+ # Save
65
+ $xml.Save($webConfigPath.FullName)
66
+ Write-Host "web.config updated successfully."
67
+ } else {
68
+ Write-Warning "Element system.webServer/aspNetCore not found in web.config (XPath: //system.webServer/aspNetCore). Skipping."
69
+ }
70
+ } else {
71
+ Write-Warning "web.config not found in artifact. Skipping environment variable injection."
72
+ }
73
+ } else {
74
+ Write-Warning "Artifact path is not a directory (possibly a ZIP file?). Cannot modify web.config directly."
75
+ }
76
+ displayName: 'Pre-modify web.config (Inject Environment Variable)'
77
+ condition: ${{ parameters.runCondition }}
@@ -0,0 +1,22 @@
1
+ ---
2
+ name: clarification
3
+ description: 系統化引導使用者釐清模糊需求,並將其轉換為結構化的規格文件。
4
+ ---
5
+
6
+ # Requirement Clarification Assistant
7
+
8
+ ## Perceive
9
+ 1. Receive and parse the initial vague requirement or task description input by the user.
10
+ 2. Identify the professional domain context of the task (e.g., software development, business workflow, content creation).
11
+ 3. Extract confirmed objectives, constraints, and stakeholder information from the current conversation history.
12
+
13
+ ## Reason
14
+ 1. Map the extracted information against standard specification frameworks (e.g., 5W1H model or SMART criteria).
15
+ 2. Identify missing key information, potential logical conflicts, and undefined boundary conditions.
16
+ 3. Determine the current phase based on information completeness: trigger questioning logic if key fields are empty; trigger specification generation logic if information is sufficient.
17
+ 4. Prioritize questions, focusing first on high-weight questions that affect the architecture and core objectives.
18
+
19
+ ## Act
20
+ 1. Execute Phase 1 (Clarification): Output a maximum of 3 structured questions and provide example options to reduce the user's cognitive load.
21
+ 2. Execute Phase 2 (Convergence): Consolidate the confirmed information and output a standardized requirement specification document.
22
+ 3. Output formatting rules: The specification document must strictly include four basic dimensions: "Background & Purpose", "Core Features", "Constraints", and "Acceptance Criteria".
@@ -0,0 +1,72 @@
1
+ ---
2
+ name: code-review-architect
3
+ description: 分析程式碼變更,從安全性、效能與風格等多個面向找出問題、潛在 Bug 與改善空間。
4
+ ---
5
+
6
+ # Code Review Specifications
7
+
8
+ ## Perceive (Analysis Phase)
9
+ 1. **Scope Identification**:
10
+ - Analyze the provided code diffs or file contents.
11
+ - Identify the languages and frameworks involved (e.g., TypeScript, C#, Python, React).
12
+ - Determine the nature of the change (e.g., Feature, Bugfix, Refactor, Config).
13
+
14
+ 2. **Context Gathering**:
15
+ - Look for surrounding code to understand the impact of changes.
16
+ - Check for relevant configuration files (e.g., `tsconfig.json`, `.eslintrc`, security policies) if available in the provided context.
17
+
18
+ ## Reason (Evaluation Phase)
19
+ Evaluate the code against the following dimensions:
20
+
21
+ 1. **Correctness & Logic**:
22
+ - Does the code do what it's supposed to do?
23
+ - Are there any edge cases missing?
24
+ - Are there potential concurrency issues (race conditions, deadlocks)?
25
+
26
+ 2. **Security (Critical)**:
27
+ - **Injection Flaws**: SQLi, XSS, Command Injection.
28
+ - **Data Exposure**: Hardcoded secrets, sensitive data logging.
29
+ - **Auth**: Improper authentication or authorization checks.
30
+ - **Dependencies**: Use of known insecure functions or patterns.
31
+
32
+ 3. **Performance**:
33
+ - **Efficiency**: Algorithmic complexity (Big O).
34
+ - **Resources**: Memory leaks, unclosed file handles/connections.
35
+ - **Database**: N+1 queries, missing indexes.
36
+
37
+ 4. **Maintainability & Readability**:
38
+ - **Clarity**: Variable/function naming, comment quality.
39
+ - **Complexity**: Cyclomatic complexity, function length.
40
+ - **Modularity**: DRY (Don't Repeat Yourself), SOLID principles.
41
+ - **Testing**: Is the code testable? Are tests included?
42
+
43
+ 5. **Style & Standards**:
44
+ - Adherence to language-specific conventions (e.g., PEP8 for Python, Airbnb for JS).
45
+ - Consistency with the existing project style.
46
+
47
+ ## Act (Reporting Phase)
48
+ Generate a structured Code Review Report in **Traditional Chinese (Taiwan)** with the following sections:
49
+
50
+ 1. **🔍 審查摘要 (Summary)**:
51
+ - Brief overview of the changes.
52
+ - Overall assessment (e.g., "Ready to merge", "Needs changes", "Major rework needed").
53
+
54
+ 2. **🔴 嚴重問題 (Critical Issues)**:
55
+ - **Must-fix** items (Security vulnerabilities, Logic bugs, Breaking changes).
56
+ - Clear explanation of *why* it is critical.
57
+
58
+ 3. **🟡 改進建議 (Suggestions)**:
59
+ - Performance improvements.
60
+ - Refactoring opportunities (Clean Code).
61
+ - Edge case handling.
62
+
63
+ 4. **🟢 優秀之處 (Praise)** (Optional):
64
+ - Highlight well-written code or clever solutions.
65
+
66
+ 5. **❓ 疑問 (Questions)** (Optional):
67
+ - Clarification needed on business logic or intent.
68
+
69
+ **Style Guidelines for the Report**:
70
+ - Be constructive and respectful.
71
+ - Use code snippets to illustrate the problem or suggested fix.
72
+ - Focus on the *code*, not the *coder*.
@@ -0,0 +1,87 @@
1
+ ---
2
+ name: csharp
3
+ version: "1.4.0"
4
+ category: "Core"
5
+ description: "跨版本 C# 專家技能 (10, 11, 12, 13, 14+)。支援從 .NET 6 (LTS) 到 .NET 10 (LTS) 的現代開發模式,涵蓋 File-scoped namespaces 到 Extension Types 的全方位演進。"
6
+ compatibility: "Supports C# 10 through 14. Adaptive to .NET 6.0, 7.0, 8.0, 9.0, and 10.0 environments."
7
+ ---
8
+
9
+ # Modern C# (10+) Expert Skill
10
+
11
+ ## Trigger On
12
+ - The user asks to write, debug, refactor, or review C# code.
13
+ - The project directory contains `*.cs`, `*.csproj`, or single-file C# scripts.
14
+ - The target framework is .NET 6.0 (LTS) and above.
15
+ - Code modernization is needed (e.g., converting legacy nested namespaces to File-scoped namespaces).
16
+
17
+ ## Workflow
18
+ 1. **Perceive (Version Awareness):**
19
+ - Check `.csproj` to identify `TargetFramework` and determine the syntax upper limit:
20
+ - `net6.0`: C# 10 (File-scoped namespaces, Global usings).
21
+ - `net7.0`: C# 11 (Raw string literals, Required members).
22
+ - `net8.0`: C# 12 (Primary Constructors, Collection Expressions).
23
+ - `net9.0`: C# 13 (`params` collections, `Lock` object).
24
+ - `net10.0`: C# 14 (Extension members, `field` keyword).
25
+ 2. **Reason (Planning Phase):**
26
+ - Evaluate the modernization level of the current code to determine the refactoring strategy.
27
+ - In lower version environments (like .NET 6), avoid using higher version syntax (like Primary Constructors), but prioritize using File-scoped namespaces.
28
+ - In higher version environments, actively adopt new features to reduce boilerplate code.
29
+ 3. **Act (Execution Phase):**
30
+ - Write high-quality code, prioritizing "syntactic sugar" to improve readability.
31
+ - Implement strong typing and immutable data structures (`record`, `record struct`).
32
+ - Utilize **Interpolated string handlers** and **Span<T>** to optimize performance-sensitive paths.
33
+ 4. **Validate (Standard Validation):**
34
+ - Validate the safety of NRT (Nullable Reference Types).
35
+ - Check if asynchronous operations correctly handle cancellation tokens (`CancellationToken`).
36
+ - Ensure naming conventions comply with official .NET recommendations.
37
+
38
+ ## Feature Roadmap (C# 10 - 14)
39
+
40
+ ### C# 10 & 11 (Foundation)
41
+ - **File-scoped Namespaces:** Reduce indentation levels.
42
+ - **Global Using Directives:** Centralize common namespaces management.
43
+ - **Raw String Literals:** `"""..."""` easily handle multi-line and special characters.
44
+ - **Required Members:** Ensure required properties during object initialization.
45
+ - **List Patterns:** `if (list is [1, 2, ..])` powerful collection matching.
46
+
47
+ ### C# 12 & 13 (Productivity)
48
+ - **Primary Constructors:** Simplify class-level dependency injection.
49
+ - **Collection Expressions:** Uniformly use `[1, 2, 3]` to initialize collections.
50
+ - **`params` Collections:** Method parameters support various collection types.
51
+ - **Implicit Span Conversion:** Handle memory-safe code more naturally.
52
+
53
+ ### C# 14+ (Cutting Edge)
54
+ - **Extension Members:** Extension properties, operators, and static members.
55
+ - **`field` Keyword:** Directly access backing fields in property logic.
56
+ - **Null-conditional Assignment:** `target?.Property = value;`.
57
+ - **Scripting:** Support `dotnet run file.cs` for direct execution.
58
+
59
+ ## Coding Standards
60
+ - **Clean Structure:** Prioritize using File-scoped namespaces.
61
+ - **Immutability:** Use `record` for Data Transfer Objects (DTO).
62
+ - **Performance:** Use `Span<T>` and `ReadOnlySpan<char>` in critical paths.
63
+ - **Async Safety:** Always pass `CancellationToken`, avoid `.Result` or `.Wait()`.
64
+
65
+ ## Deliver
66
+ - **Version-Optimized Code:** Provide the most appropriate modernized syntax code based on the target C# version.
67
+ - **Modernization Insights:** Provide specific refactoring suggestions for upgrading from older C# syntax to new features (e.g., from nested namespaces to File-scoped namespaces).
68
+ - **Syntax Explanations:** Clearly explain the design intent and syntax advantages behind the new C# features used.
69
+
70
+ ## Validate
71
+ - Ensure the provided code complies with the syntax specifications of the target C# version.
72
+ - Validate whether the code follows C# strong typing and Null safety (NRT) principles.
73
+ - Confirm the code has good readability and best practices at the pure C# language level (e.g., proper use of `Span<T>`, `record`, etc.).
74
+
75
+ ## Documentation
76
+ ### Official References
77
+ - [What's new in C# 14 (Extension Members, field keyword)](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-14)
78
+ - [What's new in C# 13 (params collections, Lock object)](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-13)
79
+ - [What's new in C# 12 (Primary Constructors, Collection Expressions)](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12)
80
+ - [What's new in C# 11 (Raw String Literals, Required Members)](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history#c-version-11)
81
+ - [What's new in C# 10 (File-scoped Namespaces, Global Usings)](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history#c-version-10)
82
+ - [Nullable Reference Types](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references)
83
+
84
+ ### Internal References
85
+ - [C# Coding Style and Naming Conventions Guide](reference/coding-style.md)
86
+ - [C# Anti-Patterns and Best Practices](reference/anti-patterns.md)
87
+ - [Modern C# Patterns Guide](reference/patterns.md)
@@ -0,0 +1,142 @@
1
+ # C# Anti-Patterns & Best Practices
2
+
3
+ This document lists common mistakes (Anti-Patterns) in C# development and their corresponding correct practices (Best Practices).
4
+
5
+ ## 1. Asynchronous Programming
6
+
7
+ ### 1.1 Avoid `Sync over Async`
8
+ **Problem**: Using `.Result` or `.Wait()` blocks the thread and can easily lead to deadlocks in ASP.NET or UI applications.
9
+
10
+ - **Bad**:
11
+ ```csharp
12
+ public IActionResult Get()
13
+ {
14
+ var data = _service.GetDataAsync().Result; // May cause deadlock
15
+ return Ok(data);
16
+ }
17
+ ```
18
+ - **Good**:
19
+ ```csharp
20
+ public async Task<IActionResult> Get(CancellationToken ct)
21
+ {
22
+ var data = await _service.GetDataAsync(ct);
23
+ return Ok(data);
24
+ }
25
+ ```
26
+
27
+ ### 1.2 Avoid `async void`
28
+ **Problem**: `async void` methods cannot be `await`ed, and exceptions thrown within them cannot be caught by the caller, leading to direct process crashes.
29
+
30
+ - **Bad**:
31
+ ```csharp
32
+ public async void ProcessDataAsync() { ... }
33
+ ```
34
+ - **Good**:
35
+ ```csharp
36
+ public async Task ProcessDataAsync() { ... } // Unless it's an Event Handler
37
+ ```
38
+
39
+ ---
40
+
41
+ ## 2. Memory & Performance
42
+
43
+ ### 2.1 Avoid string concatenation in loops
44
+ **Problem**: Strings are immutable, so every `+` creates a new string object, causing massive memory allocations.
45
+
46
+ - **Bad**:
47
+ ```csharp
48
+ string result = "";
49
+ foreach (var s in items) { result += s; }
50
+ ```
51
+ - **Good**:
52
+ ```csharp
53
+ var sb = new StringBuilder();
54
+ foreach (var s in items) { sb.Append(s); }
55
+ string result = sb.ToString();
56
+ ```
57
+
58
+ ### 2.2 Leverage `Span<T>` and `ReadOnlySpan<T>`
59
+ **Problem**: Frequent use of `Substring` creates substring copies.
60
+
61
+ - **Bad**:
62
+ ```csharp
63
+ string sub = largeString.Substring(0, 10);
64
+ ```
65
+ - **Good**:
66
+ ```csharp
67
+ ReadOnlySpan<char> span = largeString.AsSpan(0, 10); // No copy allocation needed
68
+ ```
69
+
70
+ ---
71
+
72
+ ## 3. Exception Handling
73
+
74
+ ### 3.1 Avoid swallowing exceptions
75
+ **Problem**: Catching exceptions without handling or logging them hides potential bugs, making debugging extremely difficult.
76
+
77
+ - **Bad**:
78
+ ```csharp
79
+ try { ... } catch (Exception) { } // Do nothing
80
+ ```
81
+ - **Good**:
82
+ ```csharp
83
+ try { ... }
84
+ catch (Exception ex)
85
+ {
86
+ _logger.LogError(ex, "An error occurred");
87
+ throw; // Or handle according to logic
88
+ }
89
+ ```
90
+
91
+ ### 3.2 Rethrow exceptions correctly
92
+ **Problem**: Using `throw ex;` clears the original stack trace.
93
+
94
+ - **Bad**:
95
+ ```csharp
96
+ catch (Exception ex) { throw ex; }
97
+ ```
98
+ - **Good**:
99
+ ```csharp
100
+ catch (Exception ex) { throw; } // Preserve original stack trace
101
+ ```
102
+
103
+ ---
104
+
105
+ ## 4. Modern C# Patterns
106
+
107
+ ### 4.1 Null checks (C# 9.0+)
108
+ - **Legacy**: `if (obj != null)`
109
+ - **Modern**: `if (obj is not null)` (Clearer semantics, unaffected by `!=` operator overloading)
110
+
111
+ ### 4.2 Collection initialization (C# 12+)
112
+ - **Legacy**: `var list = new List<int> { 1, 2, 3 };`
113
+ - **Modern**: `List<int> list = [1, 2, 3];` (Using Collection Expressions)
114
+
115
+ ### 4.3 Property backing fields (C# 14+)
116
+ - **Legacy**:
117
+ ```csharp
118
+ private string _name;
119
+ public string Name { get => _name; set => _name = value.Trim(); }
120
+ ```
121
+ - **Modern**:
122
+ ```csharp
123
+ public string Name { get; set => field = value.Trim(); } // Using the field keyword
124
+ ```
125
+
126
+ ---
127
+
128
+ ## 5. Resource Management
129
+
130
+ ### 5.1 Always use `using` declarations
131
+ **Problem**: Failing to properly release objects implementing `IDisposable` (like database connections, file streams) leads to resource leaks.
132
+
133
+ - **Bad**:
134
+ ```csharp
135
+ var stream = new FileStream(path, FileMode.Open);
136
+ // ... If an exception occurs in between, stream is never closed
137
+ stream.Dispose();
138
+ ```
139
+ - **Good**:
140
+ ```csharp
141
+ using var stream = new FileStream(path, FileMode.Open); // Automatically Disposed at end of scope
142
+ ```
@@ -0,0 +1,86 @@
1
+ # C# Coding Conventions
2
+
3
+ This guide is based on Microsoft's official [C# Coding Conventions](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions) and [C# Naming Conventions](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/coding-style/naming-conventions), aimed at improving development efficiency and maintaining project consistency.
4
+
5
+ ## 1. Naming Conventions
6
+
7
+ Good naming is the core of self-documenting code and reduces communication overhead.
8
+
9
+ ### 1.1 PascalCase
10
+ Used for **public members** and **type names**.
11
+ - **Class & Struct**: `public class OrderManager`
12
+ - **Interface**: Must start with a capital **`I`**, e.g., `public interface IRepository`
13
+ - **Property**: `public string FullName { get; set; }`
14
+ - **Method**: `public void ExecuteTask()`
15
+ - **Enum**: `public enum OrderStatus`
16
+
17
+ ### 1.2 camelCase
18
+ Used for **internal, local, or private members**.
19
+ - **Local Variable**: `var totalCount = 0;`
20
+ - **Parameter**: `public void UpdateUser(int userId)`
21
+ - **Private Field**: **Must have an underscore prefix `_`**. This instantly distinguishes it as class state rather than a local variable or parameter.
22
+ - Recommended: `private readonly ILogger _logger;`
23
+
24
+ ---
25
+
26
+ ## 2. File Organization
27
+
28
+ - **File name matching**: The file name must match the primary type name (e.g., `CustomerService.cs` should contain `class CustomerService`).
29
+ - **Single Responsibility**: In principle, **one file should define only one type** (Class, Interface, Enum) to facilitate version control and code search.
30
+ - **Namespace**:
31
+ - Prioritize **File-scoped Namespace** (C# 10+) to reduce indentation levels:
32
+ ```csharp
33
+ namespace MyProject.Services; // Recommended (C# 10+)
34
+ ```
35
+
36
+ ---
37
+
38
+ ## 3. Formatting
39
+
40
+ ### 3.1 Allman Style (Braces on new line)
41
+ The opening brace `{` must be on its own line, aligned with the class, method, or control statement. This is the standard C# style.
42
+ ```csharp
43
+ // Correct approach
44
+ public void Process()
45
+ {
46
+ if (isReady)
47
+ {
48
+ DoWork();
49
+ }
50
+ }
51
+ ```
52
+
53
+ ### 3.2 Indentation and Spacing
54
+ - **Indentation**: Fixed at **4 spaces**. The use of Tab characters is strictly prohibited to ensure consistent display across platforms.
55
+ - **Blank lines**: Leave one blank line between methods; use a single blank line to separate logical blocks within a method.
56
+
57
+ ---
58
+
59
+ ## 4. Asynchronous Programming
60
+
61
+ - **Async Suffix**: All asynchronous methods returning `Task` or `ValueTask` must end with the **`Async`** suffix.
62
+ - **CancellationToken**: Asynchronous methods should prioritize accepting a `CancellationToken` parameter and pass it to downstream asynchronous operations.
63
+ ```csharp
64
+ public async Task<User?> GetUserByIdAsync(int id, CancellationToken ct = default)
65
+ {
66
+ return await _context.Users.FindAsync([id], ct);
67
+ }
68
+ ```
69
+
70
+ ---
71
+
72
+ ## 5. Modern C# Best Practices
73
+
74
+ - **Type Inference (var)**: When the variable type is obvious from the right side of the assignment (like `new`, casting), use `var`.
75
+ - Recommended: `var users = new List<User>();`
76
+ - **Null Checks**: Use `is not null` for checking, as the semantics are closer to natural language and bypass operator overloading.
77
+ - Recommended: `if (input is not null) { ... }`
78
+ - **Object Initialization**: Prioritize using object initializers and collection expressions (C# 12+).
79
+ - Recommended: `List<int> numbers = [1, 2, 3];`
80
+
81
+ ---
82
+
83
+ ## 6. Commenting Conventions
84
+
85
+ - **XML Comments**: Public APIs must use `///` to provide XML comments so IDEs can show IntelliSense descriptions.
86
+ - **Logical Comments**: Comments should explain "Why" the processing is done this way, rather than repeating "What" the code does.
@@ -0,0 +1,142 @@
1
+ # Modern C# Patterns Guide
2
+
3
+ This document introduces recommended development patterns in C# 10 through 14+, aiming to simplify code and improve performance using modern syntax.
4
+
5
+ ## 1. Architecture and Declaration Patterns
6
+
7
+ ### 1.1 File-scoped Namespaces (C# 10+)
8
+ **Recommendation**: Reduce brace nesting to make the code structure flatter.
9
+ ```csharp
10
+ namespace MyProject.Services; // Recommended
11
+
12
+ public class CustomerService { ... }
13
+ ```
14
+
15
+ ### 1.2 Primary Constructors (C# 12+)
16
+ **Recommendation**: Simplify class-level dependency injection declarations.
17
+ ```csharp
18
+ // Declare parameters directly after the class name to initialize properties or fields
19
+ public class UserService(IUserRepository repository, ILogger logger)
20
+ {
21
+ public async Task<User?> GetUserAsync(int id) => await repository.FindByIdAsync(id);
22
+ }
23
+ ```
24
+
25
+ ---
26
+
27
+ ## 2. Data Structures and Initialization
28
+
29
+ ### 2.1 Use Record for Immutable Data
30
+ **Recommendation**: When defining DTOs or value objects, prioritize using `record` to gain built-in equality comparison and immutability.
31
+ ```csharp
32
+ public record UserDto(int Id, string Name, string Email);
33
+ ```
34
+
35
+ ### 2.2 Collection Expressions (C# 12+)
36
+ **Recommendation**: Use the consistent `[]` syntax to initialize various collection types.
37
+ ```csharp
38
+ int[] array = [1, 2, 3];
39
+ List<string> names = ["Alice", "Bob"];
40
+ Span<byte> buffer = [0x01, 0x02];
41
+ ```
42
+
43
+ ### 2.3 Raw String Literals (C# 11+)
44
+ **Recommendation**: Avoid tedious escape characters when dealing with JSON, SQL, or multi-line text.
45
+ ```csharp
46
+ string json = """
47
+ {
48
+ "name": "Gemini",
49
+ "version": "1.4"
50
+ }
51
+ """;
52
+ ```
53
+
54
+ ---
55
+
56
+ ## 3. Logic and Expressions
57
+
58
+ ### 3.1 Pattern Matching
59
+ **Recommendation**: Use `switch` expressions instead of traditional `switch` statements, and utilize property patterns.
60
+ ```csharp
61
+ public decimal GetDiscount(Order order) => order switch
62
+ {
63
+ { TotalAmount: > 1000 } => 0.1m,
64
+ { Items.Count: > 5 } => 0.05m,
65
+ _ => 0m
66
+ };
67
+ ```
68
+
69
+ ### 3.2 Expression-bodied Members
70
+ **Recommendation**: Use `=>` to shorten code for single-line methods or read-only properties.
71
+ ```csharp
72
+ public override string ToString() => $"{FirstName} {LastName}";
73
+ ```
74
+
75
+ ---
76
+
77
+ ## 4. C# 14+ Forward-looking Patterns
78
+
79
+ ### 4.1 Field-backed Properties
80
+ **Recommendation**: Use the `field` keyword in auto-properties that require simple logic.
81
+ ```csharp
82
+ public string Nickname
83
+ {
84
+ get;
85
+ set => field = value?.Trim() ?? "Guest";
86
+ }
87
+ ```
88
+
89
+ ### 4.2 Extension Members
90
+ **Recommendation**: Use `extension` blocks to add properties or static members to existing types, not just methods.
91
+ ```csharp
92
+ public extension UserExtension for User
93
+ {
94
+ public bool IsAdmin => this.Roles.Contains("Admin");
95
+ }
96
+ ```
97
+
98
+ ---
99
+
100
+ ## 5. Security and Performance
101
+
102
+ ### 5.1 Readonly Members
103
+ **Recommendation**: In `struct`s, if a method does not modify state, it should be marked as `readonly` to facilitate compiler optimizations.
104
+ ```csharp
105
+ public readonly struct Point(double x, double y)
106
+ {
107
+ public readonly double Distance => Math.Sqrt(x * x + y * y);
108
+ }
109
+ ```
110
+
111
+ ### 5.2 Default Lambda Parameters
112
+ **Recommendation**: Provide default values for Lambda expressions to increase flexibility.
113
+ ```csharp
114
+ var greeter = (string name = "Guest") => $"Hello, {name}!";
115
+ ```
116
+
117
+ ---
118
+
119
+ ## 6. Null Safety
120
+
121
+ ### 6.1 Nullable Reference Types (C# 8.0+)
122
+ **Recommendation**: Enable NRT at the project level, explicitly distinguish between "non-nullable" and "nullable" reference types, and shift null checks from runtime to compile time.
123
+ ```csharp
124
+ public class UserProfile
125
+ {
126
+ // Use required to ensure it's not Null after construction
127
+ public required string Username { get; set; }
128
+
129
+ // Use ? to mark this field as allowing Null
130
+ public string? Bio { get; set; }
131
+ }
132
+ ```
133
+
134
+ ### 6.2 Improved Null Check Semantics
135
+ **Recommendation**: Use `is not null` and the `??=` operator to make null handling logic cleaner and more readable.
136
+ ```csharp
137
+ // Use is not null
138
+ if (input is not null) { ... }
139
+
140
+ // Use null-coalescing assignment operator
141
+ _logger ??= NullLogger.Instance;
142
+ ```
@@ -0,0 +1,40 @@
1
+ ---
2
+ name: csharp-interface-generator
3
+ version: "1.0.0"
4
+ category: "Core"
5
+ description: "專注於C#介面生成與檔案結構管理。"
6
+ compatibility: "Supports C# 12/13 and .NET 10.0."
7
+ ---
8
+
9
+ # C# Interface Generator Skill Specification
10
+
11
+ ## Perceive
12
+ 1. **Code Structure Recognition**: Parse C# Class content, identify properties, methods, and access modifiers.
13
+ 2. **Constraint Check**:
14
+ - Identify members with the `virtual` keyword.
15
+ - Identify non-`public` members.
16
+ 3. **Environment Awareness**: When the user specifies a target file, read the file content to check for the existence of an Interface with the same name.
17
+
18
+ ## Reason
19
+ 1. **Interface Generation Logic**:
20
+ - **Naming Convention**: The Interface name must be the Class name prefixed with `I`.
21
+ - **Property Filtering**:
22
+ - **Keep only** simple properties.
23
+ - **Strictly prohibit** properties containing the `virtual` modifier.
24
+ - **Getter Only**: All properties in the interface MUST only have a `get;` accessor. No `set;` or `init;` is allowed.
25
+ - Include only `public` members.
26
+ - **Formatting**: Ensure the generated Interface follows standard C# indentation and brace styles.
27
+ 2. **Smart Overwrite Strategy**:
28
+ - If the target file does not exist: Plan to create a new file with necessary namespaces.
29
+ - If the target file exists but has no Interface with the same name: Plan to append the new Interface to the end of the file.
30
+ - If the target file exists and already contains an Interface with the same name:
31
+ - Use regular expressions or block matching to find the start and end positions of the Interface.
32
+ - Plan to replace only that specific block, preserving other classes, interfaces, or using declarations in the file.
33
+
34
+ ## Act
35
+ 1. **Code Generation**: Output a C# Interface that complies with the Reason logic.
36
+ 2. **User Confirmation**:
37
+ - After generation, pause and ask the user: "In which file should this Interface be stored? (Please provide a relative path)".
38
+ 3. **Execution Write**:
39
+ - Based on the user's response, perform `read_file` (if the file exists) -> logical replacement -> `write_file`.
40
+ - Inform the user of the result (created, appended, or overwritten).