aiswarm
Copilot instructions15 starsChanged 16 months agoMITView on GitHub
This codebase follows strict Test-Driven Development (TDD) practices and clean code principles. Focus on these essential patterns and workflows: Critical: Never write production code without a failing test first. Refactoring must never change behavior. Wrong GREEN Approach: Over-engineering with complex branching or premature abstractions Correct GREEN Approach: Add minimal logic to handle the new test case while preserving existing functionality TDD GREEN Phase Example:
The file
Show its rules and text
We split this copilot-instructions.md into the rules it gives an agent
42 rules. About 0 are common, 38 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈38
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 7
RED: Write ONE failing test that describes desired behavior - test should fail for the right reason
- Distinctive: line 8
GREEN: Write minimal production code to make the test pass - don't over-engineer
- Distinctive: line 9
COMMIT: Commit both test and production code together with clear message
- Distinctive: line 11
COMMIT: Commit refactoring changes separately with descriptive message
- Distinctive: line 12
One Test at a Time: Always write only ONE test method per RED-GREEN-REFACTOR cycle
- Distinctive: line 13
Focus on Edge Cases First: Start with edge cases and error conditions first (invalid input, missing data, etc.)
- Distinctive: line 14
ALWAYS: When prompted to work on any code changes, first repeat these TDD instructions to confirm understanding of the workflow before …
- Distinctive: line 16
Critical: Never write production code without a failing test first.
- Distinctive: line 21
Maintain All Tests: Keep all existing tests passing while making the new test pass
- Distinctive: line 22
Literal Minimum: Write the smallest possible change to turn the current test from red to green
- Distinctive: line 23
No Over-Engineering: Don't add extra functionality beyond what tests require
- Distinctive: line 25
Simple Implementation: Use the simplest approach that satisfies all current tests
- Distinctive: line 26
Example: If testing value validation, add value validation logic alongside existing key validation
- Distinctive: line 29
Correct GREEN Approach: Add minimal logic to handle the new test case while preserving existing functionality
- Distinctive: line 62
Write only ONE test method per RED-GREEN-REFACTOR cycle
- Distinctive: line 63
Start with edge cases and error conditions first (invalid input, missing data, etc.)
- Distinctive: line 66
Never write multiple test methods before implementing the production code
- Distinctive: line 67
GREEN Phase: Write minimal code for the current failing test while keeping all existing tests green
- Very specific: line 77
System Under Test: Use SystemUnderTest property pattern for clean test setup
- Distinctive: line 91
Database Test Setup: Use in-memory database with unique names for test isolation
- Very specific: line 98
Test Data Setup: Use using scopes for database operations in Arrange sections
- Very specific: line 107
Time-based Testing: Use FakeTimeService for predictable time-dependent behavior
- Distinctive: line 121
Mock Verification: Verify external service interactions using Moq
- Distinctive: line 126
Comprehensive State Verification: Test all relevant entity properties after operations
- Distinctive: line 134
Assertion Comments: Add clarifying comments to explain complex assertion logic
- Distinctive: line 153
Test Isolation Verification: Ensure tests don't affect each other's data
- Distinctive: line 176
Database Scope Pattern: Use scoped operations for data setup and teardown
- Distinctive: line 185
Direct Database Assertions: Verify state changes directly in database, not through service layer
- Distinctive: line 193
Entity Builder Pattern: Create complete test entities with all required properties
- Very specific: line 204
Time-Dependent Testing: Use FakeTimeService for predictable temporal behavior
- Distinctive: line 216
Multi-Entity Testing: Test complex scenarios with multiple related entities
- Distinctive: line 234
Multi-line Constructor Parameters: Always place each parameter on its own line for better readability
- Distinctive: line 241
Multi-line Method Signatures: Use vertical formatting for methods with multiple parameters
- Distinctive: line 266
Design Patterns: Look for SOLID principles, appropriate abstraction levels
- Distinctive: line 267
Test Coverage: Ensure behavior is tested, not just implementation details
- Distinctive: line 270
Duplication: Remove code duplication through extraction and composition
- Distinctive: line 277
Coverage: Use Coverlet integration for test coverage analysis
- Distinctive: line 289
Evidence-Based Changes: Only refactor based on actual duplication found in existing code
- Distinctive: line 292
Verify Usage: Every refactored pattern must be actually used, not just potentially useful
- Distinctive: line 293
No Speculation: Don't create builder patterns, configuration objects, or abstractions unless tests already demonstrate the need
- Distinctive: line 307
Critical Refactoring Rule: If you create something during refactoring that isn't immediately used by existing code, it's over-engineering …
- Distinctive: line 309
Essential Rule: All new code follows TDD cycle.
≈ “Common” is an estimate: at least 1 in 5 of the 1,644 Copilot instructions files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
TDD and Clean Code - Copilot Instructions
This codebase follows strict Test-Driven Development (TDD) practices and clean code principles. Focus on these essential patterns and workflows:
TDD Workflow (RED-GREEN-REFACTOR-COMMIT)
- RED: Write ONE failing test that describes desired behavior - test should fail for the right reason
- GREEN: Write minimal production code to make the test pass - don't over-engineer
- COMMIT: Commit both test and production code together with clear message
- REFACTOR: Improve code quality while keeping all tests green (if needed)
- COMMIT: Commit refactoring changes separately with descriptive message
- One Test at a Time: Always write only ONE test method per RED-GREEN-REFACTOR cycle
- Focus on Edge Cases First: Start with edge cases and error conditions first (invalid input, missing data, etc.)
- ALWAYS: When prompted to work on any code changes, first repeat these TDD instructions to confirm understanding of the workflow before proceeding.
Critical: Never write production code without a failing test first. Refactoring must never change behavior.
GREEN Phase "Minimal" Discipline:
"Minimal" means write ONLY the code needed to make the current failing test pass while keeping all existing tests green.
- Maintain All Tests: Keep all existing tests passing while making the new test pass
- Literal Minimum: Write the smallest possible change to turn the current test from red to green
- No Over-Engineering: Don't add extra functionality beyond what tests require
- Single Focus: Focus on making the current test pass with minimal additional code
- Simple Implementation: Use the simplest approach that satisfies all current tests
- Example: If testing value validation, add value validation logic alongside existing key validation
Wrong GREEN Approach: Over-engineering with complex branching or premature abstractions Correct GREEN Approach: Add minimal logic to handle the new test case while preserving existing functionality
TDD GREEN Phase Example:
// Current implementation (make key validation test pass)
public Task<Result> ValidateInput(string key, string value)
{
return Task.FromResult(Result.Failure("key required"));
}
// Step 2: New failing test: value validation
public Task<Result> ValidateInput(string key, string value)
{
if (string.IsNullOrEmpty(value)) // Only handles new test
return Task.FromResult(Result.Failure("value required"));
return Task.FromResult(Result.Failure("key required")); // existing test still passes
}
// Step 3: Create positive test that forces full implementation
public Task<Result> ValidateInput(string key, string value)
{
if (string.IsNullOrEmpty(key))
return Task.FromResult(Result.Failure("key required"));
if (string.IsNullOrEmpty(value)) // Add minimal logic for new test
return Task.FromResult(Result.Failure("value required"));
return Task.FromResult(Result.Success("Valid input")); // New test passes, existing tests still pass
}One Test at a Time Discipline:
- Write only ONE test method per RED-GREEN-REFACTOR cycle
- Start with edge cases and error conditions first (invalid input, missing data, etc.)
- Then write tests for main happy path logic
- Each test should verify one specific behavior or scenario
- Never write multiple test methods before implementing the production code
- GREEN Phase: Write minimal code for the current failing test while keeping all existing tests green
- REFACTOR Phase: Improve code structure and design while maintaining all test functionality
Test Architecture Patterns
- Testing Framework: xUnit with Shouldly assertions, Moq for mocking, Coverlet for coverage
- Test Structure: AAA pattern (Arrange-Act-Assert) with clear separation
- Naming:
WhenCondition_ShouldExpectedOutcomefor test methods - Test Doubles: Dedicated
TestDoubles/folder withTestLogger,FakeFileSystemService,PassThroughProcessLauncher,FakeTimeService - System Under Test: Use
SystemUnderTestproperty pattern for clean test setup
Test Class Organization Patterns
- Nested Test Classes: Group related tests using nested classes that inherit from the parent test class
public class ServiceTests : IDisposable, ISystemUnderTest<Service> { public class RegistrationTests : ServiceTests { } public class ValidationTests : ServiceTests { } public class DeletionTests : ServiceTests { } } - Database Test Setup: Use in-memory database with unique names for test isolation
var options = new DbContextOptionsBuilder<DbContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; - Test Data Setup: Use
usingscopes for database operations in Arrange sectionsusing (var scope = _scopeService.CreateWriteScope()) { scope.Entities.Add(new Entity { /* test data */ }); await scope.SaveChangesAsync(); } - Time-based Testing: Use
FakeTimeServicefor predictable time-dependent behavior_timeService.AdvanceTime(TimeSpan.FromMinutes(1)); entity.Timestamp.ShouldBe(_timeService.UtcNow); - Direct Database Verification: Assert against database state directly rather than service APIs
// Assert - Check database directly instead of using service API var entityInDb = await _dbContext.Entities.FindAsync(entityId); entityInDb.ShouldNotBeNull(); entityInDb.Property.ShouldBe(expectedValue); - Mock Verification: Verify external service interactions using Moq
_mockService.Verify(s => s.MethodAsync(expectedParameter), Times.Once); - Comprehensive State Verification: Test all relevant entity properties after operations
entity.Id.ShouldBe(expectedId); entity.Status.ShouldBe(ExpectedStatus.Value); entity.CreatedAt.ShouldBe(_timeService.UtcNow); entity.UpdatedAt.ShouldBe(_timeService.UtcNow); - Assertion Comments: Add clarifying comments to explain complex assertion logic
// Assert - Check database directly instead of using service API var entityInDb = await _dbContext.Entities.FindAsync(entityId); // Task 1 was InProgress for this agent - should be Failed updatedTask1!.Status.ShouldBe(TaskStatus.Failed); // Task 2 was only Pending for this agent - should remain Pending updatedTask2!.Status.ShouldBe(TaskStatus.Pending); - Edge Case Documentation: Include descriptive test method names that explain edge cases
WhenRegisteringAgentWithMinimalFields_ShouldSetRequiredPropertiesOnly() WhenAgentDoesNotExist_ShouldDoNothing() WhenKillingAgentWithInProgressTasks_ShouldFailDanglingTasks() - Test Isolation Verification: Ensure tests don't affect each other's data
// Verify database contains exactly 2 agents var totalAgents = await _dbContext.Agents.CountAsync(); totalAgents.ShouldBe(2);
Composition and Dependency Injection
- Constructor Injection: Services injected via constructor for testability
- Interface Segregation: Small, focused interfaces (
IContextService,IFileSystemService,IGeminiService) - Composition Root: DI container setup in
Program.csviaservices.AddAgentLauncherServices() - Test Isolation: Mock external dependencies, if the mocks are getting complicated, use a fake instead to simplify test setup.
Entity Framework and Database Testing Patterns
- In-Memory Database Isolation: Each test class gets unique database instance
var options = new DbContextOptionsBuilder<CoordinationDbContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; - Database Scope Pattern: Use scoped operations for data setup and teardown
using (var scope = _scopeService.CreateWriteScope()) { scope.Entities.Add(testEntity); await scope.SaveChangesAsync(); } - Direct Database Assertions: Verify state changes directly in database, not through service layer
// Assert - Check database directly instead of using service API var entityInDb = await _dbContext.Entities.FindAsync(entityId); entityInDb.ShouldNotBeNull(); entityInDb.Status.ShouldBe(ExpectedStatus.Active); - Entity Builder Pattern: Create complete test entities with all required properties
var testEntity = new Entity { Id = Guid.NewGuid().ToString(), RequiredProperty = "test-value", CreatedAt = _timeService.UtcNow, Status = EntityStatus.Active }; - Time-Dependent Testing: Use
FakeTimeServicefor predictable temporal behavior// Arrange with initial time entity.CreatedAt = _timeService.UtcNow.AddMinutes(-5); // Act with time advancement _timeService.AdvanceTime(TimeSpan.FromMinutes(1)); // Assert with current time entity.UpdatedAt.ShouldBe(_timeService.UtcNow); - Multi-Entity Testing: Test complex scenarios with multiple related entities
// Create related entities to test cascade behaviors var agent = new Agent { Id = agentId, Status = AgentStatus.Running }; var task1 = new WorkItem { Id = "task-1", AgentId = agentId, Status = TaskStatus.InProgress }; var task2 = new WorkItem { Id = "task-2", AgentId = agentId, Status = TaskStatus.Pending };
Clean Code Principles (Kent Beck & Kevlin Henney)
- Single Responsibility: Each class has one reason to change
- Intention-Revealing Names: Method and variable names explain purpose clearly
- Small Functions: Functions do one thing well, readable at single level of abstraction
- No Surprises: Code behaves as its name suggests, no hidden side effects
- Composition Over Inheritance: Favor object composition and interfaces over class inheritance
Code Formatting Standards
- Multi-line Constructor Parameters: Always place each parameter on its own line for better readability
public SomeClass( IDependency dependency, IService service) - Multi-line Method Signatures: Use vertical formatting for methods with multiple parameters
public async Task<Result> MethodAsync( string parameter1, string parameter2, string parameter3) - Multi-line Return Statements: Break long return statements with method chaining
return SomeResult .Failure($"Error message: {details}"); - Multi-line String Concatenation: Format complex error messages clearly
return Result .Failure($"First part: {value1}. " + $"Second part: {value2}");
Formatting Rule: Apply consistent multi-line formatting for constructors, methods, and complex return statements to improve readability and maintainability.
Code Review Focus Areas
- Design Patterns: Look for SOLID principles, appropriate abstraction levels
- Test Coverage: Ensure behavior is tested, not just implementation details
- Error Handling: Validate error paths with explicit tests
- Readability: Code should read like well-written prose
- Duplication: Remove code duplication through extraction and composition
Development Commands
- Build:
dotnet buildfor compilation check - Test:
dotnet testfor full test suite (required before any commit) - Test Watch:
dotnet test --watchfor continuous testing during development - Coverage: Use Coverlet integration for test coverage analysis
Service Layer Patterns
- Command Handler Pattern: Separate handlers for each CLI command (
LaunchAgentCommandHandler) - Service Abstractions: Mock external processes (
IProcessLauncher) and file system (IFileSystemService) - Logging: Structured logging via
IAppLoggerinterface for testability - Configuration: Environment-based configuration with clear interfaces
Refactoring Discipline
- Preserve Functionality Only: Refactoring must NEVER add new features or anticipate future needs
- Evidence-Based Changes: Only refactor based on actual duplication found in existing code
- YAGNI Principle: You Aren't Gonna Need It - don't create patterns that aren't immediately used
- Conservative Approach: Make minimal changes that eliminate existing duplication
- Verify Usage: Every refactored pattern must be actually used, not just potentially useful
- No Speculation: Don't create builder patterns, configuration objects, or abstractions unless tests already demonstrate the need
Refactoring Anti-Patterns to Avoid
// WRONG: Creating unused builder patterns
public class AgentBuilder { } // Never used in tests = dead code
// WRONG: Over-engineered configuration objects
public class McpToolConfiguration { } // Not needed = complexity
// RIGHT: Only extract what's actually duplicated
public abstract class Result<T> { } // Used by 10+ existing Result classesCritical Refactoring Rule: If you create something during refactoring that isn't immediately used by existing code, it's over-engineering and should be removed.
Essential Rule: All new code follows TDD cycle. Tests pass after every change. Refactoring preserves existing behavior while improving structure without adding unused abstractions.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

