SqlNexus
Copilot instructions430 starsChanged 59 days agoMITView on GitHub
These instructions apply to all AI-assisted code changes in this repository. Follow them for every contribution, now and in the future. - Language / runtime: C# 7.3 on .NET Framework 4.8 (legacy, non-SDK product projects). - Solution: sqlnexus.sln with multiple importer/engine assemblies (e.g. sqlnexus, RowsetImportEngine, NexusInterfaces, PerfmonImporter, ErrorLogImporter, BulkLoadEx, ReadTraceNexusImporter, LinuxPerfImporter, TraceEventImporter). - Purpose: SqlNexus imports SQL Server diagnostic data (PSSDIAG/SQLLogScout output) into a SQL Server database and runs reports over it. Every code change that adds or modifies behavior…
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, 17 are distinctive, and 25 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈17
Distinctive · estimate
This author's own choices. Worth a look.
25
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 19
Place tests in TestingInfrastructure/UnitTests/SqlNexus.UnitTests/, in a subfolder that mirrors the source project/namespace being tested.
- Very specific: line 21
Use MSTest ([TestClass] / [TestMethod]), target net48.
- Distinctive: line 23
Follow Arrange / Act / Assert.
- Very specific: line 30
If the code under test uses internal members, prefer adding [assembly: InternalsVisibleTo("SqlNexus.UnitTests")] to the product project …
- Distinctive: line 33
When you cannot fully wire a test to production code, still add a clearly-labeled scaffolding test and a TODO explaining the required …
- Very specific: line 38
No injection: Never build SQL, shell, or file paths via string concatenation of untrusted input.
- Distinctive: line 41
Least privilege / explicit allowlisting: Prefer explicit, code-controlled allowlists over dynamic discovery for anything that executes code …
- Distinctive: line 46
Secrets: never log connection strings, passwords, or credentials.
- Distinctive: line 48
Error handling: do not swallow exceptions silently in a way that hides failures.
- Distinctive: line 50
Dependencies: avoid adding new packages unless necessary.
- Very specific: line 54
Data minimization: Only read/store/transmit the diagnostic data needed for the feature.
- Distinctive: line 55
No telemetry of user content: Do not add logging that emits personal data, server names, credentials, query text, or customer data to …
- Distinctive: line 57
Be explicit about data handling: If a change imports or persists new data, document what is stored and why in the PR description.
- Distinctive: line 59
Redaction: when logging for diagnostics, prefer counts, table names, and status over raw row content or identifiers.
- Distinctive: line 67
Ensure keyboard navigation works (tab order, mnemonics/access keys, Enter/Space activation).
- Distinctive: line 68
Do not convey information by color alone.
- Distinctive: line 71
Ensure labels are associated with their inputs and that status/progress is announced via text, not only visual cues.
- Distinctive: line 77
Keep changes minimal and focused.
- Distinctive: line 78
Prefer clear names; add comments only where they clarify non-obvious intent (as the codebase does).
- Very specific: line 79
Do not introduce new warnings.
- Very specific: line 88
Check whether any file listed in ScriptIntegrityChecker.ScriptHashes changed.
- Distinctive: line 111
Use only APIs available in .NET Framework 4.8 — do not suggest .NET Core / .NET 5+ APIs
- Very specific: line 115
All importers implement INexusImporter (and optionally INexusFileImporter, INexusProgressReporter) from NexusInterfaces
- Very specific: line 135
Use ScriptIntegrityChecker.VerifyScript() before executing any .sql or .cmd file on disk
- Very specific: line 136
When changing a script listed in ScriptIntegrityChecker.ScriptHashes, update its SHA-256 allowlist value in ScriptIntegrity.cs after all …
- Very specific: line 139
Do not use Assembly.LoadFile on untrusted paths without verification
- Very specific: line 140
Do not log passwords or connection strings with credentials via LogMessage
- Very specific: line 146
Use AccessibleTextBox (the project's custom subclass) instead of plain TextBox for all user-editable fields — it implements the UIA Text …
- Very specific: line 155
When Windows High Contrast mode is active (SystemInformation.HighContrast), defer to SystemColors rather than theme colors — see …
- Very specific: line 160
Every report must declare a ContrastTheme parameter with valid values None, Aquatic, Desert
- Very specific: line 170
All chart axes, titles, and legend text must have an explicit <Color> set to =Variables!ReportTextColor.Value so they remain readable in …
- Very specific: line 183
When iterating TopToolStripPanel rows, use ToolStripPanel.Join(toolStrip, rowIndex) to restore toolbar row position after database changes
- Very specific: line 206
Use the actual header line from the diagnostic output script (e.g.
- Distinctive: line 208
If the identifier could appear in multiple unrelated contexts, make it more specific
- Very specific: line 211
Use the most appropriate type from RowsetImportEngine — do not default everything to VarCharColumn:
- Very specific: line 251
Never leave a catch block empty — a silent catch hides bugs and makes failures impossible to diagnose
- Very specific: line 253
Every catch block must do at least one of: log the exception via MainForm.LogMessage(...) or Util.Logger.LogMessage(...), rethrow, or …
- Very specific: line 255
Prefer catch (Exception ex) with a named variable over bare catch {} — the exception message, source, and stack trace should be accessible …
- Very specific: line 257
Use Globals.HandleException(ex, this, MainForm) for unhandled exceptions in UI event handlers — it logs to both the silent log and the …
- Very specific: line 262
Do not swallow SqlException silently — always log sqlex.Message and, where appropriate, surface it to the user via MessageOptions.Dialog
- Very specific: line 264
When an inner try/catch exists solely to protect a logging call (as in Globals.HandleException), fall back to …
- Distinctive: line 267
Do not use exceptions for control flow — validate inputs before calling methods rather than relying on catching the resulting exception
≈ “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.
Files
GitHub Copilot Instructions for SqlNexus
These instructions apply to all AI-assisted code changes in this repository. Follow them for every contribution, now and in the future.
Project context
- Language / runtime: C# 7.3 on .NET Framework 4.8 (legacy, non-SDK product projects).
- Solution:
sqlnexus.slnwith multiple importer/engine assemblies (e.g.sqlnexus,RowsetImportEngine,NexusInterfaces,PerfmonImporter,ErrorLogImporter,BulkLoadEx,ReadTraceNexusImporter,LinuxPerfImporter,TraceEventImporter). - Purpose: SqlNexus imports SQL Server diagnostic data (PSSDIAG/SQLLogScout output) into a SQL Server database and runs reports over it.
Unit testing requirement (mandatory)
Every code change that adds or modifies behavior MUST be accompanied by unit tests.
- Place tests in
TestingInfrastructure/UnitTests/SqlNexus.UnitTests/, in a subfolder that mirrors the source project/namespace being tested. - Use MSTest (
[TestClass]/[TestMethod]), targetnet48. - Name files
<TypeUnderTest>Tests.cs; name methodsScenario_ExpectedResult. - Follow Arrange / Act / Assert. Keep tests deterministic, isolated, and fast (no live SQL Server, network, or file-system dependencies unless explicitly mocked or using temp fixtures).
- Cover, at minimum:
- The happy path.
- Boundary/edge cases (empty, null, min/max, out-of-range, malformed input).
- Negative cases (invalid input is rejected/handled, not silently accepted).
- Any bug being fixed — add a regression test that fails before the fix and passes after.
- If the code under test uses
internalmembers, prefer adding[assembly: InternalsVisibleTo("SqlNexus.UnitTests")]to the product project rather than making members public solely for testing. - When you cannot fully wire a test to production code, still add a clearly-labeled scaffolding test and a TODO explaining the required wiring (project reference / InternalsVisibleTo).
Security requirements (Microsoft SDL — always build in this spirit)
- No injection. Never build SQL, shell, or file paths via string concatenation of untrusted
input. Use parameterized
SqlCommandparameters. For dynamic object names, validate against a strict allowlist/regex (see existingIsSafeSqlIdentifier). - Least privilege / explicit allowlisting. Prefer explicit, code-controlled allowlists over dynamic discovery for anything that executes code (e.g. importer selection). Do not auto-execute drop-in/unknown assemblies.
- Validate all external input (command-line args, file contents, config, DB results). Reject unknown/empty tokens explicitly; fail closed, not open.
- Secrets: never log connection strings, passwords, or credentials. Mask sensitive values.
- Safe defaults: new options should default to the most secure behavior.
- Error handling: do not swallow exceptions silently in a way that hides failures; surface failures in status/results (do not report success when a step failed).
- Dependencies: avoid adding new packages unless necessary; prefer maintained, trusted ones.
Privacy requirements (always build in this spirit)
- Data minimization. Only read/store/transmit the diagnostic data needed for the feature.
- No telemetry of user content. Do not add logging that emits personal data, server names, credentials, query text, or customer data to external sinks. Diagnostic logs should stay local.
- Be explicit about data handling. If a change imports or persists new data, document what is stored and why in the PR description.
- Redaction: when logging for diagnostics, prefer counts, table names, and status over raw row content or identifiers.
Accessibility requirements (Microsoft accessibility standards — always build in this spirit)
For any WinForms UI changes:
- Provide
AccessibleNameandAccessibleDescriptionfor meaningful controls. - Ensure keyboard navigation works (tab order, mnemonics/access keys, Enter/Space activation).
- Do not convey information by color alone; pair color with text/iconography.
- Respect system theme/high-contrast; avoid hard-coded colors that break contrast (use the
existing
ThemeManagerpatterns). - Ensure labels are associated with their inputs and that status/progress is announced via text, not only visual cues.
Coding conventions
- Match the existing style of the file/project you are editing.
- Keep changes minimal and focused; do not reformat unrelated code.
- Prefer clear names; add comments only where they clarify non-obvious intent (as the codebase does).
- Do not introduce new warnings; keep the build clean (
net48, C# 7.3 language features only).
Definition of done for a change
- Behavior implemented with minimal, focused edits.
- Unit tests added/updated and passing (including a regression test for any bug fix).
- Security, privacy, and accessibility considerations addressed (or explicitly noted as N/A).
- Build is green; no new warnings.
- PR description explains the change, any data-handling implications, and test coverage.
- Check whether any file listed in
ScriptIntegrityChecker.ScriptHasheschanged; if so, compute its new SHA-256 hash from the final file contents and update the corresponding allowlist entry.
Project overview (projects and responsibilities)
SqlNexus is a Windows Forms desktop application for importing and analyzing SQL Server diagnostic data (PSSdiag, SQL LogScout, XEL, TRC, Perfmon, Linux perf). Key projects:
- sqlnexus — Main WinForms host (UI, report viewer, theme engine, import orchestration)
- NexusInterfaces — Shared importer interfaces (
INexusImporter,INexusFileImporter, etc.) - RowsetImportEngine — Core T-SQL rowset importer
- ReadTraceNexusImporter — XEL/TRC trace importer (legacy)
- PerfmonImporter — Windows Performance Monitor (.blg/.csv) importer
- LinuxPerfImporter — Linux performance data importer
- ErrorLogImporter — SQL Server error log importer
- BulkLoadEx — Native bulk-load helper
- TraceEventImporter — New importer for XEL files using SQL Server's TraceEvent API XeLite (future replacement for ReadTraceNexusImporter)
Framework specifics:
- Windows Forms for all UI
- Microsoft.Reporting.WinForms (ReportViewer) for RDLC report rendering
- Microsoft.Data.SqlClient for all SQL Server connectivity (prefer over
System.Data.SqlClient) - Use only APIs available in .NET Framework 4.8 — do not suggest .NET Core / .NET 5+ APIs
Architecture conventions
- All importers implement
INexusImporter(and optionallyINexusFileImporter,INexusProgressReporter) fromNexusInterfaces - Importer ordering is controlled in
fmImport.OrderedImporterFiles()— TraceEventImporter (150) must run after RowsetImportEngine (100) - ReadTrace and TraceEventImporter are mutually exclusive — never enable both simultaneously
- The
CustomXELImporterhandles SQLDiag, AlwaysOn, and System Health XEL files independently of the plugin importers - Report parameters are set via
ReportParameterobjects;ContrastThememust be propagated to every report that declares it ThemeManagerowns all color definitions for the three themes: Default, Aquatic (#202020background), and Desert (#FFFAEFbackground)- The
TopToolStripPanellayout is order-sensitive:menuBarMain ? toolbarService ? toolbarReport ? toolbarMain(last added = topmost row)
Security — CodeQL specifics
In addition to the SDL requirements above:
- Database names passed to SQL commands must be bracket-escaped (
[dbname]) before use — see theCodeQL [SM03934]annotation pattern infmImport.cs - Use
ScriptIntegrityChecker.VerifyScript()before executing any.sqlor.cmdfile on disk - When changing a script listed in
ScriptIntegrityChecker.ScriptHashes, update its SHA-256 allowlist value inScriptIntegrity.csafter all edits to the script are complete - Validate all file paths before use; reject paths containing directory traversal sequences
- Do not use
Assembly.LoadFileon untrusted paths without verification - Do not log passwords or connection strings with credentials via
LogMessage
Accessibility — WinForms/WCAG specifics
In addition to the accessibility requirements above:
- Use
AccessibleTextBox(the project's custom subclass) instead of plainTextBoxfor all user-editable fields — it implements the UIA Text pattern required for screen readers - Disabled
Labelcontrols must not rely on WinForms' default disabled rendering (which ignoresForeColor) — keep labelsEnabled = trueand set a mutedForeColorviaThemeManager.CurrentThemeNameto simulate the disabled appearance ToolStripLabelandToolStripComboBoxitems must haveAccessibleNameset- Submenus must remain open when the user toggles a checkbox option
(
ToolStripDropDownCloseReason.ItemClickedshould be cancelled) - Link labels must always use
LinkBehavior.AlwaysUnderlinefor WCAG 1.4.1 compliance - When Windows High Contrast mode is active (
SystemInformation.HighContrast), defer toSystemColorsrather than theme colors — seeThemeManager.ApplyHighContrastTheme()
RDLC report theming
- Every report must declare a
ContrastThemeparameter with valid valuesNone,Aquatic,Desert - Define exactly 11 theme variables:
ReportTextColor,BodyBackgroundColor,TitleColor,TableHeadingColor,TableHeadingFontColor,ChartColor,ChartSecondaryColor,ChartGradientStyle,TableShowCell,TableHidcell,URILinkFontColor - Replace all hardcoded colors in
<Style>blocks with the appropriate variable reference:- Header
<BackgroundColor>?=Variables!TableHeadingColor.Value - Body
<BackgroundColor>?=Variables!BodyBackgroundColor.Value - Drillthrough/hyperlink
<Color>?=Variables!URILinkFontColor.Value - Chart area and chart background ?
=Variables!ChartColor.Value - All
<TextRun>font-styled text without an explicit color ?=Variables!ReportTextColor.Value
- Header
- All chart axes, titles, and legend text must have an explicit
<Color>set to=Variables!ReportTextColor.Valueso they remain readable in all contrast themes - The "No Data Available" warning banner uses a
Goldbackground — its text must always beBlackregardless of theme
Toolbar and settings persistence
- Toolbar visibility (
ShowStandardToolbar,ShowReportToolbar,ShowDataCollectionToolbar) must be explicitly saved infmNexus_FormClosing— DataBindings alone are not reliable ShowHideUIElements()must explicitly settoolbarMain.Visiblefrom the persisted setting to guard against DataBinding desync duringInitializeComponentSelectLoadReport()must readProperties.Settings.Default.ShowReportToolbaras the source of truth when settingtoolbarReport.Visible— never blindly set it totrue- When iterating
TopToolStripPanelrows, useToolStripPanel.Join(toolStrip, rowIndex)to restore toolbar row position after database changes
TextRowsets.xml — rowset definition standards
TextRowsets.xml (and its custom extension TextRowsetsCustom.xml) define how the
RowsetImportEngine maps sections of SQL Server diagnostic text output files into SQL tables.
Structure
- The root element is
<TextImport>containing a single<KnownRowsets>block - Each rowset is a
<Rowset>element with mandatory attributes:name,enabled,identifier, andtype - Column definitions go inside
<KnownColumns>— columns not listed are imported asVarCharColumnby default
Naming
- Table names (
nameattribute) must be prefixed withtbl_ - Column names must match exactly the column headers that appear in the source diagnostic text
output — including spaces if present (e.g.
"Wait Time")
Identifiers
- The
identifierattribute is the exact string the engine uses to detect the start of this rowset in the text file — it must be unique across all rowsets in the file - Use the actual header line from the diagnostic output script (e.g.
"-- sysperfinfo","-- sys.dm_os_memory_health_history --") — do not paraphrase it - If the identifier could appear in multiple unrelated contexts, make it more specific
Column types
Use the most appropriate type from RowsetImportEngine — do not default everything to
VarCharColumn:
| Type | Use for |
DateTimeColumn | Any runtime, timestamp, or date/time column |
BigIntColumn | rownum, large integer counters |
IntColumn | SPIDs, counts, flags |
FloatColumn | Decimal metrics (wait time, CPU %) |
DecimalColumn | Precise decimal values |
VarCharColumn | Short string identifiers, names |
NVarCharColumn | Unicode text, query text, messages |
VarBinaryColumn | Binary handles (e.g. query_hash) |
Required columns
- In some cases may include
rownumtyped asBigIntColumnwithvaluetoken="ROWNUMBER"as the first column - In some cases include
runtimetyped asDateTimeColumnwithvaluetoken="RUNTIME"as the second column — this is used by most reports to filter by time range
Value tokens and define tokens
valuetokencolumns are populated by the engine from context (e.g.ROWNUMBER,RUNTIME,SCRIPTNAME,USERNAME,IMPORTDATE,INPUTFILENAME) — do not parse these from the text filedefinetokencolumns extract a value from the identifier/header line itself and store it for use byvaluetokencolumns later in the same rowset
Enabled flag
- Set
enabled="true"for all rowsets that should be active by default - Set
enabled="false"only for rowsets that are experimental, deprecated, or conditionally loaded — always add a comment explaining why
Security
- The
nameattribute becomes a SQL table name — it must not be constructed from user input and must only contain alphanumeric characters and underscores - Column
lengthattributes are used to sizeVARCHAR/NVARCHARcolumns — always specify an explicitlengthfor string columns; omitting it defaults to a short platform-defined length that may truncate data
Exception handling
- Never leave a
catchblock empty — a silent catch hides bugs and makes failures impossible to diagnose - Every
catchblock must do at least one of: log the exception viaMainForm.LogMessage(...)orUtil.Logger.LogMessage(...), rethrow, or return a meaningful failure value - Prefer
catch (Exception ex)with a named variable over barecatch {}— the exception message, source, and stack trace should be accessible for logging - Use
Globals.HandleException(ex, this, MainForm)for unhandled exceptions in UI event handlers — it logs to both the silent log and the dialog, and setsExceptionEncountered = true - For expected, recoverable failures (e.g. file not found, SQL connection refused) catch the most
specific exception type (
SqlException,IOException,UnauthorizedAccessException) rather than the baseException - Do not swallow
SqlExceptionsilently — always logsqlex.Messageand, where appropriate, surface it to the user viaMessageOptions.Dialog - When an inner try/catch exists solely to protect a logging call (as in
Globals.HandleException), fall back toSystem.Diagnostics.Debug.WriteLineso the failure is at minimum visible in the debugger output window - Do not use exceptions for control flow — validate inputs before calling methods rather than relying on catching the resulting exception
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
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.

