agentleFS
mrlarson2007mrlarson2007/aiswarm/.github/copilot-instructions.md

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
  1. Distinctive:

    RED: Write ONE failing test that describes desired behavior - test should fail for the right reason

    line 7
  2. Distinctive:

    GREEN: Write minimal production code to make the test pass - don't over-engineer

    line 8
  3. Distinctive:

    COMMIT: Commit both test and production code together with clear message

    line 9
  4. Distinctive:

    COMMIT: Commit refactoring changes separately with descriptive message

    line 11
  5. Distinctive:

    One Test at a Time: Always write only ONE test method per RED-GREEN-REFACTOR cycle

    line 12
  6. Distinctive:

    Focus on Edge Cases First: Start with edge cases and error conditions first (invalid input, missing data, etc.)

    line 13
  7. Distinctive:

    ALWAYS: When prompted to work on any code changes, first repeat these TDD instructions to confirm understanding of the workflow before …

    line 14
  8. Distinctive:

    Critical: Never write production code without a failing test first.

    line 16
  9. Distinctive:

    Maintain All Tests: Keep all existing tests passing while making the new test pass

    line 21
  10. Distinctive:

    Literal Minimum: Write the smallest possible change to turn the current test from red to green

    line 22
  11. Distinctive:

    No Over-Engineering: Don't add extra functionality beyond what tests require

    line 23
  12. Distinctive:

    Simple Implementation: Use the simplest approach that satisfies all current tests

    line 25
  13. Distinctive:

    Example: If testing value validation, add value validation logic alongside existing key validation

    line 26
  14. Distinctive:

    Correct GREEN Approach: Add minimal logic to handle the new test case while preserving existing functionality

    line 29
  15. Distinctive:

    Write only ONE test method per RED-GREEN-REFACTOR cycle

    line 62
  16. Distinctive:

    Start with edge cases and error conditions first (invalid input, missing data, etc.)

    line 63
  17. Distinctive:

    Never write multiple test methods before implementing the production code

    line 66
  18. Distinctive:

    GREEN Phase: Write minimal code for the current failing test while keeping all existing tests green

    line 67
  19. Very specific:

    System Under Test: Use SystemUnderTest property pattern for clean test setup

    line 77
  20. Distinctive:

    Database Test Setup: Use in-memory database with unique names for test isolation

    line 91
  21. Very specific:

    Test Data Setup: Use using scopes for database operations in Arrange sections

    line 98
  22. Very specific:

    Time-based Testing: Use FakeTimeService for predictable time-dependent behavior

    line 107
  23. Distinctive:

    Mock Verification: Verify external service interactions using Moq

    line 121
  24. Distinctive:

    Comprehensive State Verification: Test all relevant entity properties after operations

    line 126
  25. Distinctive:

    Assertion Comments: Add clarifying comments to explain complex assertion logic

    line 134
  26. Distinctive:

    Test Isolation Verification: Ensure tests don't affect each other's data

    line 153
  27. Distinctive:

    Database Scope Pattern: Use scoped operations for data setup and teardown

    line 176
  28. Distinctive:

    Direct Database Assertions: Verify state changes directly in database, not through service layer

    line 185
  29. Distinctive:

    Entity Builder Pattern: Create complete test entities with all required properties

    line 193
  30. Very specific:

    Time-Dependent Testing: Use FakeTimeService for predictable temporal behavior

    line 204
  31. Distinctive:

    Multi-Entity Testing: Test complex scenarios with multiple related entities

    line 216
  32. Distinctive:

    Multi-line Constructor Parameters: Always place each parameter on its own line for better readability

    line 234
  33. Distinctive:

    Multi-line Method Signatures: Use vertical formatting for methods with multiple parameters

    line 241
  34. Distinctive:

    Design Patterns: Look for SOLID principles, appropriate abstraction levels

    line 266
  35. Distinctive:

    Test Coverage: Ensure behavior is tested, not just implementation details

    line 267
  36. Distinctive:

    Duplication: Remove code duplication through extraction and composition

    line 270
  37. Distinctive:

    Coverage: Use Coverlet integration for test coverage analysis

    line 277
  38. Distinctive:

    Evidence-Based Changes: Only refactor based on actual duplication found in existing code

    line 289
  39. Distinctive:

    Verify Usage: Every refactored pattern must be actually used, not just potentially useful

    line 292
  40. Distinctive:

    No Speculation: Don't create builder patterns, configuration objects, or abstractions unless tests already demonstrate the need

    line 293
  41. Distinctive:

    Critical Refactoring Rule: If you create something during refactoring that isn't immediately used by existing code, it's over-engineering …

    line 307
  42. Distinctive:

    Essential Rule: All new code follows TDD cycle.

    line 309

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
copilot-instructions.md

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)

  1. RED: Write ONE failing test that describes desired behavior - test should fail for the right reason
  2. GREEN: Write minimal production code to make the test pass - don't over-engineer
  3. COMMIT: Commit both test and production code together with clear message
  4. REFACTOR: Improve code quality while keeping all tests green (if needed)
  5. COMMIT: Commit refactoring changes separately with descriptive message
  6. One Test at a Time: Always write only ONE test method per RED-GREEN-REFACTOR cycle
  7. Focus on Edge Cases First: Start with edge cases and error conditions first (invalid input, missing data, etc.)
  8. 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_ShouldExpectedOutcome for test methods
  • Test Doubles: Dedicated TestDoubles/ folder with TestLogger, FakeFileSystemService, PassThroughProcessLauncher, FakeTimeService
  • System Under Test: Use SystemUnderTest property 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 using scopes for database operations in Arrange sections
    using (var scope = _scopeService.CreateWriteScope())
    {
        scope.Entities.Add(new Entity { /* test data */ });
        await scope.SaveChangesAsync();
    }
  • Time-based Testing: Use FakeTimeService for 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.cs via services.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 FakeTimeService for 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 build for compilation check
  • Test: dotnet test for full test suite (required before any commit)
  • Test Watch: dotnet test --watch for 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 IAppLogger interface 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 classes

Critical 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.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.