microsoft/hve-core

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
hve-core-v3.1.46

Branches

Tags

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

Clone

HTTPS

Download ZIP

docs/contributing/instructions.md

667lines · modecode

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