Skip to content

03 Layer Farol.Engine Workspaces and Loading

Yuri Augusto Francisco de Paiva edited this page Nov 17, 2026 · 1 revision

Layer: Farol.Engine — Workspaces & Loading

The Workspaces and Loading subsystem inside Farol.Engine is responsible for discovering, evaluating, loading, and tracking C# and VB.NET solutions. It provides the immutable snapshot foundation upon which all analysis, navigation, verification, and refactoring tools operate.


1. Subsystem Architecture

Farol.Engine (Workspaces & Loading)
├── Toolchain/
│   └── ToolchainProbe.cs           # Discovers .NET SDKs and Visual Studio installations via vswhere
├── Loading/
│   ├── MSBuildWorkspaceLoader.cs   # Roslyn MSBuildWorkspace orchestrator with dual BuildHosts
│   ├── AnalyzerCompatibility.cs    # Analyzers built for a newer compiler: SDK fallback or a load issue (AC-46)
│   ├── AnalyzerCopies.cs           # Copies analyzers and generators under the temp directory (AC-47)
│   └── CopiedAnalyzerLoader.cs     # Assembly loader for those copies, one load context per copy folder
└── Workspaces/
    ├── WorkspaceManager.cs         # Multi-session registry & default workspace resolution
    ├── WorkspaceDiscovery.cs       # Finds .sln/.slnx and project files (a .slnf only when named)
    ├── WorkspaceSession.cs         # Manages workspace lifecycle, background warmup, and snapshot refresh
    ├── WorkspaceSnapshot.cs        # Immutable snapshot representation (Solution, Catalog, Load Baseline)
    ├── WorkspaceTarget.cs          # Target identifier (solution vs standalone project)
    ├── WorkspaceWarmup.cs          # Background compilation & symbol index warming
    ├── WorkspaceWatcher.cs         # Multi-directory filesystem event monitor
    ├── ProjectCatalog.cs           # High-level index of projects, target frameworks, and configurations
    ├── ProjectFileInspector.cs     # Fast XML inspection of project formats and properties
    └── LoadReport.cs               # Diagnostic report of workspace load performance and issues

2. Toolchain Probing (ToolchainProbe)

To support both modern .NET and classic .NET Framework, Farol must identify the tools installed on the host machine.

Visual Studio Discovery via vswhere.exe

On Windows, ToolchainProbe executes vswhere.exe from %ProgramFiles(x86)%\Microsoft Visual Studio\Installer\:

  • Queries for installations with the Microsoft.Component.MSBuild workload.
  • Resolves the newest Visual Studio instance (Visual Studio 2022, 2026, or Build Tools).
  • Locates MSBuild.exe under MSBuild\Current\Bin\MSBuild.exe.
  • Locates vstest.console.exe under Common7\IDE\Extensions\TestPlatform\vstest.console.exe.
  • Sanitizes non-breaking spaces commonly inserted by Microsoft installers into product display names.

.NET SDK Discovery

Executes dotnet --version within the target workspace directory. Because dotnet respects local global.json files, this probe identifies the exact active SDK version governing the repository.


3. MSBuild Workspace Loading (MSBuildWorkspaceLoader)

Farol uses Roslyn's MSBuildWorkspace configured with custom global properties to load full solution graphs.

The Dual BuildHost Isolation Mechanism

When Roslyn loads a project, it delegates MSBuild evaluation to an external out-of-process BuildHost:

  1. Modern SDK-Style Projects: The .NET SDK BuildHost executes using the modern .NET runtime.
  2. Classic .NET Framework Projects: The BuildHost-net472 executes using full .NET Framework 4.7.2+, invoking Visual Studio's MSBuild engine. This enables classic ASP.NET WebForms, WCF, ASMX, WinForms, and legacy VB.NET projects to resolve their MSBuild targets, GAC references, and design-time outputs.

Automatic VSToolsPath Injection

Certain legacy projects (such as ASP.NET MVC 5 or WebApplication projects) use SDK-style project formats while importing legacy Visual Studio targets:

<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />

Because Roslyn routes SDK-style projects to the .NET SDK host by default, VSToolsPath would be undefined, causing evaluation to fail. Farol detects the installed Visual Studio via ToolchainProbe and automatically sets VSToolsPath in the workspace's global MSBuild properties:

var path = Path.Combine(visualStudio.InstallationPath, "MSBuild", "Microsoft", "VisualStudio", $"v{visualStudio.Version.Split('.')[0]}.0");

Unresolved Analyzer Stripping

In complex solutions, projects often reference internal source generators or analyzer projects that have not yet been compiled to disk. By default, Roslyn throws a fatal exception when attempting to search symbols in projects with missing analyzer binaries. MSBuildWorkspaceLoader.WithoutUnresolvedAnalyzers intercepts UnresolvedAnalyzerReference entries, removes them from the in-memory Solution, and emits an informative warning advising the developer to build the generator project once.

Analyzers Built for a Newer Compiler (AnalyzerCompatibility, AC-46)

Farol runs Roslyn 5.12, the compiler of .NET 11 (Directory.Packages.props). An analyzer or source generator built against a newer Microsoft.CodeAnalysis does not run inside Farol, and the code it generates is missing, which shows up as false errors (a preview SDK's Razor generator did this to Blazor solutions). After unresolved analyzers are dropped, AnalyzerCompatibility.WithRunnableAnalyzers reads the compiler version each analyzer file references and handles the ones that need a newer one:

  • SDK analyzers (fallback): when the analyzer lives in an installed .NET SDK, no global.json pins an SDK version, and another installed SDK has the same files built for a compiler Farol runs, Farol takes them from the newest such SDK. MSBuild still evaluates the projects with the SDK dotnet build uses. A load issue (warning) names the analyzers, both SDK versions and the projects, and says the generated code may differ.
  • Otherwise (load issue): a load issue (error) names the analyzer, the compiler version it needs and the projects missing its code, and says how to fix it: pin an earlier installed SDK in global.json (or install one), or use a Farol version that runs that compiler.

Analyzer Copies (AnalyzerCopies & CopiedAnalyzerLoader, AC-47)

Roslyn's default loader keeps the analyzer files it loads open until the process exits, so a solution that builds its own source generators could not rebuild them while Farol ran. Farol therefore loads copies:

  • Each folder of analyzers is copied, whole, to %TEMP%/farol/analyzers/<pid>-<guid>/<folder name>. The folder name is a hash of the source folder and the names, sizes and times of its files, so a rebuilt generator gets a new copy and an unchanged one is not copied again.
  • CopiedAnalyzerLoader replaces Roslyn's loader for these copies. It creates one AssemblyLoadContext per copy folder; the compiler, the framework and everything else Farol itself runs come from the default context first, so analyzers and Farol share the compiler's types. A dependency is looked up among the load's copies only, never in the original folders.
  • A copy folder whose analyzers need nothing from other folders is shared by every load in the process, so reloading after a rebuild loads only the folders that changed (a load context cannot be unloaded).
  • A folder that cannot be copied (for example a file a build is writing) loads from its own files, and a warning load issue says rebuilding it fails while Farol runs.
  • Copies are removed by a later Farol server once the process that made them has exited.

Eager Document Text Loading (ReadAllTextAsync)

Roslyn loads document source text lazily upon first access. If an agent modified a file on disk after the workspace was initialized but before Farol read that document, Roslyn would load the modified text as part of its original snapshot. This would contaminate the load baseline, rendering the edit invisible to dotnet_check. To prevent this, MSBuildWorkspaceLoader eagerly reads the source text of every document in parallel (ReadAllTextAsync) during initialization. A load takes seconds to about a minute, so a file edited while it runs can still be read already changed; the session records those files (see "Edits During a Load" below).

Design-Time Warning Reclassification

MSBuildWorkspace treats all messages from design-time builds as failures. When NuGet restore records package warnings (such as advisory warnings NU1901–NU1904), these were previously surfaced as load failures. Farol cross-references messages against project.assets.json and properly categorizes them as load warnings with their official NuGet codes.


4. The Workspace Session Lifecycle (WorkspaceSession)

A WorkspaceSession manages the lifecycle of a loaded solution or project:

[NotLoaded] ──► (StartLoading) ──► [Loading] ──► (Success) ──► [Ready]
                                        │                          │
                                        ▼ (Error)                  ▼
                                     [Failed]               (File Watcher / Edits)
                                        │                          │
                                        └── (ReloadAsync) ◄────────┘ (Project file edited)

1. Lazy Snapshot Refreshing (RefreshAsync)

When a tool requests a snapshot:

  • If no filesystem changes have occurred and no edits are pending, the cached immutable WorkspaceSnapshot is returned immediately.
  • If changes have occurred, RefreshAsync drains the pending file changes within a concurrency gate (_refreshGate), applies them, and returns an updated snapshot.

2. Eliminating Watcher Races (NotifyChanged & NotifyEdited)

Filesystem events (FileSystemWatcher) on Windows are asynchronous and subject to OS delivery latency. If an agent writes a file and immediately runs dotnet_check, the check might execute before the OS event fires. Farol resolves this via two mechanisms:

  • NotifyChanged(paths): Invoked when Farol's own tools (like dotnet_code_actions apply=true) write files. Queues the paths immediately into memory.
  • NotifyEdited(paths): Accepts file paths the caller reports (the Claude Code edit hook passes edited to dotnet_check), so the next snapshot reads them from disk without waiting for the watcher. A claimed file the workspace does not compile joins it only when the file was created after the load and is outside bin and obj, so a file the project leaves out (Compile Remove) stays out.
  • The file watcher follows the same rule: an edit to a file the workspace does not compile is ignored; a file joins only when it arrives (created, renamed or moved in), and a new file its writer still holds is read again on the next request.

3. Edits During a Load (AC-48)

A load of a large solution takes from tens of seconds up to about a minute, and an agent can edit meanwhile. Such a file may have been read already edited, so its load diagnostics are no baseline. WorkspaceSession keeps, in WorkspaceLoad.ChangedDuringLoad, the C# and VB files of the solution that:

  • Farol heard of through NotifyEdited before the load was done (the hook's edited, or a path), including before the load started; or
  • have a time on disk at most one second before the load's start, or later (file times can lag the clock). This covers clients that never say what they edit. Files under bin and obj, which the load's design-time builds write, do not count.

The session reads these files again after the load, since the file watcher starts only once the load is done. The baseline itself is not changed: dotnet_check treats every diagnostic located in such a file as new, and checks the file even when its text equals the one the load read (see the Verification page).

4. Project File Reload vs. Document Update

  • When a .cs or .vb source file changes, WorkspaceSession updates the document text inside the Roslyn Solution in memory without reloading the workspace.
  • When a project or build file changes (.csproj, .vbproj, .fsproj, .props, .targets, .sln, .slnx, .slnf, or global.json, packages.config, nuget.config, Directory.Build.rsp), WorkspaceSession reloads the workspace (ReloadAsync), re-evaluating the entire MSBuild graph; a call made meanwhile waits for it.

5. Background Compilation Warm-Up (WorkspaceWarmup)

Immediately after a solution loads, Farol initiates a background task (WorkspaceWarmup):

  • Eagerly compiles every project in the solution across all target frameworks.
  • Warms Roslyn's internal declaration tables, symbol caches, and syntax trees.
  • Builds the reference and inheritance indexes. While warmup runs, tool calls execute safely against the ready snapshot. dotnet_workspace says the warm-up is still running (searches are slower until it ends), then how long it took, so benchmarks and clients know when full speed is reached.

6. Status While Loading (AC-45)

While the load runs, dotnet_workspace with action='status' reports the number of project evaluation steps done and the time elapsed. It also says that the other dotnet_* tools wait for the load to finish, so the agent can call the one it needs now (action='load' waits for it there), and how long the last load of that workspace in the same server process took, when there was one (WorkspaceSession.LastLoadTook). An agent told only to call again had gone back to grep.


5. Workspace Discovery & Ambiguity Handling (WorkspaceManager)

WorkspaceManager manages active sessions and resolves default workspaces.

Multi-Solution Discovery Rules

  1. If the tool call passes workspace (a .sln, .slnx, .slnf, .csproj or .vbproj, or a folder that holds one), that workspace is used.
  2. If workspace is omitted, Farol uses --workspace when it was set; otherwise it discovers one in the root: a .slnx or .sln at the top of the root (a .slnx wins over a .sln of the same name), else a .csproj or .vbproj at the top, else solutions nested up to two folders deep (skipping bin, obj, .git, .vs, .idea, node_modules, packages, artifacts, TestResults). A .slnf is never discovered: pass it explicitly.
  3. Ambiguity Resolution (AC-4, AC-41): one candidate is used. With several or none, a call without workspace means the workspace already in use in this server process when there is exactly one; otherwise Farol returns workspace_ambiguous or workspace_not_found, listing the candidates (relative to the root) or the workspaces in use.
  4. Calls About a File (AC-44): when the root holds no single solution and the call names a file without workspace (the hook's edited, a path, or a path:line symbol; the tools that take one are dotnet_check, dotnet_code_actions, dotnet_outline, dotnet_symbol, dotnet_find_references, dotnet_hierarchy, dotnet_call_hierarchy, dotnet_config_inspect and dotnet_test with affectedBy), WorkspaceManager picks, in order: the workspace in use whose folder holds the file (the deepest one if several do); else the solution nearest above the file (WorkspaceDiscovery.NearestAbove: the first folder up from the file's, up to the root, that holds exactly one solution, where a .slnx wins over a .sln of the same name; the file need not exist yet); else the AC-41 rule above. A relative path is resolved as AC-42 does. Started in a folder of repositories, each edit is thus checked against its own solution.
  5. Protected Directory Traversal: folders that cannot be listed (such as System Volume Information or parts of a user profile) are passed over, so starting Farol at a drive root or a user profile works; the startup preload runs in the background and never stops the server.

Farol Wiki Documentation

Welcome to the official technical documentation for Farol, an open-source Model Context Protocol (MCP) server that equips AI coding agents (Claude Code, GitHub Copilot, Google Antigravity, Cursor, Codex) with compiler-accurate understanding of C# and VB.NET solutions.


Core Documentation

Clone this wiki locally