================================================================================ SAGEFS LIVE TESTING & COVERAGE SYSTEM - IMPLEMENTATION GUIDE

STATUS: Live testing is functional but still being stabilized. Rough edges remain around session switching and test-discovery timing. Expecto has the best coverage. It's what I test against every day, so it's what gets exercised hardest. This guide describes the internal design for people who want to go spelunking in the source; line numbers are approximate and drift as the code changes, so treat them as “look near here,” not “line X exactly.” I'd rather you find the real thing three lines off than trust a number I never re-checked.

QUICK REFERENCE - KEY FILES & FUNCTIONS

  1. Test Discovery & Execution:

    • File: SageFs.Core/Features/LiveTestingExecutors.fs
    • Key Functions:
      • AttributeDiscovery.discoverInAssembly: Scan types for test attributes
      • AttributeDiscovery.discoverWithRunner: Discovery + execution closures
      • ReflectionExecutor.executeMethod: Invoke via MethodInfo.Invoke
      • ExpectoExecutor: Custom reflection-based Expecto runner
    • Frameworks: Expecto is driven end to end. xUnit (incl. xUnit v3), NUnit, MSTest and TUnit share one attribute path that is tested only with made-up attributes, so for those four it is expected to work and unproven
    • Key Type: DiscoveryResult { Tests: TestCase list; RunTest: TestCase → Async }
  2. Coverage Instrumentation (IL-Level):

    • File: SageFs.Core/Features/CoverageInstrumenter.fs
    • Key Functions:
      • collectSequencePoints: Extract all non-hidden IL probes
      • injectTracker: Create __SageFsCoverage class
      • insertProbes: Inject Hit() calls before sequence points
      • instrumentAssembly: Full instrumentation pipeline
    • Key Type: InstrumentationMap { Slots: SequencePoint[]; TotalProbes: int }
    • Coverage Bitmap: CoverageBitmap { Bits: uint64[]; Count: int } (8x memory vs bool[])
  3. Dependency Graph (Symbol → Test Mapping):

    • File: SageFs.Core/Features/LiveTestingTypes.fs
    • Key Functions:
      • TestDependencyGraph.buildFromSymbolUses: Build from FCS extracts
      • TestDependencyGraph.findAffected: Get tests for changed symbols
      • TestDependencyGraph.computeTransitiveCoverage: BFS through call graph
    • Key Type: TestDependencyGraph { SymbolToTests; TransitiveCoverage; PerFileIndex; SourceVersion }
  4. Flaky Test Classification:

    • File: SageFs.Core/Features/LiveTestingTypes.fs
    • Key Functions:
      • FlakyDetection.classifyFlakiness: Classify Environmental vs Property
      • FlakyDetection.isFsCheckFailure: Extract shrunk counterexample
    • Key Type:
      • FlakyClassification = Insufficient | Stable | Environmental(int) | PropertyCounterexample(string)
      • ResultWindow (circular buffer): Track last 10 outcomes, count flips
    • Defaults: windowSize=10, flipThreshold=2, minSamples=3
  5. Failure Narratives (Causal Analysis):

    • File: SageFs.Core/Features/LiveTestingTypes.fs
    • Key Types:
      • FailureNarrative { LastPassedAt; TimeSinceLastPass; CausalChanges; PropertyViolation; Summary }
      • CausalChange = SymbolChanged(string) | FileChanged(string) | Unknown
      • PropertyViolationDetail { PropertyName; ShrunkCounterexample; AlgebraicCategory }
    • Algebraic Categories Detected: associativity, commutativity, identity, idempotence, distributivity, inverse, absorption, closure
  6. Test Prioritization:

    • File: SageFs.Core/Features/LiveTestingTypes.fs
    • Key Functions:
      • TestPrioritization.computeTier: Assign tier (0=failed, 4=notrun)
      • TestPrioritization.buildSortKey: Lexicographic (tier, -coverage, duration)
    • Tier Rules: Failed(0) → New(1) → Passed(2) → Skipped(3) → NotRun(4)
    • Environmental flaky failures demoted from tier 0 to tier 2
  7. Test Explainer & Verification:

    • File: SageFs/Mcp.fs
    • MCP tools (what agents actually call):
      • explain_test_failure: why a test failed
      • targeted_verify: run and verify specific tests
      • list_tests: list discovered tests
      • coverage_intel: coverage summary
    • Internal functions behind these (not standalone MCP tools):
      • explainTestRun: computes why a test ran
      • getFileCoverage: per-line coverage; surfaced to editors via SSE file_annotations and the HTTP API (GET /api/live-testing/file-annotations), not as an MCP tool
    • run_tests is the one MCP door for running tests. It dispatches the same RunTestsRequested event the editors and the dashboard use (POST /api/live-testing/run) and reads the engine's own record of that request back as a receipt, so the result is never a second runner's opinion.
    • There is no enable_live_testing, get_live_test_status, get_test_trace, explain_test_run, or get_file_coverage MCP tool. Live-testing enable/disable/status are HTTP API endpoints under /api/live-testing/… used by editors and the dashboard, on purpose.
  8. Per-Line Coverage Data:

    • File: SageFs.Core/Features/LiveTestingTypes.fs
    • Key Functions:
      • FileAnnotations.projectWithCoverage: Get per-line coverage
      • FileAnnotations.resolveFilePath: Resolve partial paths
    • Output: CoverageLineAnnotation { Line; EndLine; EndColumn; Detail; CoveringTestIds; BranchCoverage }
    • BranchCoverage: FullyCovered | PartiallyCovered(covered, total) | NotCovered

================================================================================ EXECUTION FLOW - AS-YOU-TYPE LIVE TESTING

  1. KEYSTROKE EVENT:

    • LiveTestCycleState.onKeystroke marks phase as edited
    • Triggers the TreeSitter debounce (50 ms by default, Timeouts.liveTestTreeSitterDebounce); the FCS type-check waits 300 ms (liveTestFcsDebounce) and backs off to 2 s when typing keeps cancelling it
  2. TREESITTER PARSES FILE:

    • Extract test function locations (source-mapped)
    • Emit TreeSitterComplete effect
  3. AFTER TREESITTER:

    • Request FCS type-check for file
  4. FCS TYPE-CHECK COMPLETES:

    • Extract symbol references (SymbolUse with FullName, UseKind)
    • FileAnalysisCache.update: compute changed symbols
    • SymbolGraphBuilder.updateGraph: incrementally update DepGraph
    • Emit ChangedSymbols list
  5. TEST CYCLE ORCHESTRATOR DECIDES:

    • Get affected tests: TestDependencyGraph.findAffected(changedSymbols)
    • Filter by RunPolicy (OnEveryChange, OnSaveOnly, OnDemand, Disabled)
    • If any tests → FullCycle decision, else TreeSitterOnly
  6. TEST EXECUTION (If FullCycle):

    • Prioritize tests: tier → -coverageWeight → duration
    • Execute (per-session executors): in parallel chunks for a project with no instrumented assemblies, one test at a time for one with them, so each coverage reading is one test's
    • Collect TestRunResult + coverage bitmaps
    • Update FlakyHistory (ResultWindow)
    • Build FailureNarratives for Passed→Failed transitions
    • Recompute StatusEntries
  7. STREAM RESULTS:

    • SSE (Server-Sent Events) deduped via StateVersion
    • Only send if LiveTestState changed

================================================================================ STATE MACHINE - KEY TYPES

TestCase: { Id: TestId // Stable SHA256 hash FullName: string // e.g. “MyTests.test_add” DisplayName: string // e.g. “test_add” Origin: TestOrigin // SourceMapped(file, line) | ReflectionOnly Labels: string list Framework: TestFramework // Expecto | XUnit | NUnit | MSTest | TUnit | Unknown of string Category: TestCategory // Unit | Integration | Browser | Benchmark | Architecture | Property | Custom of string }

TestRunResult: { TestId: TestId TestName: string Result: TestResult // Passed(duration) | Failed(failure, duration) | Skipped | NotRun Timestamp: DateTimeOffset Output: string option // Captured console output }

LiveTestState: { DiscoveredTests: TestCase[] LastResults: Map<TestId, TestRunResult> // Latest outcome per test StatusEntries: TestStatusEntry[] // state behind the editor marks RunPhases: Map<string, TestRunPhase> // Per-session execution phase TestSessionMap: Map<TestId, string> // Routing: TestId → session TestCoverageBitmaps: Map<TestId, CoverageBitmap> // IL coverage per test FlakyHistory: Map<TestId, ResultWindow> // Classification input FailureNarratives: Map<TestId, FailureNarrative> // Why test failed StateVersion: int64 // Dedup counter // ... more fields }

LiveTestCycleState: { TestState: LiveTestState DepGraph: TestDependencyGraph // Symbol → test mapping InstrumentationMaps: Map<sessionId, InstrumentationMap[]> // IL coverage maps AnalysisCache: FileAnalysisCache // File → symbol defs Debounce: TestCycleDebounce // TreeSitter + FCS channels AdaptiveDebounce: AdaptiveDebounce // Dynamic delay tuning LastTrigger: RunTrigger ChangedSymbols: string[] // ... more fields }

================================================================================ KEY INVARIANTS & GUARANTEES

  1. InstrumentationMap Slot Order: Once assigned, slot IDs never change → Enables stable CoverageBitmap comparison across test runs

  2. CoverageBitmap Compatibility: All bitmaps must match current InstrumentationMap size → Stale instrumentation generation detected + skipped

  3. TestId Determinism: SHA256(fullName + framework) always produces same ID → Enables stable cross-session test identity

  4. StateVersion Monotonic: Increments on every LiveTestState mutation → O(1) dedup via version check instead of deep equality

  5. FlakyHistory Circular: Never shrinks, overwrites oldest when full → Bounded memory for result windows

  6. FailureNarrative Transient: Cleared when test passes, rebuilt on next failure → Captures transition points, not static state

  7. Tier Invariant: Environmental flaky failures demoted tier 0→2 → Prevents attention-stealing; allows honest failures to surface

  8. Coverage is attributed per test: the worker reads and clears the coverage probes after each test and sends the reading with that test's result, so a bitmap belongs to one test. To make that true, the tests of a project with instrumented assemblies run one at a time. (Earlier there was one bitmap per run batch, shared by every test in it, which was a safe upper bound and could not say which test reached a line. how-live-testing-works.md has the details.)

================================================================================ EXTENSION POINTS FOR CUSTOMIZATION

To build on top of SageFs live testing:

  1. Custom Test Frameworks: → Implement TestExecutor with custom Discover function → Register in BuiltInExecutors list → Examples: Pytest, Jest, Go testing, Rust criterion

  2. Custom Failure Analysis: → Hook FailureNarrativeBuilder.detectAlgebraicCategory for new patterns → Extend PropertyViolationDetail with custom fields → Add regex matchers for domain-specific failures

  3. Custom Test Prioritization: → Extend PrioritizationContext with custom fields → Implement custom buildSortKey logic → Example: prioritize by test cost (speed × resource usage)

  4. Custom Symbol Analysis: → Override SymbolGraphBuilder.updateGraph for language-specific semantics → Implement custom FileAnalysisCache.update for different parsers → Example: Support Python, TypeScript, C# analyzers

  5. Custom Coverage Analysis: → Extend CoverageBitmap operations (beyond intersect/union/xor) → Implement custom file masking logic → Example: Code-churn based coverage weighting

  6. Custom Flaky Detection: → Hook FlakyDetection.classifyFlakiness with new classifiers → Add custom Result Window strategies (e.g., exponential weighting) → Example: Network timeout detection, resource exhaustion patterns

  7. Custom Reporting: → Extend formatFileCoverageResponse for custom metrics → Implement custom FailurePresentation formats → Example: Generate HTML reports, integrations with issue tracking

None of these extension points have an actual second implementation behind them yet. I've kept the seams open (interfaces, registries, extend-not-edit shapes) because I've been burned before by code that assumed it would only ever have one test framework, one language, one output format. Nobody's built a Pytest bridge. If you do, I'd love to hear about it.

================================================================================

SSE Event Formats

Wire formats for live-testing SSE events consumed by editor integrations.

test_source_locations

event: test_source_locations
data: {"SessionId":"<id>", "Locations": [{"CellId":int, "TestName":"string", "FilePath":"string", "StartLine":int, "EndLine":int}]}

file_annotations

event: file_annotations
data: {"SessionId":"<id>", "Annotations": {"<filePath>": {"CoverageAnnotations": [{"Line":int, "Health":"AllPassing|SomeFailing|NoCoverage", "Tests":["testName"]}], "InlineFailures": [{"Line":int, "TestName":"string", "Presentation":"AssertionDiff|ExceptionMessage|Timeout|RawMessage", "Details":{...}}]}}}

failure_narratives

event: failure_narratives
data: {"SessionId":"<id>", "Narratives": [{"TestId":"string", "TestName":"string", "Summary":"string", "TimeSinceLastPass":"string", "CausalChanges":[{"Symbol":"string", "File":"string"}], "PropertyViolation":null|{...}}]}

Debugging a failing test

You can debug a failing test from VS Code and from Neovim. In VS Code a failing test gets a Debug lens next to its result, a Debug link in the hover of its mark, and Debug Test in the Test Explorer (that is also what puts Debug Test on the glyph). In Neovim, :SageFsDebugTest debugs the failing test on the cursor's line (or the file's only failing test after you confirm, or a test you name by name or id), <leader>rtg does the same from a buffer, and D on a row of the test panel debugs that row's test. Neovim attaches through nvim-dap and netcoredbg. Without nvim-dap it still holds the test and prints the process id to attach to.

How it works: the test runs in the process that loaded your code, which is the isolated FSI host (or the worker, for an in-process session). So the editor attaches a .NET debugger to that process.

  1. The editor asks the daemon to debug a test. The host holds the test and answers with its process id and a ticket.
  2. The editor attaches its coreclr debugger to that process.
  3. The editor continues. The host checks that a debugger is really attached, runs the test under it, and answers when it finishes. The editor then detaches.
  4. The daemon puts the verdict on the test's row, the same row a normal run fills, so the mark, the lens, the Test Explorer row and every other client show what you just saw, with no normal run. The row carries the provenance of the code the test ran against (Compiled when it had a PDB, Evaluated when an eval defined it) and no duration, because the host's clock ran through every breakpoint. A debug run is not a flake sample, not a line in the run summary and not a discovery. A hold that ended without a verdict (nobody released it, no debugger attached, the host ended) changes no row. The daemon records a ticket once, so a repeated continue records nothing more.

While VS Code holds a test, it pauses live testing for the session (when it was running) and resumes it when the debug run ends, however it ends, so no automatic run queues behind a test stopped at a breakpoint. A pause you set yourself stays as it is.

Several tests. Select more than one test in the Test Explorer and choose Debug Test. VS Code attaches once, to the first test, and takes the tests in turn: each later test is held and released with the debugger still attached, and each verdict lands on its row as that test ends. A test the daemon does not know is skipped and the rest go on. If the debug session ends, the host is lost or no debugger attaches, the batch stops and the summary says how many did not run. The host still holds one test at a time, so the tests run one after another and never in parallel.

If nobody releases the test within two minutes (Timeouts.debugHold), the host drops the hold and the test never runs. Nothing runs without a debugger. An editor can release the test as soon as its attach request is accepted, ahead of the debugger (netcoredbg took longer than 1.5 seconds to finish attaching to the host), so a release that finds no debugger yet is not refused at once: the host waits for one that is still attaching, for Timeouts.debugAttachGrace (five seconds on a fast machine, scaled by the machine tier). A debugger that attaches inside that wait runs the test. If none does, the answer is released_without_debugger and the test does not run. The host looks for the attach every Timeouts.debugAttachLook because the runtime raises no event when a debugger attaches. A host that ends during the wait is told as host_lost, not as a missing debugger. The continue request stays open through the wait, like it does while the test runs.

Which debugger you need. One that provides the coreclr debug type. In Microsoft's VS Code that is the C# extension (ms-dotnettools.csharp). If nothing installed provides it, the extension says so and offers to install it. Microsoft's debugger is licensed for Microsoft's own build of VS Code. In another build you need some other extension that provides coreclr. In Neovim it is netcoredbg, which nvim-dap drives as its coreclr adapter.

What the debugger can stop in.

  • Code in your project's compiled assemblies has a PDB, so breakpoints bind. Build in Debug, or with portable PDBs. An optimized build will skip lines and hide locals, like any optimized build. The session runs an instrumented copy of the assembly (for coverage) from a shadow directory; its debug directory names the pdb that sits beside it, which is how a debugger finds the symbols. Until 2026-11-10 it named a .instrumented.pdb that did not exist, so netcoredbg said “no symbols loaded” and a breakpoint stayed pending.
  • Code you evaluated in the session (a test file SageFs re-evaluated when you saved it) lives in a dynamic assembly. It has no PDB, so breakpoints inside it will not bind. The debugger still runs the test, it just will not stop in that code. SageFs says so when you start. To debug the compiled copy, hard reset the session with a rebuild first.
  • A compiled method that hot reload has detoured to a new body has the same problem for that method.

Linux. Attaching to a process that is not your child needs ptrace permission. With kernel.yama.ptrace_scope at 1 (the default on many distros) the host opens that door itself for the length of the hold and closes it after, so the attach works without you changing anything. At 2 only root may attach, and at 3 nobody may. SageFs tells you which one it hit and what to change, but it cannot fix those for you.

What it does not do yet.

  • Neovim debugs one test at a time (:SageFsDebugTest). VS Code takes several, one after another. The host holds one test, and a second hold request is refused until the first ends.
  • Breakpoints do not bind in a test an eval defined. The daemon says so when it holds the test. Offering the compiled copy waits on confirm builds without restarting the worker.
  • A debug run does not record the coverage it set: the host clears the probes around it, so the next ordinary test's reading starts clean.
  • I have run the host side against a real isolated host with a real managed debugger, netcoredbg 3.2.0-1092 (netcoredbg --interpreter=cli --attach <pid>, then continue on its console, then the release), and the --integration-lt tier runs that path on every gate: the test runs under the debugger and answers attached, the row shows the verdict with its provenance and no duration, a breakpoint in the test's own source binds and stops the host (the release answers host_not_answering and names netcoredbg, and the same ticket answers attached once the debugger goes on), and a ticket held across a confirming build is not lost. I have not run a full attach with Microsoft's C# extension debugger from this repo's tests: that adapter is checked by hand per release. The VS Code side is covered by contract tests that run without VS Code, and by the extension-host case in --integration-host, which drives netcoredbg as the coreclr adapter.

A test held across a confirming build. A build that confirms an edit swaps the session's worker when the worker holds nothing a swap would lose, and the host the test is held in goes with the worker. So a held test counts as something a swap would lose, like a value you bound by hand in the REPL: the confirmation runs in a throwaway worker, the session's own worker keeps its pid, and the ticket still releases to a verdict. The daemon notes a hold when it forwards the hold or any release, and takes the note back when a release hears that the hold ended. A note nobody has renewed for Timeouts.debugHold lapses, because the host drops a hold by itself and says nothing when it does. Before this, a hold on a session with nothing else in it was swapped away and the release answered 409 no_such_hold (hand run, 2026-11-10).

The two routes, for any editor client. Both answer the same JSON shape (camelCase) and read the body whatever the status code is.

Route Body Answers
POST /api/live-testing/debug { "testId": "<id>" } or { "pattern": "<name>" }, and "sessionId" (VS Code and Neovim both send it; without it the daemon picks a session by its fallback rules) status held with pid, ticket, testName, symbols (compiled or eval), symbolsNote, access (open or blocked), accessNote, holdMs
POST /api/live-testing/debug/continue { "ticket": "<ticket>" }, optional "sessionId" still_running (ask again), host_not_answering (HTTP 504, ask again after whatever holds the host lets go), or attached with outcome and detail, or one of the dead ends below

A host that answers nothing. A debugger stopped at a breakpoint, an inspector such as dotnet-debug attach or dotnet-dump, and a debugger that was killed and left the runtime stopped all freeze the test host. The host process is alive and its connection is open, so nothing says it died, and it reads nothing. continue used to wait for it with no bound, so the request never answered (measured on 2026-11-09: no answer in 120 seconds with an inspector attached, and again on three releases after the inspector was killed). Now the wait ends at Timeouts.debugContinuePark (20 seconds) plus Timeouts.debugHostAnswerGrace (five seconds on a fast machine, scaled by the machine tier), and the daemon answers host_not_answering with HTTP 504. The host is alive, so this is not host_lost. The message says the host's pid, how long it was given, what holds it when that can be found (a process the kernel names as tracing it, or a known debugger or inspector that names the pid in its command line; otherwise it says a debugger or inspector may hold it), and the next action: continue it in the debugger, or detach the debugger or quit the inspector, then ask again. The ticket stays valid. The hold is the host's and the silence does not touch it, so asking again after the host runs finds its real answer: still_running, attached, or a typed ending such as released_without_debugger (the host handles the release it had read when it thaws, finds no debugger, and says so). If nothing is attached and the host stays silent, hard reset the session. A begin sent to a silent host answers host_unavailable with the same description. The daemon's own wait on the worker that relays the answer ends one more grace later (worker_failed), so a stuck worker also ends in a named answer.

While the host is silent the session does not read plain Ready: its health is Degraded with the same description, in /api/sessions, get_session_status, and the dashboard's viewed-session panel. The daemon notes the silence when a continue ends with host_not_answering and takes the note back when the host answers a later continue or debug request. A host that is stopped with nobody asking it anything is not noticed, because only a request finds out.

The other statuses are hold_already_open, no_debugger_within, released_without_debugger, no_such_hold, host_lost, host_unavailable, not_discovered, no_test_matched, ambiguous_test, no_session, no_worker, worker_failed and bad_request. Every response carries a message that says what happened and what to do about it.

Editor Integrations

  • VS Code: FileAnnotationsListener.fs parses file_annotations. Extension.fs renders the coverage marks (text in front of the code, not gutter icons) + inline failures. TestControllerAdapter.fs enriches test items with failure narratives, and registers the Debug profile. TestDebugCommand.fs and TestDebugPure.fs debug a failing test (see above).
  • Neovim: lives in its own repo, sagefs.nvim (not in this tree). Its testing.lua caches source_locations and failure_narratives, telescope_picker.lua jumps to source on <CR>, and commands.lua shows a narrative floating window on <C-d>. debug_test.lua and debug_test_ui.lua debug a failing test through nvim-dap (:SageFsDebugTest, <leader>rtg, D on a panel row; see above).