microsoft/hve-core

Public

mirrored fromhttps://github.com/microsoft/hve-coreAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
hve-core-v2.2.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

docs/contributing/instructions.md

621lines · modecode

1---
2title: 'Contributing Instructions to HVE Core'
3description: 'Requirements and standards for contributing GitHub Copilot instruction files to hve-core'
4author: Microsoft
5ms.date: 2025-11-26
6ms.topic: how-to
7---
8
9This guide defines the requirements, standards, and best practices for contributing GitHub Copilot instruction files (`.instructions.md`) to the hve-core library.
10
11**⚙️ Common Standards**: See [AI Artifacts Common Standards](ai-artifacts-common.md) for shared requirements (XML blocks, markdown quality, RFC 2119, validation, testing).
12
13## What is an Instructions File?
14
15An **instructions file** is a technology-specific or pattern-specific guidance document that defines coding standards, conventions, and best practices for GitHub Copilot to follow when working with particular file types, languages, or frameworks.
16
17## Use Cases for Instructions Files
18
19Create an instructions file when you need to:
20
21* Define language-specific coding standards (e.g., Python, C#, Bash)
22* Establish framework-specific conventions (e.g., Terraform, Bicep)
23* Document file type requirements (e.g., Markdown, YAML)
24* Specify workflow patterns (e.g., commit messages, PR creation)
25* Codify project-specific style guidelines
26* Auto-apply rules based on file patterns (`applyTo` glob matching)
27
28## File Structure Requirements
29
30### Location
31
32All instruction files **MUST** be placed in:
33
34```text
35.github/instructions/
36├── language-name.instructions.md # Language-specific
37├── framework-name.instructions.md # Framework-specific
38├── workflow-name.instructions.md # Workflow-specific
39└── subfolder/
40 └── specialized.instructions.md # Organized by domain
41```
42
43**Examples**:
44
45* `.github/instructions/python-script.instructions.md`
46* `.github/instructions/markdown.instructions.md`
47* `.github/instructions/csharp/csharp.instructions.md`
48* `.github/instructions/bash/bash.instructions.md`
49
50### Naming Convention
51
52* Use lowercase kebab-case: `python-script.instructions.md`
53* Be specific about target: `csharp-tests.instructions.md`
54* Include domain prefix when needed: `ado-wit-planning.instructions.md`
55* Avoid generic names: `code.instructions.md` ❌ → `python-script.instructions.md` ✅
56
57### File Format
58
59Instruction files **MUST**:
60
611. Use the `.instructions.md` extension
622. Start with valid YAML frontmatter between `---` delimiters
633. End with single newline character
64
65## Frontmatter Requirements
66
67### Required Fields
68
69**`description`** (string, MANDATORY)
70
71* **Purpose**: Concise explanation of instruction scope and target
72* **Format**: Single sentence, 10-200 characters
73* **Style**: Sentence case with proper punctuation
74* **Example**: `'Required instructions for Python script implementation with type hints and docstrings'`
75
76**`applyTo`** (string, MANDATORY for auto-applied instructions)
77
78* **Purpose**: Glob pattern(s) defining when these instructions activate
79* **Format**: Valid glob pattern or comma-separated patterns
80* **Scope**: Matches from repository root
81* **Examples**:
82 * Single pattern: `**/*.py`
83 * Multiple files: `**/*.py, **/*.ipynb`
84 * Directory scope: `**/src/**/*.sh`
85 * Specific paths: `**/.copilot-tracking/pr/new/**`
86
87**`maturity`** (string enum, MANDATORY)
88
89* **Purpose**: Controls which extension channel includes this instruction
90* **Valid values**:
91 * `stable` - Production-ready, included in Stable and Pre-release channels
92 * `preview` - Feature-complete, included in Pre-release channel only
93 * `experimental` - Early development, included in Pre-release channel only
94 * `deprecated` - Scheduled for removal, excluded from all channels
95* **Default**: New instructions should use `stable` unless targeting early adopters
96* **Example**: `stable`
97
98### Optional Fields
99
100**`version`** (string)
101
102* **Purpose**: Tracks instruction file revisions
103* **Format**: Semantic versioning (e.g., `1.0.0`)
104* **Pattern**: `^\d+\.\d+(\.\d+)?$` (major.minor or major.minor.patch)
105
106**`author`** (string)
107
108* **Purpose**: Attribution for instruction creator
109* **Example**: `microsoft/hve-core`, `your-team-name`
110
111**`lastUpdated`** (string)
112
113* **Purpose**: Timestamp of last modification
114* **Format**: ISO 8601 date (YYYY-MM-DD)
115
116### Frontmatter Example
117
118```yaml
119---
120description: 'Required instructions for Python script implementation with type hints, docstrings, and error handling'
121applyTo: '**/*.py, **/*.ipynb'
122maturity: 'stable'
123version: '1.0.0'
124author: 'microsoft/hve-core'
125lastUpdated: '2025-11-19'
126---
127```
128
129## Content Structure Standards
130
131### Required Sections
132
133#### 1. Title (H1)
134
135* Clear heading describing target technology/pattern
136* Should align with filename and scope
137
138```markdown
139# Python Script Implementation Instructions
140```
141
142#### 2. Overview/Scope
143
144* Explains what these instructions cover
145* Defines when they apply
146* Lists any prerequisites or assumptions
147
148```markdown
149## Scope
150
151These instructions apply to all Python scripts in the repository, covering:
152
153* Code structure and organization
154* Type hinting and documentation
155* Error handling patterns
156* Testing requirements
157```
158
159#### 3. Core Standards/Conventions
160
161* Defines mandatory coding patterns
162* Uses RFC 2119 keywords (MUST, SHOULD, MAY)
163* Organizes by category (structure, naming, patterns)
164* Provides rationale for key decisions
165
166```markdown
167## Code Structure
168
169Scripts MUST follow this organization:
170
1711. Shebang (if executable)
1722. Module docstring
1733. Imports (standard library → third-party → local)
1744. Constants
1755. Functions/classes
1766. Main execution block
177```
178
179#### 4. Naming Conventions
180
181* Specifies naming patterns for identifiers
182* Covers files, functions, classes, variables, constants
183* Provides examples of correct usage
184
185```markdown
186## Naming Conventions
187
188* **Files**: `snake_case.py` (e.g., `data_processor.py`)
189* **Functions**: `snake_case()` (e.g., `process_data()`)
190* **Classes**: `PascalCase` (e.g., `DataProcessor`)
191* **Constants**: `SCREAMING_SNAKE_CASE` (e.g., `MAX_RETRIES`)
192* **Private**: `_leading_underscore` (e.g., `_internal_helper()`)
193```
194
195#### 5. Code Examples
196
197* Demonstrates correct patterns with working code
198* Shows both positive (✅) and negative (❌) examples
199* Wraps in XML-style blocks for reusability
200* Includes inline comments explaining key points
201
202````markdown
203<!-- <example-python-function> -->
204```python
205def calculate_average(numbers: list[float]) -> float:
206 """
207 Calculate the arithmetic mean of a list of numbers.
208
209 Args:
210 numbers: List of numeric values to average
211
212 Returns:
213 Arithmetic mean of the input numbers
214
215 Raises:
216 ValueError: If the input list is empty
217 """
218 if not numbers:
219 raise ValueError("Cannot calculate average of empty list")
220
221 return sum(numbers) / len(numbers)
222```
223<!-- </example-python-function> -->
224````
225
226#### 6. Anti-Patterns
227
228* Documents what to avoid
229* Explains why patterns are problematic
230* Shows correct alternatives
231
232```markdown
233## Anti-Patterns
234
235❌ **Bare except clauses**:
236```python
237try:
238 risky_operation()
239except: # DON'T DO THIS
240 pass
241```
242
243✅ **Specific exception handling**:
244
245```python
246try:
247 risky_operation()
248except FileNotFoundError as e:
249 logger.error(f"File not found: {e}")
250 raise
251```
252
253#### 7. Validation/Testing
254
255* Specifies validation tools and commands
256* Defines testing requirements
257* Lists quality gates
258
259```markdown
260## Validation
261
262All Python code MUST pass:
263
264* **Linting**: `ruff check .`
265* **Type checking**: `mypy --strict .`
266* **Testing**: `pytest tests/ --cov=src`
267* **Coverage**: Minimum 80% line coverage
268```
269
270#### 8. Attribution Footer
271
272* **MANDATORY**: Include at end of file
273
274```markdown
275---
276
277Brought to you by microsoft/hve-core
278```
279
280### XML-Style Block Requirements
281
282See [AI Artifacts Common Standards - XML-Style Block Standards](ai-artifacts-common.md#xml-style-block-standards) for complete rules. Common tags for instructions:
283
284* `<!-- <example-{pattern-name}> -->` - Code examples
285* `<!-- <convention-{category}> -->` - Convention blocks
286* `<!-- <anti-pattern-{issue}> -->` - Things to avoid
287* `<!-- <validation-checklist> -->` - Validation steps
288* `<!-- <file-structure> -->` - File organization
289
290### Directive Language Standards
291
292Use RFC 2119 compliant keywords (MUST/SHOULD/MAY). See [AI Artifacts Common Standards - RFC 2119 Directive Language](ai-artifacts-common.md#rfc-2119-directive-language) for complete guidance.
293
294## Pattern Definition Standards
295
296Instructions should clearly define:
297
298### File Organization
299
300Structure for target files:
301
302````markdown
303<!-- <file-structure-python-script> -->
304```python
305#!/usr/bin/env python3
306"""
307Module-level docstring describing purpose and usage.
308"""
309
310# Standard library imports
311import os
312import sys
313from pathlib import Path
314
315# Third-party imports
316import requests
317import pandas as pd
318
319# Local imports
320from .utils import helper_function
321
322# Constants
323MAX_RETRIES = 3
324DEFAULT_TIMEOUT = 30
325
326# Functions and classes
327def main() -> int:
328 """Main entry point."""
329 return 0
330
331# Main execution
332if __name__ == "__main__":
333 sys.exit(main())
334```
335<!-- </file-structure-python-script> -->
336````
337
338### Code Patterns
339
340Approved implementation patterns:
341
342````markdown
343## Error Handling Pattern
344
345<!-- <pattern-error-handling> -->
346```python
347def process_file(file_path: Path) -> dict[str, Any]:
348 """
349 Process a configuration file with proper error handling.
350
351 Args:
352 file_path: Path to configuration file
353
354 Returns:
355 Parsed configuration dictionary
356
357 Raises:
358 FileNotFoundError: If configuration file doesn't exist
359 ValueError: If configuration is invalid
360 """
361 if not file_path.exists():
362 raise FileNotFoundError(f"Configuration not found: {file_path}")
363
364 try:
365 with file_path.open() as f:
366 config = json.load(f)
367 except json.JSONDecodeError as e:
368 raise ValueError(f"Invalid JSON in {file_path}: {e}")
369
370 # Validate required keys
371 required = {"version", "settings"}
372 if not required.issubset(config.keys()):
373 missing = required - config.keys()
374 raise ValueError(f"Missing required keys: {missing}")
375
376 return config
377```
378<!-- </pattern-error-handling> -->
379````
380
381### Style Conventions
382
383Formatting and style rules:
384
385```markdown
386## Style Conventions
387
388* **Indentation**: 4 spaces (no tabs)
389* **Line length**: 88 characters (Black formatter default)
390* **Quotes**: Double quotes for strings, single for dict keys
391* **Imports**: Organized by isort with Black-compatible settings
392* **Trailing commas**: Use in multi-line collections
393* **Type hints**: Use modern syntax (`list[str]` not `List[str]`)
394```
395
396## Validation and Tooling
397
398### Linting Configuration
399
400Specify tools and configurations:
401
402````markdown
403## Linting
404
405All Python code MUST pass Ruff checks:
406
407<!-- <config-ruff> -->
408```toml
409[tool.ruff]
410line-length = 88
411target-version = "py311"
412
413[tool.ruff.lint]
414select = ["E", "F", "I", "N", "W", "UP"]
415ignore = ["E501"] # Line too long (handled by formatter)
416```
417<!-- </config-ruff> -->
418
419Run: `ruff check . --fix`
420````
421
422### Testing Requirements
423
424Define test expectations:
425
426```markdown
427## Testing Requirements
428
429* **Coverage**: Minimum 80% line coverage
430* **Test location**: `tests/` directory mirroring `src/` structure
431* **Test naming**: `test_*.py` files, `test_*` functions
432* **Fixtures**: Use pytest fixtures for shared test data
433* **Mocking**: Mock external dependencies (file I/O, network calls)
434
435<!-- <example-pytest-test> -->
436```python
437import pytest
438from pathlib import Path
439from mymodule import process_file
440
441def test_process_file_valid(tmp_path: Path) -> None:
442 """Test processing valid configuration file."""
443 config_file = tmp_path / "config.json"
444 config_file.write_text('{"version": "1.0", "settings": {}}')
445
446 result = process_file(config_file)
447
448 assert result["version"] == "1.0"
449 assert "settings" in result
450
451def test_process_file_missing(tmp_path: Path) -> None:
452 """Test handling of missing configuration file."""
453 config_file = tmp_path / "missing.json"
454
455 with pytest.raises(FileNotFoundError):
456 process_file(config_file)
457```
458<!-- </example-pytest-test> -->
459
460## Glob Pattern Guidelines
461
462The `applyTo` field uses glob patterns to match files:
463
464### Pattern Syntax
465
466* `*` - Matches any characters except `/`
467* `**` - Matches any characters including `/` (recursive)
468* `?` - Matches single character
469* `[abc]` - Matches any character in brackets
470* `{a,b}` - Matches either `a` or `b`
471
472### Common Patterns
473
474```yaml
475# Single file extension
476applyTo: '**/*.py'
477
478# Multiple extensions
479applyTo: '**/*.py, **/*.ipynb'
480
481# Specific directory
482applyTo: '**/src/**/*.ts'
483
484# Specific path pattern
485applyTo: '**/.copilot-tracking/plans/*.md'
486
487# Exclude pattern (handled by negative patterns in schema-mapping.json)
488# Not directly in applyTo, but can be configured
489```
490
491### Testing Patterns
492
493Verify your glob pattern matches intended files:
494
495```bash
496# PowerShell
497Get-ChildItem -Path . -Recurse -Include *.py
498
499# Bash
500find . -name "*.py"
501```
502
503## Validation Checklist
504
505Before submitting your instructions file, verify:
506
507### File Format Structure
508
509* [ ] File uses `.instructions.md` extension
510* [ ] File starts with YAML frontmatter between `---` delimiters
511* [ ] File ends with single newline character (EOF)
512* [ ] No trailing whitespace on any lines
513* [ ] Uses UTF-8 encoding
514
515### Frontmatter
516
517* [ ] Valid YAML between `---` delimiters
518* [ ] `description` field present and descriptive (10-200 chars)
519* [ ] `applyTo` field with valid glob pattern (if auto-applied)
520* [ ] `version` follows semantic versioning format (if present)
521* [ ] No trailing whitespace in values
522
523### Content Structure
524
525* [ ] Clear H1 title describing target
526* [ ] Overview/scope section
527* [ ] Core standards with RFC 2119 keywords
528* [ ] Naming conventions documented
529* [ ] Code examples wrapped in XML-style blocks
530* [ ] Anti-patterns section with alternatives
531* [ ] Validation/testing requirements
532* [ ] Attribution footer present
533
534### Code Examples
535
536* [ ] All examples are syntactically correct
537* [ ] Examples include necessary imports/context
538* [ ] Both positive and negative examples provided
539* [ ] Examples wrapped in XML-style blocks with unique names
540* [ ] Code blocks have language tags
541* [ ] Inline comments explain key points
542
543### Common Standards
544
545* [ ] Markdown quality (see [Common Standards - Markdown Quality](ai-artifacts-common.md#markdown-quality-standards))
546* [ ] XML-style blocks properly formatted (see [Common Standards - XML-Style Blocks](ai-artifacts-common.md#xml-style-block-standards))
547* [ ] RFC 2119 keywords used consistently (see [Common Standards - RFC 2119](ai-artifacts-common.md#rfc-2119-directive-language))
548
549### Technical Validation
550
551* [ ] Glob pattern in `applyTo` is valid and tested
552* [ ] All file references point to existing files
553* [ ] External links are valid and accessible
554* [ ] Tool/command references are correct
555* [ ] No conflicts with existing instructions files
556
557### Integration
558
559* [ ] Aligns with `.github/copilot-instructions.md`
560* [ ] Follows repository conventions
561* [ ] Compatible with existing instructions
562* [ ] Does not duplicate existing instruction functionality
563* [ ] Glob pattern doesn't conflict with other instructions
564
565## Testing Your Instructions
566
567See [AI Artifacts Common Standards - Common Testing Practices](ai-artifacts-common.md#common-testing-practices) for testing guidelines. For instructions specifically:
568
5691. Verify `applyTo` glob pattern matches intended files
5702. Test all code examples execute correctly
5713. Have Copilot generate code following your instructions
5724. Validate specified linting/validation commands work
573
574## Common Issues and Fixes
575
576### Instructions-Specific Issues
577
578### Invalid Glob Pattern
579
580* **Problem**: Glob patterns that only match root directory or contain syntax errors
581* **Solution**: Use `**/` prefix for recursive matching (e.g., `**/*.py` for all Python files recursively)
582
583### Conflicting Patterns
584
585* **Problem**: Multiple instruction files with overlapping glob patterns causing ambiguity
586* **Solution**: Make patterns more specific (e.g., `**/tests/**/*.py` vs `**/*.py`) or ensure they target distinct file sets
587
588For additional common issues (XML blocks, markdown, directives), see [AI Artifacts Common Standards - Common Issues and Fixes](ai-artifacts-common.md#common-issues-and-fixes).
589
590## Automated Validation
591
592Run these commands before submission (see [Common Standards - Common Validation](ai-artifacts-common.md#common-validation-standards)):
593
594* `npm run lint:frontmatter`
595* `npm run lint:md`
596* `npm run spell-check`
597* `npm run lint:md-links`
598
599All checks **MUST** pass before merge.
600
601## Related Documentation
602
603* [AI Artifacts Common Standards](ai-artifacts-common.md) - Shared standards for all contributions
604* [Contributing Custom Agents](custom-agents.md) - AI agent configuration files
605* [Contributing Prompts](prompts.md) - Workflow-specific guidance
606* [Pull Request Template](../../.github/PULL_REQUEST_TEMPLATE.md) - Submission requirements
607
608## Getting Help
609
610See [AI Artifacts Common Standards - Getting Help](ai-artifacts-common.md#getting-help) for support resources. For instructions-specific assistance:
611
612* Review existing examples in `.github/instructions/`
613* Test glob patterns using file search commands
614* Use `prompt-builder.agent.md` agent for assistance
615
616---
617
618<!-- markdownlint-disable MD036 -->
619*🤖 Crafted with precision by ✨Copilot following brilliant human instruction,
620then carefully refined by our team of discerning human reviewers.*
621<!-- markdownlint-enable MD036 -->
622