agentleFS
MicrosoftKnown publishermicrosoft/component-detection/.github/copilot-instructions.md

component-detection

Copilot instructions555 starsChanged 13 months agoMITView on GitHub

3. Register Detector in DI: Add to ServiceCollectionExtensions.AddComponentDetection() in Orchestrator:

The file

We split this copilot-instructions.md into the rules it gives an agent

12 rules. About 0 are common, 1 is distinctive, and 11 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 11

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    All new detectors start as IDefaultOffComponentDetector (must be explicitly enabled via DetectorArgs).

    line 24
  2. Very specific:

    All services register via ServiceCollectionExtensions.AddComponentDetection() in Orchestrator using standard .NET DI.

    line 28
  3. Very specific:

    Add enum to DetectorClass and ComponentType in Contracts

    line 34
  4. Very specific:

    Create YourEcosystemComponent : TypedComponent with required properties

    line 35
  5. Very specific:

    Use ValidateRequiredInput() for mandatory fields

    line 36
  6. Very specific:

    Add to ServiceCollectionExtensions.AddComponentDetection() in Orchestrator:

    line 66
  7. Distinctive:

    Use minimal file content needed to exercise specific scenarios.

    line 107
  8. Very specific:

    Add test resources to test/Microsoft.ComponentDetection.VerificationTests/resources/[ecosystem]/ with real-world examples that fully …

    line 110
  9. Very specific:

    Add --Debug flag to wait for debugger attachment on startup (prints PID).

    line 136
  10. Very specific:

    Use RegisterUsage() to add nodes and edges

    line 144
  11. Very specific:

    Don't: use setters on TypedComponent - pass required values to constructor.

    line 159
  12. Very specific:

    Always: test with DetectorTestUtility pattern, not manual ComponentRecorder setup.

    line 160

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

Component Detection - AI Coding Agent Instructions

Project Overview

Component Detection is a package scanning tool that detects open-source dependencies across 15+ ecosystems (npm, NuGet, Maven, Go, etc.) and outputs a dependency graph. It's designed for build-time scanning and can be used as a library or CLI tool.

Architecture

Core Concepts

  • Detectors: Ecosystem-specific parsers that discover and parse manifest files (e.g., package.json, requirements.txt)
  • Component Recorders: Immutable graph stores that track detected components and their relationships
  • Typed Components: Strongly-typed models for each ecosystem (e.g., NpmComponent, PipComponent) in src/Microsoft.ComponentDetection.Contracts/TypedComponent/

Project Structure

src/
├── Microsoft.ComponentDetection/           # CLI entry point (Program.cs)
├── Microsoft.ComponentDetection.Orchestrator/  # Command execution, DI setup, detector coordination
├── Microsoft.ComponentDetection.Contracts/     # Interfaces (IComponentDetector, IComponentRecorder) and TypedComponent models
├── Microsoft.ComponentDetection.Common/        # Shared utilities (file I/O, Docker, CLI invocation)
└── Microsoft.ComponentDetection.Detectors/     # Per-ecosystem detector implementations (npm/, pip/, nuget/, etc.)

Detector Lifecycle Stages

All new detectors start as IDefaultOffComponentDetector (must be explicitly enabled via DetectorArgs). Maintainers promote through:

  1. DefaultOff → 2. IExperimentalDetector (enabled but output not captured) → 3. Default (fully integrated)

Dependency Injection

All services register via ServiceCollectionExtensions.AddComponentDetection() in Orchestrator using standard .NET DI. Detectors use constructor injection for dependencies.

Creating a New Detector

Required Steps

  1. Define Component Type (if new ecosystem):
    • Add enum to DetectorClass and ComponentType in Contracts
    • Create YourEcosystemComponent : TypedComponent with required properties
    • Use ValidateRequiredInput() for mandatory fields
  2. Implement Detector:
    public class YourDetector : FileComponentDetector, IDefaultOffComponentDetector
    {
        public YourDetector(
            IComponentStreamEnumerableFactory componentStreamEnumerableFactory,
            IObservableDirectoryWalkerFactory walkerFactory,
            ILogger<YourDetector> logger)
        {
            this.ComponentStreamEnumerableFactory = componentStreamEnumerableFactory;
            this.Scanner = walkerFactory;
            this.Logger = logger;
        }
    
        public override string Id => "YourEcosystem";
        public override IEnumerable<string> Categories => [DetectorClass.YourCategory];
        public override IEnumerable<ComponentType> SupportedComponentTypes => [ComponentType.YourType];
        public override IEnumerable<string> SearchPatterns => ["manifest.lock"]; // Glob patterns
    
        protected override Task OnFileFoundAsync(ProcessRequest request, IDictionary<string, string> detectorArgs)
        {
            var recorder = request.SingleFileComponentRecorder;
            // Parse file, create components, call recorder.RegisterUsage()
        }
    }
  3. Register Detector in DI: Add to ServiceCollectionExtensions.AddComponentDetection() in Orchestrator:
    services.AddSingleton<IComponentDetector, YourDetector>();
  4. Register Components in Code:
    var component = new DetectedComponent(new YourComponent("name", "1.0.0"));
    recorder.RegisterUsage(
        component,
        isExplicitReferencedDependency: true,  // Direct dependency?
        parentComponentId: parentId,           // For graph edges (can be null)
        isDevelopmentDependency: false         // Build-only dependency?
    );

Detector Lifecycle Methods

  • OnPrepareDetection() - Optional: Pre-processing (e.g., filter files before parsing)
  • OnFileFoundAsync() - Required: Main parsing logic for matched files
  • OnDetectionFinished() - Optional: Cleanup (e.g., delete temp files)

Testing Pattern

[TestClass]
public class YourDetectorTests : BaseDetectorTest<YourDetector>
{
    [TestMethod]
    public async Task TestBasicDetection()
    {
        var fileContent = "name: pkg\nversion: 1.0.0";
        var (scanResult, componentRecorder) = await this.DetectorTestUtility
            .WithFile("manifest.lock", fileContent, ["manifest.lock"])
            .ExecuteDetectorAsync();

        scanResult.ResultCode.Should().Be(ProcessingResultCode.Success);
        var components = componentRecorder.GetDetectedComponents();
        components.Should().HaveCount(1);
    }
}

Use minimal file content needed to exercise specific scenarios. Avoid testing multiple features in one test.

End-to-End Verification

Add test resources to test/Microsoft.ComponentDetection.VerificationTests/resources/[ecosystem]/ with real-world examples that fully exercise your detector. These run in CI to prevent regressions.

Development Workflows

Build & Run

# Build
dotnet build

# Run scan with new detector (replace YourDetectorId)
dotnet run --project src/Microsoft.ComponentDetection/Microsoft.ComponentDetection.csproj scan \
  --Verbosity Verbose \
  --SourceDirectory /path/to/scan \
  --DetectorArgs YourDetectorId=EnableIfDefaultOff

Testing

# Run all tests
dotnet test

# Run specific test project
dotnet test test/Microsoft.ComponentDetection.Detectors.Tests/

Debug Mode

Add --Debug flag to wait for debugger attachment on startup (prints PID).

Key Patterns

File Discovery

Detectors specify SearchPatterns (glob patterns like *.csproj or package-lock.json). The orchestrator handles file traversal; detectors receive matched files via ProcessRequest.ComponentStream.

Graph Construction

  • Use RegisterUsage() to add nodes and edges
  • isExplicitReferencedDependency: true marks direct dependencies (like packages in package.json)
  • parentComponentId creates parent-child edges (omit for flat graphs)
  • Some ecosystems don't support graphs (e.g., Go modules) - register components without parents

Component Immutability

TypedComponent classes must be immutable (no setters). Validation happens in constructors via ValidateRequiredInput().

Directory Exclusion

Detectors can filter directories in OnPrepareDetection(). Example: npm detector ignores node_modules if a root lockfile exists.

Common Pitfalls

  • Don't implement IComponentDetector directly unless doing one-shot scanning (like Linux detector). Use FileComponentDetector for manifest-based detection.
  • Don't guess parent relationships - only create edges if the manifest explicitly defines them.
  • Don't use setters on TypedComponent - pass required values to constructor.
  • Always test with DetectorTestUtility pattern, not manual ComponentRecorder setup.
  • Remember new detectors must implement IDefaultOffComponentDetector until promoted by maintainers.

References

  • Detector implementation examples: src/Microsoft.ComponentDetection.Detectors/npm/, pip/, nuget/
  • Creating detectors: docs/creating-a-new-detector.md
  • CLI arguments: docs/detector-arguments.md
  • Test utilities: test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtility.cs

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.