Repository navigation
03 Layer Farol.Engine Workspaces and 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.
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
To support both modern .NET and classic .NET Framework, Farol must identify the tools installed on the host machine.
On Windows, ToolchainProbe executes vswhere.exe from %ProgramFiles(x86)%\Microsoft Visual Studio\Installer\:
- Queries for installations with the
Microsoft.Component.MSBuildworkload. - Resolves the newest Visual Studio instance (Visual Studio 2022, 2026, or Build Tools).
- Locates
MSBuild.exeunderMSBuild\Current\Bin\MSBuild.exe. - Locates
vstest.console.exeunderCommon7\IDE\Extensions\TestPlatform\vstest.console.exe. - Sanitizes non-breaking spaces commonly inserted by Microsoft installers into product display names.
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.
Farol uses Roslyn's MSBuildWorkspace configured with custom global properties to load full solution graphs.
When Roslyn loads a project, it delegates MSBuild evaluation to an external out-of-process BuildHost:
- Modern SDK-Style Projects: The .NET SDK BuildHost executes using the modern .NET runtime.
-
Classic .NET Framework Projects: The
BuildHost-net472executes 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.
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");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.
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.jsonpins 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 SDKdotnet builduses. 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.
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. -
CopiedAnalyzerLoaderreplaces Roslyn's loader for these copies. It creates oneAssemblyLoadContextper 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.
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).
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.
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)
When a tool requests a snapshot:
- If no filesystem changes have occurred and no edits are pending, the cached immutable
WorkspaceSnapshotis returned immediately. - If changes have occurred,
RefreshAsyncdrains the pending file changes within a concurrency gate (_refreshGate), applies them, and returns an updated snapshot.
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 (likedotnet_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 passeseditedtodotnet_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 outsidebinandobj, 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.
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
NotifyEditedbefore the load was done (the hook'sedited, or apath), 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
binandobj, 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).
- When a
.csor.vbsource file changes,WorkspaceSessionupdates the document text inside the RoslynSolutionin memory without reloading the workspace. - When a project or build file changes (
.csproj,.vbproj,.fsproj,.props,.targets,.sln,.slnx,.slnf, orglobal.json,packages.config,nuget.config,Directory.Build.rsp),WorkspaceSessionreloads the workspace (ReloadAsync), re-evaluating the entire MSBuild graph; a call made meanwhile waits for it.
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_workspacesays 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.
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.
WorkspaceManager manages active sessions and resolves default workspaces.
- If the tool call passes
workspace(a.sln,.slnx,.slnf,.csprojor.vbproj, or a folder that holds one), that workspace is used. - If
workspaceis omitted, Farol uses--workspacewhen it was set; otherwise it discovers one in the root: a.slnxor.slnat the top of the root (a.slnxwins over a.slnof the same name), else a.csprojor.vbprojat the top, else solutions nested up to two folders deep (skippingbin,obj,.git,.vs,.idea,node_modules,packages,artifacts,TestResults). A.slnfis never discovered: pass it explicitly. -
Ambiguity Resolution (AC-4, AC-41): one candidate is used. With several or none, a call without
workspacemeans the workspace already in use in this server process when there is exactly one; otherwise Farol returnsworkspace_ambiguousorworkspace_not_found, listing the candidates (relative to the root) or the workspaces in use. -
Calls About a File (AC-44): when the root holds no single solution and the call names a file without
workspace(the hook'sedited, apath, or apath:linesymbol; the tools that take one aredotnet_check,dotnet_code_actions,dotnet_outline,dotnet_symbol,dotnet_find_references,dotnet_hierarchy,dotnet_call_hierarchy,dotnet_config_inspectanddotnet_testwithaffectedBy),WorkspaceManagerpicks, 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.slnxwins over a.slnof 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. -
Protected Directory Traversal: folders that cannot be listed (such as
System Volume Informationor 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.
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.
- Home — Project overview, value proposition, quickstart, and problem statement
- 01. Architecture & Design Philosophy — Layered architecture, snapshot isolation, BuildHost model, design rationale
- 02. Layer: Farol.Core — Zero-Roslyn foundation: path sandbox, process execution, diffing, atomic writes, privacy
- 03. Layer: Farol.Engine — Workspaces & Loading — MSBuildWorkspaceLoader, analyzer copies, Visual Studio toolchain probing, background warmup, file watcher
- 04. Layer: Farol.Engine — Navigation & Markup — Compiler-accurate navigation, symbol search, IOperation classification, WebForms & XAML indexers, decompilation
- 05. Layer: Farol.Engine — Verification & Testing — Diagnostic checks in about a second, baseline fingerprinting, edits during a load, edit impact analysis, Code Actions, build & test runners
- 06. Layer: Farol.Engine — Legacy Modernization & Packages — Legacy inventory, config inspector, target surface portability, migration planner, NuGet API inspector
- 07. Layer: Farol.Tools & MCP Contract — Comprehensive reference for all 23 MCP tools, 7 prompts, the skill resources and MCP tasks
- 08. Layer: Farol.Host & CLI — Stdio transport, stream isolation, configuration precedence, privacy-first usage telemetry
- 09. Integrations & Plugins — Claude Code plugin (hook & skill), Visual Studio 2026, Copilot, Antigravity, VS Code, NuGet distribution
- 10. Benchmarks & Evals — Performance benchmarks (Umbraco & DNN Platform), evaluation suite and Phase 2 round, compiler oracle
- 11. Phase 2: Refactorings, Analyzers, Loaders & Index — Refactoring write path, analyzers in checks, heuristic and binlog loaders, persistent index, structured output, MCP Registry
- 12. Phase 3: MCP Tasks & Skills — Build, test, load and convert as MCP tasks; the playbook as three skills served by the server; exit results