microsoft/hve-core

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
hve-core-v2.3.6

Branches

Tags

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

Clone

HTTPS

Download ZIP

docs/contributing/instructions.md

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