feat(winmd-api-search): add WinMD cache generator script and related files (#45606)

<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request

Adds a new Copilot agent skill (`winmd-api-search`) that lets AI agents
discover and explore Windows desktop APIs by searching a local cache of
WinMD metadata. The skill covers Windows Platform SDK, WinAppSDK/WinUI,
NuGet package WinMDs, and project-output WinMDs — providing full API
surface details (types, members, enumeration values, namespaces) without
needing external documentation lookups.

**Key components:**

- `.github/skills/winmd-api-search/SKILL.md` — Skill definition with
usage instructions, search/detail workflows, and scoring guidance
- `scripts/Invoke-WinMdQuery.ps1` — PowerShell query engine supporting
actions: `search`, `type`, `members`, `enums`, `namespaces`, `stats`,
`projects`
- `scripts/Update-WinMdCache.ps1` — Orchestrator that builds the C#
cache generator, discovers project files, and runs the generator
- `scripts/cache-generator/CacheGenerator.csproj` + `Program.cs` — .NET
console app using `System.Reflection.Metadata` to parse WinMD files from
NuGet packages, project references, Windows SDK, and packages.config
into per-package JSON caches
- `scripts/cache-generator/Directory.Build.props`,
`Directory.Build.targets`, `Directory.Packages.props` — Empty isolation
files to prevent repo-level Central Package Management and build targets
from interfering with this standalone tool

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist

- [ ] Closes: #xxx <!-- Replace with issue number if applicable -->
- [x] **Communication:** I've discussed this with core contributors
already. If the work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass — N/A: This is an offline
agent skill (PowerShell + standalone .NET tool) with no integration into
the main product build or runtime. Validated manually by running the
cache generator across multiple project contexts (ColorPickerUI,
CmdPal.UI, runner, ImageResizer, etc.) and exercising all query actions.
- [ ] **Localization:** All end-user-facing strings can be localized —
N/A: No end-user-facing strings; this is an internal developer/agent
tool
- [ ] **Dev docs:** Added/updated — The SKILL.md itself serves as the
documentation
- [ ] **New binaries:** Added on the required places — N/A: The cache
generator is a standalone dev-time tool, not shipped in the installer
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: N/A

<!-- Provide a more detailed description of the PR, other things fixed,
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

### Cache Generator (`Program.cs`, ~1000 lines)

A self-contained .NET console app that:

1. **Discovers WinMD sources** from four channels:
   - `project.assets.json` (PackageReference — modern .csproj/.vcxproj)
   - `packages.config` (legacy NuGet format)
- `<ProjectReference>` bin/ output (class libraries producing `.winmd`)
   - Windows SDK `UnionMetadata/` (highest installed version)

2. **Parses WinMD files** using `System.Reflection.Metadata` /
`PEReader` to extract:
- Types (classes, structs, interfaces, enums, delegates) with full
namespace
- Members (methods with decoded signatures/parameters, properties with
accessors, events)
   - Enum values
   - Base types and type kinds

3. **Outputs per-package JSON** under `Generated Files/winmd-cache/`:
- `packages/<Id>/<Version>/meta.json` — package summary
(type/member/namespace counts)
   - `packages/<Id>/<Version>/namespaces.json` — ordered namespace list
- `packages/<Id>/<Version>/types/<Namespace>.json` — full type detail
per namespace
- `projects/<ProjectName>.json` — maps each project to its package set

4. **Deduplicates** at the package level — if a package+version is
already cached, it's skipped on subsequent runs.

### Build Isolation

Three empty MSBuild files (`Directory.Build.props`,
`Directory.Build.targets`, `Directory.Packages.props`) in the
cache-generator folder prevent the repo's Central Package Management and
shared build configuration from interfering with this standalone tool.

### Query Engine (`Invoke-WinMdQuery.ps1`)

Supports seven actions: `search` (fuzzy text search across
types/members), `type` (full detail for a specific type), `members`
(filtered members of a type), `enums` (enumeration values), `namespaces`
(list all namespaces), `stats` (cache statistics), and `projects` (list
cached projects with their packages).

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed

1. **Cache generation:** Ran `Update-WinMdCache.ps1` across 310+ project
files in the repo — 8 packages parsed, 316 reused from cache, all
completed without errors
2. **Query testing on multiple projects:**
   - `ColorPickerUI` — verified Windows SDK baseline (7,023 types)
- `Microsoft.CmdPal.UI.ViewModels` (after restore) — verified 13
packages, 49,799 types, 112,131 members including WinAppSDK,
AdaptiveCards, CsWinRT, Win32Metadata
   - `runner` (C++ vcxproj) — verified packages.config fallback path
   - `ImageResizerExt` — verified project reference WinMD discovery
3. **All seven query actions validated:** `stats`, `search`,
`namespaces`, `type`, `enums`, `members`, `projects` — all returned
correct results
4. **Spell-check compliance:** SKILL.md vocabulary reviewed against
repo's check-spelling dictionaries; replaced flagged words with standard
alternatives

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Gordon Lam
2026-03-11 10:15:32 +08:00
committed by GitHub
parent 70e082ce4f
commit eeeb6c0c93
9 changed files with 2186 additions and 0 deletions

192
.github/skills/winmd-api-search/SKILL.md vendored Normal file
View File

@@ -0,0 +1,192 @@
---
name: winmd-api-search
description: 'Find and explore Windows desktop APIs. Use when building features that need platform capabilities — camera, file access, notifications, UI controls, AI/ML, sensors, networking, etc. Discovers the right API for a task and retrieves full type details (methods, properties, events, enumeration values).'
license: Complete terms in LICENSE.txt
---
# WinMD API Search
This skill helps you find the right Windows API for any capability and get its full details. It searches a local cache of all WinMD metadata from:
- **Windows Platform SDK** — all `Windows.*` WinRT APIs (always available, no restore needed)
- **WinAppSDK / WinUI** — bundled as a baseline in the cache generator (always available, no restore needed)
- **NuGet packages** — any additional packages in restored projects that contain `.winmd` files
- **Project-output WinMD** — class libraries (C++/WinRT, C#) that produce `.winmd` as build output
Even on a fresh clone with no restore or build, you still get full Platform SDK + WinAppSDK coverage.
## When to Use This Skill
- User wants to build a feature and you need to find which API provides that capability
- User asks "how do I do X?" where X involves a platform feature (camera, files, notifications, sensors, AI, etc.)
- You need the exact methods, properties, events, or enumeration values of a type before writing code
- You're unsure which control, class, or interface to use for a UI or system task
## Prerequisites
- **.NET SDK 8.0 or later** — required to build the cache generator. Install from [dotnet.microsoft.com](https://dotnet.microsoft.com/download) if not available.
## Cache Setup (Required Before First Use)
All query and search commands read from a local JSON cache. **You must generate the cache before running any queries.**
```powershell
# All projects in the repo (recommended for first run)
.\.github\skills\winmd-api-search\scripts\Update-WinMdCache.ps1
# Single project
.\.github\skills\winmd-api-search\scripts\Update-WinMdCache.ps1 -ProjectDir <project-folder>
```
No project restore or build is needed for baseline coverage (Platform SDK + WinAppSDK). For additional NuGet packages, the project needs `dotnet restore` (which generates `project.assets.json`) or a `packages.config` file.
Cache is stored at `Generated Files\winmd-cache\`, deduplicated per-package+version.
### What gets indexed
| Source | When available |
|--------|----------------|
| Windows Platform SDK | Always (reads from local SDK install) |
| WinAppSDK (latest) | Always (bundled as baseline in cache generator) |
| WinAppSDK Runtime | When installed on the system (detected via `Get-AppxPackage`) |
| Project NuGet packages | After `dotnet restore` or with `packages.config` |
| Project-output `.winmd` | After project build (class libraries that produce WinMD) |
> **Note:** This cache directory should be in `.gitignore` — it's generated, not source.
## How to Use
Pick the path that matches the situation:
---
### Discover — "I don't know which API to use"
The user describes a capability in their own words. You need to find the right API.
**0. Ensure the cache exists**
If the cache hasn't been generated yet, run `Update-WinMdCache.ps1` first — see [Cache Setup](#cache-setup-required-before-first-use) above.
**1. Translate user language → search keywords**
Map the user's daily language to programming terms. Try multiple variations:
| User says | Search keywords to try (in order) |
|-----------|-----------------------------------|
| "take a picture" | `camera`, `capture`, `photo`, `MediaCapture` |
| "load from disk" | `file open`, `picker`, `FileOpen`, `StorageFile` |
| "describe what's in it" | `image description`, `Vision`, `Recognition` |
| "show a popup" | `dialog`, `flyout`, `popup`, `ContentDialog` |
| "drag and drop" | `drag`, `drop`, `DragDrop` |
| "save settings" | `settings`, `ApplicationData`, `LocalSettings` |
Start with simple everyday words. If results are weak or irrelevant, try the more technical variation.
**2. Run searches**
```powershell
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action search -Query "<keyword>"
```
This returns ranked namespaces with top matching types and the **JSON file path**.
If results have **low scores (below 60) or are irrelevant**, fall back to searching online documentation:
1. Use web search to find the right API on Microsoft Learn, for example:
- `site:learn.microsoft.com/uwp/api <capability keywords>` for `Windows.*` APIs
- `site:learn.microsoft.com/windows/windows-app-sdk/api/winrt <capability keywords>` for `Microsoft.*` WinAppSDK APIs
2. Read the documentation pages to identify which type matches the user's requirement.
3. Once you know the type name, come back and use `-Action members` or `-Action enums` to get the exact local signatures.
**3. Read the JSON to choose the right API**
Read the file at the path(s) from the top results. The JSON has all types in that namespace — full members, signatures, parameters, return types, enumeration values.
Read and decide which types and members fit the user's requirement.
**4. Look up official documentation for context**
The cache contains only signatures — no descriptions or usage guidance. For explanations, examples, and remarks, look up the type on Microsoft Learn:
| Namespace prefix | Documentation base URL |
|-----------------|----------------------|
| `Windows.*` | `https://learn.microsoft.com/uwp/api/{fully.qualified.typename}` |
| `Microsoft.*` (WinAppSDK) | `https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/{fully.qualified.typename}` |
For example, `Microsoft.UI.Xaml.Controls.NavigationView` maps to:
`https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.navigationview`
**5. Use the API knowledge to answer or write code**
---
### Lookup — "I know the API, show me the details"
You already know (or suspect) the type or namespace name. Go direct:
```powershell
# Get all members of a known type
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action members -TypeName "Microsoft.UI.Xaml.Controls.NavigationView"
# Get enum values
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action enums -TypeName "Microsoft.UI.Xaml.Visibility"
# List all types in a namespace
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action types -Namespace "Microsoft.UI.Xaml.Controls"
# Browse namespaces
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action namespaces -Filter "Microsoft.UI"
```
If you need full detail beyond what `-Action members` shows, use `-Action search` to get the JSON file path, then read the JSON file directly.
---
### Other Commands
```powershell
# List cached projects
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action projects
# List packages for a project
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action packages
# Show stats
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action stats
```
> If only one project is cached, `-Project` is auto-selected.
> If multiple projects exist, add `-Project <name>` (use `-Action projects` to see available names).
> In scan mode, manifest names include a short hash suffix to avoid collisions; you can pass the base project name without the suffix if it's unambiguous.
## Search Scoring
The search ranks type names and member names against your query:
| Score | Match type | Example |
|-------|-----------|---------|
| 100 | Exact name | `Button``Button` |
| 80 | Starts with | `Navigation``NavigationView` |
| 60 | Contains | `Dialog``ContentDialog` |
| 50 | PascalCase initials | `ASB``AutoSuggestBox` |
| 40 | Multi-keyword AND | `navigation item``NavigationViewItem` |
| 20 | Fuzzy character match | `NavVw``NavigationView` |
Results are grouped by namespace. Higher-scored namespaces appear first.
## Troubleshooting
| Issue | Fix |
|-------|-----|
| "Cache not found" | Run `Update-WinMdCache.ps1` |
| "Multiple projects cached" | Add `-Project <name>` |
| "Namespace not found" | Use `-Action namespaces` to list available ones |
| "Type not found" | Use fully qualified name (e.g., `Microsoft.UI.Xaml.Controls.Button`) |
| Stale after NuGet update | Re-run `Update-WinMdCache.ps1` |
| Cache in git history | Add `Generated Files/` to `.gitignore` |
## References
- [Windows Platform SDK API reference](https://learn.microsoft.com/uwp/api/) — documentation for `Windows.*` namespaces
- [Windows App SDK API reference](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/) — documentation for `Microsoft.*` WinAppSDK namespaces