mirror of
https://github.com/okieselbach/AutopilotMonitor.git
synced 2026-10-24 20:53:06 +00:00
Compare commits
90 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 66452621c6 | |||
| 0b23d93957 | |||
| 4281a6d81b | |||
| fe919a51aa | |||
| 0dcf0eb503 | |||
| e2fb99d5d8 | |||
| a3ee613b60 | |||
| d2197c6a57 | |||
| e5997bc50e | |||
| 75138016ce | |||
| fc4772efb0 | |||
| 0bde428fa0 | |||
| 16ca3a059c | |||
| 1bfc80e6db | |||
| fa705a2ef6 | |||
| 81f807e124 | |||
| a4f7c88785 | |||
| 54259f070f | |||
| 26cef3ab06 | |||
| 00ad230ffe | |||
| 3d920a8113 | |||
| f6eac1964a | |||
| e1b5b9d163 | |||
| 094833f831 | |||
| 3579ce0add | |||
| 0188860d1c | |||
| 871a1ac059 | |||
| 298a182fbb | |||
| e71223507c | |||
| 02187f0f3c | |||
| 3e2f62daeb | |||
| c8b8a8dbb4 | |||
| 9e4c5f11c5 | |||
| b16e72c10e | |||
| 5cb9b0b30b | |||
| c925001a8a | |||
| e494334720 | |||
| 1554540431 | |||
| fef09690d2 | |||
| 3a975fa74f | |||
| 69c6353fb1 | |||
| 2b9bf3cd3f | |||
| d99e16314b | |||
| e4203e0f15 | |||
| 2a5366d9c3 | |||
| 9c9cf24ddc | |||
| ec0d8ad735 | |||
| fc9e9d13e6 | |||
| d0cb7e66f4 | |||
| bd66480ccc | |||
| b05f1f6bcf | |||
| 12ad9c9436 | |||
| c8ce7cdb37 | |||
| 56d4dd8b84 | |||
| 86fdc5aca9 | |||
| 87c5bc59dc | |||
| 21b30b21c2 | |||
| f94f1c0c4e | |||
| a6a9883451 | |||
| 03116a97d1 | |||
| 2abc78ab6d | |||
| 6e54b52376 | |||
| 7cef2ea361 | |||
| 5b5ee0e8fd | |||
| 7bcc4f00b1 | |||
| 34ec44e3d4 | |||
| f607e21c13 | |||
| 5940e9fc6a | |||
| 98cfd76232 | |||
| 09e68a614f | |||
| 88290caadc | |||
| f442dce9a4 | |||
| 4f03f39e9a | |||
| 38b667799c | |||
| a5f74d6abc | |||
| d0e09301a1 | |||
| 177915ea6b | |||
| b89008e745 | |||
| cfa1cbbed2 | |||
| aa1881ec44 | |||
| 744e35ee9b | |||
| 884b74cb8c | |||
| 67316a0fbd | |||
| 501f994c7a | |||
| c38f0cf2b0 | |||
| 729ee56bde | |||
| f0a3f04398 | |||
| 49013c3cc4 | |||
| 32cbc3620e | |||
| ae9c1b0744 |
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Agent Directives
|
||||
|
||||
- **Plan first.** Enter plan mode for any non-trivial task (3+ steps or an architectural decision) and write the spec before building. If something goes sideways, stop and re-plan instead of pushing on.
|
||||
- **Plan first.** Enter plan mode for any non-trivial task (3+ steps or an architectural decision) and write the spec before building. The plan file is `internal/work/plans/<slug>.md` from the first draft; the harness plan folder outside the repo is never the storage place, at most a copy for the approval dialog. If something goes sideways, stop and re-plan instead of pushing on.
|
||||
- **Use subagents liberally** for research, exploration, and parallel analysis — one focus each — to keep the main context clean.
|
||||
- **Verify before claiming done.** Run the tests, check the logs, show the evidence. Diff against `main` where behaviour could regress.
|
||||
- **Fix bugs autonomously.** Given a report, a failing test, or an error, resolve it — no hand-holding.
|
||||
|
||||
+1
-1
Submodule .claude/commands updated: 4bb1f7142f...9b48783b26
@@ -27,6 +27,10 @@ on:
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
release_notes:
|
||||
description: 'Customer-facing notes for the GitHub Release (Markdown bullets). Empty = generic fallback linking to the docs changelog'
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -326,7 +330,13 @@ jobs:
|
||||
|
||||
# First-party `gh` instead of a third-party action: this job holds contents:write,
|
||||
# id-token:write and attestations:write, so no code we do not control runs here.
|
||||
# --generate-notes appends the auto-generated notes below the body.
|
||||
# The "What's new" section comes ONLY from the release_notes input -- CI never
|
||||
# composes customer-facing text from commits. An empty input writes a generic
|
||||
# fallback that links to the docs changelog and carries the HTML-comment marker
|
||||
# below; the operator tooling scans release bodies for that marker to find the
|
||||
# last release with real notes, so the next noted release covers the gap.
|
||||
# Never rename the marker. --generate-notes is not used: it lists pull requests
|
||||
# only (Dependabot noise); the compare link to the previous tag replaces it.
|
||||
- name: Create GitHub Release
|
||||
if: inputs.create_release
|
||||
shell: pwsh
|
||||
@@ -336,19 +346,8 @@ jobs:
|
||||
RELEASE_NAME: Autopilot Monitor Agent ${{ steps.version.outputs.version }}
|
||||
RELEASE_PRERELEASE: ${{ inputs.prerelease }}
|
||||
RELEASE_ZIP: ${{ steps.artifact.outputs.versioned_zip_release }}
|
||||
RELEASE_BODY: |
|
||||
## Autopilot Monitor Agent ${{ steps.version.outputs.version }}
|
||||
|
||||
### Installation
|
||||
1. Download `AutopilotMonitor-Agent-v${{ steps.version.outputs.version }}.zip`
|
||||
2. Extract to `C:\ProgramData\AutopilotMonitor\Agent\`
|
||||
3. Run `AutopilotMonitor.Agent.exe --install` to register the Scheduled Task
|
||||
|
||||
### Included Components
|
||||
- **AutopilotMonitor.Agent.exe** - Monitoring agent (V2 release line)
|
||||
- **AutopilotMonitor.SummaryDialog.exe** - Enrollment summary dialog (WPF)
|
||||
- **version-v2.json** - Per-line version manifest
|
||||
|
||||
RELEASE_NOTES: ${{ inputs.release_notes }}
|
||||
RELEASE_BODY_TAIL: |
|
||||
### Version Info
|
||||
- **Version:** ${{ steps.version.outputs.version }}
|
||||
- **Build Number:** ${{ steps.version.outputs.build_number }}
|
||||
@@ -363,8 +362,29 @@ jobs:
|
||||
```
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$notes = "$env:RELEASE_NOTES".Trim()
|
||||
if ($notes -eq '') {
|
||||
$notes = "Minor enhancements and bug fixes. See the [Agent Changelog](https://docs.autopilotmonitor.com/changelog/agent-changelog) for details.`n<!-- release-notes: none -->"
|
||||
}
|
||||
|
||||
# Previous release for the compare link. Fail-soft: the first release has none,
|
||||
# and a listing hiccup must never fail a release.
|
||||
$prevTag = ''
|
||||
$eap = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
$prevTag = "$(gh release list --repo $env:GITHUB_REPOSITORY --limit 1 --exclude-drafts --json tagName -q '.[0].tagName' 2>$null)".Trim()
|
||||
} catch { $prevTag = '' }
|
||||
$ErrorActionPreference = $eap
|
||||
$compare = ''
|
||||
if ($prevTag -ne '' -and $prevTag -ne $env:RELEASE_TAG) {
|
||||
$compare = "`n`n**Full changelog:** https://github.com/$env:GITHUB_REPOSITORY/compare/$prevTag...$env:RELEASE_TAG`n"
|
||||
}
|
||||
|
||||
$body = "### What's new`n$notes`n`n" + "$env:RELEASE_BODY_TAIL".TrimEnd() + $compare
|
||||
$notesFile = Join-Path $env:RUNNER_TEMP 'release-notes.md'
|
||||
Set-Content -Path $notesFile -Value $env:RELEASE_BODY -Encoding utf8 -NoNewline
|
||||
Set-Content -Path $notesFile -Value $body -Encoding utf8 -NoNewline
|
||||
|
||||
$ghArgs = @(
|
||||
'release', 'create', $env:RELEASE_TAG,
|
||||
@@ -372,8 +392,7 @@ jobs:
|
||||
'--repo', $env:GITHUB_REPOSITORY,
|
||||
'--target', $env:GITHUB_SHA,
|
||||
'--title', $env:RELEASE_NAME,
|
||||
'--notes-file', $notesFile,
|
||||
'--generate-notes'
|
||||
'--notes-file', $notesFile
|
||||
)
|
||||
if ($env:RELEASE_PRERELEASE -eq 'true') { $ghArgs += '--prerelease' }
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ name: CI
|
||||
# red run reports rather than blocks. Read the result and follow up.
|
||||
#
|
||||
# Path filters: commits that only bump a private submodule gitlink (internal/, infra/,
|
||||
# .claude/commands) or touch prose cannot change anything the suites cover, so they are
|
||||
# skipped instead of burning ~15 runner-minutes each. A gitlink bump reports the bare
|
||||
# .claude/commands), touch prose or edit another workflow cannot change anything the
|
||||
# suites cover, so they are skipped instead of burning ~15 runner-minutes each. A gitlink bump reports the bare
|
||||
# path ('internal', no trailing slash), which 'internal/**' does NOT match — both forms
|
||||
# are listed. GitHub skips only when EVERY changed path matches; a commit that touches
|
||||
# docs AND code still runs.
|
||||
@@ -30,6 +30,23 @@ on:
|
||||
- '.github/FUNDING.yml'
|
||||
- '.github/dependabot.yml'
|
||||
- '.github/assets/**'
|
||||
- '.github/codeql/**'
|
||||
- '.github/scripts/**'
|
||||
# Every other workflow: nothing here builds or tests anything CI covers. paths-ignore
|
||||
# cannot negate, so they are listed one by one; ci.yml itself stays out of the list
|
||||
# so a change to CI runs CI. A new workflow file is opt-in — add it here too.
|
||||
- '.github/workflows/bootstrap-script-gates.yml'
|
||||
- '.github/workflows/build-agent.yml'
|
||||
- '.github/workflows/build-msi.yml'
|
||||
- '.github/workflows/codeql.yml'
|
||||
- '.github/workflows/combine-rules.yml'
|
||||
- '.github/workflows/deploy-backend.yml'
|
||||
- '.github/workflows/deploy-mcp.yml'
|
||||
- '.github/workflows/deploy-web.yml'
|
||||
- '.github/workflows/indexnow-notify.yml'
|
||||
- '.github/workflows/oidc-login-test.yml'
|
||||
- '.github/workflows/pester.yml'
|
||||
- '.github/workflows/publish-scripts.yml'
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
@@ -45,6 +62,23 @@ on:
|
||||
- '.github/FUNDING.yml'
|
||||
- '.github/dependabot.yml'
|
||||
- '.github/assets/**'
|
||||
- '.github/codeql/**'
|
||||
- '.github/scripts/**'
|
||||
# Every other workflow: nothing here builds or tests anything CI covers. paths-ignore
|
||||
# cannot negate, so they are listed one by one; ci.yml itself stays out of the list
|
||||
# so a change to CI runs CI. A new workflow file is opt-in — add it here too.
|
||||
- '.github/workflows/bootstrap-script-gates.yml'
|
||||
- '.github/workflows/build-agent.yml'
|
||||
- '.github/workflows/build-msi.yml'
|
||||
- '.github/workflows/codeql.yml'
|
||||
- '.github/workflows/combine-rules.yml'
|
||||
- '.github/workflows/deploy-backend.yml'
|
||||
- '.github/workflows/deploy-mcp.yml'
|
||||
- '.github/workflows/deploy-web.yml'
|
||||
- '.github/workflows/indexnow-notify.yml'
|
||||
- '.github/workflows/oidc-login-test.yml'
|
||||
- '.github/workflows/pester.yml'
|
||||
- '.github/workflows/publish-scripts.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -6,7 +6,7 @@ name: CodeQL
|
||||
# A gitlink bump reports the bare path ('internal', no trailing slash), which
|
||||
# 'internal/**' does NOT match — both forms are listed. A commit that touches docs
|
||||
# AND code still runs: GitHub skips only when EVERY changed path matches the filter.
|
||||
# Same list as ci.yml; keep them in step.
|
||||
# Same list as ci.yml except that each file leaves itself out; keep them in step.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
@@ -23,6 +23,22 @@ on:
|
||||
- '.github/FUNDING.yml'
|
||||
- '.github/dependabot.yml'
|
||||
- '.github/assets/**'
|
||||
- '.github/scripts/**'
|
||||
# Every other workflow: none of them changes the C# or TypeScript CodeQL analyzes.
|
||||
# paths-ignore cannot negate, so they are listed one by one; codeql.yml itself and
|
||||
# .github/codeql/ stay out of the list. A new workflow file is opt-in — add it here too.
|
||||
- '.github/workflows/bootstrap-script-gates.yml'
|
||||
- '.github/workflows/build-agent.yml'
|
||||
- '.github/workflows/build-msi.yml'
|
||||
- '.github/workflows/ci.yml'
|
||||
- '.github/workflows/combine-rules.yml'
|
||||
- '.github/workflows/deploy-backend.yml'
|
||||
- '.github/workflows/deploy-mcp.yml'
|
||||
- '.github/workflows/deploy-web.yml'
|
||||
- '.github/workflows/indexnow-notify.yml'
|
||||
- '.github/workflows/oidc-login-test.yml'
|
||||
- '.github/workflows/pester.yml'
|
||||
- '.github/workflows/publish-scripts.yml'
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
@@ -38,6 +54,22 @@ on:
|
||||
- '.github/FUNDING.yml'
|
||||
- '.github/dependabot.yml'
|
||||
- '.github/assets/**'
|
||||
- '.github/scripts/**'
|
||||
# Every other workflow: none of them changes the C# or TypeScript CodeQL analyzes.
|
||||
# paths-ignore cannot negate, so they are listed one by one; codeql.yml itself and
|
||||
# .github/codeql/ stay out of the list. A new workflow file is opt-in — add it here too.
|
||||
- '.github/workflows/bootstrap-script-gates.yml'
|
||||
- '.github/workflows/build-agent.yml'
|
||||
- '.github/workflows/build-msi.yml'
|
||||
- '.github/workflows/ci.yml'
|
||||
- '.github/workflows/combine-rules.yml'
|
||||
- '.github/workflows/deploy-backend.yml'
|
||||
- '.github/workflows/deploy-mcp.yml'
|
||||
- '.github/workflows/deploy-web.yml'
|
||||
- '.github/workflows/indexnow-notify.yml'
|
||||
- '.github/workflows/oidc-login-test.yml'
|
||||
- '.github/workflows/pester.yml'
|
||||
- '.github/workflows/publish-scripts.yml'
|
||||
schedule:
|
||||
# Weekly, so advisories published after a merge still surface. Deliberately
|
||||
# unfiltered — it re-analyzes the whole tree regardless of what changed, which
|
||||
|
||||
@@ -1,33 +1,63 @@
|
||||
# <img src=".github/assets/logo.svg" height="28" alt="" /> Autopilot Monitor
|
||||
# <img src=".github/assets/logo.svg" height="28" alt="Autopilot Monitor logo" /> Autopilot Monitor
|
||||
|
||||
[](https://www.autopilotmonitor.com)
|
||||
[](LICENSE)
|
||||
[](https://www.autopilotmonitor.com)
|
||||
|
||||
Advanced monitoring and troubleshooting solution for Windows Autopilot deployments. Gain full visibility into every enrollment session with a detailed event timeline, fleet health dashboards, and session reporting. Define custom analysis rules to automatically detect issues and gather rules to collect targeted evidence. Retrieve diagnostics packages on demand, configure agent settings like auto-reboot behavior and automatic timezone adjustment — all managed centrally from the web dashboard.
|
||||
Autopilot Monitor is an open-source, real-time monitoring and troubleshooting platform for **Windows Autopilot** and **Microsoft Intune** enrollment. It records enrollment events, application installations, policies, device state, and diagnostics while provisioning is still running, instead of collecting logs by hand after a failure. Administrators get live enrollment tracking, Enrollment Status Page (ESP) visibility, detailed session timelines, automated issue detection, on-demand diagnostics, fleet health analytics, and AI-assisted troubleshooting through a hosted Model Context Protocol (MCP) server.
|
||||
|
||||
The platform supports classic Windows Autopilot and modern Intune provisioning scenarios, including **Windows Autopilot Device Preparation**.
|
||||
|
||||
## Availability
|
||||
|
||||
Autopilot Monitor is **publicly available** — the Community plan is free. Sign in with your work account at **[autopilotmonitor.com](https://www.autopilotmonitor.com)**; new organizations complete a short activation step after first sign-in.
|
||||
|
||||
<p align="center">
|
||||
<img src=".github/assets/SessionList.png" width="45%" />
|
||||
<img src=".github/assets/FleetHealth.png" width="45%" />
|
||||
<img src=".github/assets/SessionList.png" width="45%" alt="Autopilot Monitor dashboard showing live Windows Autopilot and Intune enrollment sessions" />
|
||||
<img src=".github/assets/FleetHealth.png" width="45%" alt="Autopilot Monitor fleet health dashboard with Windows Autopilot enrollment analytics and success metrics" />
|
||||
</p>
|
||||
<p align="center">
|
||||
<img src=".github/assets/SessionDetails.png" width="45%" />
|
||||
<img src=".github/assets/SessionTimeline.png" width="45%" />
|
||||
<img src=".github/assets/SessionDetails.png" width="45%" alt="Autopilot Monitor session details showing device information, diagnostics, apps, policies, and enrollment status" />
|
||||
<img src=".github/assets/SessionTimeline.png" width="45%" alt="Windows Autopilot enrollment timeline showing ESP phases, application installs, policies, events, and errors" />
|
||||
</p>
|
||||
|
||||
## Overview
|
||||
## Key Features
|
||||
|
||||
Autopilot Monitor provides real-time tracking, intelligent diagnostics, and automated troubleshooting for Windows Autopilot enrollment processes. It consists of:
|
||||
- **Real-time Windows Autopilot monitoring** — follow device provisioning while enrollment is still running
|
||||
- **Detailed enrollment timelines** — correlate Autopilot, ESP, Intune Management Extension, apps, policies, device state, and system events
|
||||
- **Enrollment Status Page visibility** — see which phase, application, or policy is delaying provisioning
|
||||
- **Automated issue detection** — define custom analysis rules that identify known failure patterns
|
||||
- **Targeted evidence collection** — gather registry values, event log entries, files, log-parser matches, and allow-listed commands when specific conditions are detected
|
||||
- **On-demand diagnostics** — request diagnostics packages from enrolled devices remotely
|
||||
- **Fleet health analytics** — success rates, deployment duration, device models, applications, errors, and recurring issues
|
||||
- **Session reporting** — inspect and share detailed enrollment information for individual devices
|
||||
- **Windows Autopilot Device Preparation support** — monitor Device Preparation deployments alongside classic Autopilot scenarios
|
||||
- **Centralized agent configuration** — control diagnostic behavior, automatic reboots, timezone adjustment, and other monitoring settings from the web dashboard
|
||||
- **AI-assisted troubleshooting** — query enrollment data through the built-in Model Context Protocol server
|
||||
|
||||
- **Bootstrap Script** — PowerShell script deployed via Intune that starts monitoring early in the enrollment process
|
||||
- **Monitoring Agent** — Lightweight .NET application that collects telemetry and evidence during enrollment
|
||||
## How it works
|
||||
|
||||
Autopilot Monitor consists of several components working together throughout Windows enrollment:
|
||||
|
||||
- **Bootstrap Script** — PowerShell script deployed through Microsoft Intune that starts monitoring early in the provisioning process
|
||||
- **Monitoring Agent** — lightweight .NET application that collects telemetry and evidence during enrollment
|
||||
- **Backend API** — Azure Functions-based ingestion and processing pipeline
|
||||
- **Web Dashboard** — Next.js application for real-time monitoring and fleet analytics
|
||||
- **MCP Server** — Model Context Protocol server that lets AI assistants query and troubleshoot enrollments in natural language
|
||||
- **Web Dashboard** — Next.js application for real-time monitoring, troubleshooting, and fleet analytics
|
||||
- **MCP Server** — Model Context Protocol server that lets AI assistants query Autopilot Monitor data in natural language
|
||||
|
||||
## Windows Autopilot and Intune Troubleshooting
|
||||
|
||||
Autopilot Monitor helps investigate common Windows provisioning and enrollment problems such as:
|
||||
|
||||
- Windows Autopilot deployments that fail or appear stuck
|
||||
- Enrollment Status Page (ESP) delays and unusually long deployment phases
|
||||
- Win32 application installation failures and slow application downloads
|
||||
- Intune Management Extension problems
|
||||
- Microsoft Entra join, Hybrid Join, and device registration issues
|
||||
- policies that block or delay provisioning
|
||||
- inconsistent behavior across hardware models and recurring failures affecting multiple devices
|
||||
|
||||
Because telemetry is collected during enrollment, many problems can be investigated without reproducing the issue or manually collecting logs from the affected device.
|
||||
|
||||
## AI Integration (MCP)
|
||||
|
||||
@@ -35,13 +65,19 @@ Autopilot Monitor ships a hosted **[Model Context Protocol](https://modelcontext
|
||||
|
||||
- *"Show me all failed enrollments from the last 24 hours and group them by failure reason."*
|
||||
- *"Why did session X fail, and which app install caused the delay?"*
|
||||
- *"Which devices had unusually long ESP application phases this week?"*
|
||||
- *"Which device models have the highest Autopilot failure rate?"*
|
||||
- *"Which devices in my fleet are affected by CVE-2024-30078?"*
|
||||
|
||||
Server URL: `https://mcp.autopilotmonitor.com/mcp` — sign-in runs through your existing work account, access is scoped to your tenant exactly like in the portal, and no credentials are stored. Setup guide: **[AI Integration (MCP)](https://docs.autopilotmonitor.com/integrations/ai-integration-mcp)**.
|
||||
Server URL: `https://mcp.autopilotmonitor.com/mcp` — sign-in runs through your existing work account, access is scoped to your tenant exactly like in the portal, and the MCP server stores no credentials. Setup guide: **[AI Integration (MCP)](https://docs.autopilotmonitor.com/integrations/ai-integration-mcp)**.
|
||||
|
||||
## Documentation
|
||||
|
||||
Full admin documentation is available at **[docs.autopilotmonitor.com](https://docs.autopilotmonitor.com)**
|
||||
Full admin documentation is available at **[docs.autopilotmonitor.com](https://docs.autopilotmonitor.com)** — deployment, configuration, monitoring, diagnostics, troubleshooting, analysis and gather rules, integrations, and AI-assisted troubleshooting.
|
||||
|
||||
## Open Source
|
||||
|
||||
Autopilot Monitor is developed openly on GitHub. The source is published so that customers and security reviewers can see what runs on their devices and with their data: the repository contains the device agent, shared library, backend, web dashboard, and MCP server.
|
||||
|
||||
## Feedback
|
||||
|
||||
|
||||
+1
-1
Submodule infra updated: 3bab9bbf83...2c2687b6ab
+1
-1
Submodule internal updated: cd935442a2...2496a42aa8
@@ -5,7 +5,7 @@
|
||||
"description": "Detects when the Enrollment Status Page failed on the Apps subcategory and the agent's AppX deployment log scan identified a suspected MSIX/Store package. Store/MSIX apps install outside the Win32 pipeline, so the regular per-app tracking sees nothing — this correlation names the likely culprit.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
@@ -93,7 +93,7 @@
|
||||
"steps": [
|
||||
"Open Event Viewer → Applications and Services Logs → Microsoft → Windows → AppXDeploymentServer → Operational on the device (or in the diagnostics archive if uploaded)",
|
||||
"Filter for Error-level events around the ESP failure time and confirm the package name and HRESULT match this finding",
|
||||
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = invalid/corrupt package, 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
|
||||
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = package could not be opened (unsigned, publisher mismatch, or not found), 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"$schema": "../schema/analyze-rule.schema.json",
|
||||
"ruleId": "ANALYZE-APP-018",
|
||||
"title": "App Return Code Requested a Reboot During Enrollment",
|
||||
"description": "Detects Win32 apps whose installer exit code maps to Soft reboot or Hard reboot in the app's Intune return-code table (the '[Win32App] lpExitCode is defined as ...' line). Hard reboot stops app processing and restarts the device in Device Setup - the mid-enrollment restart and second sign-in; Soft reboot leaves the app pending until the next restart while the ESP moves on. Confidence rises for Hard reboot and when a reboot was actually observed in the session.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
"whiteglove_sealed"
|
||||
],
|
||||
"trigger": "single",
|
||||
"baseConfidence": 60,
|
||||
"conditions": [
|
||||
{
|
||||
"signal": "reboot_return_code",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_completed",
|
||||
"dataField": "exitCodeClass",
|
||||
"operator": "in",
|
||||
"value": "SoftReboot,HardReboot",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "hard_reboot_return_code",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_completed",
|
||||
"dataField": "exitCodeClass",
|
||||
"operator": "equals",
|
||||
"value": "HardReboot",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"signal": "reboot_observed",
|
||||
"source": "event_count",
|
||||
"eventType": "system_reboot_detected",
|
||||
"operator": "count_gte",
|
||||
"value": "1",
|
||||
"required": false
|
||||
}
|
||||
],
|
||||
"confidenceFactors": [
|
||||
{
|
||||
"signal": "hard_reboot_return_code",
|
||||
"condition": "exists",
|
||||
"weight": 25
|
||||
},
|
||||
{
|
||||
"signal": "reboot_observed",
|
||||
"condition": "exists",
|
||||
"weight": 15
|
||||
}
|
||||
],
|
||||
"confidenceThreshold": 60,
|
||||
"explanation": "App **{{appName}}** returned exit code **{{exitCode}}**, which its Intune return-code table maps to **{{exitCodeClass}}** - the installer asked for a restart before its work is complete.\n\n- **SoftReboot**: the Intune Management Extension reports the app as *pending reboot*. The Enrollment Status Page treats it as completed and moves on, and Intune only marks the app installed after the next restart re-evaluates the detection rule. Until then the app may be unusable or half-configured, and the user sees a restart notification.\n- **HardReboot**: the Intune Management Extension stops processing further apps and, in Device Setup, restarts the device right away (the restart grace period does not apply during the ESP) - the same mid-enrollment restart and second sign-in that ANALYZE-ESP-005 attributes to reboot-required policies. In Account Setup the extension does not restart the device itself and the app stays pending.\n\nA restart requested by an installer is normal for many MSI packages (exit codes 3010 and 1641), but during Autopilot it lengthens the ESP, can surprise the user with a restart, and hides the app's real state until after the reboot. The return-code class is the app's own configuration in Intune, not a device fault.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Check the app's return-code mapping",
|
||||
"steps": [
|
||||
"Open the app in the Intune admin center > Properties > Program and review the return codes table: exit code {{exitCode}} is currently mapped to {{exitCodeClass}}",
|
||||
"If the installer only recommends a restart (MSI 3010 ERROR_SUCCESS_REBOOT_REQUIRED, 1641 ERROR_SUCCESS_REBOOT_INITIATED), map the code to Soft reboot instead of Hard reboot so the next app can install before the restart",
|
||||
"If the app works without an immediate restart, suppress the installer's own reboot (for MSI: REBOOT=ReallySuppress on the install command) so it returns 0 and the restart happens on your schedule",
|
||||
"Keep Hard reboot only when the following apps genuinely cannot install before the restart - and then expect the mid-ESP restart in every enrollment"
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "Take the app out of the ESP critical path",
|
||||
"steps": [
|
||||
"If the app is not needed for first use, remove it from the ESP blocking-app list so the restart happens after the user reaches the desktop",
|
||||
"If it must stay blocking, order it last in Device Setup (dependencies or install order) so a hard reboot does not interrupt the remaining apps",
|
||||
"For Soft reboot apps, plan a restart at the end of enrollment or accept that the app finishes on the user's first restart"
|
||||
]
|
||||
}
|
||||
],
|
||||
"relatedDocs": [
|
||||
{
|
||||
"title": "Microsoft Learn: Add a Win32 app - Program step (device restart behavior and return codes)",
|
||||
"url": "https://learn.microsoft.com/en-us/intune/app-management/deployment/add-win32#step-2-program"
|
||||
},
|
||||
{
|
||||
"title": "Microsoft Learn: Enrollment Status Page tracking",
|
||||
"url": "https://learn.microsoft.com/en-us/autopilot/enrollment-status"
|
||||
}
|
||||
],
|
||||
"markSessionAsFailedDefault": false,
|
||||
"tags": [
|
||||
"apps",
|
||||
"reboot",
|
||||
"return-code",
|
||||
"soft-reboot",
|
||||
"hard-reboot",
|
||||
"esp",
|
||||
"second-sign-in"
|
||||
]
|
||||
}
|
||||
@@ -2,10 +2,10 @@
|
||||
"$schema": "../schema/analyze-rule.schema.json",
|
||||
"ruleId": "ANALYZE-DEV-012",
|
||||
"title": "Device Entered Standby During Enrollment",
|
||||
"description": "Detects that the device completed a sleep, hibernate or Modern Standby episode of at least 5 minutes while the enrollment was running (system_sleep_episode event from the agent's system timeline watcher, recorded retroactively at wake from the Windows event log — pre-agent episodes are backfilled). Uses a single required condition on the episode's durationSeconds so the match is pinned to one event instance and the interpolated duration is the matched value. Short Modern Standby screen-off scenarios (under 60 s of real sleep) never emit the event, and this rule adds a 5-minute floor so brief lid-close moments do not fire it.",
|
||||
"description": "Detects that the device completed a sleep, hibernate or Modern Standby episode of at least 5 minutes while the enrollment was running (system_sleep_episode event from the agent's system timeline watcher, recorded retroactively at wake from the Windows event log). The watcher also backfills pre-agent episodes from the last 24 h for timeline context (backfilled=true); those ended before the enrollment started and are excluded via the same-event filter backfilled equals false — a separate condition could not do that, because each condition scans all events on its own and a pre-session hibernate would still satisfy the duration test. A single required condition keeps the match pinned to one event instance so the interpolated duration is the matched value. Short Modern Standby screen-off scenarios (under 60 s of real sleep) never emit the event, and this rule adds a 5-minute floor so brief lid-close moments do not fire it.",
|
||||
"severity": "info",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
@@ -23,6 +23,9 @@
|
||||
"dataField": "durationSeconds",
|
||||
"operator": "gte",
|
||||
"value": "300",
|
||||
"filterField": "backfilled",
|
||||
"filterOperator": "equals",
|
||||
"filterValue": "false",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
"$schema": "../schema/analyze-rule.schema.json",
|
||||
"ruleId": "ANALYZE-ID-004",
|
||||
"title": "Hybrid Sign-In Never Establishes Entra User Affinity",
|
||||
"description": "On a hybrid-joined device the real user reached the desktop, but the Autopilot provisioning placeholder stayed active in JoinInfo and the agent repeatedly reported the hybrid sign-in as overdue. The user session never establishes Entra user affinity (no PRT), so the Account Setup ESP re-runs on every logon and the enrollment never completes.",
|
||||
"description": "On a hybrid-joined device the real user reached the desktop, but the Intune Management Extension never acquired a Microsoft Entra user token for that user within the wait window — repeatedly across reboots when the warning recurs. Without a user token the signed-in user has no Entra user affinity: user-targeted apps and policies cannot apply, Windows Hello for Business cannot provision, and with a user ESP the Account Setup page re-runs on every logon.",
|
||||
"severity": "high",
|
||||
"category": "identity",
|
||||
"version": "1.2.0",
|
||||
"version": "2.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"trigger": "correlation",
|
||||
"evaluateOn": ["enrollment_end", "on_event:hybrid_login_pending"],
|
||||
"evaluateOn": ["enrollment_end", "on_event:entra_user_affinity_pending"],
|
||||
"baseConfidence": 60,
|
||||
"confidenceThreshold": 75,
|
||||
"preconditions": [
|
||||
@@ -17,14 +17,14 @@
|
||||
"source": "event_data",
|
||||
"eventType": "enrollment_complete",
|
||||
"operator": "not_exists",
|
||||
"description": "Suppress when the session eventually completed — a single overdue-login warning followed by a successful sign-in is normal hybrid latency, not a broken affinity."
|
||||
"description": "Suppress when the session eventually completed — a single pending-affinity warning followed by a successful token acquisition is hybrid latency, not a broken affinity."
|
||||
}
|
||||
],
|
||||
"conditions": [
|
||||
{
|
||||
"signal": "hybrid_login_overdue",
|
||||
"signal": "user_affinity_pending",
|
||||
"source": "event_type",
|
||||
"eventType": "hybrid_login_pending",
|
||||
"eventType": "entra_user_affinity_pending",
|
||||
"operator": "exists",
|
||||
"value": "",
|
||||
"required": true
|
||||
@@ -38,28 +38,27 @@
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "placeholder_still_active",
|
||||
"signal": "no_user_token",
|
||||
"source": "event_type",
|
||||
"eventType": "aad_placeholder_user_detected",
|
||||
"operator": "exists",
|
||||
"eventType": "ime_user_token_acquired",
|
||||
"operator": "not_exists",
|
||||
"value": "",
|
||||
"required": false
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"confidenceFactors": [
|
||||
{ "signal": "hybrid_login_pending", "condition": "count >= 2", "weight": 20 },
|
||||
{ "signal": "hybrid_login_pending", "condition": "count >= 3", "weight": 10 },
|
||||
{ "signal": "aad_placeholder_user_detected", "condition": "count >= 3", "weight": 10 }
|
||||
{ "signal": "entra_user_affinity_pending", "condition": "count >= 2", "weight": 20 },
|
||||
{ "signal": "entra_user_affinity_pending", "condition": "count >= 3", "weight": 10 }
|
||||
],
|
||||
"explanation": "A real user signed in and reached the desktop, but the device kept reporting the **Autopilot provisioning placeholder** as the active identity in JoinInfo and the hybrid sign-in as **overdue** — across multiple reboots. This means the signed-in user never established **Microsoft Entra user affinity** (no Primary Refresh Token), so:\n\n- the Account Setup ESP page re-appears on every logon,\n- user-targeted required apps and policies cannot settle,\n- the enrollment never reaches completion.\n\nAfter this many hours this is not normal Entra Connect sync latency — something is structurally preventing the user (or the computer object) from registering:\n\n- the computer object's `userCertificate` attribute is not syncing to Entra ID (sync scope / OU filtering),\n- the signing-in user is not synced, or their UPN does not match a verified Entra domain,\n- the device has no line of sight to a domain controller **at logon time**, so the hybrid PRT flow cannot finish,\n- time skew or a proxy blocking `login.microsoftonline.com` / `enterpriseregistration.windows.net` from the user context.\n\nA frequent variant: the user's **first sign-in happens without domain-controller reachability** — for example when a pre-logon VPN tunnel (GlobalProtect, Always On VPN, Zscaler ZPA) is not established yet at the logon screen. Windows falls back to cached credentials, the hybrid PRT flow silently never runs, and later reboots do not fix it — sessions in this state typically show repeated reboots and network flapping while the placeholder identity stays active.\n\nA visible side effect: **the Windows Hello for Business wizard never appears**, because Hello provisioning requires an Entra user token (PRT). Hello is a downstream symptom here, not the cause.",
|
||||
"explanation": "**What was measured.** A real user signed in and reached the desktop (`desktop_arrived`), and by the end of the agent's wait window the Intune Management Extension (IME) had still not acquired a **Microsoft Entra user token** for that user (`entra_user_affinity_pending`). That event lists the IME token error codes observed after the desktop (`tokenFailureCodes`) and how often the acquisition failed (`tokenFailureCount`). Each agent run reports this at most once, so a second or third occurrence means the same outcome across reboots — that repetition is what raises the confidence of this finding. No `ime_user_token_acquired` event followed in this session.\n\n**Why this means no user affinity.** IME's user check-in acquires the user token through the Windows web account manager (WAM), which needs the signed-in user's Entra identity — the Primary Refresh Token (PRT) that a hybrid sign-in establishes at logon. When that PRT was never issued, every token request fails and the user has **no Entra user affinity** on this device. Consequences:\n\n- user-targeted required apps and policies cannot apply,\n- Windows Hello for Business cannot provision (it requires a user token),\n- with a user ESP the Account Setup page re-appears on every logon instead of completing.\n\n**What this diagnosis does not use.** The Autopilot provisioning placeholder in JoinInfo (`aad_placeholder_user_detected`) is not part of this finding — on hybrid devices it can stay present through a perfectly healthy sign-in. Likewise, `dsregcmd /status` collected by the agent runs as SYSTEM and shows only the **device** join state; the per-user PRT state is visible only when the command runs as the signed-in user.\n\n**Typical causes** — something structurally prevents the user (or the computer object) from registering:\n\n- the computer object's `userCertificate` attribute is not syncing to Entra ID (sync scope / OU filtering),\n- the signing-in user is not synced, or their UPN does not match a verified Entra domain,\n- the device has no line of sight to a domain controller **at logon time**, so the hybrid PRT flow cannot finish,\n- time skew or a proxy blocking `login.microsoftonline.com` / `enterpriseregistration.windows.net` from the user context.\n\nA frequent variant: the user's **first sign-in happens without domain-controller reachability** — for example when a pre-logon VPN tunnel (GlobalProtect, Always On VPN, Zscaler ZPA) is not established yet at the logon screen. Windows falls back to cached credentials, the hybrid PRT flow silently never runs, and later reboots do not fix it.\n\nThe `device_registration_event` entries in the timeline (User Device Registration events 304/305) carry the OS-side record of the failed registration; the error codes in `entra_user_affinity_pending` carry the token side. A missing Windows Hello for Business wizard is a downstream symptom here, not the cause.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Verify user affinity on the device",
|
||||
"steps": [
|
||||
"Sign in as the affected user and run: dsregcmd /status — under 'SSO State' the value AzureAdPrt must be YES. NO means the user has no Entra token and this diagnosis is confirmed.",
|
||||
"Also check 'Device State': AzureAdJoined = YES and DomainJoined = YES are expected for hybrid join.",
|
||||
"Check Event Viewer: Applications and Services Logs > Microsoft > Windows > User Device Registration > Admin for PRT / registration errors (e.g. event 304/305/362).",
|
||||
"Enable the gather rules 'Collect dsregcmd join status' so future sessions capture this state automatically."
|
||||
"Also check 'Device State': AzureAdJoined = YES and DomainJoined = YES are expected for hybrid join — they prove the device join only, not the user's registration.",
|
||||
"Check Event Viewer: Applications and Services Logs > Microsoft > Windows > User Device Registration > Admin for PRT / registration errors (e.g. event 304/305/362). The device_registration_event entries (304/305) in the session timeline carry the same OS-side failure record.",
|
||||
"Enable the gather rule GATHER-DEVICE-006 (dsregcmd /status at the moment of the finding — device state only, the agent runs as SYSTEM). GATHER-DEVICE-007 and GATHER-DEVICE-008 (Microsoft-Windows-AAD/Operational events 1098 and 1097 at the same moment) are on by default."
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
+120
-25
@@ -615,7 +615,7 @@
|
||||
"description": "Detects when the Enrollment Status Page failed on the Apps subcategory and the agent's AppX deployment log scan identified a suspected MSIX/Store package. Store/MSIX apps install outside the Win32 pipeline, so the regular per-app tracking sees nothing — this correlation names the likely culprit.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
@@ -703,7 +703,7 @@
|
||||
"steps": [
|
||||
"Open Event Viewer → Applications and Services Logs → Microsoft → Windows → AppXDeploymentServer → Operational on the device (or in the diagnostics archive if uploaded)",
|
||||
"Filter for Error-level events around the ESP failure time and confirm the package name and HRESULT match this finding",
|
||||
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = invalid/corrupt package, 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
|
||||
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = package could not be opened (unsigned, publisher mismatch, or not found), 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -1034,6 +1034,103 @@
|
||||
"esp"
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "ANALYZE-APP-018",
|
||||
"title": "App Return Code Requested a Reboot During Enrollment",
|
||||
"description": "Detects Win32 apps whose installer exit code maps to Soft reboot or Hard reboot in the app's Intune return-code table (the '[Win32App] lpExitCode is defined as ...' line). Hard reboot stops app processing and restarts the device in Device Setup - the mid-enrollment restart and second sign-in; Soft reboot leaves the app pending until the next restart while the ESP moves on. Confidence rises for Hard reboot and when a reboot was actually observed in the session.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
"whiteglove_sealed"
|
||||
],
|
||||
"trigger": "single",
|
||||
"baseConfidence": 60,
|
||||
"conditions": [
|
||||
{
|
||||
"signal": "reboot_return_code",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_completed",
|
||||
"dataField": "exitCodeClass",
|
||||
"operator": "in",
|
||||
"value": "SoftReboot,HardReboot",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "hard_reboot_return_code",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_completed",
|
||||
"dataField": "exitCodeClass",
|
||||
"operator": "equals",
|
||||
"value": "HardReboot",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"signal": "reboot_observed",
|
||||
"source": "event_count",
|
||||
"eventType": "system_reboot_detected",
|
||||
"operator": "count_gte",
|
||||
"value": "1",
|
||||
"required": false
|
||||
}
|
||||
],
|
||||
"confidenceFactors": [
|
||||
{
|
||||
"signal": "hard_reboot_return_code",
|
||||
"condition": "exists",
|
||||
"weight": 25
|
||||
},
|
||||
{
|
||||
"signal": "reboot_observed",
|
||||
"condition": "exists",
|
||||
"weight": 15
|
||||
}
|
||||
],
|
||||
"confidenceThreshold": 60,
|
||||
"explanation": "App **{{appName}}** returned exit code **{{exitCode}}**, which its Intune return-code table maps to **{{exitCodeClass}}** - the installer asked for a restart before its work is complete.\n\n- **SoftReboot**: the Intune Management Extension reports the app as *pending reboot*. The Enrollment Status Page treats it as completed and moves on, and Intune only marks the app installed after the next restart re-evaluates the detection rule. Until then the app may be unusable or half-configured, and the user sees a restart notification.\n- **HardReboot**: the Intune Management Extension stops processing further apps and, in Device Setup, restarts the device right away (the restart grace period does not apply during the ESP) - the same mid-enrollment restart and second sign-in that ANALYZE-ESP-005 attributes to reboot-required policies. In Account Setup the extension does not restart the device itself and the app stays pending.\n\nA restart requested by an installer is normal for many MSI packages (exit codes 3010 and 1641), but during Autopilot it lengthens the ESP, can surprise the user with a restart, and hides the app's real state until after the reboot. The return-code class is the app's own configuration in Intune, not a device fault.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Check the app's return-code mapping",
|
||||
"steps": [
|
||||
"Open the app in the Intune admin center > Properties > Program and review the return codes table: exit code {{exitCode}} is currently mapped to {{exitCodeClass}}",
|
||||
"If the installer only recommends a restart (MSI 3010 ERROR_SUCCESS_REBOOT_REQUIRED, 1641 ERROR_SUCCESS_REBOOT_INITIATED), map the code to Soft reboot instead of Hard reboot so the next app can install before the restart",
|
||||
"If the app works without an immediate restart, suppress the installer's own reboot (for MSI: REBOOT=ReallySuppress on the install command) so it returns 0 and the restart happens on your schedule",
|
||||
"Keep Hard reboot only when the following apps genuinely cannot install before the restart - and then expect the mid-ESP restart in every enrollment"
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "Take the app out of the ESP critical path",
|
||||
"steps": [
|
||||
"If the app is not needed for first use, remove it from the ESP blocking-app list so the restart happens after the user reaches the desktop",
|
||||
"If it must stay blocking, order it last in Device Setup (dependencies or install order) so a hard reboot does not interrupt the remaining apps",
|
||||
"For Soft reboot apps, plan a restart at the end of enrollment or accept that the app finishes on the user's first restart"
|
||||
]
|
||||
}
|
||||
],
|
||||
"relatedDocs": [
|
||||
{
|
||||
"title": "Microsoft Learn: Add a Win32 app - Program step (device restart behavior and return codes)",
|
||||
"url": "https://learn.microsoft.com/en-us/intune/app-management/deployment/add-win32#step-2-program"
|
||||
},
|
||||
{
|
||||
"title": "Microsoft Learn: Enrollment Status Page tracking",
|
||||
"url": "https://learn.microsoft.com/en-us/autopilot/enrollment-status"
|
||||
}
|
||||
],
|
||||
"markSessionAsFailedDefault": false,
|
||||
"tags": [
|
||||
"apps",
|
||||
"reboot",
|
||||
"return-code",
|
||||
"soft-reboot",
|
||||
"hard-reboot",
|
||||
"esp",
|
||||
"second-sign-in"
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "ANALYZE-CORR-003",
|
||||
"title": "Proxy Configuration Causing Download Failure",
|
||||
@@ -1772,10 +1869,10 @@
|
||||
{
|
||||
"ruleId": "ANALYZE-DEV-012",
|
||||
"title": "Device Entered Standby During Enrollment",
|
||||
"description": "Detects that the device completed a sleep, hibernate or Modern Standby episode of at least 5 minutes while the enrollment was running (system_sleep_episode event from the agent's system timeline watcher, recorded retroactively at wake from the Windows event log — pre-agent episodes are backfilled). Uses a single required condition on the episode's durationSeconds so the match is pinned to one event instance and the interpolated duration is the matched value. Short Modern Standby screen-off scenarios (under 60 s of real sleep) never emit the event, and this rule adds a 5-minute floor so brief lid-close moments do not fire it.",
|
||||
"description": "Detects that the device completed a sleep, hibernate or Modern Standby episode of at least 5 minutes while the enrollment was running (system_sleep_episode event from the agent's system timeline watcher, recorded retroactively at wake from the Windows event log). The watcher also backfills pre-agent episodes from the last 24 h for timeline context (backfilled=true); those ended before the enrollment started and are excluded via the same-event filter backfilled equals false — a separate condition could not do that, because each condition scans all events on its own and a pre-session hibernate would still satisfy the duration test. A single required condition keeps the match pinned to one event instance so the interpolated duration is the matched value. Short Modern Standby screen-off scenarios (under 60 s of real sleep) never emit the event, and this rule adds a 5-minute floor so brief lid-close moments do not fire it.",
|
||||
"severity": "info",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
@@ -1793,6 +1890,9 @@
|
||||
"dataField": "durationSeconds",
|
||||
"operator": "gte",
|
||||
"value": "300",
|
||||
"filterField": "backfilled",
|
||||
"filterOperator": "equals",
|
||||
"filterValue": "false",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
@@ -2937,16 +3037,16 @@
|
||||
{
|
||||
"ruleId": "ANALYZE-ID-004",
|
||||
"title": "Hybrid Sign-In Never Establishes Entra User Affinity",
|
||||
"description": "On a hybrid-joined device the real user reached the desktop, but the Autopilot provisioning placeholder stayed active in JoinInfo and the agent repeatedly reported the hybrid sign-in as overdue. The user session never establishes Entra user affinity (no PRT), so the Account Setup ESP re-runs on every logon and the enrollment never completes.",
|
||||
"description": "On a hybrid-joined device the real user reached the desktop, but the Intune Management Extension never acquired a Microsoft Entra user token for that user within the wait window — repeatedly across reboots when the warning recurs. Without a user token the signed-in user has no Entra user affinity: user-targeted apps and policies cannot apply, Windows Hello for Business cannot provision, and with a user ESP the Account Setup page re-runs on every logon.",
|
||||
"severity": "high",
|
||||
"category": "identity",
|
||||
"version": "1.2.0",
|
||||
"version": "2.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"trigger": "correlation",
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
"on_event:hybrid_login_pending"
|
||||
"on_event:entra_user_affinity_pending"
|
||||
],
|
||||
"baseConfidence": 60,
|
||||
"confidenceThreshold": 75,
|
||||
@@ -2955,14 +3055,14 @@
|
||||
"source": "event_data",
|
||||
"eventType": "enrollment_complete",
|
||||
"operator": "not_exists",
|
||||
"description": "Suppress when the session eventually completed — a single overdue-login warning followed by a successful sign-in is normal hybrid latency, not a broken affinity."
|
||||
"description": "Suppress when the session eventually completed — a single pending-affinity warning followed by a successful token acquisition is hybrid latency, not a broken affinity."
|
||||
}
|
||||
],
|
||||
"conditions": [
|
||||
{
|
||||
"signal": "hybrid_login_overdue",
|
||||
"signal": "user_affinity_pending",
|
||||
"source": "event_type",
|
||||
"eventType": "hybrid_login_pending",
|
||||
"eventType": "entra_user_affinity_pending",
|
||||
"operator": "exists",
|
||||
"value": "",
|
||||
"required": true
|
||||
@@ -2976,40 +3076,35 @@
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "placeholder_still_active",
|
||||
"signal": "no_user_token",
|
||||
"source": "event_type",
|
||||
"eventType": "aad_placeholder_user_detected",
|
||||
"operator": "exists",
|
||||
"eventType": "ime_user_token_acquired",
|
||||
"operator": "not_exists",
|
||||
"value": "",
|
||||
"required": false
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"confidenceFactors": [
|
||||
{
|
||||
"signal": "hybrid_login_pending",
|
||||
"signal": "entra_user_affinity_pending",
|
||||
"condition": "count >= 2",
|
||||
"weight": 20
|
||||
},
|
||||
{
|
||||
"signal": "hybrid_login_pending",
|
||||
"condition": "count >= 3",
|
||||
"weight": 10
|
||||
},
|
||||
{
|
||||
"signal": "aad_placeholder_user_detected",
|
||||
"signal": "entra_user_affinity_pending",
|
||||
"condition": "count >= 3",
|
||||
"weight": 10
|
||||
}
|
||||
],
|
||||
"explanation": "A real user signed in and reached the desktop, but the device kept reporting the **Autopilot provisioning placeholder** as the active identity in JoinInfo and the hybrid sign-in as **overdue** — across multiple reboots. This means the signed-in user never established **Microsoft Entra user affinity** (no Primary Refresh Token), so:\n\n- the Account Setup ESP page re-appears on every logon,\n- user-targeted required apps and policies cannot settle,\n- the enrollment never reaches completion.\n\nAfter this many hours this is not normal Entra Connect sync latency — something is structurally preventing the user (or the computer object) from registering:\n\n- the computer object's `userCertificate` attribute is not syncing to Entra ID (sync scope / OU filtering),\n- the signing-in user is not synced, or their UPN does not match a verified Entra domain,\n- the device has no line of sight to a domain controller **at logon time**, so the hybrid PRT flow cannot finish,\n- time skew or a proxy blocking `login.microsoftonline.com` / `enterpriseregistration.windows.net` from the user context.\n\nA frequent variant: the user's **first sign-in happens without domain-controller reachability** — for example when a pre-logon VPN tunnel (GlobalProtect, Always On VPN, Zscaler ZPA) is not established yet at the logon screen. Windows falls back to cached credentials, the hybrid PRT flow silently never runs, and later reboots do not fix it — sessions in this state typically show repeated reboots and network flapping while the placeholder identity stays active.\n\nA visible side effect: **the Windows Hello for Business wizard never appears**, because Hello provisioning requires an Entra user token (PRT). Hello is a downstream symptom here, not the cause.",
|
||||
"explanation": "**What was measured.** A real user signed in and reached the desktop (`desktop_arrived`), and by the end of the agent's wait window the Intune Management Extension (IME) had still not acquired a **Microsoft Entra user token** for that user (`entra_user_affinity_pending`). That event lists the IME token error codes observed after the desktop (`tokenFailureCodes`) and how often the acquisition failed (`tokenFailureCount`). Each agent run reports this at most once, so a second or third occurrence means the same outcome across reboots — that repetition is what raises the confidence of this finding. No `ime_user_token_acquired` event followed in this session.\n\n**Why this means no user affinity.** IME's user check-in acquires the user token through the Windows web account manager (WAM), which needs the signed-in user's Entra identity — the Primary Refresh Token (PRT) that a hybrid sign-in establishes at logon. When that PRT was never issued, every token request fails and the user has **no Entra user affinity** on this device. Consequences:\n\n- user-targeted required apps and policies cannot apply,\n- Windows Hello for Business cannot provision (it requires a user token),\n- with a user ESP the Account Setup page re-appears on every logon instead of completing.\n\n**What this diagnosis does not use.** The Autopilot provisioning placeholder in JoinInfo (`aad_placeholder_user_detected`) is not part of this finding — on hybrid devices it can stay present through a perfectly healthy sign-in. Likewise, `dsregcmd /status` collected by the agent runs as SYSTEM and shows only the **device** join state; the per-user PRT state is visible only when the command runs as the signed-in user.\n\n**Typical causes** — something structurally prevents the user (or the computer object) from registering:\n\n- the computer object's `userCertificate` attribute is not syncing to Entra ID (sync scope / OU filtering),\n- the signing-in user is not synced, or their UPN does not match a verified Entra domain,\n- the device has no line of sight to a domain controller **at logon time**, so the hybrid PRT flow cannot finish,\n- time skew or a proxy blocking `login.microsoftonline.com` / `enterpriseregistration.windows.net` from the user context.\n\nA frequent variant: the user's **first sign-in happens without domain-controller reachability** — for example when a pre-logon VPN tunnel (GlobalProtect, Always On VPN, Zscaler ZPA) is not established yet at the logon screen. Windows falls back to cached credentials, the hybrid PRT flow silently never runs, and later reboots do not fix it.\n\nThe `device_registration_event` entries in the timeline (User Device Registration events 304/305) carry the OS-side record of the failed registration; the error codes in `entra_user_affinity_pending` carry the token side. A missing Windows Hello for Business wizard is a downstream symptom here, not the cause.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Verify user affinity on the device",
|
||||
"steps": [
|
||||
"Sign in as the affected user and run: dsregcmd /status — under 'SSO State' the value AzureAdPrt must be YES. NO means the user has no Entra token and this diagnosis is confirmed.",
|
||||
"Also check 'Device State': AzureAdJoined = YES and DomainJoined = YES are expected for hybrid join.",
|
||||
"Check Event Viewer: Applications and Services Logs > Microsoft > Windows > User Device Registration > Admin for PRT / registration errors (e.g. event 304/305/362).",
|
||||
"Enable the gather rules 'Collect dsregcmd join status' so future sessions capture this state automatically."
|
||||
"Also check 'Device State': AzureAdJoined = YES and DomainJoined = YES are expected for hybrid join — they prove the device join only, not the user's registration.",
|
||||
"Check Event Viewer: Applications and Services Logs > Microsoft > Windows > User Device Registration > Admin for PRT / registration errors (e.g. event 304/305/362). The device_registration_event entries (304/305) in the session timeline carry the same OS-side failure record.",
|
||||
"Enable the gather rule GATHER-DEVICE-006 (dsregcmd /status at the moment of the finding — device state only, the agent runs as SYSTEM). GATHER-DEVICE-007 and GATHER-DEVICE-008 (Microsoft-Windows-AAD/Operational events 1098 and 1097 at the same moment) are on by default."
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
+52
-4
@@ -130,16 +130,16 @@
|
||||
},
|
||||
{
|
||||
"ruleId": "GATHER-DEVICE-006",
|
||||
"title": "Collect dsregcmd join status on overdue hybrid sign-in",
|
||||
"description": "Runs dsregcmd /status the moment the agent reports a hybrid sign-in as overdue (hybrid_login_pending), capturing the Entra join and registration state at exactly the point where the problem is detected. Complements GATHER-DEVICE-001 (snapshot on entering Account Setup). Note: the agent runs as SYSTEM, so the output shows device join state — the per-user SSO/PRT state still requires running dsregcmd as the signed-in user.",
|
||||
"title": "Collect dsregcmd join status on pending user affinity",
|
||||
"description": "Runs dsregcmd /status the moment the agent reports that the signed-in user still has no Entra user token (entra_user_affinity_pending), capturing the device join and registration state at exactly the point where ANALYZE-ID-004 draws its evidence. Complements GATHER-DEVICE-001 (snapshot on entering Account Setup). Note: the agent runs as SYSTEM, so the output shows device join state — the per-user SSO/PRT state still requires running dsregcmd as the signed-in user.",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": false,
|
||||
"collectorType": "command_allowlisted",
|
||||
"target": "dsregcmd /status",
|
||||
"trigger": "on_event",
|
||||
"triggerEventType": "hybrid_login_pending",
|
||||
"triggerEventType": "entra_user_affinity_pending",
|
||||
"outputEventType": "gather_dsregcmd_status",
|
||||
"outputSeverity": "Info",
|
||||
"tags": [
|
||||
@@ -149,6 +149,54 @@
|
||||
"hybrid"
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "GATHER-DEVICE-007",
|
||||
"title": "Collect Entra operational log on pending user affinity (event 1098)",
|
||||
"description": "Collects the most recent Entra token-broker operational events with ID 1098 from Microsoft-Windows-AAD/Operational the moment the agent reports that the signed-in user still has no Entra user token (entra_user_affinity_pending). Captures the OS-side token-broker record at exactly the point where ANALYZE-ID-004 draws its evidence. The event log collector filters on one event ID per rule; GATHER-DEVICE-008 collects event 1097 from the same channel.",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"collectorType": "eventlog",
|
||||
"target": "Microsoft-Windows-AAD/Operational",
|
||||
"parameters": {
|
||||
"eventId": "1098",
|
||||
"maxEntries": "20"
|
||||
},
|
||||
"trigger": "on_event",
|
||||
"triggerEventType": "entra_user_affinity_pending",
|
||||
"outputEventType": "gather_aad_operational_events",
|
||||
"outputSeverity": "Warning",
|
||||
"tags": [
|
||||
"device",
|
||||
"entra",
|
||||
"hybrid"
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "GATHER-DEVICE-008",
|
||||
"title": "Collect Entra operational log on pending user affinity (event 1097)",
|
||||
"description": "Collects the most recent Entra token-broker operational events with ID 1097 from Microsoft-Windows-AAD/Operational the moment the agent reports that the signed-in user still has no Entra user token (entra_user_affinity_pending). Captures the OS-side token-broker record at exactly the point where ANALYZE-ID-004 draws its evidence. The event log collector filters on one event ID per rule; GATHER-DEVICE-007 collects event 1098 from the same channel.",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"collectorType": "eventlog",
|
||||
"target": "Microsoft-Windows-AAD/Operational",
|
||||
"parameters": {
|
||||
"eventId": "1097",
|
||||
"maxEntries": "20"
|
||||
},
|
||||
"trigger": "on_event",
|
||||
"triggerEventType": "entra_user_affinity_pending",
|
||||
"outputEventType": "gather_aad_operational_events",
|
||||
"outputSeverity": "Warning",
|
||||
"tags": [
|
||||
"device",
|
||||
"entra",
|
||||
"hybrid"
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "GATHER-ENROLL-001",
|
||||
"title": "MDM enrollment diagnostic events",
|
||||
|
||||
+11
@@ -339,6 +339,17 @@
|
||||
"description": "Captures the installer exit code (lpExitCode) for the current app.",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"patternId": "IME-EXITCODE-CLASS",
|
||||
"category": "currentPhase",
|
||||
"pattern": "^\\[Win32App\\] lpExitCode is defined as (?<exitCodeClass>Success|SoftReboot|HardReboot|Retry|Failed)$",
|
||||
"action": "captureExitCodeClass",
|
||||
"parameters": {
|
||||
"useCurrentApp": "true"
|
||||
},
|
||||
"description": "Captures the admin-defined return-code class of the installer exit code for the current app ('[Win32App] lpExitCode is defined as <Failed|Success|SoftReboot|HardReboot|Retry>', Win32AppInstaller.cs, enum AppReturnCodeType - literal identical from IME 1.50 through 1.105). Stored as exitCodeClass on the app and emitted on its terminal events; the last value wins, so a Retry loop that ends in Success reports Success. Anchored on both ends on purpose: the no-mapping warning ('... defined as <n>, fall into default now.') and an unparsable numeric type print a raw number and must not match. Companion of IME-EXITCODE (the number, logged just before) and IME-EXITCODE-MAPPED-FAILED (the Failed state transition), which still owns the error path.",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"patternId": "IME-EXITCODE-MAPPED-FAILED",
|
||||
"category": "currentPhase",
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"$schema": "../schema/gather-rule.schema.json",
|
||||
"ruleId": "GATHER-DEVICE-006",
|
||||
"title": "Collect dsregcmd join status on overdue hybrid sign-in",
|
||||
"description": "Runs dsregcmd /status the moment the agent reports a hybrid sign-in as overdue (hybrid_login_pending), capturing the Entra join and registration state at exactly the point where the problem is detected. Complements GATHER-DEVICE-001 (snapshot on entering Account Setup). Note: the agent runs as SYSTEM, so the output shows device join state — the per-user SSO/PRT state still requires running dsregcmd as the signed-in user.",
|
||||
"title": "Collect dsregcmd join status on pending user affinity",
|
||||
"description": "Runs dsregcmd /status the moment the agent reports that the signed-in user still has no Entra user token (entra_user_affinity_pending), capturing the device join and registration state at exactly the point where ANALYZE-ID-004 draws its evidence. Complements GATHER-DEVICE-001 (snapshot on entering Account Setup). Note: the agent runs as SYSTEM, so the output shows device join state — the per-user SSO/PRT state still requires running dsregcmd as the signed-in user.",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": false,
|
||||
"collectorType": "command_allowlisted",
|
||||
"target": "dsregcmd /status",
|
||||
"trigger": "on_event",
|
||||
"triggerEventType": "hybrid_login_pending",
|
||||
"triggerEventType": "entra_user_affinity_pending",
|
||||
"outputEventType": "gather_dsregcmd_status",
|
||||
"outputSeverity": "Info",
|
||||
"tags": ["device", "entra", "join", "hybrid"]
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "../schema/gather-rule.schema.json",
|
||||
"ruleId": "GATHER-DEVICE-007",
|
||||
"title": "Collect Entra operational log on pending user affinity (event 1098)",
|
||||
"description": "Collects the most recent Entra token-broker operational events with ID 1098 from Microsoft-Windows-AAD/Operational the moment the agent reports that the signed-in user still has no Entra user token (entra_user_affinity_pending). Captures the OS-side token-broker record at exactly the point where ANALYZE-ID-004 draws its evidence. The event log collector filters on one event ID per rule; GATHER-DEVICE-008 collects event 1097 from the same channel.",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"collectorType": "eventlog",
|
||||
"target": "Microsoft-Windows-AAD/Operational",
|
||||
"parameters": {
|
||||
"eventId": "1098",
|
||||
"maxEntries": "20"
|
||||
},
|
||||
"trigger": "on_event",
|
||||
"triggerEventType": "entra_user_affinity_pending",
|
||||
"outputEventType": "gather_aad_operational_events",
|
||||
"outputSeverity": "Warning",
|
||||
"tags": ["device", "entra", "hybrid"]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "../schema/gather-rule.schema.json",
|
||||
"ruleId": "GATHER-DEVICE-008",
|
||||
"title": "Collect Entra operational log on pending user affinity (event 1097)",
|
||||
"description": "Collects the most recent Entra token-broker operational events with ID 1097 from Microsoft-Windows-AAD/Operational the moment the agent reports that the signed-in user still has no Entra user token (entra_user_affinity_pending). Captures the OS-side token-broker record at exactly the point where ANALYZE-ID-004 draws its evidence. The event log collector filters on one event ID per rule; GATHER-DEVICE-007 collects event 1098 from the same channel.",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"collectorType": "eventlog",
|
||||
"target": "Microsoft-Windows-AAD/Operational",
|
||||
"parameters": {
|
||||
"eventId": "1097",
|
||||
"maxEntries": "20"
|
||||
},
|
||||
"trigger": "on_event",
|
||||
"triggerEventType": "entra_user_affinity_pending",
|
||||
"outputEventType": "gather_aad_operational_events",
|
||||
"outputSeverity": "Warning",
|
||||
"tags": ["device", "entra", "hybrid"]
|
||||
}
|
||||
@@ -282,5 +282,25 @@
|
||||
"log_entry",
|
||||
"agent_trace",
|
||||
"stall_probe_check"
|
||||
],
|
||||
"imeLogDerivedEventTypes": [
|
||||
"app_install_started",
|
||||
"app_install_completed",
|
||||
"app_install_failed",
|
||||
"app_install_skipped",
|
||||
"app_download_started",
|
||||
"app_tracking_summary",
|
||||
"download_progress",
|
||||
"do_telemetry",
|
||||
"script_started",
|
||||
"script_completed",
|
||||
"script_failed",
|
||||
"script_timeout_suspected",
|
||||
"esp_phase_changed",
|
||||
"ime_agent_version",
|
||||
"ime_token_failure",
|
||||
"ime_user_session_completed",
|
||||
"ime_process_exited",
|
||||
"ime_user_token_acquired"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "../schema/ime-log-pattern.schema.json",
|
||||
"patternId": "IME-EXITCODE-CLASS",
|
||||
"category": "currentPhase",
|
||||
"pattern": "^\\[Win32App\\] lpExitCode is defined as (?<exitCodeClass>Success|SoftReboot|HardReboot|Retry|Failed)$",
|
||||
"action": "captureExitCodeClass",
|
||||
"parameters": { "useCurrentApp": "true" },
|
||||
"description": "Captures the admin-defined return-code class of the installer exit code for the current app ('[Win32App] lpExitCode is defined as <Failed|Success|SoftReboot|HardReboot|Retry>', Win32AppInstaller.cs, enum AppReturnCodeType - literal identical from IME 1.50 through 1.105). Stored as exitCodeClass on the app and emitted on its terminal events; the last value wins, so a Retry loop that ends in Success reports Success. Anchored on both ends on purpose: the no-mapping warning ('... defined as <n>, fall into default now.') and an unparsable numeric type print a raw number and must not match. Companion of IME-EXITCODE (the number, logged just before) and IME-EXITCODE-MAPPED-FAILED (the Failed state transition), which still owns the error path.",
|
||||
"enabled": true
|
||||
}
|
||||
@@ -168,7 +168,7 @@
|
||||
},
|
||||
"source": {
|
||||
"type": "string",
|
||||
"description": "Source of the signal.",
|
||||
"description": "Source of the signal. phase_duration and app_install_duration never derive a duration from a span with mixed timestamp provenance (exactly one IME-log endpoint with sourceOffsetOrigin=reader-zone-fallback, i.e. the writer timezone was unknown to the agent for one endpoint only): such a condition evaluates false with evidence timestampProvenance=reader-zone-fallback. Two fallback endpoints share the same error and stay measurable.",
|
||||
"enum": ["event_type", "event_data", "event_data_array", "phase_duration", "event_count", "app_install_duration", "event_correlation", "clock_skew"]
|
||||
},
|
||||
"skewMetric": {
|
||||
@@ -204,16 +204,16 @@
|
||||
},
|
||||
"filterField": {
|
||||
"type": "string",
|
||||
"description": "For event_count only: optional value filter — only events whose filterField satisfies filterOperator/filterValue are counted (e.g. count only performance_snapshot events with memory_used_percent > 90). Applies before counting for both count_gte and count_per_group_gte."
|
||||
"description": "Optional same-event value filter for event_count, event_data and event_data_array: only events whose filterField satisfies filterOperator/filterValue are considered. For event_count it applies before counting (both count_gte and count_per_group_gte, e.g. count only performance_snapshot events with memory_used_percent > 90). For event_data/event_data_array the filter and the main dataField/operator test are evaluated on the SAME event instance — the only way to pin two fields of one event together, since separate conditions each scan all events independently (e.g. system_sleep_episode with durationSeconds gte 300 AND backfilled equals false)."
|
||||
},
|
||||
"filterOperator": {
|
||||
"type": "string",
|
||||
"description": "Operator for the event_count value filter.",
|
||||
"description": "Operator for the same-event value filter. Same vocabulary as operator.",
|
||||
"enum": ["equals", "not_equals", "contains", "not_contains", "regex", "not_regex", "gt", "lt", "gte", "lte", "exists", "not_exists", "in", "not_in"]
|
||||
},
|
||||
"filterValue": {
|
||||
"type": "string",
|
||||
"description": "Value for the event_count value filter."
|
||||
"description": "Value for the same-event value filter. Boolean values are stringified (\"true\"/\"false\")."
|
||||
},
|
||||
"correlateEventType": {
|
||||
"type": "string",
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"blockedFilePrefixes": { "$ref": "#/$defs/stringList" },
|
||||
"blockedCommandPatterns": { "$ref": "#/$defs/stringList" },
|
||||
"blockedInterimTriggerEventTypes": { "$ref": "#/$defs/stringList" },
|
||||
"imeLogDerivedEventTypes": { "$ref": "#/$defs/stringList" },
|
||||
"maxCommandLength": { "type": "integer", "minimum": 1, "maximum": 100000 }
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -79,7 +79,8 @@
|
||||
"captureAppTypeWinGet",
|
||||
"captureAppTypeMsi",
|
||||
"captureAttemptNumber",
|
||||
"captureDetectionResult"
|
||||
"captureDetectionResult",
|
||||
"captureExitCodeClass"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
|
||||
@@ -142,6 +142,7 @@ if (fs.existsSync(guardrailsPath)) {
|
||||
assertStringList(guardrails[key], key);
|
||||
}
|
||||
assertStringList(guardrails.blockedInterimTriggerEventTypes ?? [], 'blockedInterimTriggerEventTypes');
|
||||
assertStringList(guardrails.imeLogDerivedEventTypes ?? [], 'imeLogDerivedEventTypes');
|
||||
if (!Number.isInteger(guardrails.maxCommandLength) || guardrails.maxCommandLength < 1) {
|
||||
fail(`maxCommandLength: expected a positive integer, got ${JSON.stringify(guardrails.maxCommandLength)}`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# Error-code catalog generator
|
||||
|
||||
`generate.mjs` rebuilds `src/Shared/AutopilotMonitor.Shared/Resources/error-codes.json`
|
||||
(schemaVersion 2) from primary sources and refreshes the web copy through
|
||||
`src/Web/autopilot-monitor-web/scripts/sync-error-codes.js`. The catalog is never edited by
|
||||
hand: a wrong or missing entry is fixed in the generator (a source, a pin, a family rule) and
|
||||
regenerated, so the next regeneration cannot lose the fix.
|
||||
|
||||
```
|
||||
IME_ENUMS_JSON=<path> node scripts/error-codes/generate.mjs [--cache-dir DIR] [--check]
|
||||
```
|
||||
|
||||
- `IME_ENUMS_JSON` — enum extract of one Intune Management Extension build (`imeVersion`,
|
||||
`customErrorCodes`, `enforcementStates`, `msiRetriableErrorCodes`, `deliveryOptimization`).
|
||||
Produced by operator tooling; the generator only reads the JSON.
|
||||
- `--cache-dir DIR` — keeps the fetched pages as files for offline reruns.
|
||||
- `--check` — exits 1 when the committed catalog differs from the generator output.
|
||||
|
||||
## Entry shape
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| key | lowercase 8-digit hex (`0x80070005`) or a decimal MSI exit code (`1603`). Decimal keys exist only for `0`, `1601`–`1654` and `3010`: exit codes of other installers are author-defined. Win32 codes live only as `0x8007xxxx`; a `HRESULT_FROM_WIN32` value whose low word is in the MSI range resolves to the decimal entry at lookup time (`derivedFromWin32`). |
|
||||
| `description` | one line, taken from the source (see rules below) |
|
||||
| `confidence` | `high` = MS Learn table/page or the IME build named in `source`; `medium` = paraphrase of an enum member name or of an analysis rule; `low` = carried over from the v1 catalog without a primary source |
|
||||
| `source` | `msdoc:<learn.microsoft.com URL>` · `ime:<version>` · `winerror.h` · `rule:<RULE-ID>` · `legacy-catalog-v1` |
|
||||
| `category` | `msi` `win32` `com` `appx` `windows-update` `cbs` `intune-win32` `intune-mobile` `mdm-enrollment` `autopilot` `entra-join` `delivery-optimization` |
|
||||
| `symbol` | optional: the `winerror.h`/WU/AppX symbol, or the IME enum member name |
|
||||
| `imeRetriesDuringEsp` | optional: one of the MSI return codes the IME retries automatically during the Autopilot ESP |
|
||||
|
||||
`enforcementStates` is a second map: IME app enforcement state number → `{ name, description }`.
|
||||
|
||||
## Sources and family rules
|
||||
|
||||
Families are processed in this order; the first family that yields a key wins and later
|
||||
duplicates are reported on stderr.
|
||||
|
||||
| Family | Source | Rule |
|
||||
|---|---|---|
|
||||
| win32 | [System Error Codes](https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes) (per-range pages), [WinHTTP error messages](https://learn.microsoft.com/en-us/windows/win32/winhttp/error-messages) | Seed = codes seen in the field (`WIN32_FIELD_SEEN`) ∪ the IME MSI-retry list ∪ every `0x8007xxxx` code another family names, minus the MSI decimal range and the AppX page's own range. Symbol and text verbatim. A seed code the reference does not list fails the run. |
|
||||
| msi | [Windows Installer error codes](https://learn.microsoft.com/en-us/windows/win32/msi/error-codes) | Rows in the MSI decimal range only; verbatim. |
|
||||
| com | `winerror.h` | Hand-listed HRESULTs that are not Win32-derived (`S_OK`, `E_FAIL`, `E_UNEXPECTED`, HTTP/RPC status HRESULTs the Delivery Optimization client names). |
|
||||
| appx | [Troubleshooting packaging, deployment, and query of Windows apps](https://learn.microsoft.com/en-us/windows/win32/appxpkg/troubleshooting) | Whole table; first sentence of the cell. Authority for its own `0x80073Cxx`/`0x80073Dxx` range. |
|
||||
| windows-update | [Windows Update error codes by component](https://learn.microsoft.com/en-us/windows/deployment/update/windows-update-error-reference) | Sections an enrollment can meet (agent core, handlers, download manager, protocol talker, data store, drivers, MSI handler, agent setup, AU client); verbatim. |
|
||||
| windows-update / cbs | [Windows Update common errors](https://learn.microsoft.com/en-us/windows/deployment/update/windows-update-errors) | One table per single-code heading; symbol = text before `;` in the Message cell, description = text after it, else the Description cell. `0x800F…` → `cbs`. |
|
||||
| intune-mobile / intune-win32 | [Intune app installation error codes](https://learn.microsoft.com/en-us/troubleshoot/mem/intune/app-management/app-install-error-codes) | iOS/iPadOS and Windows tables (Android skipped); description = the message cell. |
|
||||
| mdm-enrollment / autopilot / entra-join | [Windows enrollment errors](https://learn.microsoft.com/en-us/troubleshoot/mem/intune/device-enrollment/troubleshoot-windows-enrollment-errors), [Autopilot known issues](https://learn.microsoft.com/en-us/autopilot/known-issues) | Prose pages: one-sentence paraphrase listed in `PROSE_ENTRIES`; the generator asserts the code appears on the page. Codes only our analysis rules name carry `rule:` and `medium`. |
|
||||
| intune-win32 (`0x87D3xxxx`) | IME `CustomErrorCodes` enum | Member name as symbol, humanised as description, `medium`. Two known sign/digit defects in the enum source are corrected by `IME_ENUM_FIXUPS`; a build that fixes them makes the run fail so the fixup is removed. |
|
||||
| delivery-optimization (`0x80D0xxxx`) | IME `DeliveryOptimizationConstants` | Member name as symbol, humanised, `medium`. |
|
||||
| legacy | v1 catalog | Entries no primary source covers, `low`. |
|
||||
|
||||
Description rules: whole sentences up to 200 characters, cross-reference sentences
|
||||
("For more information, see …") dropped, no trailing period. `DESCRIPTION_PINS` holds the
|
||||
few wordings consumers depend on (each says the same as the source row it replaces).
|
||||
|
||||
## Regeneration checklist
|
||||
|
||||
1. Run the generator (with `--cache-dir` when iterating).
|
||||
2. Read the stderr summary: entry count per family, dropped duplicates.
|
||||
3. `git diff` the catalog; a removed key needs a reason (the C#, web and MCP tests pin the
|
||||
keys the product relies on).
|
||||
4. Spot-check ten random entries per family against the source page.
|
||||
5. Build and run the Backend, Web and MCP test suites.
|
||||
@@ -0,0 +1,563 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Error-code catalog generator (schemaVersion 2).
|
||||
*
|
||||
* Rebuilds src/Shared/AutopilotMonitor.Shared/Resources/error-codes.json from primary
|
||||
* sources and writes the web copy through the web sync script. Every entry carries the
|
||||
* source it was taken from; nothing is typed in from memory.
|
||||
*
|
||||
* node scripts/error-codes/generate.mjs [--cache-dir DIR] [--check]
|
||||
*
|
||||
* IME_ENUMS_JSON required — path to the enum extract of one Intune Management Extension
|
||||
* build (customErrorCodes, enforcementStates, msiRetriableErrorCodes,
|
||||
* deliveryOptimization). Produced by operator tooling; the generator has
|
||||
* no notion of where the enums come from.
|
||||
* --cache-dir DIR read/write the fetched MS Learn pages as files in DIR (offline reruns).
|
||||
* --check do not write; exit 1 when the committed catalog differs from the output.
|
||||
*
|
||||
* Families, in precedence order (the first family that yields a key wins; later duplicates
|
||||
* are reported and dropped):
|
||||
* win32 MS "System Error Codes" + WinHTTP error page, keyed 0x8007xxxx
|
||||
* msi MS "Windows Installer error codes", decimal keys 0 / 1601-1654 / 3010
|
||||
* com winerror.h HRESULTs that are not Win32-derived (S_OK, E_FAIL, ...)
|
||||
* appx MS "Troubleshooting packaging, deployment, and query of Windows apps"
|
||||
* windows-update MS "Windows Update error codes by component" (reference tables)
|
||||
* cbs / windows-update MS "Windows Update common errors and mitigation" (per-code tables)
|
||||
* intune-* MS "Intune app installation error codes" (iOS + Windows tables)
|
||||
* mdm-enrollment/ MS enrollment troubleshooting + Autopilot known-issues pages (prose:
|
||||
* autopilot/entra-join one-sentence paraphrase, presence-checked against the page)
|
||||
* intune-win32 IME CustomErrorCodes enum (0x87D3xxxx), member name paraphrased
|
||||
* delivery-optimization IME DeliveryOptimizationConstants (0x80D0xxxx), member name paraphrased
|
||||
* legacy v1 entries without a primary source, kept at confidence "low"
|
||||
*
|
||||
* See README.md next to this file for the source list and the description rules.
|
||||
*/
|
||||
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO_ROOT = path.resolve(HERE, "..", "..");
|
||||
const TARGET = path.join(REPO_ROOT, "src", "Shared", "AutopilotMonitor.Shared", "Resources", "error-codes.json");
|
||||
const WEB_SYNC = path.join(REPO_ROOT, "src", "Web", "autopilot-monitor-web", "scripts", "sync-error-codes.js");
|
||||
|
||||
// ── CLI ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const cacheDir = args.includes("--cache-dir") ? args[args.indexOf("--cache-dir") + 1] : undefined;
|
||||
const checkOnly = args.includes("--check");
|
||||
const imeEnumsPath = process.env.IME_ENUMS_JSON;
|
||||
if (!imeEnumsPath || !existsSync(imeEnumsPath)) {
|
||||
console.error("IME_ENUMS_JSON must point to the IME enum extract (see README.md).");
|
||||
process.exit(2);
|
||||
}
|
||||
const ime = JSON.parse(readFileSync(imeEnumsPath, "utf8"));
|
||||
if (!/^\d+(\.\d+)+$/.test(String(ime.imeVersion ?? ""))) {
|
||||
console.error("IME enum extract has no imeVersion.");
|
||||
process.exit(2);
|
||||
}
|
||||
const IME_SOURCE = `ime:${ime.imeVersion}`;
|
||||
|
||||
// ── Vocabulary (mirrored by the C#, web and MCP tests) ───────────────────────
|
||||
|
||||
export const CATEGORIES = [
|
||||
"msi", "win32", "com", "appx", "windows-update", "cbs", "intune-win32", "intune-mobile",
|
||||
"mdm-enrollment", "autopilot", "entra-join", "delivery-optimization",
|
||||
];
|
||||
export const CONFIDENCES = ["high", "medium", "low"];
|
||||
export const SOURCE_PATTERN = /^(msdoc:https:\/\/learn\.microsoft\.com\/[^\s]+|ime:\d+(\.\d+)+|winerror\.h|rule:[A-Z]+-[A-Z]+-\d{3}|legacy-catalog-v1)$/;
|
||||
export const KEY_PATTERN = /^(0x[0-9a-f]{8}|\d+)$/;
|
||||
// winerror-style (ERROR_INSTALL_FAILURE) or an enum member (UnzipError); never a phrase.
|
||||
const SYMBOL_PATTERN = /^[A-Za-z][A-Za-z0-9_]{2,}$/;
|
||||
const MAX_DESCRIPTION = 200;
|
||||
|
||||
// ── Sources ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const URL = {
|
||||
msi: "https://learn.microsoft.com/en-us/windows/win32/msi/error-codes",
|
||||
appx: "https://learn.microsoft.com/en-us/windows/win32/appxpkg/troubleshooting",
|
||||
wuReference: "https://learn.microsoft.com/en-us/windows/deployment/update/windows-update-error-reference",
|
||||
wuErrors: "https://learn.microsoft.com/en-us/windows/deployment/update/windows-update-errors",
|
||||
intuneApps: "https://learn.microsoft.com/en-us/troubleshoot/mem/intune/app-management/app-install-error-codes",
|
||||
enrollErrors: "https://learn.microsoft.com/en-us/troubleshoot/mem/intune/device-enrollment/troubleshoot-windows-enrollment-errors",
|
||||
knownIssues: "https://learn.microsoft.com/en-us/autopilot/known-issues",
|
||||
winhttp: "https://learn.microsoft.com/en-us/windows/win32/winhttp/error-messages",
|
||||
win32: (range) => `https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--${range}-`,
|
||||
};
|
||||
const WIN32_RANGES = [[0, 499], [500, 999], [1000, 1299], [1300, 1699], [1700, 3999], [4000, 5999], [6000, 8199], [8200, 8999], [9000, 11999], [12000, 15999]];
|
||||
const WINHTTP_RANGE = [12000, 12200];
|
||||
|
||||
const msdoc = (url) => `msdoc:${url}`;
|
||||
|
||||
const pageCache = new Map();
|
||||
async function fetchPage(url) {
|
||||
if (pageCache.has(url)) return pageCache.get(url);
|
||||
const cacheFile = cacheDir ? path.join(cacheDir, url.replace(/^https?:\/\//, "").replace(/[^a-z0-9.-]+/gi, "_") + ".html") : null;
|
||||
let html;
|
||||
if (cacheFile && existsSync(cacheFile)) {
|
||||
html = readFileSync(cacheFile, "utf8");
|
||||
} else {
|
||||
const res = await fetch(url, { headers: { "user-agent": "Mozilla/5.0 (error-code catalog generator)" } });
|
||||
if (!res.ok) throw new Error(`GET ${url} → ${res.status}`);
|
||||
html = await res.text();
|
||||
if (cacheFile) {
|
||||
mkdirSync(path.dirname(cacheFile), { recursive: true });
|
||||
writeFileSync(cacheFile, html, "utf8");
|
||||
}
|
||||
}
|
||||
pageCache.set(url, html);
|
||||
return html;
|
||||
}
|
||||
|
||||
// ── HTML helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
const ENTITIES = { nbsp: " ", amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'", "#x27": "'" };
|
||||
|
||||
/**
|
||||
* Cell markup → plain text. Tags are stripped until none remain (a nested "<scr<b>ipt>" cannot
|
||||
* survive), and entities are decoded in ONE pass so "&lt;" yields "<", never "<".
|
||||
*/
|
||||
const decode = (s) => {
|
||||
let text = s.replace(/<br\s*\/?>/gi, " ").replace(/<\/(p|li|div)>/gi, " ");
|
||||
let previous;
|
||||
do {
|
||||
previous = text;
|
||||
text = text.replace(/<[^>]*>/g, "");
|
||||
} while (text !== previous);
|
||||
return text
|
||||
.replace(/&(nbsp|amp|lt|gt|quot|#39|#x27);/g, (_, name) => ENTITIES[name])
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
};
|
||||
|
||||
/** Every <table> of a page as rows of decoded cell strings, in document order. */
|
||||
function parseTables(html) {
|
||||
return [...html.matchAll(/<table[\s\S]*?<\/table>/gi)].map((t) =>
|
||||
[...t[0].matchAll(/<tr[\s\S]*?<\/tr>/gi)]
|
||||
.map((r) => [...r[0].matchAll(/<t[hd][^>]*>([\s\S]*?)<\/t[hd]>/gi)].map((c) => decode(c[1])))
|
||||
.filter((cells) => cells.length > 0));
|
||||
}
|
||||
|
||||
/** h2/h3 headings and the table that follows each, in order (the "one table per code" pages). */
|
||||
function parseHeadedTables(html) {
|
||||
const out = [];
|
||||
const seq = [...html.matchAll(/<h([23])[^>]*>([\s\S]*?)<\/h\1>|<table[\s\S]*?<\/table>/gi)];
|
||||
let heading = null;
|
||||
for (const m of seq) {
|
||||
if (m[0].startsWith("<h")) { heading = decode(m[2]); continue; }
|
||||
if (!heading) continue;
|
||||
const rows = [...m[0].matchAll(/<tr[\s\S]*?<\/tr>/gi)]
|
||||
.map((r) => [...r[0].matchAll(/<t[hd][^>]*>([\s\S]*?)<\/t[hd]>/gi)].map((c) => decode(c[1])));
|
||||
out.push({ heading, rows });
|
||||
heading = null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* winerror.h-style reference pages: `<strong>SYMBOL</strong>` followed by a paragraph with the
|
||||
* decimal value (optionally "(0x…)") and a paragraph with the text. Shape shared by the
|
||||
* System Error Codes pages and the WinHTTP error page.
|
||||
*/
|
||||
function parseSymbolPage(html) {
|
||||
const map = new Map();
|
||||
const re = /<strong>([A-Z][A-Z0-9_]+)<\/strong><\/p>(?:\s|<\/?(?:dt|dd|dl)>)*<p>(\d+)(?:\s*\(0x[0-9A-Fa-f]+\))?<\/p>(?:\s|<\/?(?:dt|dd|dl)>)*<p>([\s\S]*?)<\/p>/g;
|
||||
for (const m of html.matchAll(re)) {
|
||||
const value = Number(m[2]);
|
||||
if (!map.has(value)) map.set(value, { symbol: m[1], text: decode(m[3]) });
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
// ── Description shaping ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* One short line per code: whole sentences from the source text up to MAX_DESCRIPTION
|
||||
* characters (at least one sentence; a single over-long sentence is cut with an ellipsis).
|
||||
* Cross-reference sentences ("For more information, see …", "See …") are dropped. Pages whose
|
||||
* cell continues with troubleshooting prose pass `firstSentence` and keep only the first one.
|
||||
*/
|
||||
export function shapeDescription(text, { firstSentence = false } = {}) {
|
||||
const clean = String(text).replace(/\s+/g, " ").trim();
|
||||
const sentences = clean.split(/(?<=[.!?])\s+(?=[A-Z0-9("'])/)
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s && !/^(For (more )?information|See |Refer to)/i.test(s));
|
||||
const kept = [];
|
||||
let length = 0;
|
||||
for (const s of sentences) {
|
||||
if (kept.length > 0 && (firstSentence || length + 1 + s.length > MAX_DESCRIPTION)) break;
|
||||
kept.push(s);
|
||||
length += (kept.length > 1 ? 1 : 0) + s.length;
|
||||
}
|
||||
let result = kept.join(" ") || clean;
|
||||
if (result.length > MAX_DESCRIPTION + 20) result = result.slice(0, MAX_DESCRIPTION).trimEnd() + "…";
|
||||
result = result.replace(/\.$/, "");
|
||||
return result.charAt(0).toUpperCase() + result.slice(1);
|
||||
}
|
||||
|
||||
/** "InvalidDetectionRuleUnknownDetectionType" → "Invalid detection rule: unknown detection type". */
|
||||
export function humanizeMember(name) {
|
||||
const PREFIXES = ["InvalidDetectionRule", "InvalidRequirementRule", "AppLogUpload", "NotAttempted", "InProgress", "SuccessBut", "Success", "Error", "ResumeJobFailure"];
|
||||
const ACRONYMS = { CDN: "CDN", DO: "DO", SAS: "SAS", MSI: "MSI", VPP: "VPP", IOS: "iOS", TPM: "TPM", MDM: "MDM", HTTP: "HTTP", URL: "URL", COM: "COM", APK: "APK", CP: "CP", ID: "ID" };
|
||||
const words = (s) => s
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
|
||||
.split(" ")
|
||||
.map((w) => ACRONYMS[w.toUpperCase()] ?? w.toLowerCase());
|
||||
const prefix = PREFIXES.find((p) => name.startsWith(p) && name.length > p.length);
|
||||
if (prefix) {
|
||||
const head = words(prefix);
|
||||
const tail = words(name.slice(prefix.length));
|
||||
return capitalize(head.join(" ")) + ": " + tail.join(" ");
|
||||
}
|
||||
return capitalize(words(name).join(" "));
|
||||
}
|
||||
const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
|
||||
|
||||
// ── Key helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
const hexKey = (n) => "0x" + ((n >>> 0).toString(16)).padStart(8, "0");
|
||||
const fromSigned = (n) => hexKey(n < 0 ? n + 0x100000000 : n);
|
||||
const normalizeHex = (raw) => hexKey(parseInt(raw.replace(/^0x/i, ""), 16));
|
||||
const isFacility7 = (key) => key.startsWith("0x8007");
|
||||
const MSI_DECIMAL = (n) => n === 0 || (n >= 1601 && n <= 1654) || n === 3010;
|
||||
|
||||
// ── Families ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Win32 codes that the field has shown as 0x8007xxxx HRESULTs (beyond what other families name). */
|
||||
const WIN32_FIELD_SEEN = [
|
||||
1, 2, 3, 4, 5, 6, 8, 13, 14, 23, 32, 50, 53, 64, 67, 87, 112, 120, 122, 258, 314, 995, 1053, 1058, 1067,
|
||||
1114, 1168, 1203, 1219, 1220, 1222, 1223, 1231, 1232, 1235, 1259, 1311, 1312, 1326, 1327, 1355, 1385,
|
||||
1392, 1450, 1460, 1717, 1722, 1726, 1780, 1784, 1789, 1908, 1909, 3017, 8239,
|
||||
12002, 12007, 12029, 12030, 12152, 12175, 14081, 14107,
|
||||
];
|
||||
|
||||
/** HRESULTs that are not Win32-derived; text as in winerror.h. */
|
||||
const COM_ENTRIES = [
|
||||
["0x00000000", "S_OK", "Success"],
|
||||
["0x80004001", "E_NOTIMPL", "Not implemented"],
|
||||
["0x80004002", "E_NOINTERFACE", "No such interface supported"],
|
||||
["0x80004003", "E_POINTER", "Invalid pointer"],
|
||||
["0x80004004", "E_ABORT", "Operation aborted"],
|
||||
["0x80004005", "E_FAIL", "Unspecified error"],
|
||||
["0x8000ffff", "E_UNEXPECTED", "Catastrophic failure"],
|
||||
["0x80010108", "RPC_E_DISCONNECTED", "The object invoked has disconnected from its clients"],
|
||||
["0x80020005", "DISP_E_TYPEMISMATCH", "Type mismatch"],
|
||||
["0x80190193", "HTTP_E_STATUS_FORBIDDEN", "Forbidden (403)"],
|
||||
["0x80190194", "HTTP_E_STATUS_NOT_FOUND", "Not found (404)"],
|
||||
];
|
||||
|
||||
/**
|
||||
* Codes documented on prose pages (no table to parse). The generator asserts that the code
|
||||
* appears on the named page; the description is a one-sentence paraphrase of that page.
|
||||
*/
|
||||
const PROSE_ENTRIES = [
|
||||
{ key: "0x80180014", category: "mdm-enrollment", page: URL.enrollErrors,
|
||||
description: "Your organization does not support this version of Windows: MDM enrollment is disabled or restricted in the tenant, or an Autopilot device record still exists on redeploy" },
|
||||
{ key: "0x80180022", category: "autopilot", page: URL.enrollErrors,
|
||||
description: "Autopilot device enrollment failed: the device runs Windows Home edition (Pro or higher is required)" },
|
||||
{ key: "0x8018002b", category: "mdm-enrollment", page: URL.enrollErrors,
|
||||
description: "Automatic MDM enrollment failed: the user's UPN has an unverified or non-routable domain, or the MDM user scope is set to None" },
|
||||
{ key: "0x801c03ea", category: "entra-join", page: URL.enrollErrors,
|
||||
description: "Registering the device for mobile management failed: the TPM supports 2.0 but has not been upgraded to 2.0, or the device is in two groups with different Autopilot profiles" },
|
||||
{ key: "0x801c03f3", category: "entra-join", page: URL.knownIssues,
|
||||
description: "Microsoft Entra ID has no device object for the device being deployed (the object was deleted); remove the device from Entra ID, Intune and Autopilot and re-register it" },
|
||||
{ key: "0x81039001", category: "autopilot", page: URL.knownIssues, symbol: "E_AUTOPILOT_CLIENT_TPM_MAX_ATTESTATION_RETRY_EXCEEDED",
|
||||
description: "TPM attestation failed intermittently during self-deploying or pre-provisioning (Securing your hardware); a subsequent provisioning attempt often succeeds" },
|
||||
{ key: "0x81039023", category: "autopilot", page: URL.knownIssues,
|
||||
description: "TPM attestation failed on Windows 11 during self-deploying or pre-provisioning; fixed by the May 2022 cumulative update (KB5013943) or later" },
|
||||
{ key: "0x81039024", category: "autopilot", page: URL.knownIssues,
|
||||
description: "TPM attestation failed because known vulnerabilities were detected in the TPM; update the TPM firmware from the PC manufacturer" },
|
||||
{ key: "0xc1036501", category: "mdm-enrollment", page: URL.knownIssues,
|
||||
description: "The device cannot do an automatic MDM enrollment because there are multiple MDM configurations in Microsoft Entra ID" },
|
||||
// Named only in our own analysis rule, no MS page found: confidence medium.
|
||||
{ key: "0x80180018", category: "mdm-enrollment", source: "rule:ANALYZE-ENRL-004", confidence: "medium",
|
||||
description: "MDM enrollment refused for the user: missing Intune, EMS or Microsoft 365 license, or the device enrollment limit was exceeded" },
|
||||
];
|
||||
|
||||
/** v1 entries that no primary source covers — kept, marked low. */
|
||||
const LEGACY_ENTRIES = [
|
||||
["0x87d00213", "intune-win32", "App not applicable"],
|
||||
["0x87d00215", "intune-win32", "App dependency failed"],
|
||||
["0x87d00216", "intune-win32", "App supersedence conflict"],
|
||||
["0x87d00324", "intune-win32", "App installation failed"],
|
||||
["0x87d00607", "intune-win32", "App download failed"],
|
||||
["0x87d00651", "intune-win32", "Detection rules not met after install"],
|
||||
["0x87d13b88", "intune-mobile", "License assignment failed with token expired (VPP)"],
|
||||
["0x87d1fde8", "intune-win32", "Remediation failed"],
|
||||
["0x800f0991", "cbs", "A payload file is missing from the component store", "PSFX_E_MISSING_PAYLOAD_FILE"],
|
||||
];
|
||||
|
||||
/**
|
||||
* Wording pins: consumers (tests, rule explanations) depend on these exact phrases. Each pin
|
||||
* says the same thing as the source row it replaces; the confidence stays with the source.
|
||||
*/
|
||||
const DESCRIPTION_PINS = {
|
||||
"0x87d1041c": { description: "Application not detected after installation completed successfully" },
|
||||
// The MS row describes one dated incident ("The July cumulative update failed…"); the code itself is generic.
|
||||
"0x800f0922": { description: "Windows servicing: a package installer failed during update installation", confidence: "medium" },
|
||||
};
|
||||
|
||||
/**
|
||||
* Known defects in the IME enum source (sign / digit typos). The fixup applies the intended
|
||||
* value and FAILS when the source no longer shows the defect, so a fixed build drops the fixup.
|
||||
*/
|
||||
const IME_ENUM_FIXUPS = {
|
||||
InvalidRequirementRuleUnknownRequirementType: { seen: 2016215026, intended: -2016215026 },
|
||||
AppLogUploadSasUrlExpired: { seen: -216214830, intended: -2016214830 },
|
||||
};
|
||||
|
||||
// ── Build ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const entries = new Map(); // key → entry
|
||||
const dropped = []; // { key, family, reason }
|
||||
function add(family, key, entry) {
|
||||
if (!KEY_PATTERN.test(key)) throw new Error(`${family}: bad key ${key}`);
|
||||
if (entries.has(key)) { dropped.push({ key, family, reason: `already defined by ${entries.get(key)._family}` }); return; }
|
||||
const description = shapeDescription(entry.description, { firstSentence: entry.firstSentence });
|
||||
if (!description) throw new Error(`${family}: empty description for ${key}`);
|
||||
const out = { description, confidence: entry.confidence, source: entry.source, category: entry.category };
|
||||
// Symbol cells may be wrapped with <br> ("ERROR_INSTALL_OPEN_ PACKAGE_FAILED"); the token has no spaces.
|
||||
const symbol = entry.symbol ? String(entry.symbol).replace(/\s+/g, "") : "";
|
||||
if (symbol && SYMBOL_PATTERN.test(symbol)) out.symbol = symbol;
|
||||
if (entry.imeRetriesDuringEsp) out.imeRetriesDuringEsp = true;
|
||||
const pin = DESCRIPTION_PINS[key];
|
||||
if (pin) { out.description = pin.description; if (pin.confidence) out.confidence = pin.confidence; }
|
||||
Object.defineProperty(out, "_family", { value: family, enumerable: false });
|
||||
entries.set(key, out);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const retriable = new Set(ime.msiRetriableErrorCodes.map(Number));
|
||||
|
||||
// Families other than Win32 are collected first so every 0x8007xxxx code they name can be
|
||||
// resolved against the Win32 reference, which then takes precedence.
|
||||
const pending = [];
|
||||
const queue = (family, key, entry) => pending.push({ family, key, entry });
|
||||
|
||||
// msi — decimal keys, MSI range only (other rows are plain Win32 codes and live as 0x8007xxxx).
|
||||
{
|
||||
const [table] = parseTables(await fetchPage(URL.msi));
|
||||
for (const [symbol, value, description] of table.slice(1)) {
|
||||
const n = Number(value);
|
||||
if (!Number.isInteger(n) || !MSI_DECIMAL(n)) continue;
|
||||
queue("msi", String(n), { symbol, description, confidence: "high", source: msdoc(URL.msi), category: "msi", imeRetriesDuringEsp: retriable.has(n) });
|
||||
}
|
||||
}
|
||||
|
||||
// com
|
||||
for (const [key, symbol, description] of COM_ENTRIES) queue("com", key, { symbol, description, confidence: "high", source: "winerror.h", category: "com" });
|
||||
|
||||
// appx
|
||||
{
|
||||
const [table] = parseTables(await fetchPage(URL.appx));
|
||||
for (const [symbol, value, description] of table.slice(1)) {
|
||||
if (!/^0x[0-9a-f]{8}$/i.test(value)) continue;
|
||||
queue("appx", normalizeHex(value), { symbol, description, firstSentence: true, confidence: "high", source: msdoc(URL.appx), category: "appx" });
|
||||
}
|
||||
}
|
||||
|
||||
// windows-update reference (Error code | Message | Description), the components an
|
||||
// enrollment can meet: agent core, handlers, download manager, protocol talker (HTTP),
|
||||
// data store, drivers, MSI handler, agent setup, AU client. Inventory / expression
|
||||
// evaluator / reporter / redirector are WSUS-internal and left out.
|
||||
const WU_SECTIONS = /^(Automatic Update Errors|Windows Update UI errors|Protocol Talker errors|Other Protocol Talker errors|Download Manager errors|Update Handler errors|Data Store errors|Driver Util errors|Windows Update error codes|Windows Update success codes|Windows Installer minor errors|Windows Update Agent update and setup errors)$/;
|
||||
for (const { heading, rows: table } of parseHeadedTables(await fetchPage(URL.wuReference))) {
|
||||
if (!WU_SECTIONS.test(heading)) continue;
|
||||
for (const [value, message, description] of table.slice(1)) {
|
||||
if (!/^0x[0-9a-f]{8}$/i.test(value)) continue;
|
||||
const key = normalizeHex(value);
|
||||
queue("windows-update", key, { symbol: message, description, confidence: "high", source: msdoc(URL.wuReference), category: categoryForWuKey(key) });
|
||||
}
|
||||
}
|
||||
|
||||
// windows-update common errors (one table per heading; Message | Description | Mitigation)
|
||||
for (const { heading, rows } of parseHeadedTables(await fetchPage(URL.wuErrors))) {
|
||||
// A heading that lumps several codes into one table ("0x80072EFD or 0x80072EFE or 0x80D02002")
|
||||
// describes a symptom, not the codes; only single-code sections are taken.
|
||||
const codes = [...heading.matchAll(/0x[0-9a-f]{8}/gi)].map((m) => normalizeHex(m[0]));
|
||||
if (codes.length !== 1 || rows.length < 2) continue;
|
||||
const [message, description] = rows[1];
|
||||
const [symbolPart, ...textParts] = message.split(";");
|
||||
const symbol = symbolPart.trim();
|
||||
const text = textParts.join(";").trim() || (description && description !== "NA" ? description : "");
|
||||
if (!text) continue;
|
||||
for (const key of codes) queue("windows-update", key, { symbol, description: text, firstSentence: true, confidence: "high", source: msdoc(URL.wuErrors), category: categoryForWuKey(key) });
|
||||
}
|
||||
|
||||
// intune — skip the Android table (heading order: Android, iOS/iPadOS, Other)
|
||||
{
|
||||
const tables = parseTables(await fetchPage(URL.intuneApps));
|
||||
for (const table of tables.slice(1)) {
|
||||
for (const [value, , message, description] of table.slice(1)) {
|
||||
if (!/^0x[0-9a-f]{8}$/i.test(value)) continue;
|
||||
const key = normalizeHex(value);
|
||||
const text = /^\(client error\)$/i.test(message) ? description : message;
|
||||
const category = key === "0x87d1041c" || key === "0x87d103e8" ? "intune-win32" : key.startsWith("0x87d1") ? "intune-mobile" : "appx";
|
||||
queue("intune", key, { description: text, firstSentence: true, confidence: "high", source: msdoc(URL.intuneApps), category });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// prose pages
|
||||
for (const e of PROSE_ENTRIES) {
|
||||
if (e.page) {
|
||||
const html = (await fetchPage(e.page)).toLowerCase();
|
||||
if (!html.includes(e.key.toLowerCase())) throw new Error(`prose: ${e.key} not found on ${e.page}`);
|
||||
}
|
||||
queue("prose", e.key, { symbol: e.symbol, description: e.description, confidence: e.confidence ?? "high", source: e.source ?? msdoc(e.page), category: e.category });
|
||||
}
|
||||
|
||||
// IME CustomErrorCodes (0x87D3xxxx)
|
||||
for (const [name, rawValue] of Object.entries(ime.customErrorCodes)) {
|
||||
if (name === "Undefined") continue;
|
||||
let value = Number(rawValue);
|
||||
const fix = IME_ENUM_FIXUPS[name];
|
||||
if (fix) {
|
||||
if (value !== fix.seen) throw new Error(`IME fixup for ${name} is stale: source shows ${value}, fixup expects ${fix.seen}`);
|
||||
value = fix.intended;
|
||||
}
|
||||
queue("ime-custom", fromSigned(value), { symbol: name, description: humanizeMember(name), confidence: "medium", source: IME_SOURCE, category: "intune-win32" });
|
||||
}
|
||||
for (const missing of Object.keys(IME_ENUM_FIXUPS).filter((n) => !(n in ime.customErrorCodes))) {
|
||||
throw new Error(`IME fixup names ${missing}, which the enum extract does not contain`);
|
||||
}
|
||||
|
||||
// IME Delivery Optimization constants
|
||||
const doc = ime.deliveryOptimization;
|
||||
for (const group of [doc.errorCodesDoSvc, doc.transientErrorCodesDoSvc]) {
|
||||
for (const [name, value] of Object.entries(group)) {
|
||||
queue("ime-do", fromSigned(Number(value)), { symbol: name, description: humanizeMember(name), confidence: "medium", source: IME_SOURCE, category: "delivery-optimization" });
|
||||
}
|
||||
}
|
||||
const doWindowsCodes = Object.values(doc.windowsErrorCodes).map((v) => fromSigned(Number(v)));
|
||||
|
||||
// legacy
|
||||
for (const [key, category, description, symbol] of LEGACY_ENTRIES) queue("legacy", key, { symbol, description, confidence: "low", source: "legacy-catalog-v1", category });
|
||||
|
||||
// win32 — seed: field list ∪ retriable ∪ every facility-7 code any family named, minus the MSI decimal range.
|
||||
const win32Seed = new Set(WIN32_FIELD_SEEN);
|
||||
for (const n of retriable) win32Seed.add(n);
|
||||
// The AppX page is the authority for its own facility-7 range (0x80073Cxx/0x80073Dxx): its rows
|
||||
// carry the packaging-specific wording, so those codes are not routed through the Win32 reference.
|
||||
const appxKeys = new Set(pending.filter((p) => p.family === "appx").map((p) => p.key));
|
||||
for (const key of [...pending.map((p) => p.key), ...doWindowsCodes]) {
|
||||
if (isFacility7(key) && !appxKeys.has(key)) win32Seed.add(parseInt(key.slice(6), 16));
|
||||
}
|
||||
for (const n of [...win32Seed]) if (MSI_DECIMAL(n)) win32Seed.delete(n);
|
||||
|
||||
const win32Pages = new Map();
|
||||
const resolveWin32 = async (n) => {
|
||||
const useWinHttp = n >= WINHTTP_RANGE[0] && n <= WINHTTP_RANGE[1];
|
||||
const range = WIN32_RANGES.find(([lo, hi]) => n >= lo && n <= hi);
|
||||
const candidates = useWinHttp ? [URL.winhttp] : [];
|
||||
if (range) candidates.push(URL.win32(`${range[0]}-${range[1]}`));
|
||||
for (const url of candidates) {
|
||||
if (!win32Pages.has(url)) win32Pages.set(url, parseSymbolPage(await fetchPage(url)));
|
||||
const hit = win32Pages.get(url).get(n);
|
||||
if (hit) return { ...hit, url };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
// A code another family names but the Win32 reference does not list (the AppX page carries
|
||||
// 0x80073Dxx symbols the System Error Codes pages omit) stays with that family; a code from
|
||||
// the explicit seed must resolve.
|
||||
const mustResolve = new Set([...WIN32_FIELD_SEEN, ...retriable]);
|
||||
const unresolved = [];
|
||||
for (const n of [...win32Seed].sort((a, b) => a - b)) {
|
||||
const hit = await resolveWin32(n);
|
||||
if (!hit) { if (mustResolve.has(n)) unresolved.push(n); continue; }
|
||||
add("win32", hexKey(0x80070000 + n), { symbol: hit.symbol, description: hit.text, confidence: "high", source: msdoc(hit.url), category: "win32", imeRetriesDuringEsp: retriable.has(n) });
|
||||
}
|
||||
if (unresolved.length > 0) throw new Error(`win32: no reference entry for ${unresolved.join(", ")}`);
|
||||
|
||||
for (const p of pending) add(p.family, p.key, p.entry);
|
||||
|
||||
// enforcement states
|
||||
const enforcementStates = {};
|
||||
for (const [name, value] of Object.entries(ime.enforcementStates)) {
|
||||
enforcementStates[String(value)] = { name, description: humanizeMember(name) };
|
||||
}
|
||||
|
||||
validate(entries, enforcementStates);
|
||||
|
||||
// ── Emit ──
|
||||
const keys = [...entries.keys()].sort((a, b) => {
|
||||
const ah = a.startsWith("0x"), bh = b.startsWith("0x");
|
||||
if (ah !== bh) return ah ? 1 : -1;
|
||||
return ah ? a.localeCompare(b) : Number(a) - Number(b);
|
||||
});
|
||||
const stateKeys = Object.keys(enforcementStates).sort((a, b) => Number(a) - Number(b));
|
||||
const header = {
|
||||
schemaVersion: 2,
|
||||
description:
|
||||
"Single-source catalog of Windows / MSI / Intune error codes, generated by scripts/error-codes/generate.mjs from primary sources — " +
|
||||
"never edit by hand. Consumed by the backend (ErrorCodeCatalog.cs, ErrorCodeEnricher.cs), the web app (utils/errorCodeMap.ts via the " +
|
||||
"sync-error-codes prebuild step) and the MCP server (lookup_error_code). Keys are lowercase 8-digit hex ('0x80070005') or decimal MSI exit " +
|
||||
"codes ('1603'; only 0, 1601-1654, 3010 — other decimal exit codes are installer-defined). Win32 codes live only as 0x8007xxxx entries; " +
|
||||
"HRESULT_FROM_WIN32 values in the MSI range resolve to the decimal entry at lookup time. confidence: high = MS Learn or the IME build named " +
|
||||
"in source; medium = paraphrase of an enum member name or of an analysis rule; low = carried over from the v1 catalog without a primary " +
|
||||
"source. category is one of: " + CATEGORIES.join(", ") + ". imeRetriesDuringEsp marks the MSI return codes the IME retries automatically " +
|
||||
"during the Autopilot ESP. enforcementStates maps the IME app enforcement state numbers to their names.",
|
||||
};
|
||||
const lines = [];
|
||||
lines.push("{");
|
||||
lines.push(` "schemaVersion": ${header.schemaVersion},`);
|
||||
lines.push(` "description": ${JSON.stringify(header.description)},`);
|
||||
lines.push(` "entries": {`);
|
||||
keys.forEach((k, i) => lines.push(` ${JSON.stringify(k)}: ${JSON.stringify(entries.get(k))}${i < keys.length - 1 ? "," : ""}`));
|
||||
lines.push(` },`);
|
||||
lines.push(` "enforcementStates": {`);
|
||||
stateKeys.forEach((k, i) => lines.push(` ${JSON.stringify(k)}: ${JSON.stringify(enforcementStates[k])}${i < stateKeys.length - 1 ? "," : ""}`));
|
||||
lines.push(` }`);
|
||||
lines.push("}");
|
||||
const output = lines.join("\n") + "\n";
|
||||
|
||||
const byFamily = {};
|
||||
for (const e of entries.values()) byFamily[e._family] = (byFamily[e._family] ?? 0) + 1;
|
||||
console.error(`entries: ${entries.size} (${Object.entries(byFamily).map(([f, n]) => `${f} ${n}`).join(", ")}), enforcementStates: ${stateKeys.length}`);
|
||||
if (dropped.length > 0) console.error(`dropped duplicates: ${dropped.map((d) => `${d.key}←${d.family} (${d.reason})`).join("; ")}`);
|
||||
|
||||
if (checkOnly) {
|
||||
const current = existsSync(TARGET) ? readFileSync(TARGET, "utf8") : "";
|
||||
if (current !== output) { console.error("catalog differs from generator output"); process.exit(1); }
|
||||
console.error("catalog is up to date");
|
||||
return;
|
||||
}
|
||||
writeFileSync(TARGET, output, "utf8");
|
||||
console.error(`wrote ${path.relative(REPO_ROOT, TARGET)}`);
|
||||
execFileSync(process.execPath, [WEB_SYNC], { stdio: "inherit" });
|
||||
}
|
||||
|
||||
function categoryForWuKey(key) {
|
||||
if (key.startsWith("0x800f")) return "cbs";
|
||||
if (key.startsWith("0x80d0")) return "delivery-optimization";
|
||||
return "windows-update";
|
||||
}
|
||||
|
||||
function validate(map, states) {
|
||||
const symbols = new Map();
|
||||
for (const [key, e] of map) {
|
||||
if (!KEY_PATTERN.test(key)) throw new Error(`bad key ${key}`);
|
||||
if (!e.description) throw new Error(`${key}: empty description`);
|
||||
if (e.description.length > MAX_DESCRIPTION + 21) throw new Error(`${key}: description too long`);
|
||||
if (!CONFIDENCES.includes(e.confidence)) throw new Error(`${key}: bad confidence ${e.confidence}`);
|
||||
if (!CATEGORIES.includes(e.category)) throw new Error(`${key}: bad category ${e.category}`);
|
||||
if (!SOURCE_PATTERN.test(e.source)) throw new Error(`${key}: bad source ${e.source}`);
|
||||
if (e.symbol) {
|
||||
if (symbols.has(e.symbol)) throw new Error(`symbol ${e.symbol} on both ${symbols.get(e.symbol)} and ${key}`);
|
||||
symbols.set(e.symbol, key);
|
||||
}
|
||||
}
|
||||
const names = new Set();
|
||||
for (const [k, s] of Object.entries(states)) {
|
||||
if (!/^-?\d+$/.test(k)) throw new Error(`enforcement state key ${k}`);
|
||||
if (names.has(s.name)) throw new Error(`enforcement state name ${s.name} twice`);
|
||||
names.add(s.name);
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
main().catch((err) => { console.error(err.stack ?? String(err)); process.exit(1); });
|
||||
}
|
||||
@@ -34,6 +34,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests
|
||||
new Regex("\\[\"eventType\"\\]\\s*=\\s*\"([a-z][a-z0-9_]*)\"", RegexOptions.Compiled),
|
||||
};
|
||||
|
||||
// Multi-line callback shape (2026-09-04, D-072 gap): `OnTraceEvent?.Invoke(` at the end
|
||||
// of one line, the event-type literal alone on the NEXT line. The single-line patterns
|
||||
// above never saw `desktop_real_user_detected` / `desktop_excluded_user` this way.
|
||||
private static readonly Regex InvokeOpener = new Regex("\\.Invoke\\(\\s*$", RegexOptions.Compiled);
|
||||
private static readonly Regex BareLiteralLine = new Regex("^\\s*\"([a-z][a-z0-9_]*)\"\\s*,?\\s*$", RegexOptions.Compiled);
|
||||
|
||||
// The reducer/param key name itself ("eventType") and the like are not event types.
|
||||
private static readonly HashSet<string> NotEventTypes = new(StringComparer.Ordinal)
|
||||
{
|
||||
@@ -59,33 +65,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests
|
||||
Assert.True(Directory.Exists(full), $"V2 source dir not found: {full}");
|
||||
|
||||
foreach (var file in EnumerateSourceFiles(full))
|
||||
{
|
||||
var lines = File.ReadAllLines(file);
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
var line = lines[i];
|
||||
var trimmed = line.TrimStart();
|
||||
|
||||
// Skip comments and const DEFINITIONS (Constants/DeadlineNames key names etc.).
|
||||
if (trimmed.StartsWith("//") || trimmed.StartsWith("*") || trimmed.StartsWith("///"))
|
||||
continue;
|
||||
if (line.Contains("const ")) continue;
|
||||
|
||||
foreach (var pattern in EmitPatterns)
|
||||
{
|
||||
foreach (Match m in pattern.Matches(line))
|
||||
{
|
||||
var literal = m.Groups[1].Value;
|
||||
if (NotEventTypes.Contains(literal)) continue;
|
||||
if (!known.Contains(literal))
|
||||
{
|
||||
offenders.Add(
|
||||
$"{Path.GetFileName(file)}:{i + 1} \"{literal}\" -> {line.Trim()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
offenders.AddRange(FindOffenders(Path.GetFileName(file), File.ReadAllLines(file), known));
|
||||
}
|
||||
|
||||
Assert.True(
|
||||
@@ -95,6 +75,65 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests
|
||||
string.Join("\n ", offenders));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Guard_detects_multiline_Invoke_literal()
|
||||
{
|
||||
// Mutation proof for the multi-line shape: a synthetic emit site with an unknown
|
||||
// literal on the line after `OnTraceEvent?.Invoke(` must be reported; the same
|
||||
// shape with a known type must not.
|
||||
var known = new HashSet<string>(StringComparer.Ordinal) { "desktop_arrived" };
|
||||
string[] bad =
|
||||
{
|
||||
" OnTraceEvent?.Invoke(",
|
||||
" \"desktop_not_a_real_type\",",
|
||||
" $\"Real user desktop detected\",",
|
||||
};
|
||||
string[] good =
|
||||
{
|
||||
" OnTraceEvent?.Invoke(",
|
||||
" \"desktop_arrived\",",
|
||||
};
|
||||
|
||||
var offender = Assert.Single(FindOffenders("X.cs", bad, known));
|
||||
Assert.Contains("desktop_not_a_real_type", offender);
|
||||
Assert.Empty(FindOffenders("X.cs", good, known));
|
||||
}
|
||||
|
||||
private static List<string> FindOffenders(string fileName, string[] lines, HashSet<string> known)
|
||||
{
|
||||
var offenders = new List<string>();
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
var line = lines[i];
|
||||
var trimmed = line.TrimStart();
|
||||
|
||||
// Skip comments and const DEFINITIONS (Constants/DeadlineNames key names etc.).
|
||||
if (trimmed.StartsWith("//") || trimmed.StartsWith("*") || trimmed.StartsWith("///"))
|
||||
continue;
|
||||
if (line.Contains("const ")) continue;
|
||||
|
||||
foreach (var pattern in EmitPatterns)
|
||||
{
|
||||
foreach (Match m in pattern.Matches(line))
|
||||
Check(m.Groups[1].Value, line, i);
|
||||
}
|
||||
|
||||
if (i > 0 && InvokeOpener.IsMatch(lines[i - 1]))
|
||||
{
|
||||
var bare = BareLiteralLine.Match(line);
|
||||
if (bare.Success) Check(bare.Groups[1].Value, line, i);
|
||||
}
|
||||
}
|
||||
return offenders;
|
||||
|
||||
void Check(string literal, string line, int index)
|
||||
{
|
||||
if (NotEventTypes.Contains(literal)) return;
|
||||
if (!known.Contains(literal))
|
||||
offenders.Add($"{fileName}:{index + 1} \"{literal}\" -> {line.Trim()}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>All string-const values declared on <see cref="Constants.EventTypes"/>.</summary>
|
||||
private static HashSet<string> KnownEventTypes()
|
||||
{
|
||||
@@ -113,18 +152,6 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests
|
||||
.Where(p => !p.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}")
|
||||
&& !p.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}"));
|
||||
|
||||
private static string RepoRoot()
|
||||
{
|
||||
var dir = AppContext.BaseDirectory;
|
||||
for (int i = 0; i < 12; i++)
|
||||
{
|
||||
if (File.Exists(Path.Combine(dir, "AutopilotMonitor.sln"))) return dir;
|
||||
var parent = Directory.GetParent(dir)?.FullName;
|
||||
if (parent == null || parent == dir) break;
|
||||
dir = parent;
|
||||
}
|
||||
throw new DirectoryNotFoundException(
|
||||
"Could not locate repo root (AutopilotMonitor.sln) from " + AppContext.BaseDirectory);
|
||||
}
|
||||
private static string RepoRoot() => Harness.RepoPaths.Root();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Harness
|
||||
{
|
||||
/// <summary>Repository paths for tests that read or write checked-in files (guards, fixtures).</summary>
|
||||
internal static class RepoPaths
|
||||
{
|
||||
/// <summary>Walks up from the test binary to the directory holding <c>AutopilotMonitor.sln</c>.</summary>
|
||||
public static string Root()
|
||||
{
|
||||
var dir = AppContext.BaseDirectory;
|
||||
for (int i = 0; i < 12; i++)
|
||||
{
|
||||
if (File.Exists(Path.Combine(dir, "AutopilotMonitor.sln"))) return dir;
|
||||
var parent = Directory.GetParent(dir)?.FullName;
|
||||
if (parent == null || parent == dir) break;
|
||||
dir = parent;
|
||||
}
|
||||
throw new DirectoryNotFoundException(
|
||||
"Could not locate repo root (AutopilotMonitor.sln) from " + AppContext.BaseDirectory);
|
||||
}
|
||||
|
||||
/// <summary><c>tests/fixtures/<name></c> under the repo root.</summary>
|
||||
public static string Fixtures(string name) => Path.Combine(Root(), "tests", "fixtures", name);
|
||||
}
|
||||
}
|
||||
+1
@@ -13,6 +13,7 @@ using AutopilotMonitor.DecisionCore.Classifiers;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Integration
|
||||
{
|
||||
|
||||
@@ -5,6 +5,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using AutopilotMonitor.DecisionCore.Classifiers;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
#pragma warning disable xUnit1031 // SpinWait.SpinUntil for uploader-batch-arrival assertion
|
||||
|
||||
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Linq;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals;
|
||||
using AutopilotMonitor.Agent.V2.Core.Orchestration;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Orchestration;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using SharedEventTypes = AutopilotMonitor.Shared.Constants.EventTypes;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring
|
||||
{
|
||||
/// <summary>
|
||||
/// Entra user affinity after the real-user desktop (2026-09-04, session a7140f98). The
|
||||
/// contracts that matter: arm only on Hybrid devices and only at the desktop; the first
|
||||
/// IME user-token line AFTER the desktop cancels and posts <c>ime_user_token_acquired</c>;
|
||||
/// token lines from before the desktop (device phase) are ignored; the timer posts
|
||||
/// <c>entra_user_affinity_pending</c> with the failure codes seen since the desktop; both
|
||||
/// emissions are single-shot per process.
|
||||
/// </summary>
|
||||
public sealed class EntraUserAffinityDetectorTests
|
||||
{
|
||||
private static readonly DateTime Fixed = new DateTime(2026, 9, 4, 13, 54, 6, DateTimeKind.Utc);
|
||||
|
||||
private sealed class Fixture : IDisposable
|
||||
{
|
||||
public TempDirectory Tmp { get; } = new TempDirectory();
|
||||
public AgentLogger Logger { get; }
|
||||
public FakeSignalIngressSink Ingress { get; } = new FakeSignalIngressSink();
|
||||
public VirtualClock Clock { get; } = new VirtualClock(Fixed);
|
||||
public InformationalEventPost Post { get; }
|
||||
public bool Hybrid { get; set; } = true;
|
||||
public bool PlaceholderActive { get; set; } = true;
|
||||
|
||||
public Fixture()
|
||||
{
|
||||
Logger = new AgentLogger(Tmp.Path, AgentLogLevel.Info);
|
||||
Post = new InformationalEventPost(Ingress, Clock);
|
||||
}
|
||||
|
||||
public EntraUserAffinityDetector Build() => new EntraUserAffinityDetector(
|
||||
Post, Logger,
|
||||
isHybridJoinProbe: () => Hybrid,
|
||||
placeholderActiveProbe: () => PlaceholderActive,
|
||||
delay: TimeSpan.FromMinutes(10),
|
||||
utcNow: () => Clock.UtcNow);
|
||||
|
||||
public void Dispose() => Tmp.Dispose();
|
||||
}
|
||||
|
||||
private static FakeSignalIngressSink.PostedSignal? Find(FakeSignalIngressSink ingress, string eventType) =>
|
||||
ingress.Posted.FirstOrDefault(p =>
|
||||
p.Kind == DecisionSignalKind.InformationalEvent
|
||||
&& p.Payload != null
|
||||
&& p.Payload.TryGetValue(SignalPayloadKeys.EventType, out var et)
|
||||
&& et == eventType);
|
||||
|
||||
[Fact]
|
||||
public void Desktop_on_hybrid_device_arms()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
|
||||
Assert.True(d.IsArmedForTest);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Desktop_on_non_hybrid_device_does_not_arm()
|
||||
{
|
||||
using var f = new Fixture { Hybrid = false };
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.TriggerFromTest();
|
||||
|
||||
Assert.False(d.IsArmedForTest);
|
||||
Assert.Null(Find(f.Ingress, SharedEventTypes.EntraUserAffinityPending));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Timer_without_token_emits_pending_with_failure_codes()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.NotifyTokenFailureLine("3399548929", f.Clock.UtcNow.AddMinutes(1));
|
||||
d.NotifyTokenFailureLine("3399548929", f.Clock.UtcNow.AddMinutes(3));
|
||||
d.NotifyTokenFailureLine("3400073247", f.Clock.UtcNow.AddMinutes(5));
|
||||
f.Clock.Advance(TimeSpan.FromMinutes(10));
|
||||
d.TriggerFromTest();
|
||||
|
||||
var pending = Find(f.Ingress, SharedEventTypes.EntraUserAffinityPending);
|
||||
Assert.NotNull(pending);
|
||||
Assert.Equal("Warning", pending!.Payload![SignalPayloadKeys.Severity]);
|
||||
Assert.Equal("true", pending.Payload[SignalPayloadKeys.ImmediateUpload]);
|
||||
Assert.Equal("EntraUserAffinityDetector", pending.Payload[SignalPayloadKeys.Source]);
|
||||
Assert.Equal("10", pending.Payload["delayMinutes"]);
|
||||
Assert.Equal("timer_fired", pending.Payload["reason"]);
|
||||
Assert.Equal("3", pending.Payload["tokenFailureCount"]);
|
||||
Assert.Equal("3399548929,3400073247", pending.Payload["tokenFailureCodes"]);
|
||||
Assert.Equal("true", pending.Payload["placeholderActive"]);
|
||||
Assert.Equal("10.0", pending.Payload["minutesSinceDesktop"]);
|
||||
Assert.True(d.HasFiredForTest);
|
||||
Assert.Null(Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Token_after_desktop_cancels_and_posts_token_acquired()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.NotifyTokenFailureLine("3399548929", f.Clock.UtcNow.AddSeconds(30));
|
||||
var tokenAt = f.Clock.UtcNow.AddMinutes(3.7);
|
||||
d.NotifyUserTokenAcquired(tokenAt);
|
||||
f.Clock.Advance(TimeSpan.FromMinutes(10));
|
||||
d.TriggerFromTest();
|
||||
|
||||
var acquired = Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired);
|
||||
Assert.NotNull(acquired);
|
||||
Assert.Equal("Info", acquired!.Payload![SignalPayloadKeys.Severity]);
|
||||
Assert.Equal("3.7", acquired.Payload["minutesAfterDesktop"]);
|
||||
Assert.Equal("1", acquired.Payload["tokenFailuresBeforeSuccess"]);
|
||||
Assert.Equal(tokenAt, acquired.OccurredAtUtc);
|
||||
Assert.True(d.TokenAcquiredPostedForTest);
|
||||
Assert.False(d.HasFiredForTest);
|
||||
Assert.Null(Find(f.Ingress, SharedEventTypes.EntraUserAffinityPending));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Token_lines_from_before_the_desktop_are_ignored()
|
||||
{
|
||||
// Device-phase token lines ("Failed to get AAD token" is routine there; a success
|
||||
// can be the device check-in) must neither count nor cancel — the 2-min tolerance
|
||||
// only covers the desktop poll interval.
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.NotifyUserTokenAcquired(f.Clock.UtcNow.AddMinutes(-20));
|
||||
d.NotifyTokenFailureLine("3399548929", f.Clock.UtcNow.AddMinutes(-15));
|
||||
f.Clock.Advance(TimeSpan.FromMinutes(10));
|
||||
d.TriggerFromTest();
|
||||
|
||||
Assert.Null(Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired));
|
||||
var pending = Find(f.Ingress, SharedEventTypes.EntraUserAffinityPending);
|
||||
Assert.NotNull(pending);
|
||||
Assert.Equal("0", pending!.Payload!["tokenFailureCount"]);
|
||||
Assert.Equal(string.Empty, pending.Payload["tokenFailureCodes"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Token_within_desktop_poll_tolerance_counts_as_after_desktop()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.NotifyUserTokenAcquired(f.Clock.UtcNow.AddSeconds(-90));
|
||||
|
||||
Assert.NotNull(Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired));
|
||||
Assert.Equal("0.0", Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired)!.Payload!["minutesAfterDesktop"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Token_without_arm_is_ignored()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyUserTokenAcquired(f.Clock.UtcNow);
|
||||
|
||||
Assert.Null(Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pending_fires_once_and_a_late_token_still_resolves_it_once()
|
||||
{
|
||||
// A token that arrives AFTER the warning is the most useful thing the timeline can
|
||||
// show ("affinity came late") and lets the backend rule drop the finding — so it is
|
||||
// posted, but like the warning only once per process.
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.NotifyRealUserDesktop();
|
||||
f.Clock.Advance(TimeSpan.FromMinutes(10));
|
||||
d.TriggerFromTest();
|
||||
d.TriggerFromTest();
|
||||
d.NotifyUserTokenAcquired(f.Clock.UtcNow);
|
||||
d.NotifyUserTokenAcquired(f.Clock.UtcNow.AddMinutes(1));
|
||||
|
||||
Assert.Single(f.Ingress.Posted, p =>
|
||||
p.Payload != null && p.Payload.TryGetValue(SignalPayloadKeys.EventType, out var et)
|
||||
&& et == SharedEventTypes.EntraUserAffinityPending);
|
||||
Assert.Single(f.Ingress.Posted, p =>
|
||||
p.Payload != null && p.Payload.TryGetValue(SignalPayloadKeys.EventType, out var et)
|
||||
&& et == SharedEventTypes.ImeUserTokenAcquired);
|
||||
Assert.Equal("10.0", Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired)!.Payload!["minutesAfterDesktop"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Hybrid_probe_throwing_does_not_arm()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var d = new EntraUserAffinityDetector(
|
||||
f.Post, f.Logger,
|
||||
isHybridJoinProbe: () => throw new InvalidOperationException("registry"),
|
||||
utcNow: () => f.Clock.UtcNow);
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
|
||||
Assert.False(d.IsArmedForTest);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_after_arm_does_not_throw_and_blocks_emission()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.Dispose();
|
||||
d.TriggerFromTest();
|
||||
|
||||
Assert.Null(Find(f.Ingress, SharedEventTypes.EntraUserAffinityPending));
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
@@ -73,6 +73,27 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring
|
||||
Assert.Equal("true", info.Payload![SignalPayloadKeys.ImmediateUpload]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(304, "join phase")]
|
||||
[InlineData(305, "authentication phase")]
|
||||
public void ProcessHelloEvent_304_305_emit_device_registration_event_with_immediate_upload(int eventId, string phaseLabel)
|
||||
{
|
||||
// Hybrid affinity companion (2026-09-04): UDR 304/305 ride the already-armed
|
||||
// watcher and surface as device_registration_event — a Warning, flushed at once,
|
||||
// and never a Hello completion.
|
||||
using var f = new Fixture();
|
||||
|
||||
f.Tracker.ProcessHelloEvent(eventId, Fixed, "Microsoft-Windows-User Device Registration", isBackfill: false);
|
||||
|
||||
var info = f.InfoEvent("device_registration_event");
|
||||
Assert.Equal("Warning", info.Payload![SignalPayloadKeys.Severity]);
|
||||
Assert.Equal("true", info.Payload[SignalPayloadKeys.ImmediateUpload]);
|
||||
Assert.Contains(phaseLabel, info.Payload[SignalPayloadKeys.Message]);
|
||||
Assert.DoesNotContain(f.Ingress.Posted, p =>
|
||||
p.Payload != null && p.Payload.TryGetValue(SignalPayloadKeys.EventType, out var et)
|
||||
&& et.StartsWith("hello_provisioning"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProcessHelloEvent_358_willlaunch_is_suppressed()
|
||||
{
|
||||
|
||||
+52
@@ -194,6 +194,58 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring
|
||||
Assert.NotNull(FindHybridLoginPending(f.Ingress));
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Real-user desktop cancel path (2026-09-04, session a7140f98)
|
||||
// ============================================================================
|
||||
|
||||
[Fact]
|
||||
public void Real_user_desktop_after_Arm_cancels_emission()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var detector = new HybridLoginPendingDetector(f.Watcher, f.Post, f.Logger);
|
||||
|
||||
detector.Arm();
|
||||
detector.NotifyRealUserDesktop();
|
||||
detector.TriggerFromTest();
|
||||
|
||||
Assert.True(detector.IsCancelledByDesktopForTest);
|
||||
Assert.False(detector.HasFiredForTest);
|
||||
Assert.Null(FindHybridLoginPending(f.Ingress));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Real_user_desktop_before_Arm_short_circuits_Arm()
|
||||
{
|
||||
// The DAD first poll runs seconds after start; the arm request comes from the
|
||||
// runtime host slightly later. A desktop seen first must make the arm a no-op.
|
||||
using var f = new Fixture();
|
||||
using var detector = new HybridLoginPendingDetector(f.Watcher, f.Post, f.Logger);
|
||||
|
||||
detector.NotifyRealUserDesktop();
|
||||
detector.Arm();
|
||||
detector.TriggerFromTest();
|
||||
|
||||
Assert.False(detector.IsArmedForTest);
|
||||
Assert.Null(FindHybridLoginPending(f.Ingress));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Emission_reports_desktop_absence_and_placeholder_as_fact()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var detector = new HybridLoginPendingDetector(f.Watcher, f.Post, f.Logger);
|
||||
|
||||
detector.Arm();
|
||||
detector.TriggerFromTest();
|
||||
|
||||
var info = FindHybridLoginPending(f.Ingress);
|
||||
Assert.NotNull(info);
|
||||
Assert.Equal("false", info!.Payload!["realUserDesktopSeen"]);
|
||||
Assert.Equal("false", info.Payload["placeholderActive"]); // watcher never saw JoinInfo in this fixture
|
||||
Assert.Contains("no real-user desktop", info.Payload[SignalPayloadKeys.Message]);
|
||||
Assert.DoesNotContain("placeholder still active", info.Payload[SignalPayloadKeys.Message]);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Lifecycle / Dispose
|
||||
// ============================================================================
|
||||
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// Backlog era anchoring (2026-09-04, session a7140f98). The property under test: the
|
||||
/// bootstrap execution record — stdout in AgentExecutor.log, policy result in the service
|
||||
/// log — measured against the install marker anchors exactly the era it sits in; a SKIP
|
||||
/// re-run, a missing marker, an MSI bootstrap and an off-grid residual anchor nothing; the
|
||||
/// anchor never crosses an "EMS Agent Started" boundary; sibling files join by local time
|
||||
/// only while the service eras are unambiguous.
|
||||
/// </summary>
|
||||
public sealed class ImeLogEraPreScanTests
|
||||
{
|
||||
private static readonly DateTime Deployed = new DateTime(2026, 9, 4, 13, 31, 49, 100, DateTimeKind.Utc);
|
||||
private static readonly TimeSpan Pacific = TimeSpan.FromHours(-7);
|
||||
private static readonly TimeSpan Eastern = TimeSpan.FromHours(-4);
|
||||
private const string PolicyId = "93d9df23-1111-2222-3333-444455556666";
|
||||
|
||||
private static string Entry(string message, DateTime utcInstant, TimeSpan writerOffset)
|
||||
{
|
||||
var local = utcInstant + writerOffset;
|
||||
return $"<![LOG[{message}]LOG]!><time=\"{local:HH:mm:ss.fffffff}\" date=\"{local:M-d-yyyy}\" " +
|
||||
"component=\"X\" context=\"\" type=\"1\" thread=\"1\" file=\"\">";
|
||||
}
|
||||
|
||||
private static string ScriptStart(DateTime utc, TimeSpan offset) =>
|
||||
Entry($@"Adding argument powershell with value C:\Program Files (x86)\Microsoft Intune Management Extension\Policies\Scripts\00000000-0000-0000-0000-000000000000_{PolicyId}.ps1", utc, offset);
|
||||
|
||||
private static string BootstrapStdout(DateTime utc, TimeSpan offset, string tail = "===== Bootstrap Completed Successfully =====") =>
|
||||
Entry("write output done. output = ===== Autopilot Monitor Bootstrap Started =====\nBootstrap script version: v2.0\nAgent install mode completed successfully\n" + tail + ", error = ", utc, offset);
|
||||
|
||||
private static string PolicyResult(DateTime utc, TimeSpan offset, string policyId = PolicyId) =>
|
||||
Entry($"[PowerShell] User Id = 00000000-0000-0000-0000-000000000000, Policy id = {policyId}, policy result = Success", utc, offset);
|
||||
|
||||
private static string ServiceStarted(DateTime utc, TimeSpan offset) => Entry("EMS Agent Started", utc, offset);
|
||||
|
||||
private sealed class Fixture : IDisposable
|
||||
{
|
||||
public TempDirectory Tmp { get; } = new TempDirectory();
|
||||
private readonly List<ImeLogEraPreScan.ScanInput> _inputs = new List<ImeLogEraPreScan.ScanInput>();
|
||||
|
||||
public string Write(string fileName, params string[] entries)
|
||||
{
|
||||
var path = Path.Combine(Tmp.Path, fileName);
|
||||
File.WriteAllText(path, string.Join(Environment.NewLine, entries) + Environment.NewLine);
|
||||
_inputs.Add(new ImeLogEraPreScan.ScanInput(path, 0));
|
||||
return path;
|
||||
}
|
||||
|
||||
public long OffsetOfLine(string fileName, int lineIndex)
|
||||
{
|
||||
// Entries are written line by line; the byte offset of entry N is the sum of the
|
||||
// preceding lines (CRLF-agnostic through Environment.NewLine).
|
||||
var path = Path.Combine(Tmp.Path, fileName);
|
||||
var lines = File.ReadAllLines(path);
|
||||
long offset = 0;
|
||||
for (var i = 0; i < lineIndex; i++)
|
||||
offset += System.Text.Encoding.UTF8.GetByteCount(lines[i]) + Environment.NewLine.Length;
|
||||
return offset;
|
||||
}
|
||||
|
||||
public CmTraceEraTable Build(DateTime? deployed) =>
|
||||
ImeLogEraPreScan.Build(_inputs, deployed, ImeLogTracker.MaxEntryBytes, null);
|
||||
|
||||
public void Dispose() => Tmp.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Bootstrap_record_anchors_service_era_and_executor_block_only_within_their_boundaries()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
f.Write("AgentExecutor.log",
|
||||
ScriptStart(Deployed.AddSeconds(-20), Pacific),
|
||||
BootstrapStdout(Deployed.AddMilliseconds(200), Pacific),
|
||||
Entry("Adding argument powershell with value C:\\x\\Policies\\Scripts\\u_aaaaaaaa-0000-0000-0000-000000000000.ps1", Deployed.AddMinutes(5), Pacific),
|
||||
Entry("write output done. output = other script, error = ", Deployed.AddMinutes(5).AddSeconds(2), Pacific));
|
||||
f.Write("IntuneManagementExtension.log",
|
||||
Entry("In EspPhase: DeviceSetup", Deployed.AddMinutes(-1), Pacific), // line 0, era 0
|
||||
PolicyResult(Deployed.AddMilliseconds(260), Pacific), // line 1, anchor
|
||||
Entry("In EspPhase: DeviceSetup", Deployed.AddMinutes(10), Pacific), // line 2, era 0
|
||||
ServiceStarted(Deployed.AddMinutes(20), Eastern), // line 3, era 1 (post-boot, new zone)
|
||||
Entry("Successfully get the token", Deployed.AddMinutes(21), Eastern)); // line 4, era 1
|
||||
|
||||
var table = f.Build(Deployed);
|
||||
|
||||
Assert.Equal(2, table.AnchoredEraCount);
|
||||
Assert.False(table.TransferAmbiguous);
|
||||
|
||||
// Service era 0: every offset before "EMS Agent Started" resolves to the Pacific offset.
|
||||
Assert.True(table.TryResolveByOffset("IntuneManagementExtension.log", f.OffsetOfLine("IntuneManagementExtension.log", 0), out var off0, out var kind0));
|
||||
Assert.Equal(Pacific, off0);
|
||||
Assert.Equal(ImeLogEraPreScan.AnchorKindBootstrapPolicyResult, kind0);
|
||||
Assert.True(table.TryResolveByOffset("IntuneManagementExtension.log", f.OffsetOfLine("IntuneManagementExtension.log", 2), out var off2, out _));
|
||||
Assert.Equal(Pacific, off2);
|
||||
|
||||
// Era 1 has no anchor of its own — the Pacific anchor must not leak across the boundary.
|
||||
Assert.False(table.TryResolveByOffset("IntuneManagementExtension.log", f.OffsetOfLine("IntuneManagementExtension.log", 3), out _, out _));
|
||||
Assert.False(table.TryResolveByOffset("IntuneManagementExtension.log", f.OffsetOfLine("IntuneManagementExtension.log", 4), out _, out _));
|
||||
|
||||
// Executor: only the bootstrap execution block is anchored, not the next script's block.
|
||||
Assert.True(table.TryResolveByOffset("AgentExecutor.log", f.OffsetOfLine("AgentExecutor.log", 0), out var offX, out var kindX));
|
||||
Assert.Equal(Pacific, offX);
|
||||
Assert.Equal(ImeLogEraPreScan.AnchorKindBootstrapStdout, kindX);
|
||||
Assert.False(table.TryResolveByOffset("AgentExecutor.log", f.OffsetOfLine("AgentExecutor.log", 5), out _, out _));
|
||||
|
||||
// Transfer for in-process sibling files: a local time inside era 0's range resolves,
|
||||
// one inside era 1's range does not.
|
||||
Assert.True(table.TryResolveByLocalTime(Deployed.AddMinutes(5) + Pacific, out var offT, out var kindT));
|
||||
Assert.Equal(Pacific, offT);
|
||||
Assert.EndsWith("/service-era-transfer", kindT);
|
||||
Assert.False(table.TryResolveByLocalTime(Deployed.AddMinutes(25) + Eastern, out _, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Without_deployed_marker_nothing_is_anchored()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
f.Write("AgentExecutor.log", ScriptStart(Deployed.AddSeconds(-20), Pacific), BootstrapStdout(Deployed.AddMilliseconds(200), Pacific));
|
||||
f.Write("IntuneManagementExtension.log", PolicyResult(Deployed.AddMilliseconds(260), Pacific));
|
||||
|
||||
var table = f.Build(null);
|
||||
|
||||
Assert.Equal(0, table.AnchoredEraCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Msi_bootstrap_without_stdout_record_anchors_nothing()
|
||||
{
|
||||
// The MSI runner never passes through AgentExecutor; without the policy id the
|
||||
// service log's result lines cannot be told apart from any other script's.
|
||||
using var f = new Fixture();
|
||||
f.Write("AgentExecutor.log", Entry("Adding argument powershell with value C:\\x\\Policies\\Scripts\\u_aaaaaaaa-0000-0000-0000-000000000000.ps1", Deployed.AddMinutes(3), Pacific));
|
||||
f.Write("IntuneManagementExtension.log", PolicyResult(Deployed.AddMilliseconds(260), Pacific));
|
||||
|
||||
var table = f.Build(Deployed);
|
||||
|
||||
Assert.Equal(0, table.AnchoredEraCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Skip_rerun_record_is_never_offered_and_first_record_off_grid_anchors_nothing()
|
||||
{
|
||||
// The install run is the FIRST bootstrap record; a SKIP re-run 15 minutes later
|
||||
// would round onto the grid with zero residual and anchor a wrong offset.
|
||||
using var f = new Fixture();
|
||||
f.Write("AgentExecutor.log",
|
||||
ScriptStart(Deployed.AddMinutes(-9), Pacific),
|
||||
BootstrapStdout(Deployed.AddMinutes(-8), Pacific), // first record: residual 8 min → rejected
|
||||
ScriptStart(Deployed.AddMinutes(15).AddSeconds(-2), Pacific),
|
||||
BootstrapStdout(Deployed.AddMinutes(15), Pacific)); // would be a perfect (wrong) grid hit
|
||||
f.Write("IntuneManagementExtension.log",
|
||||
PolicyResult(Deployed.AddMinutes(-8), Pacific),
|
||||
PolicyResult(Deployed.AddMinutes(15), Pacific));
|
||||
|
||||
var table = f.Build(Deployed);
|
||||
|
||||
Assert.Equal(0, table.AnchoredEraCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Service_era_continues_across_a_log_rotation()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
f.Write("AgentExecutor.log", ScriptStart(Deployed.AddSeconds(-20), Pacific), BootstrapStdout(Deployed.AddMilliseconds(200), Pacific));
|
||||
f.Write("IntuneManagementExtension-20260904-133000.log",
|
||||
PolicyResult(Deployed.AddMilliseconds(260), Pacific),
|
||||
Entry("In EspPhase: DeviceSetup", Deployed.AddMinutes(2), Pacific));
|
||||
f.Write("IntuneManagementExtension.log",
|
||||
Entry("In EspPhase: DeviceSetup", Deployed.AddMinutes(12), Pacific), // same process, rotated file
|
||||
ServiceStarted(Deployed.AddMinutes(20), Eastern));
|
||||
|
||||
var table = f.Build(Deployed);
|
||||
|
||||
Assert.True(table.TryResolveByOffset("IntuneManagementExtension.log", 0, out var off, out _));
|
||||
Assert.Equal(Pacific, off);
|
||||
Assert.False(table.TryResolveByOffset("IntuneManagementExtension.log", f.OffsetOfLine("IntuneManagementExtension.log", 1), out _, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Overlapping_service_era_local_ranges_disable_the_transfer()
|
||||
{
|
||||
// A westward zone change between two service starts makes era 1 start "before"
|
||||
// era 0 in local time; the sibling-file transfer must refuse rather than guess.
|
||||
using var f = new Fixture();
|
||||
f.Write("AgentExecutor.log", ScriptStart(Deployed.AddSeconds(-20), TimeSpan.FromHours(2)), BootstrapStdout(Deployed.AddMilliseconds(200), TimeSpan.FromHours(2)));
|
||||
f.Write("IntuneManagementExtension.log",
|
||||
ServiceStarted(Deployed.AddMinutes(-30), TimeSpan.FromHours(2)),
|
||||
PolicyResult(Deployed.AddMilliseconds(260), TimeSpan.FromHours(2)),
|
||||
ServiceStarted(Deployed.AddMinutes(20), TimeSpan.FromHours(-7)));
|
||||
|
||||
var table = f.Build(Deployed);
|
||||
|
||||
Assert.True(table.TransferAmbiguous);
|
||||
Assert.False(table.TryResolveByLocalTime(Deployed.AddMinutes(5) + TimeSpan.FromHours(2), out _, out _));
|
||||
// Offset-based lookup is unaffected.
|
||||
Assert.True(table.TryResolveByOffset("IntuneManagementExtension.log", f.OffsetOfLine("IntuneManagementExtension.log", 1), out var off, out _));
|
||||
Assert.Equal(TimeSpan.FromHours(2), off);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deployment_marker_parses_roundtrip_utc()
|
||||
{
|
||||
Assert.Equal(Deployed, AutopilotMonitor.Agent.V2.Core.Security.DeploymentMarker.Parse("2026-09-04T13:31:49.1000000Z"));
|
||||
Assert.Null(AutopilotMonitor.Agent.V2.Core.Security.DeploymentMarker.Parse(""));
|
||||
Assert.Null(AutopilotMonitor.Agent.V2.Core.Security.DeploymentMarker.Parse("not a date"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+33
@@ -311,6 +311,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
"[Win32App] Admin did NOT set mapping for lpExitCode: 1603 of app: " + Guid1,
|
||||
new[] { "exitCode=1603", "id=" + Guid1 }
|
||||
};
|
||||
// Win32AppInstaller.cs "[Win32App] lpExitCode is defined as {0}", enum AppReturnCodeType
|
||||
// (identical 1.50–1.105).
|
||||
yield return new object[]
|
||||
{
|
||||
"IME-EXITCODE-CLASS",
|
||||
"[Win32App] lpExitCode is defined as SoftReboot",
|
||||
new[] { "exitCodeClass=SoftReboot" }
|
||||
};
|
||||
yield return new object[]
|
||||
{
|
||||
"IME-GRS-SKIP",
|
||||
@@ -361,6 +369,31 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Success")]
|
||||
[InlineData("SoftReboot")]
|
||||
[InlineData("HardReboot")]
|
||||
[InlineData("Retry")]
|
||||
[InlineData("Failed")]
|
||||
public void IME_EXITCODE_CLASS_captures_every_AppReturnCodeType_member(string member)
|
||||
{
|
||||
var m = Compile(Get("IME-EXITCODE-CLASS")).Match("[Win32App] lpExitCode is defined as " + member);
|
||||
Assert.True(m.Success);
|
||||
Assert.Equal(member, m.Groups["exitCodeClass"].Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IME_EXITCODE_CLASS_ignores_the_no_mapping_warning_and_raw_numeric_types()
|
||||
{
|
||||
// The default branch logs "... defined as {0}, fall into default now." and an admin
|
||||
// type outside the enum prints as a raw number; neither is a class the app carries.
|
||||
var regex = Compile(Get("IME-EXITCODE-CLASS"));
|
||||
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode is defined as 5, fall into default now.");
|
||||
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode is defined as SoftReboot, fall into default now.");
|
||||
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode is defined as 5");
|
||||
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode 3010");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PS_SCRIPT_CONTEXT_no_longer_fires_on_Win32App_detection_script_lines()
|
||||
{
|
||||
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// End-to-end through the tracker: a restart/first-sight backlog whose pre-reboot era was
|
||||
/// written under the OOBE default zone (a7140f98: Pacific) while the agent believes the
|
||||
/// zone Windows set later (Eastern). With the bootstrap record anchoring that era, every
|
||||
/// pre-reboot line resolves to its true instant with origin <c>era-anchored</c>; the
|
||||
/// post-reboot era without an anchor keeps the marked fallback; in-process sibling files
|
||||
/// join by local time; a fresh pass still self-anchors per line.
|
||||
/// </summary>
|
||||
public sealed class ImeLogTrackerEraAnchoringTests
|
||||
{
|
||||
private static readonly DateTime Deployed = new DateTime(2026, 9, 4, 13, 31, 49, 100, DateTimeKind.Utc);
|
||||
private static readonly TimeSpan Pacific = TimeSpan.FromHours(-7);
|
||||
private static readonly TimeSpan Eastern = TimeSpan.FromHours(-4);
|
||||
private const string PolicyId = "93d9df23-1111-2222-3333-444455556666";
|
||||
|
||||
private static List<ImeLogPattern> Patterns() => new List<ImeLogPattern>
|
||||
{
|
||||
new ImeLogPattern
|
||||
{
|
||||
PatternId = "T-ALL", Category = "always", Enabled = true,
|
||||
Pattern = @"marker (?<n>\d+)",
|
||||
Action = "noop",
|
||||
Parameters = new Dictionary<string, string>(),
|
||||
},
|
||||
};
|
||||
|
||||
private static string Entry(string message, DateTime utcInstant, TimeSpan writerOffset)
|
||||
{
|
||||
var local = utcInstant + writerOffset;
|
||||
return $"<![LOG[{message}]LOG]!><time=\"{local:HH:mm:ss.fffffff}\" date=\"{local:M-d-yyyy}\" " +
|
||||
"component=\"X\" context=\"\" type=\"1\" thread=\"1\" file=\"\">";
|
||||
}
|
||||
|
||||
private sealed class Harness : IDisposable
|
||||
{
|
||||
private readonly TempDirectory _tmp = new TempDirectory();
|
||||
public ImeLogTracker Tracker { get; }
|
||||
public DateTime Now { get; set; } = Deployed.AddMinutes(30);
|
||||
public List<(string Message, DateTime? Ts, CmTraceOffsetOrigin Origin, int? Offset, string Anchor)> Resolved { get; } =
|
||||
new List<(string, DateTime?, CmTraceOffsetOrigin, int?, string)>();
|
||||
|
||||
public Harness()
|
||||
{
|
||||
Tracker = new ImeLogTracker(
|
||||
logFolder: _tmp.Path,
|
||||
patterns: Patterns(),
|
||||
logger: new AgentLogger(_tmp.Path, AgentLogLevel.Info));
|
||||
Tracker.UtcNowProvider = () => Now;
|
||||
Tracker.DeployedUtcProvider = () => Deployed;
|
||||
Tracker.OnPatternMatched += _ => Resolved.Add((
|
||||
Tracker.LastMatchedPatternId ?? string.Empty,
|
||||
Tracker.LastMatchedLogTimestamp,
|
||||
Tracker.LastMatchedSourceOffsetOrigin,
|
||||
Tracker.LastMatchedSourceOffsetMinutes,
|
||||
Tracker.LastMatchedEraAnchorKind));
|
||||
}
|
||||
|
||||
public void Append(string fileName, params string[] lines)
|
||||
=> File.AppendAllText(Path.Combine(_tmp.Path, fileName), string.Join(Environment.NewLine, lines) + Environment.NewLine);
|
||||
|
||||
public Task Pass() => Tracker.CheckLogFilesAsync(CancellationToken.None);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Tracker.Dispose();
|
||||
_tmp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Backlog_lines_of_the_bootstrap_era_resolve_through_the_anchor_and_the_next_era_stays_on_fallback()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Append("AgentExecutor.log",
|
||||
Entry($@"Adding argument powershell with value C:\x\Policies\Scripts\u_{PolicyId}.ps1", Deployed.AddSeconds(-20), Pacific),
|
||||
Entry("write output done. output = ===== Autopilot Monitor Bootstrap Started =====\n===== Bootstrap Completed Successfully =====, error = ", Deployed.AddMilliseconds(200), Pacific),
|
||||
Entry("marker 10", Deployed.AddSeconds(1), Pacific));
|
||||
h.Append("IntuneManagementExtension.log",
|
||||
Entry("marker 1", Deployed.AddMinutes(-1), Pacific),
|
||||
Entry($"[PowerShell] User Id = 00000000-0000-0000-0000-000000000000, Policy id = {PolicyId}, policy result = Success", Deployed.AddMilliseconds(260), Pacific),
|
||||
Entry("marker 2", Deployed.AddMinutes(10), Pacific),
|
||||
Entry("EMS Agent Started", Deployed.AddMinutes(20), Eastern),
|
||||
Entry("marker 3", Deployed.AddMinutes(21), Eastern));
|
||||
h.Append("AppWorkload.log",
|
||||
Entry("marker 4", Deployed.AddMinutes(5), Pacific),
|
||||
Entry("marker 5", Deployed.AddMinutes(25), Eastern));
|
||||
|
||||
h.Tracker.PreScanEras();
|
||||
await h.Pass(); // first sight: backlog, never fresh
|
||||
|
||||
var byMarker = new Dictionary<string, (string Message, DateTime? Ts, CmTraceOffsetOrigin Origin, int? Offset, string Anchor)>();
|
||||
foreach (var r in h.Resolved) byMarker[r.Message] = r;
|
||||
Assert.Equal(6, h.Resolved.Count);
|
||||
|
||||
// Marker text is the pattern id (T-ALL) — index by resolution order instead.
|
||||
var r1 = h.Resolved[0]; // AgentExecutor marker 10 (files sort: AgentExecutor < AppWorkload < IntuneManagementExtension)
|
||||
Assert.Equal(CmTraceOffsetOrigin.EraAnchored, r1.Origin);
|
||||
Assert.Equal(Deployed.AddSeconds(1), r1.Ts);
|
||||
Assert.Equal(-420, r1.Offset);
|
||||
Assert.Equal(ImeLogEraPreScan.AnchorKindBootstrapStdout, r1.Anchor);
|
||||
|
||||
var r4 = h.Resolved[1]; // AppWorkload marker 4 — transfer by local time into the service era
|
||||
Assert.Equal(CmTraceOffsetOrigin.EraAnchored, r4.Origin);
|
||||
Assert.Equal(Deployed.AddMinutes(5), r4.Ts);
|
||||
Assert.EndsWith("/service-era-transfer", r4.Anchor);
|
||||
|
||||
var r5 = h.Resolved[2]; // AppWorkload marker 5 — post-boot era, unanchored
|
||||
Assert.Equal(CmTraceOffsetOrigin.None, r5.Origin);
|
||||
Assert.Equal(string.Empty, r5.Anchor);
|
||||
|
||||
var rm1 = h.Resolved[3]; // IME marker 1
|
||||
Assert.Equal(CmTraceOffsetOrigin.EraAnchored, rm1.Origin);
|
||||
Assert.Equal(Deployed.AddMinutes(-1), rm1.Ts);
|
||||
Assert.Equal(ImeLogEraPreScan.AnchorKindBootstrapPolicyResult, rm1.Anchor);
|
||||
|
||||
var rm2 = h.Resolved[4]; // IME marker 2
|
||||
Assert.Equal(CmTraceOffsetOrigin.EraAnchored, rm2.Origin);
|
||||
Assert.Equal(Deployed.AddMinutes(10), rm2.Ts);
|
||||
|
||||
var rm3 = h.Resolved[5]; // IME marker 3 — after "EMS Agent Started", no anchor
|
||||
Assert.Equal(CmTraceOffsetOrigin.None, rm3.Origin);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Fresh_lines_still_self_anchor_after_the_pre_scan()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Append("IntuneManagementExtension.log", Entry("marker 1", h.Now, Eastern));
|
||||
h.Tracker.PreScanEras();
|
||||
await h.Pass();
|
||||
|
||||
h.Now = h.Now.AddSeconds(10);
|
||||
var writtenAt = h.Now.AddMilliseconds(-80);
|
||||
h.Append("IntuneManagementExtension.log", Entry("marker 2", writtenAt, Eastern));
|
||||
await h.Pass();
|
||||
|
||||
var last = h.Resolved[h.Resolved.Count - 1];
|
||||
Assert.Equal(CmTraceOffsetOrigin.LineAnchored, last.Origin);
|
||||
Assert.Equal(writtenAt, last.Ts);
|
||||
Assert.Equal(string.Empty, last.Anchor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Without_marker_the_backlog_keeps_the_reader_zone_fallback()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Tracker.DeployedUtcProvider = () => null;
|
||||
h.Append("IntuneManagementExtension.log", Entry("marker 1", Deployed.AddMinutes(-1), Pacific));
|
||||
h.Tracker.PreScanEras();
|
||||
await h.Pass();
|
||||
|
||||
Assert.Single(h.Resolved);
|
||||
Assert.Equal(CmTraceOffsetOrigin.None, h.Resolved[0].Origin);
|
||||
Assert.Equal(0, h.Tracker.EraTable.AnchoredEraCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Newtonsoft.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// Return-code class of the installer exit code (IME "[Win32App] lpExitCode is defined as
|
||||
/// {AppReturnCodeType}"): captured by the shipped IME-EXITCODE-CLASS pattern into
|
||||
/// <see cref="AppPackageState.ExitCodeClass"/>, last value wins across a Retry loop, the
|
||||
/// no-mapping/default-branch variants are ignored, and the value survives the agent
|
||||
/// restart that a SoftReboot/HardReboot app causes (persistence round trip).
|
||||
/// </summary>
|
||||
public sealed class ImeLogTrackerExitCodeClassTests
|
||||
{
|
||||
private const string AppId = "5c95bf94-1cf4-4629-88d1-3f616e7a405c";
|
||||
|
||||
// ---------------------------------------------------------------- AppPackageState
|
||||
|
||||
[Fact]
|
||||
public void UpdateExitCodeClass_last_value_wins_and_ignores_empty()
|
||||
{
|
||||
var pkg = new AppPackageState(AppId, 0);
|
||||
Assert.Null(pkg.ExitCodeClass);
|
||||
|
||||
Assert.True(pkg.UpdateExitCodeClass("Retry"));
|
||||
Assert.True(pkg.UpdateExitCodeClass(" Success "));
|
||||
Assert.Equal("Success", pkg.ExitCodeClass);
|
||||
Assert.False(pkg.UpdateExitCodeClass("Success"));
|
||||
Assert.False(pkg.UpdateExitCodeClass(""));
|
||||
Assert.False(pkg.UpdateExitCodeClass(null));
|
||||
Assert.Equal("Success", pkg.ExitCodeClass);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToEventData_carries_the_class_only_when_known()
|
||||
{
|
||||
var pkg = new AppPackageState(AppId, 0);
|
||||
Assert.False(pkg.ToEventData().ContainsKey("exitCodeClass"));
|
||||
|
||||
pkg.UpdateExitCode("3010");
|
||||
pkg.UpdateExitCodeClass("SoftReboot");
|
||||
var data = pkg.ToEventData();
|
||||
Assert.Equal("3010", data["exitCode"]);
|
||||
Assert.Equal("SoftReboot", data["exitCodeClass"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Restore_round_trips_the_class()
|
||||
{
|
||||
var pkg = AppPackageState.Restore(
|
||||
AppId, 0, "Contoso VPN",
|
||||
AppRunAs.System, AppIntent.Install, AppTargeted.Device,
|
||||
new HashSet<string>(),
|
||||
AppInstallationState.Installed, true, 100, 0, 0,
|
||||
exitCode: "3010", exitCodeClass: "SoftReboot");
|
||||
|
||||
Assert.Equal("SoftReboot", pkg.ExitCodeClass);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- shipped pack, end to end
|
||||
|
||||
private static string FindRulesPatternDir()
|
||||
{
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (dir != null)
|
||||
{
|
||||
var candidate = Path.Combine(dir.FullName, "rules", "ime-log-patterns");
|
||||
if (Directory.Exists(candidate)) return candidate;
|
||||
dir = dir.Parent;
|
||||
}
|
||||
throw new DirectoryNotFoundException($"Could not locate rules/ime-log-patterns walking up from {AppContext.BaseDirectory}");
|
||||
}
|
||||
|
||||
/// <summary>The shipped pack, exactly as combine.js embeds it (sorted by file name).</summary>
|
||||
private static List<ImeLogPattern> ShippedPack()
|
||||
=> Directory.GetFiles(FindRulesPatternDir(), "*.json")
|
||||
.OrderBy(f => f, StringComparer.Ordinal)
|
||||
.Select(f => JsonConvert.DeserializeObject<ImeLogPattern>(File.ReadAllText(f))!)
|
||||
.ToList();
|
||||
|
||||
private static string Entry(string message, DateTime utcInstant)
|
||||
{
|
||||
// CMTrace line with a zero writer offset: the tracker reads the local time and
|
||||
// resolves it against the reader zone; only freshness (< 24 h) matters here.
|
||||
return $"<![LOG[{message}]LOG]!><time=\"{utcInstant:HH:mm:ss.fffffff}\" date=\"{utcInstant:M-d-yyyy}\" " +
|
||||
"component=\"IntuneManagementExtension\" context=\"\" type=\"1\" thread=\"1\" file=\"\">";
|
||||
}
|
||||
|
||||
private sealed class Harness : IDisposable
|
||||
{
|
||||
private readonly TempDirectory _tmp = new TempDirectory();
|
||||
public ImeLogTracker Tracker { get; }
|
||||
public string StateDir { get; }
|
||||
public DateTime Now { get; } = new DateTime(2026, 9, 6, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
public Harness()
|
||||
{
|
||||
StateDir = Path.Combine(_tmp.Path, "State");
|
||||
Tracker = Build();
|
||||
}
|
||||
|
||||
public ImeLogTracker Build()
|
||||
{
|
||||
var tracker = new ImeLogTracker(
|
||||
logFolder: _tmp.Path,
|
||||
patterns: ShippedPack(),
|
||||
logger: new AgentLogger(_tmp.Path, AgentLogLevel.Info),
|
||||
stateDirectory: StateDir);
|
||||
// The historic-replay guard skips app-mutating actions for lines older than 24 h
|
||||
// relative to "now": pin both so the CMTrace entries below are always fresh.
|
||||
tracker.UtcNowProvider = () => Now;
|
||||
return tracker;
|
||||
}
|
||||
|
||||
public void Append(params string[] messages)
|
||||
{
|
||||
var lines = messages.Select((m, i) => Entry(m, Now.AddSeconds(-60 + i)));
|
||||
File.AppendAllText(Path.Combine(_tmp.Path, "IntuneManagementExtension.log"),
|
||||
string.Join(Environment.NewLine, lines) + Environment.NewLine);
|
||||
}
|
||||
|
||||
public Task Pass() => Tracker.CheckLogFilesAsync(CancellationToken.None);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Tracker.Dispose();
|
||||
_tmp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static string PhaseLine => "[Win32App] In EspPhase: DeviceSetup.";
|
||||
private static string CurrentAppLine => @"[Win32App] SetCurrentDirectory: C:\Windows\IMECache\" + AppId + "_1";
|
||||
|
||||
[Fact]
|
||||
public async Task Shipped_pattern_captures_the_class_for_the_current_app()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
|
||||
h.Append(
|
||||
PhaseLine, // activates the currentPhase pack (IME-EXITCODE, IME-EXITCODE-CLASS)
|
||||
CurrentAppLine, // IME-SET-CURRENT-4 → current app
|
||||
"[Win32App] lpExitCode 3010",
|
||||
"[Win32App] lpExitCode is defined as SoftReboot");
|
||||
|
||||
await h.Pass();
|
||||
|
||||
var pkg = h.Tracker.PackageStates.GetPackage(AppId);
|
||||
Assert.NotNull(pkg);
|
||||
Assert.Equal("3010", pkg!.ExitCode);
|
||||
Assert.Equal("SoftReboot", pkg.ExitCodeClass);
|
||||
Assert.NotEqual(AppInstallationState.Error, pkg.InstallationState);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Retry_loop_that_ends_in_success_reports_the_last_class()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
|
||||
h.Append(
|
||||
PhaseLine, CurrentAppLine,
|
||||
"[Win32App] lpExitCode 1618",
|
||||
"[Win32App] lpExitCode is defined as Retry",
|
||||
"[Win32App] lpExitCode 1618",
|
||||
"[Win32App] lpExitCode is defined as Retry",
|
||||
"[Win32App] lpExitCode 0",
|
||||
"[Win32App] lpExitCode is defined as Success");
|
||||
|
||||
await h.Pass();
|
||||
|
||||
var pkg = h.Tracker.PackageStates.GetPackage(AppId)!;
|
||||
Assert.Equal("0", pkg.ExitCode);
|
||||
Assert.Equal("Success", pkg.ExitCodeClass);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Failed_class_still_drives_the_error_transition_and_carries_the_class()
|
||||
{
|
||||
// IME-EXITCODE-CLASS and IME-EXITCODE-MAPPED-FAILED both match the Failed line: the
|
||||
// class is captured and the existing error path stays intact.
|
||||
using var h = new Harness();
|
||||
var pkg = new AppPackageState(AppId, 0);
|
||||
pkg.UpdateState(AppInstallationState.Installing);
|
||||
h.Tracker.PackageStates.Add(pkg);
|
||||
h.Append(
|
||||
PhaseLine, CurrentAppLine,
|
||||
"[Win32App] lpExitCode 1603",
|
||||
"[Win32App] lpExitCode is defined as Failed");
|
||||
|
||||
await h.Pass();
|
||||
|
||||
Assert.Equal(AppInstallationState.Error, pkg.InstallationState);
|
||||
Assert.Equal("Failed", pkg.ExitCodeClass);
|
||||
Assert.Equal("IME-EXITCODE-MAPPED-FAILED", pkg.ErrorPatternId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Default_branch_and_raw_numeric_types_leave_the_class_unset()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
|
||||
h.Append(
|
||||
PhaseLine, CurrentAppLine,
|
||||
"[Win32App] lpExitCode 5",
|
||||
"[Win32App] lpExitCode is defined as 5",
|
||||
"[Win32App] lpExitCode is defined as 5, fall into default now.",
|
||||
"[Win32App] Setting enforcementState as: Error with lpExitCode: 5 without mapping");
|
||||
|
||||
await h.Pass();
|
||||
|
||||
var pkg = h.Tracker.PackageStates.GetPackage(AppId)!;
|
||||
Assert.Equal("5", pkg.ExitCode);
|
||||
Assert.Null(pkg.ExitCodeClass);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Class_survives_the_state_round_trip_of_an_agent_restart()
|
||||
{
|
||||
// A SoftReboot/HardReboot app completes only after the reboot; the restarted agent
|
||||
// must still know the class when the post-reboot Success line arrives.
|
||||
using var h = new Harness();
|
||||
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
|
||||
h.Append(
|
||||
PhaseLine, CurrentAppLine,
|
||||
"[Win32App] lpExitCode 1641",
|
||||
"[Win32App] lpExitCode is defined as HardReboot");
|
||||
await h.Pass();
|
||||
h.Tracker.SaveStateForTest();
|
||||
|
||||
using var restarted = h.Build();
|
||||
restarted.LoadStateForTest();
|
||||
|
||||
var pkg = restarted.GetAllKnownPackageStates().Single(p => p.Id == AppId);
|
||||
Assert.Equal("1641", pkg.ExitCode);
|
||||
Assert.Equal("HardReboot", pkg.ExitCodeClass);
|
||||
}
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// Raw per-line token callbacks for the Entra user-affinity detector (2026-09-04).
|
||||
/// <c>OnUserTokenAcquired</c> fires on EVERY IME-TOKEN-SUCCESS line — independent of the
|
||||
/// phase-change dedup that swallows the second AccountSetup detection — and
|
||||
/// <c>OnTokenFailureLine</c> on every failure line; both honour the historic-replay gate.
|
||||
/// </summary>
|
||||
public sealed class ImeLogTrackerTokenLineCallbackTests
|
||||
{
|
||||
private static readonly DateTime Now = new DateTime(2026, 9, 4, 14, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private static List<ImeLogPattern> Patterns() => new List<ImeLogPattern>
|
||||
{
|
||||
new ImeLogPattern
|
||||
{
|
||||
PatternId = "IME-TOKEN-SUCCESS", Category = "always", Enabled = true,
|
||||
Pattern = "^Successfully get the token",
|
||||
Action = "espPhaseDetected",
|
||||
Parameters = new Dictionary<string, string> { ["phase"] = "AccountSetup" },
|
||||
},
|
||||
new ImeLogPattern
|
||||
{
|
||||
PatternId = "IME-TOKEN-FAILURE", Category = "always", Enabled = true,
|
||||
Pattern = @"^Failed to get AAD token\..*?errorCode = (?<errorCode>.*?)$",
|
||||
Action = "imeTokenFailure",
|
||||
Parameters = new Dictionary<string, string>(),
|
||||
},
|
||||
};
|
||||
|
||||
private static ImeLogTracker Build(TempDirectory tmp)
|
||||
{
|
||||
var tracker = new ImeLogTracker(
|
||||
logFolder: tmp.Path,
|
||||
patterns: Patterns(),
|
||||
logger: new AgentLogger(tmp.Path, AgentLogLevel.Info));
|
||||
tracker.UtcNowProvider = () => Now;
|
||||
return tracker;
|
||||
}
|
||||
|
||||
private const string Success = "Successfully get the token with client id fc0f3af4-6835-4174-b806-f7db311fd2f3 and resource id 26a4ae64-5862-427f-a9b0-044e62572a4f";
|
||||
private const string Failure = "Failed to get AAD token. len = 34 using client id fc0f3af4-6835-4174-b806-f7db311fd2f3 and resource id 26a4ae64-5862-427f-a9b0-044e62572a4f, errorCode = 3399548929";
|
||||
|
||||
[Fact]
|
||||
public void Every_token_success_line_invokes_callback_even_when_phase_is_deduplicated()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
using var tracker = Build(tmp);
|
||||
var tokens = new List<DateTime?>();
|
||||
tracker.OnUserTokenAcquired = ts => tokens.Add(ts);
|
||||
|
||||
// The phase-change dedup lives in the adapter (AccountSetup is emitted once);
|
||||
// the raw token callback must fire for BOTH lines regardless.
|
||||
tracker.ProcessLogMessageForTest(Success, Now.AddMinutes(-6));
|
||||
tracker.ProcessLogMessageForTest(Success, Now.AddMinutes(-2));
|
||||
|
||||
Assert.Equal(2, tokens.Count);
|
||||
Assert.Equal(Now.AddMinutes(-6), tokens[0]);
|
||||
Assert.Equal(Now.AddMinutes(-2), tokens[1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Every_failure_line_invokes_callback_with_error_code()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
using var tracker = Build(tmp);
|
||||
var failures = new List<(string code, DateTime? ts)>();
|
||||
tracker.OnTokenFailureLine = (code, ts) => failures.Add((code, ts));
|
||||
|
||||
tracker.ProcessLogMessageForTest(Failure, Now.AddMinutes(-5));
|
||||
tracker.ProcessLogMessageForTest(Failure, Now.AddMinutes(-4));
|
||||
|
||||
Assert.Equal(2, failures.Count);
|
||||
Assert.All(failures, f => Assert.Equal("3399548929", f.code));
|
||||
Assert.Equal(Now.AddMinutes(-5), failures[0].ts);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Historic_replay_lines_do_not_invoke_either_callback()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
using var tracker = Build(tmp);
|
||||
var tokens = 0;
|
||||
var failures = 0;
|
||||
tracker.OnUserTokenAcquired = _ => tokens++;
|
||||
tracker.OnTokenFailureLine = (_, __) => failures++;
|
||||
|
||||
tracker.ProcessLogMessageForTest(Success, Now.AddDays(-3));
|
||||
tracker.ProcessLogMessageForTest(Failure, Now.AddDays(-3));
|
||||
|
||||
Assert.Equal(0, tokens);
|
||||
Assert.Equal(0, failures);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Callback_exception_does_not_break_the_drain()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
using var tracker = Build(tmp);
|
||||
tracker.OnUserTokenAcquired = _ => throw new InvalidOperationException("boom");
|
||||
tracker.OnTokenFailureLine = (_, __) => throw new InvalidOperationException("boom");
|
||||
|
||||
tracker.ProcessLogMessageForTest(Success, Now.AddMinutes(-1));
|
||||
tracker.ProcessLogMessageForTest(Failure, Now.AddMinutes(-1));
|
||||
}
|
||||
}
|
||||
}
|
||||
+82
@@ -903,5 +903,87 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Runtime
|
||||
NtfsLinks.RemoveLink(link);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================= packaging counters
|
||||
|
||||
[Fact]
|
||||
public void BuildArchiveBytes_records_packaging_counters_by_reason_and_kind_without_paths()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
File.WriteAllText(Path.Combine(rig.StateFolder, "small.json"), "{}");
|
||||
File.WriteAllText(Path.Combine(rig.StateFolder, "big-1.json"), new string('x', 64));
|
||||
File.WriteAllText(Path.Combine(rig.StateFolder, "big-2.json"), new string('y', 64));
|
||||
var blockedPath = @"C:\Windows\System32\config\SYSTEM";
|
||||
|
||||
var service = rig.Build(cfg => cfg.DiagnosticsLogPaths.Add(
|
||||
new AutopilotMonitor.Shared.Models.DiagnosticsLogPath { Path = blockedPath }));
|
||||
service.Budget = new DiagnosticsBudget { MaxSingleFileBytes = 16, MaxTotalUncompressedBytes = 1L << 30, MaxFileCount = 5000 };
|
||||
|
||||
Assert.Null(service.LastPackaging);
|
||||
var bytes = service.BuildArchiveBytes(enrollmentSucceeded: true);
|
||||
|
||||
var stats = service.LastPackaging;
|
||||
Assert.NotNull(stats);
|
||||
Assert.True(stats!.Truncated);
|
||||
Assert.Equal(2, stats.SkippedFiles);
|
||||
Assert.Equal(2, stats.SkippedByReason["size"]);
|
||||
Assert.Single(stats.SkippedByReason);
|
||||
Assert.Equal(1, stats.ProblemsByKind["path-guard"]);
|
||||
Assert.Single(stats.ProblemsByKind);
|
||||
Assert.True(stats.IncludedFiles >= 1, "the small file must have been included");
|
||||
Assert.True(stats.IncludedBytes >= 2);
|
||||
|
||||
// The ZIP still carries the per-file list; the counters never do.
|
||||
Assert.NotNull(ReadZipEntryText(bytes, "_TRUNCATED.txt"));
|
||||
foreach (var key in stats.SkippedByReason.Keys.Concat(stats.ProblemsByKind.Keys))
|
||||
{
|
||||
Assert.DoesNotContain("\\", key);
|
||||
Assert.DoesNotContain(":", key);
|
||||
Assert.DoesNotContain("/", key);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildArchiveBytes_reports_a_clean_build_as_not_truncated_with_empty_maps()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
File.WriteAllText(Path.Combine(rig.StateFolder, "snapshot.json"), "{}");
|
||||
|
||||
var service = rig.Build();
|
||||
service.BuildArchiveBytes(enrollmentSucceeded: true);
|
||||
|
||||
var stats = service.LastPackaging;
|
||||
Assert.NotNull(stats);
|
||||
Assert.False(stats!.Truncated);
|
||||
Assert.Equal(0, stats.SkippedFiles);
|
||||
Assert.Empty(stats.SkippedByReason);
|
||||
Assert.Empty(stats.ProblemsByKind);
|
||||
Assert.True(stats.IncludedFiles >= 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildArchiveBytes_counts_a_rejected_source_folder_as_a_problem()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
using var outside = new TempDirectory();
|
||||
File.WriteAllText(Path.Combine(outside.Path, "snapshot.json"), "{}");
|
||||
var link = Path.Combine(rig.Tmp.Path, "StateLink");
|
||||
NtfsLinks.CreateJunction(link, outside.Path);
|
||||
|
||||
try
|
||||
{
|
||||
var service = rig.Build(sectionFolderOverrides: new Dictionary<string, string> { ["AgentState"] = link });
|
||||
service.BuildArchiveBytes(enrollmentSucceeded: true);
|
||||
|
||||
// The section is walked once per search pattern (11 patterns) but the folder
|
||||
// failed once — the counter says so.
|
||||
Assert.Equal(1, service.LastPackaging!.ProblemsByKind["folder-rejected"]);
|
||||
Assert.False(service.LastPackaging.Truncated);
|
||||
}
|
||||
finally
|
||||
{
|
||||
NtfsLinks.RemoveLink(link);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
using System;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals;
|
||||
using AutopilotMonitor.Agent.V2.Core.Orchestration;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Orchestration;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
{
|
||||
/// <summary>
|
||||
/// Backlog q8n — pins the two AccountSetup probes side by side.
|
||||
/// <para>
|
||||
/// <see cref="ProvisioningStatusTracker.HasAccountSetupActivity"/> keeps PRESENCE semantics:
|
||||
/// Windows writes <c>AccountSetupCategory.Status</c> with every subcategory <c>notStarted</c>
|
||||
/// before the Device-ESP page exits, and about one in five Classic sessions sees only that
|
||||
/// single Shell-Core 62407 for the whole enrollment — those resolve AccountSetup solely via
|
||||
/// the user-apps-settled synthesis, which needs the exit remembered as the edge. Tightening
|
||||
/// this property strands them (verified on 485 SkipUser=false sessions, 2026-09-01..04).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <see cref="ProvisioningStatusTracker.HasAccountSetupProgress"/> is the additive PROGRESS
|
||||
/// probe for the User-ESP keep-awake host: true only once a subcategory left
|
||||
/// <c>notStarted</c>, so the host can tell the real user-ESP page exit (session a2256107:
|
||||
/// 09:47:12) from the Device→Account handoff exit (09:37:53) that released the hold early.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class ProvisioningStatusTrackerAccountSetupActivityTests
|
||||
{
|
||||
private static readonly DateTime Fixed = new DateTime(2026, 9, 4, 9, 37, 42, DateTimeKind.Utc);
|
||||
|
||||
// Verbatim shape of the pre-written registry JSON seen at first_seen on 25H2/26200.
|
||||
private const string AllNotStartedJson = @"{
|
||||
""categoryState"":""notStarted"",
|
||||
""AccountSetup.WaitingForAadRegistrationSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.PrepareMultifactorAuth"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.SecurityPoliciesSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.CertificatesSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.NetworkConnectionsSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.AppsSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.SendResultsToMdmServer"":{""subcategoryState"":""notStarted""}
|
||||
}";
|
||||
|
||||
private const string FirstProgressJson = @"{
|
||||
""categoryState"":""inProgress"",
|
||||
""AccountSetup.WaitingForAadRegistrationSubcategory"":{""subcategoryState"":""succeeded"",""subcategoryStatusText"":""succeeded""},
|
||||
""AccountSetup.PrepareMultifactorAuth"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.SecurityPoliciesSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.CertificatesSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.NetworkConnectionsSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.AppsSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.SendResultsToMdmServer"":{""subcategoryState"":""notStarted""}
|
||||
}";
|
||||
|
||||
private sealed class Fixture : IDisposable
|
||||
{
|
||||
public TempDirectory Tmp { get; } = new TempDirectory();
|
||||
public FakeSignalIngressSink Sink { get; } = new FakeSignalIngressSink();
|
||||
public ProvisioningStatusTracker Tracker { get; }
|
||||
|
||||
public Fixture()
|
||||
{
|
||||
var clock = new VirtualClock(Fixed);
|
||||
var post = new InformationalEventPost(Sink, clock);
|
||||
var logger = new AgentLogger(Tmp.Path, AgentLogLevel.Info);
|
||||
Tracker = new ProvisioningStatusTracker(
|
||||
sessionId: "S1",
|
||||
tenantId: "T1",
|
||||
post: post,
|
||||
logger: logger);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Tracker.Dispose();
|
||||
Tmp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NothingTracked_NeitherActivityNorProgress()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
Assert.False(f.Tracker.HasAccountSetupActivity);
|
||||
Assert.False(f.Tracker.HasAccountSetupProgress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PreWrittenAllNotStartedJson_IsActivity_ButNotProgress()
|
||||
{
|
||||
// The registry JSON exists (7 subcategories) but nothing has started — the state at
|
||||
// the intermediate Device-ESP exit. Activity (presence) must stay true so the
|
||||
// completion guards keep remembering single-exit sessions; progress must be false so
|
||||
// the keep-awake host does not treat this exit as the user-ESP page exit.
|
||||
using var f = new Fixture();
|
||||
f.Tracker.ProcessCategoryStatusForTest("AccountSetupCategory.Status", AllNotStartedJson);
|
||||
|
||||
Assert.True(f.Tracker.HasAccountSetupActivity);
|
||||
Assert.False(f.Tracker.HasAccountSetupProgress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FirstSubcategoryLeavingNotStarted_IsProgress()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
f.Tracker.ProcessCategoryStatusForTest("AccountSetupCategory.Status", AllNotStartedJson);
|
||||
f.Tracker.ProcessCategoryStatusForTest("AccountSetupCategory.Status", FirstProgressJson);
|
||||
|
||||
Assert.True(f.Tracker.HasAccountSetupActivity);
|
||||
Assert.True(f.Tracker.HasAccountSetupProgress);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("inProgress")]
|
||||
[InlineData("in_progress")]
|
||||
[InlineData("failed")]
|
||||
[InlineData("notRequired")]
|
||||
public void AnyNonNotStartedState_IsProgress(string state)
|
||||
{
|
||||
using var f = new Fixture();
|
||||
f.Tracker.ProcessCategoryStatusForTest("AccountSetupCategory.Status",
|
||||
"{\"categoryState\":\"inProgress\"," +
|
||||
"\"AccountSetup.AppsSubcategory\":{\"subcategoryState\":\"" + state + "\"}," +
|
||||
"\"AccountSetup.CertificatesSubcategory\":{\"subcategoryState\":\"notStarted\"}}");
|
||||
|
||||
Assert.True(f.Tracker.HasAccountSetupProgress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeviceSetupProgress_DoesNotCountAsAccountSetupProgress()
|
||||
{
|
||||
// Adversarial: a fully progressed DeviceSetup category must not leak into the
|
||||
// AccountSetup answer.
|
||||
using var f = new Fixture();
|
||||
f.Tracker.ProcessCategoryStatusForTest("DeviceSetupCategory.Status",
|
||||
"{\"categoryState\":\"succeeded\",\"DeviceSetup.AppsSubcategory\":{\"subcategoryState\":\"succeeded\"}}");
|
||||
f.Tracker.ProcessCategoryStatusForTest("AccountSetupCategory.Status", AllNotStartedJson);
|
||||
|
||||
Assert.False(f.Tracker.HasAccountSetupProgress);
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-5
@@ -243,12 +243,23 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecodeHResult_KnownAndUnknown()
|
||||
public void ResolveHResultSymbol_ReadsTheSharedCatalog()
|
||||
{
|
||||
Assert.Equal("WU_E_ALL_UPDATES_FAILED", WindowsUpdateTracker.DecodeHResult(0x80240022));
|
||||
Assert.Equal("CBS_E_INSTALLERS_FAILED", WindowsUpdateTracker.DecodeHResult(0x800F0922));
|
||||
Assert.Equal("S_OK", WindowsUpdateTracker.DecodeHResult(0x00000000));
|
||||
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.DecodeHResult(0x8888DEAD));
|
||||
Assert.Equal("WU_E_ALL_UPDATES_FAILED", WindowsUpdateTracker.ResolveHResultSymbol(0x80240022));
|
||||
Assert.Equal("CBS_E_INSTALLERS_FAILED", WindowsUpdateTracker.ResolveHResultSymbol(0x800F0922));
|
||||
Assert.Equal("ERROR_TIMEOUT", WindowsUpdateTracker.ResolveHResultSymbol(0x800705B4));
|
||||
Assert.Equal("S_OK", WindowsUpdateTracker.ResolveHResultSymbol(0x00000000));
|
||||
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.ResolveHResultSymbol(0x8888DEAD));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveHResultSymbol_FallsBackWhenTheCatalogHasNoSymbolOrThrows()
|
||||
{
|
||||
// An entry without a symbol (IME/Intune paraphrases) still yields the sentinel.
|
||||
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.ResolveHResultSymbol(0x87D1041C));
|
||||
// A catalog load failure is decoration lost, never an event lost.
|
||||
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.ResolveHResultSymbol(0x80240022, _ => throw new InvalidOperationException("catalog")));
|
||||
Assert.Equal("S_OK", WindowsUpdateTracker.ResolveHResultSymbol(0, _ => throw new InvalidOperationException("catalog")));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
+1
@@ -11,6 +11,7 @@ using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
{
|
||||
|
||||
+3
-2
@@ -8,6 +8,7 @@ using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
#pragma warning disable xUnit1031
|
||||
|
||||
@@ -42,7 +43,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
// items must be a whiteglove_resumed event.
|
||||
Assert.DoesNotContain(
|
||||
rig.Uploader.Received.SelectMany(b => b),
|
||||
item => item.Kind == AutopilotMonitor.Agent.V2.Core.Transport.Telemetry.TelemetryItemKind.Event &&
|
||||
item => item.Kind == TelemetryItemKind.Event &&
|
||||
item.PayloadJson != null &&
|
||||
item.PayloadJson.Contains("\"whiteglove_resumed\""));
|
||||
}
|
||||
@@ -75,7 +76,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
var resumedEvents = rig.Uploader.Received
|
||||
.SelectMany(b => b)
|
||||
.Where(item =>
|
||||
item.Kind == AutopilotMonitor.Agent.V2.Core.Transport.Telemetry.TelemetryItemKind.Event &&
|
||||
item.Kind == TelemetryItemKind.Event &&
|
||||
item.PayloadJson != null &&
|
||||
item.PayloadJson.Contains("\"whiteglove_resumed\""))
|
||||
.ToList();
|
||||
|
||||
@@ -15,6 +15,7 @@ using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
#pragma warning disable xUnit1031
|
||||
|
||||
|
||||
+1
@@ -9,6 +9,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
#pragma warning disable xUnit1031
|
||||
|
||||
|
||||
+96
-4
@@ -114,14 +114,80 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
ing.Stop();
|
||||
}
|
||||
|
||||
private static void PostEspExiting(SignalIngress ing) =>
|
||||
ing.Post(DecisionSignalKind.EspExiting, At, "EspAndHelloTracker", Raw("exit"));
|
||||
|
||||
[Fact]
|
||||
public void Releases_on_AccountSetupProvisioningComplete()
|
||||
public void Releases_on_EspExiting_once_AccountSetup_shows_progress()
|
||||
{
|
||||
// q8n: the real user-ESP page exit is a 62407 that arrives after the AccountSetup
|
||||
// registry left notStarted (session a2256107: 09:47:12, progress since 09:38:25).
|
||||
var clock = new VirtualClock(At);
|
||||
using var ing = BuildIngress(clock);
|
||||
var api = new FakeKeepAwakeApi();
|
||||
var controller = new KeepAwakeController(NewLogger(), api);
|
||||
var host = new UserEspKeepAwakeHost("S1", "T1", ing, clock, NewLogger(), controller: controller, espTimeoutProvider: () => null);
|
||||
var progress = false;
|
||||
var host = new UserEspKeepAwakeHost("S1", "T1", ing, clock, NewLogger(), controller: controller,
|
||||
espTimeoutProvider: () => null, accountSetupProgressProbe: () => Volatile.Read(ref progress));
|
||||
|
||||
ing.Start();
|
||||
host.Start();
|
||||
PostAccountSetupPhase(ing);
|
||||
Assert.True(WaitFor(() => api.PreventCount == 1));
|
||||
|
||||
Volatile.Write(ref progress, true);
|
||||
PostEspExiting(ing);
|
||||
|
||||
Assert.True(WaitFor(() => api.AllowCount == 1), "AllowSleep should be called once on the user-ESP page exit");
|
||||
Assert.False(controller.IsEngaged);
|
||||
|
||||
host.Dispose();
|
||||
ing.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handoff_exit_before_AccountSetup_progress_keeps_the_hold()
|
||||
{
|
||||
// The Device→Account handoff 62407 (a2256107: 09:37:53) precedes any AccountSetup
|
||||
// progress — Windows pre-writes the AccountSetup JSON all-notStarted — and must not
|
||||
// release. The later exit with progress does.
|
||||
var clock = new VirtualClock(At);
|
||||
using var ing = BuildIngress(clock);
|
||||
var api = new FakeKeepAwakeApi();
|
||||
var controller = new KeepAwakeController(NewLogger(), api);
|
||||
var progress = false;
|
||||
var host = new UserEspKeepAwakeHost("S1", "T1", ing, clock, NewLogger(), controller: controller,
|
||||
espTimeoutProvider: () => null, accountSetupProgressProbe: () => Volatile.Read(ref progress));
|
||||
|
||||
ing.Start();
|
||||
host.Start();
|
||||
PostAccountSetupPhase(ing);
|
||||
Assert.True(WaitFor(() => api.PreventCount == 1));
|
||||
|
||||
PostEspExiting(ing); // handoff exit, no progress yet
|
||||
Assert.False(WaitFor(() => api.AllowCount > 0, 500), "the handoff exit must not release the hold");
|
||||
Assert.True(controller.IsEngaged);
|
||||
|
||||
Volatile.Write(ref progress, true);
|
||||
PostEspExiting(ing); // the real user-ESP page exit
|
||||
Assert.True(WaitFor(() => api.AllowCount == 1));
|
||||
Assert.False(controller.IsEngaged);
|
||||
|
||||
host.Dispose();
|
||||
ing.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AccountSetupProvisioningComplete_no_longer_releases()
|
||||
{
|
||||
// The synthesized completion fired a median 3 min before the page closed in 77 % of
|
||||
// keep-awake sessions (q8n) — it is no longer a release trigger; the cap/stop/exit are.
|
||||
var clock = new VirtualClock(At);
|
||||
using var ing = BuildIngress(clock);
|
||||
var api = new FakeKeepAwakeApi();
|
||||
var controller = new KeepAwakeController(NewLogger(), api);
|
||||
var host = new UserEspKeepAwakeHost("S1", "T1", ing, clock, NewLogger(), controller: controller,
|
||||
espTimeoutProvider: () => null, accountSetupProgressProbe: () => true);
|
||||
|
||||
ing.Start();
|
||||
host.Start();
|
||||
@@ -130,8 +196,34 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
|
||||
ing.Post(DecisionSignalKind.AccountSetupProvisioningComplete, At, "ProvisioningStatusTracker", Raw("done"));
|
||||
|
||||
Assert.True(WaitFor(() => api.AllowCount == 1), "AllowSleep should be called once on AccountSetup completion");
|
||||
Assert.False(controller.IsEngaged);
|
||||
Assert.False(WaitFor(() => api.AllowCount > 0, 500), "completion must not release the hold any more");
|
||||
Assert.True(controller.IsEngaged);
|
||||
|
||||
host.Dispose();
|
||||
ing.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EspExiting_before_engage_is_ignored()
|
||||
{
|
||||
// Exit signals while idle (e.g. a Device-ESP exit before AccountSetup) neither release
|
||||
// nor poison the later engage.
|
||||
var clock = new VirtualClock(At);
|
||||
using var ing = BuildIngress(clock);
|
||||
var api = new FakeKeepAwakeApi();
|
||||
var controller = new KeepAwakeController(NewLogger(), api);
|
||||
var host = new UserEspKeepAwakeHost("S1", "T1", ing, clock, NewLogger(), controller: controller,
|
||||
espTimeoutProvider: () => null, accountSetupProgressProbe: () => true);
|
||||
|
||||
ing.Start();
|
||||
host.Start();
|
||||
PostEspExiting(ing);
|
||||
Assert.False(WaitFor(() => api.AllowCount > 0, 300));
|
||||
|
||||
PostAccountSetupPhase(ing);
|
||||
Assert.True(WaitFor(() => api.PreventCount == 1));
|
||||
Assert.True(controller.IsEngaged);
|
||||
Assert.Equal(0, api.AllowCount);
|
||||
|
||||
host.Dispose();
|
||||
ing.Stop();
|
||||
|
||||
+10
-1
@@ -282,8 +282,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
errorPatternId: null,
|
||||
errorDetail: null,
|
||||
errorCode: null,
|
||||
exitCode: null,
|
||||
exitCode: "0",
|
||||
hresultFromWin32: null,
|
||||
exitCodeClass: "Success",
|
||||
appVersion: "11.2.1787.0",
|
||||
appType: "WinGet",
|
||||
attemptNumber: 1,
|
||||
@@ -293,6 +294,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
|
||||
var info = Assert.Single(f.InfoEvents(SharedEventTypes.AppInstallComplete));
|
||||
Assert.Equal("app-xyz", info.Payload!["appId"]);
|
||||
// Installer outcome surfaces on the terminal event even when the app succeeded: the
|
||||
// return-code class is the only evidence of a SoftReboot/HardReboot mapping and the
|
||||
// number says which code was mapped (IME-EXITCODE-CLASS, ANALYZE-APP-018).
|
||||
Assert.Equal("Success", info.Payload["exitCodeClass"]);
|
||||
Assert.Equal("0", info.Payload["exitCode"]);
|
||||
Assert.Equal("Company Portal", info.Payload["appName"]);
|
||||
Assert.Equal("Installed", info.Payload["state"]);
|
||||
Assert.Equal("Install", info.Payload["intent"]);
|
||||
@@ -331,6 +337,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
errorCode: "60001",
|
||||
exitCode: "60001",
|
||||
hresultFromWin32: "-2146964895",
|
||||
exitCodeClass: "Failed",
|
||||
attemptNumber: 1,
|
||||
detectionResult: "NotDetected");
|
||||
|
||||
@@ -340,6 +347,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
Assert.Equal("true", info.Payload!["isError"]);
|
||||
Assert.Equal("IME-ERROR-UNMAPPED-EXIT", info.Payload["errorPatternId"]);
|
||||
Assert.Equal("60001", info.Payload["errorCode"]);
|
||||
Assert.Equal("60001", info.Payload["exitCode"]);
|
||||
Assert.Equal("Failed", info.Payload["exitCodeClass"]);
|
||||
Assert.Equal("-2146964895", info.Payload["hresultFromWin32"]);
|
||||
Assert.Equal(EventSeverity.Error.ToString(), info.Payload[SignalPayloadKeys.Severity]);
|
||||
// Codex review follow-up (P1): an unrelated ErrorPatternId (here a regular
|
||||
|
||||
+1
@@ -5,6 +5,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Telemetry.Signals
|
||||
{
|
||||
|
||||
+1
@@ -8,6 +8,7 @@ using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Telemetry.Transitions
|
||||
{
|
||||
|
||||
+81
@@ -1701,5 +1701,86 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Termination
|
||||
rig.PromotionCalls[0].failureType);
|
||||
Assert.Null(rig.PromotionCalls[0].errorCode);
|
||||
}
|
||||
|
||||
// ============================================================= packaging counters on the diag events
|
||||
|
||||
[Fact]
|
||||
public void Handle_diagnostics_uploaded_carries_packaging_counters_when_the_packager_reported_them()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Completed }.Build();
|
||||
rig.DiagnosticsResult = new DiagnosticsUploadResult
|
||||
{
|
||||
BlobName = "diag-blob.zip",
|
||||
Packaging = new DiagnosticsPackagingStats
|
||||
{
|
||||
IncludedFiles = 412,
|
||||
IncludedBytes = 123456,
|
||||
SkippedFiles = 3,
|
||||
SkippedByReason = new Dictionary<string, int> { ["size"] = 2, ["total"] = 1 },
|
||||
ProblemsByKind = new Dictionary<string, int> { ["copy"] = 1 },
|
||||
},
|
||||
};
|
||||
var cfg = rig.BuildConfig(diagEnabled: true, diagMode: "Always", selfDestruct: false);
|
||||
|
||||
rig.Build(cfg).Handle(sender: null!,
|
||||
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Succeeded, SessionStage.Completed));
|
||||
|
||||
var uploaded = rig.DataOf("diagnostics_uploaded");
|
||||
Assert.NotNull(uploaded);
|
||||
Assert.Equal(true, uploaded!["truncated"]);
|
||||
Assert.Equal(412, uploaded["includedFiles"]);
|
||||
Assert.Equal(123456L, uploaded["includedBytes"]);
|
||||
Assert.Equal(3, uploaded["skippedFiles"]);
|
||||
var byReason = Assert.IsType<Dictionary<string, int>>(uploaded["skippedByReason"]);
|
||||
Assert.Equal(2, byReason["size"]);
|
||||
Assert.Equal(1, byReason["total"]);
|
||||
var problems = Assert.IsType<Dictionary<string, int>>(uploaded["problemsByKind"]);
|
||||
Assert.Equal(1, problems["copy"]);
|
||||
// Counters only — no key or value carries a file path.
|
||||
foreach (var kv in uploaded)
|
||||
Assert.False(kv.Value is string s && (s.Contains("\\") || s.Contains("/")) && kv.Key != "sasUrlPrefix",
|
||||
$"payload key {kv.Key} looks like a path: {kv.Value}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handle_diagnostics_upload_failed_after_a_build_carries_the_counters_too()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Failed }.Build();
|
||||
rig.DiagnosticsResult = new DiagnosticsUploadResult
|
||||
{
|
||||
ErrorCode = "upload_5xx",
|
||||
Packaging = new DiagnosticsPackagingStats { IncludedFiles = 40, IncludedBytes = 1000 },
|
||||
};
|
||||
var cfg = rig.BuildConfig(diagEnabled: true, diagMode: "Always", selfDestruct: false);
|
||||
|
||||
rig.Build(cfg).Handle(sender: null!,
|
||||
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Failed, SessionStage.Failed));
|
||||
|
||||
var failed = rig.DataOf("diagnostics_upload_failed");
|
||||
Assert.NotNull(failed);
|
||||
Assert.Equal("upload_5xx", (string)failed!["errorCode"]);
|
||||
Assert.Equal(false, failed["truncated"]);
|
||||
Assert.Equal(40, failed["includedFiles"]);
|
||||
Assert.Empty(Assert.IsType<Dictionary<string, int>>(failed["skippedByReason"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handle_diagnostics_events_omit_the_counters_when_no_package_was_built()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Completed }.Build();
|
||||
rig.DiagnosticsResult = new DiagnosticsUploadResult { BlobName = "diag-blob.zip" };
|
||||
var cfg = rig.BuildConfig(diagEnabled: true, diagMode: "Always", selfDestruct: false);
|
||||
|
||||
rig.Build(cfg).Handle(sender: null!,
|
||||
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Succeeded, SessionStage.Completed));
|
||||
|
||||
var uploaded = rig.DataOf("diagnostics_uploaded");
|
||||
Assert.NotNull(uploaded);
|
||||
Assert.False(uploaded!.ContainsKey("truncated"));
|
||||
Assert.False(uploaded.ContainsKey("skippedByReason"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -6,6 +6,7 @@ using System.Net.Http;
|
||||
using System.Threading;
|
||||
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
|
||||
{
|
||||
|
||||
+1
@@ -8,6 +8,7 @@ using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
|
||||
{
|
||||
|
||||
+1
@@ -7,6 +7,7 @@ using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
|
||||
{
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.Text;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
|
||||
{
|
||||
|
||||
+1
@@ -4,6 +4,7 @@ using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
|
||||
{
|
||||
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Agent.V2.Core.Telemetry.Events;
|
||||
using AutopilotMonitor.Agent.V2.Core.Telemetry.Signals;
|
||||
using AutopilotMonitor.Agent.V2.Core.Telemetry.Transitions;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Telemetry.Events;
|
||||
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
|
||||
{
|
||||
/// <summary>
|
||||
/// The agent → backend wire contract of <c>POST /api/agent/telemetry</c>, proven from the
|
||||
/// WRITER side. <see cref="TelemetryItemDto"/> (Shared) is the one class both ends serialise;
|
||||
/// <see cref="TelemetryItem.ToWire"/> is the only mapping onto it.
|
||||
/// <list type="bullet">
|
||||
/// <item>Round trip + reflection: every DTO property is populated by <c>ToWire()</c> and
|
||||
/// survives Newtonsoft defaults — a DTO field added without a mapping fails here.</item>
|
||||
/// <item>Frozen body: the real batch serialiser's output for one item per
|
||||
/// <see cref="TelemetryItemKind"/> is pinned under <c>tests/fixtures/telemetry-wire/</c>.
|
||||
/// The backend's <c>TelemetryWireFixtureTests</c> reads the same files and demands zero
|
||||
/// rejections, so a rename on either side breaks a test until both sides and the fixture
|
||||
/// agree. Regenerate with <c>AM_WRITE_WIRE_FIXTURES=1</c>.</item>
|
||||
/// <item>Poison body: the exact 422 shape the backend writes (pinned there by
|
||||
/// <c>TelemetryWireFixtureTests</c>) is parsed as an item-level poison signal here.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public sealed class TelemetryWireContractTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "b2c3d4e5-f6a7-8901-bcde-f12345678901";
|
||||
private const string FixtureFile = "agent-v2.json";
|
||||
|
||||
private static readonly DateTime At = new DateTime(2026, 4, 20, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private static TelemetryItem FullyPopulatedItem() =>
|
||||
new TelemetryItem(
|
||||
kind: TelemetryItemKind.DecisionTransition,
|
||||
partitionKey: $"{TenantId}_{SessionId}",
|
||||
rowKey: "0000000007",
|
||||
telemetryItemId: 42,
|
||||
sessionTraceOrdinal: 7,
|
||||
payloadJson: "{\"StepIndex\":7}",
|
||||
requiresImmediateFlush: true,
|
||||
enqueuedAtUtc: At,
|
||||
retryCount: 3);
|
||||
|
||||
// ============================================================ ToWire mapping
|
||||
|
||||
[Fact]
|
||||
public void ToWire_round_trips_every_property_through_Newtonsoft_defaults()
|
||||
{
|
||||
var item = FullyPopulatedItem();
|
||||
|
||||
var json = JsonConvert.SerializeObject(item.ToWire());
|
||||
var dto = JsonConvert.DeserializeObject<TelemetryItemDto>(json)!;
|
||||
|
||||
Assert.Equal("DecisionTransition", dto.Kind);
|
||||
Assert.Equal(item.PartitionKey, dto.PartitionKey);
|
||||
Assert.Equal(item.RowKey, dto.RowKey);
|
||||
Assert.Equal(item.TelemetryItemId, dto.TelemetryItemId);
|
||||
Assert.Equal(item.SessionTraceOrdinal, dto.SessionTraceOrdinal);
|
||||
Assert.Equal(item.PayloadJson, dto.PayloadJson);
|
||||
Assert.Equal(item.RequiresImmediateFlush, dto.RequiresImmediateFlush);
|
||||
Assert.Equal(item.EnqueuedAtUtc, dto.EnqueuedAtUtc);
|
||||
Assert.Equal(DateTimeKind.Utc, dto.EnqueuedAtUtc.Kind);
|
||||
Assert.Equal(item.RetryCount, dto.RetryCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToWire_populates_every_TelemetryItemDto_property()
|
||||
{
|
||||
// A DTO property that ToWire() does not set keeps its default — this catches a field
|
||||
// added to the wire type without a mapping (the backend would read the default forever).
|
||||
var dto = FullyPopulatedItem().ToWire();
|
||||
|
||||
var unset = typeof(TelemetryItemDto)
|
||||
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Where(p => IsDefault(p.GetValue(dto), p.PropertyType))
|
||||
.Select(p => p.Name)
|
||||
.ToList();
|
||||
|
||||
Assert.True(unset.Count == 0,
|
||||
"TelemetryItem.ToWire() leaves these TelemetryItemDto properties at their default: " + string.Join(", ", unset));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TelemetryItemDto_properties_mirror_TelemetryItem()
|
||||
{
|
||||
var itemProps = typeof(TelemetryItem).GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.ToDictionary(p => p.Name, p => p.PropertyType);
|
||||
|
||||
foreach (var dtoProp in typeof(TelemetryItemDto).GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
Assert.True(itemProps.TryGetValue(dtoProp.Name, out var itemType),
|
||||
$"TelemetryItemDto.{dtoProp.Name} has no counterpart on TelemetryItem");
|
||||
var expected = dtoProp.Name == nameof(TelemetryItemDto.Kind) ? typeof(TelemetryItemKind) : dtoProp.PropertyType;
|
||||
Assert.True(itemType == expected,
|
||||
$"TelemetryItemDto.{dtoProp.Name} is {dtoProp.PropertyType.Name}, TelemetryItem.{dtoProp.Name} is {itemType.Name}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Every_kind_serialises_by_name_on_the_wire_and_on_the_spool_line()
|
||||
{
|
||||
foreach (var kind in TelemetryItemKinds.All)
|
||||
{
|
||||
var item = new TelemetryItem(kind, "T_S", "rk", 1, 1, "{}", false, At);
|
||||
|
||||
var wire = JObject.Parse(JsonConvert.SerializeObject(item.ToWire()));
|
||||
Assert.Equal(kind.ToString(), (string?)wire["Kind"]);
|
||||
|
||||
// The spool line (TelemetryItemSerializer) has always written the NAME too; the enum's
|
||||
// move to Shared must not turn it into an ordinal (a crash-restart rehydrates it).
|
||||
var spool = JObject.Parse(TelemetryItemSerializer.Serialize(item));
|
||||
Assert.Equal(kind.ToString(), (string?)spool["Kind"]);
|
||||
Assert.Equal(kind, TelemetryItemSerializer.Deserialize(spool.ToString(Formatting.None)).Kind);
|
||||
|
||||
Assert.True(TelemetryItemKinds.TryParse(kind.ToString(), out var parsed));
|
||||
Assert.Equal(kind, parsed);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================ Frozen wire body
|
||||
|
||||
[Fact]
|
||||
public void Frozen_wire_body_matches_the_current_serializer()
|
||||
{
|
||||
var items = OneItemPerKind();
|
||||
Assert.Equal(TelemetryItemKinds.All.OrderBy(k => k), items.Select(i => i.Kind).Distinct().OrderBy(k => k));
|
||||
|
||||
var body = BackendTelemetryUploader.SerializeBatch(items);
|
||||
var path = Path.Combine(RepoPaths.Fixtures("telemetry-wire"), FixtureFile);
|
||||
|
||||
if (Environment.GetEnvironmentVariable("AM_WRITE_WIRE_FIXTURES") == "1")
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.WriteAllText(path, body + "\n", new UTF8Encoding(false));
|
||||
}
|
||||
|
||||
Assert.True(File.Exists(path), "Missing wire fixture " + path + " — run this test with AM_WRITE_WIRE_FIXTURES=1 to create it.");
|
||||
var frozen = File.ReadAllText(path).TrimEnd('\r', '\n');
|
||||
Assert.True(string.Equals(frozen, body, StringComparison.Ordinal),
|
||||
"The agent's telemetry wire body changed. If the change is intended, update the backend ingest " +
|
||||
"(TelemetryWireFixtureTests must still dispatch every frozen body) and regenerate with " +
|
||||
"AM_WRITE_WIRE_FIXTURES=1.\nExpected: " + frozen + "\nActual: " + body);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One item per kind through the REAL emitters (payload shapes are theirs, not hand-typed),
|
||||
/// re-based onto fixed transport fields so the body is byte-stable.
|
||||
/// </summary>
|
||||
private static IReadOnlyList<TelemetryItem> OneItemPerKind()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var transport = new FakeTelemetryTransport();
|
||||
var counter = new EventSequenceCounter(new EventSequencePersistence(tmp.File("seq.json")));
|
||||
|
||||
new TelemetryEventEmitter(transport, counter, SessionId, TenantId).Emit(new EnrollmentEvent
|
||||
{
|
||||
EventId = "00000000-0000-4000-8000-000000000001",
|
||||
EventType = Constants.EventTypes.AgentStarted,
|
||||
Severity = EventSeverity.Info,
|
||||
Source = "Agent",
|
||||
Timestamp = At,
|
||||
Phase = EnrollmentPhase.Unknown,
|
||||
Message = "Agent started",
|
||||
Data = new Dictionary<string, object> { ["agentVersion"] = "2.0.0" },
|
||||
});
|
||||
|
||||
new TelemetrySignalEmitter(transport, SessionId, TenantId).Emit(new DecisionSignal(
|
||||
sessionSignalOrdinal: 1,
|
||||
sessionTraceOrdinal: 1,
|
||||
kind: DecisionSignalKind.SessionStarted,
|
||||
kindSchemaVersion: 1,
|
||||
occurredAtUtc: At,
|
||||
sourceOrigin: "Fixture",
|
||||
evidence: new Evidence(EvidenceKind.Raw, "raw-1", "session start")));
|
||||
|
||||
new TelemetryTransitionEmitter(transport, SessionId, TenantId).Emit(new DecisionTransition(
|
||||
stepIndex: 1,
|
||||
sessionTraceOrdinal: 2,
|
||||
signalOrdinalRef: 1,
|
||||
occurredAtUtc: At,
|
||||
trigger: "SessionStarted",
|
||||
fromStage: SessionStage.Unknown,
|
||||
toStage: SessionStage.AwaitingEspPhaseChange,
|
||||
taken: true,
|
||||
deadEndReason: null,
|
||||
reducerVersion: "1.0.0"));
|
||||
|
||||
return transport.Enqueued
|
||||
.Select(e => new TelemetryItem(e.Kind, e.PartitionKey, e.RowKey, e.TelemetryItemId, e.SessionTraceOrdinal,
|
||||
e.PayloadJson, e.RequiresImmediateFlush, At))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
// ============================================================ Poison body
|
||||
|
||||
/// <summary>
|
||||
/// The exact 422 body the backend writes for rejected items (pinned byte-for-byte in the
|
||||
/// backend's TelemetryWireFixtureTests). camelCase because the backend serialises with
|
||||
/// its wire options; the agent's parser accepts both casings.
|
||||
/// </summary>
|
||||
internal const string BackendPoisonBody =
|
||||
"{\"error\":\"2 of 3 telemetry item(s) cannot be ingested (unknown Kind or unusable payload); they were not stored.\"," +
|
||||
"\"code\":\"TelemetryItemsRejected\",\"correlationId\":\"cid-1\",\"poison\":true,\"rejectedRowKeys\":[\"rk-1\",\"rk-3\"]," +
|
||||
"\"reason\":\"unknown_kind=1;unparseable=1\",\"received\":3,\"rejected\":2}";
|
||||
|
||||
[Fact]
|
||||
public async Task Backend_422_poison_body_is_parsed_as_item_level_poison()
|
||||
{
|
||||
using var handler = new RecordingHttpMessageHandler().QueueStatus((HttpStatusCode)422, BackendPoisonBody);
|
||||
using var http = new HttpClient(handler);
|
||||
var sut = new BackendTelemetryUploader(http, baseUrl: "https://backend.example.invalid", tenantId: TenantId, agentVersion: "2.0.0");
|
||||
|
||||
var result = await sut.UploadBatchAsync(new[] { FullyPopulatedItem() }, CancellationToken.None);
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.True(result.IsPoison);
|
||||
Assert.Equal(new[] { "rk-1", "rk-3" }, result.PoisonRowKeys);
|
||||
Assert.Equal("unknown_kind=1;unparseable=1", result.ErrorReason);
|
||||
}
|
||||
|
||||
private static bool IsDefault(object? value, Type type)
|
||||
{
|
||||
if (value == null) return true;
|
||||
if (type == typeof(string)) return ((string)value).Length == 0;
|
||||
var underlying = Nullable.GetUnderlyingType(type) ?? type;
|
||||
return underlying.IsValueType && value.Equals(Activator.CreateInstance(underlying));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// Installer result codes (captured from lpExitCode / hResultFromWin32 log lines)
|
||||
public string ExitCode { get; private set; }
|
||||
public string HResultFromWin32 { get; private set; }
|
||||
/// <summary>
|
||||
/// Admin-defined return-code class of the last installer exit code: Success, SoftReboot,
|
||||
/// HardReboot, Retry or Failed (IME's AppReturnCodeType, captured from the
|
||||
/// "lpExitCode is defined as X" line by IME-EXITCODE-CLASS). Last value wins, so a Retry
|
||||
/// loop that ends in Success reports Success.
|
||||
/// </summary>
|
||||
public string ExitCodeClass { get; private set; }
|
||||
|
||||
// App metadata (captured from IME log patterns — used by App Dashboard / reports)
|
||||
/// <summary>Product version detected after install (e.g. "11.2.1787.0"). From ReportingManager DetectedIdentityVersion.</summary>
|
||||
@@ -167,6 +174,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
int? progressPercent, long bytesDownloaded, long bytesTotal,
|
||||
string errorPatternId = null, string errorDetail = null, string errorCode = null,
|
||||
string exitCode = null, string hresultFromWin32 = null,
|
||||
string exitCodeClass = null,
|
||||
long doFileSize = 0, long doTotalBytesDownloaded = 0,
|
||||
long doBytesFromPeers = 0, int doPercentPeerCaching = 0,
|
||||
long doBytesFromLanPeers = 0, long doBytesFromGroupPeers = 0,
|
||||
@@ -195,6 +203,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
ErrorCode = errorCode,
|
||||
ExitCode = exitCode,
|
||||
HResultFromWin32 = hresultFromWin32,
|
||||
ExitCodeClass = exitCodeClass,
|
||||
InstallationStateLastChangedTicks = Stopwatch.GetTimestamp(),
|
||||
DoFileSize = doFileSize,
|
||||
DoTotalBytesDownloaded = doTotalBytesDownloaded,
|
||||
@@ -302,6 +311,19 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
HResultFromWin32 = code;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Captures the return-code class (Success/SoftReboot/HardReboot/Retry/Failed) IME assigned
|
||||
/// to the last exit code. Last value wins; empty values are ignored.
|
||||
/// </summary>
|
||||
public bool UpdateExitCodeClass(string exitCodeClass)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(exitCodeClass)) return false;
|
||||
var trimmed = exitCodeClass.Trim();
|
||||
if (ExitCodeClass == trimmed) return false;
|
||||
ExitCodeClass = trimmed;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the product version detected for this app (e.g. "11.2.1787.0").
|
||||
/// Only applies non-empty values so a later detection without version cannot wipe it.
|
||||
@@ -547,6 +569,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
data["exitCode"] = ExitCode;
|
||||
if (!string.IsNullOrEmpty(HResultFromWin32))
|
||||
data["hresultFromWin32"] = HResultFromWin32;
|
||||
if (!string.IsNullOrEmpty(ExitCodeClass))
|
||||
data["exitCodeClass"] = ExitCodeClass;
|
||||
|
||||
// App metadata fields (emitted whenever available so ingest can merge them).
|
||||
if (!string.IsNullOrEmpty(AppVersion))
|
||||
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// A writer era: the stretch of log written by ONE process lifetime, i.e. under one
|
||||
/// timezone belief. For the IME service family (IntuneManagementExtension*.log) an era
|
||||
/// starts at an "EMS Agent Started" entry and may continue across a log rotation into the
|
||||
/// next file; for AgentExecutor.log every script execution is its own short-lived process
|
||||
/// and therefore its own era. An era carries an offset only when an anchor inside it was
|
||||
/// matched against an instant the agent knows in UTC (<see cref="ImeLogEraPreScan"/>).
|
||||
/// </summary>
|
||||
internal sealed class CmTraceEra
|
||||
{
|
||||
/// <summary>File segments (file name → [start, end) byte range) that belong to this era, in write order.</summary>
|
||||
public List<CmTraceEraSegment> Segments { get; } = new List<CmTraceEraSegment>();
|
||||
|
||||
/// <summary>Local time of the era's first entry as written (null for a leading era whose start predates the scanned region).</summary>
|
||||
public DateTime? StartLocal { get; set; }
|
||||
|
||||
/// <summary>Local time of the next era's first entry (null for the last era).</summary>
|
||||
public DateTime? EndLocal { get; set; }
|
||||
|
||||
/// <summary>The writer's UTC offset (local = UTC + offset) when anchored.</summary>
|
||||
public TimeSpan? Offset { get; set; }
|
||||
|
||||
/// <summary>What established <see cref="Offset"/> ("bootstrap-policy-result", "bootstrap-stdout", …).</summary>
|
||||
public string? AnchorKind { get; set; }
|
||||
|
||||
public bool IsAnchored => Offset.HasValue;
|
||||
}
|
||||
|
||||
internal sealed class CmTraceEraSegment
|
||||
{
|
||||
public CmTraceEraSegment(string fileName, long startOffset, long endOffset)
|
||||
{
|
||||
FileName = fileName;
|
||||
StartOffset = startOffset;
|
||||
EndOffset = endOffset;
|
||||
}
|
||||
|
||||
public string FileName { get; }
|
||||
public long StartOffset { get; }
|
||||
/// <summary><c>long.MaxValue</c> while the era is still open in this file.</summary>
|
||||
public long EndOffset { get; set; }
|
||||
|
||||
public bool Contains(string fileName, long offset) =>
|
||||
string.Equals(FileName, fileName, StringComparison.OrdinalIgnoreCase)
|
||||
&& offset >= StartOffset && offset < EndOffset;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Era lookup for backlog lines (2026-09-04, session a7140f98). Two lookups:
|
||||
/// <list type="bullet">
|
||||
/// <item><description><see cref="TryResolveByOffset"/> — the line's own file and byte offset
|
||||
/// (IME service family and AgentExecutor.log: eras are byte ranges).</description></item>
|
||||
/// <item><description><see cref="TryResolveByLocalTime"/> — transfer for files written by the
|
||||
/// SAME process as the IME service log but without their own era marker (AppWorkload.log,
|
||||
/// AppActionProcessor.log: plugins hosted in IntuneManagementExtension.exe, verified in the
|
||||
/// decompiled build). Within one process every file shares the zone belief, so a local
|
||||
/// timestamp places the line in the service era whose local range contains it. Disabled
|
||||
/// entirely when the service eras' local ranges are not monotonic (a westward zone change
|
||||
/// between two service starts makes the ranges overlap) — ambiguity must never anchor.</description></item>
|
||||
/// </list>
|
||||
/// Everything not resolvable here stays on the marked reader-zone fallback; a partially
|
||||
/// corrected era is never produced because an anchor applies to a whole era or not at all.
|
||||
/// </summary>
|
||||
internal sealed class CmTraceEraTable
|
||||
{
|
||||
private readonly List<CmTraceEra> _offsetEras = new List<CmTraceEra>();
|
||||
private readonly List<CmTraceEra> _serviceEras = new List<CmTraceEra>();
|
||||
private bool _transferAmbiguous;
|
||||
|
||||
public IReadOnlyList<CmTraceEra> ServiceEras => _serviceEras;
|
||||
public bool TransferAmbiguous => _transferAmbiguous;
|
||||
public int AnchoredEraCount
|
||||
{
|
||||
get
|
||||
{
|
||||
var n = 0;
|
||||
foreach (var e in _offsetEras) if (e.IsAnchored) n++;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Register an era addressable by (file, offset). Service eras also take part in the local-time transfer.</summary>
|
||||
public void Add(CmTraceEra era, bool isServiceEra)
|
||||
{
|
||||
_offsetEras.Add(era);
|
||||
if (isServiceEra) _serviceEras.Add(era);
|
||||
}
|
||||
|
||||
/// <summary>Call once after all service eras are added: validates the local ranges used by the transfer.</summary>
|
||||
public void Seal()
|
||||
{
|
||||
_transferAmbiguous = false;
|
||||
DateTime? previousStart = null;
|
||||
foreach (var era in _serviceEras)
|
||||
{
|
||||
if (!era.StartLocal.HasValue) continue;
|
||||
if (previousStart.HasValue && era.StartLocal.Value <= previousStart.Value)
|
||||
{
|
||||
_transferAmbiguous = true;
|
||||
break;
|
||||
}
|
||||
previousStart = era.StartLocal;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryResolveByOffset(string fileName, long offset, out TimeSpan writerOffset, out string anchorKind)
|
||||
{
|
||||
writerOffset = TimeSpan.Zero;
|
||||
anchorKind = string.Empty;
|
||||
if (string.IsNullOrEmpty(fileName) || offset < 0) return false;
|
||||
|
||||
foreach (var era in _offsetEras)
|
||||
{
|
||||
if (!era.IsAnchored) continue;
|
||||
foreach (var seg in era.Segments)
|
||||
{
|
||||
if (seg.Contains(fileName, offset))
|
||||
{
|
||||
writerOffset = era.Offset!.Value;
|
||||
anchorKind = era.AnchorKind ?? string.Empty;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryResolveByLocalTime(DateTime localTimestamp, out TimeSpan writerOffset, out string anchorKind)
|
||||
{
|
||||
writerOffset = TimeSpan.Zero;
|
||||
anchorKind = string.Empty;
|
||||
if (_transferAmbiguous) return false;
|
||||
|
||||
var local = DateTime.SpecifyKind(localTimestamp, DateTimeKind.Unspecified);
|
||||
foreach (var era in _serviceEras)
|
||||
{
|
||||
if (!era.IsAnchored) continue;
|
||||
// A leading era with unknown start covers everything before its end.
|
||||
var afterStart = !era.StartLocal.HasValue || local >= era.StartLocal.Value;
|
||||
var beforeEnd = !era.EndLocal.HasValue || local < era.EndLocal.Value;
|
||||
if (afterStart && beforeEnd)
|
||||
{
|
||||
writerOffset = era.Offset!.Value;
|
||||
anchorKind = era.AnchorKind + "/service-era-transfer";
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
@@ -27,6 +27,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
/// <see cref="CmTraceOffsetCalibrator.TryMeasureOffset"/>.
|
||||
/// </summary>
|
||||
LineAnchored = 3,
|
||||
|
||||
/// <summary>
|
||||
/// A backlog line resolved through its writer ERA: the stretch of log written by one
|
||||
/// process lifetime, anchored by an entry inside that era whose UTC instant the agent
|
||||
/// knows exactly (the install marker vs. the IME's own record of the bootstrap script's
|
||||
/// result — a few hundred milliseconds apart). An anchor applies to a whole era or not
|
||||
/// at all, never across an "EMS Agent Started" boundary. See <c>ImeLogEraPreScan</c>
|
||||
/// (2026-09-04, session a7140f98).
|
||||
/// </summary>
|
||||
EraAnchored = 4,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Shared.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// Builds the <see cref="CmTraceEraTable"/> for the backlog the tracker is about to read
|
||||
/// (2026-09-04, session a7140f98: the IME service wrote the whole device-ESP era under the
|
||||
/// OOBE default zone, Windows moved the zone before the agent started, and the restart
|
||||
/// replay put every pre-reboot line three hours early — a 20-minute DeviceSetup became a
|
||||
/// "blocking app timeout").
|
||||
/// <para>
|
||||
/// Backlog lines can never self-anchor (their age would round onto the offset grid), so an
|
||||
/// era needs an entry whose UTC instant is known independently. The one such entry every
|
||||
/// platform-script bootstrap leaves behind is the bootstrap script's own execution: the
|
||||
/// install marker (<c>HKLM\SOFTWARE\AutopilotMonitor\Deployed</c>, UTC) is written
|
||||
/// milliseconds before the script exits, and the IME logs that exit twice — AgentExecutor.log
|
||||
/// records the script's stdout ("Bootstrap Completed Successfully"), and the service log
|
||||
/// records "[PowerShell] … Policy id = <bootstrap>, policy result = …". Field measurement
|
||||
/// (4 sessions, 2026-09-04): 0.13–0.28 s between marker and stdout record, 0.02–0.08 s more to
|
||||
/// the service record — against a 15-minute grid with a 2-minute residual guard.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Rules that keep this sound: only the FIRST bootstrap record of each file is offered (a
|
||||
/// SKIP re-run minutes later could round onto the grid); the residual guard is
|
||||
/// <see cref="CmTraceOffsetCalibrator.TryMeasureOffset"/>; an anchor applies to the whole
|
||||
/// era between two "EMS Agent Started" entries (service) or one script execution
|
||||
/// (AgentExecutor) and never beyond; nothing is anchored without a marker (MSI bootstrap,
|
||||
/// replay tooling). Everything else stays on the marked reader-zone fallback.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
internal static class ImeLogEraPreScan
|
||||
{
|
||||
internal const string AnchorKindBootstrapStdout = "bootstrap-stdout";
|
||||
internal const string AnchorKindBootstrapPolicyResult = "bootstrap-policy-result";
|
||||
|
||||
private const string ServiceStartedPrefix = "EMS Agent Started";
|
||||
private const string ExecutorScriptStartPrefix = "Adding argument powershell with value ";
|
||||
private const string ExecutorOutputPrefix = "write output done.";
|
||||
private const string BootstrapInstallRunMarker = "Bootstrap Completed Successfully";
|
||||
private const string BootstrapInstallRunMarkerAlt = "Agent install mode completed successfully";
|
||||
|
||||
private static readonly Regex ExecutorScriptPolicyId = new Regex(
|
||||
@"Policies\\Scripts\\[a-z0-9\-]+_(?<id>[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.ps1",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));
|
||||
|
||||
private static readonly Regex ServicePolicyResult = new Regex(
|
||||
@"^\[PowerShell\] User Id = [a-f0-9\-]+, Policy id = (?<id>[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}), policy result = ",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));
|
||||
|
||||
private const int MaxEntryLines = 100;
|
||||
|
||||
public sealed class ScanInput
|
||||
{
|
||||
public ScanInput(string filePath, long startOffset)
|
||||
{
|
||||
FilePath = filePath;
|
||||
StartOffset = startOffset;
|
||||
}
|
||||
|
||||
public string FilePath { get; }
|
||||
public long StartOffset { get; }
|
||||
}
|
||||
|
||||
public static bool IsServiceLogFile(string fileName) =>
|
||||
fileName.StartsWith("IntuneManagementExtension", StringComparison.OrdinalIgnoreCase)
|
||||
|| fileName.StartsWith("_IntuneManagementExtension", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public static bool IsExecutorLogFile(string fileName) =>
|
||||
fileName.StartsWith("AgentExecutor", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Files written in-process by the IME service without an era marker of their own (transfer by local time).</summary>
|
||||
public static bool IsServiceHostedFile(string fileName) =>
|
||||
fileName.StartsWith("AppWorkload", StringComparison.OrdinalIgnoreCase)
|
||||
|| fileName.StartsWith("AppActionProcessor", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Scan the given files (sort order = write order; archived before current) from their
|
||||
/// start offsets to EOF and return the era table. Never throws; a file that cannot be
|
||||
/// read contributes no eras.
|
||||
/// </summary>
|
||||
public static CmTraceEraTable Build(
|
||||
IReadOnlyList<ScanInput> files,
|
||||
DateTime? deployedUtc,
|
||||
int maxEntryBytes,
|
||||
AgentLogger? logger)
|
||||
{
|
||||
var table = new CmTraceEraTable();
|
||||
if (!deployedUtc.HasValue)
|
||||
{
|
||||
logger?.Info("ImeLogEraPreScan: no Deployed marker — backlog eras stay on the reader-zone fallback");
|
||||
return table;
|
||||
}
|
||||
|
||||
string? bootstrapPolicyId = null;
|
||||
|
||||
// AgentExecutor first: it is where the bootstrap policy id becomes known.
|
||||
foreach (var input in files)
|
||||
{
|
||||
if (!IsExecutorLogFile(Path.GetFileName(input.FilePath))) continue;
|
||||
try { ScanExecutorFile(input, deployedUtc.Value, maxEntryBytes, table, ref bootstrapPolicyId, logger); }
|
||||
catch (Exception ex) { logger?.Debug($"ImeLogEraPreScan: {Path.GetFileName(input.FilePath)} skipped: {ex.Message}"); }
|
||||
}
|
||||
|
||||
var serviceFiles = new List<ScanInput>();
|
||||
foreach (var input in files)
|
||||
if (IsServiceLogFile(Path.GetFileName(input.FilePath))) serviceFiles.Add(input);
|
||||
|
||||
try { ScanServiceFiles(serviceFiles, deployedUtc.Value, maxEntryBytes, table, bootstrapPolicyId, logger); }
|
||||
catch (Exception ex) { logger?.Debug($"ImeLogEraPreScan: service scan aborted: {ex.Message}"); }
|
||||
|
||||
table.Seal();
|
||||
|
||||
logger?.Info(
|
||||
$"ImeLogEraPreScan: {table.AnchoredEraCount} anchored era(s), {table.ServiceEras.Count} service era(s), " +
|
||||
$"bootstrapPolicyId={(bootstrapPolicyId ?? "(unknown)")}, transfer={(table.TransferAmbiguous ? "ambiguous-disabled" : "enabled")}");
|
||||
return table;
|
||||
}
|
||||
|
||||
private static void ScanExecutorFile(
|
||||
ScanInput input, DateTime deployedUtc, int maxEntryBytes, CmTraceEraTable table,
|
||||
ref string? bootstrapPolicyId, AgentLogger? logger)
|
||||
{
|
||||
var fileName = Path.GetFileName(input.FilePath);
|
||||
CmTraceEra? current = null;
|
||||
string? currentPolicyId = null;
|
||||
var anchored = false;
|
||||
|
||||
foreach (var e in ReadEntries(input, maxEntryBytes))
|
||||
{
|
||||
if (e.Message.StartsWith(ExecutorScriptStartPrefix, StringComparison.Ordinal))
|
||||
{
|
||||
if (current != null) current.Segments[0].EndOffset = e.Offset;
|
||||
current = new CmTraceEra();
|
||||
current.Segments.Add(new CmTraceEraSegment(fileName, e.Offset, long.MaxValue));
|
||||
current.StartLocal = e.HasTimestamp ? e.LocalTimestamp : (DateTime?)null;
|
||||
table.Add(current, isServiceEra: false);
|
||||
var m = ExecutorScriptPolicyId.Match(e.Message);
|
||||
currentPolicyId = m.Success ? m.Groups["id"].Value : null;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (anchored || current == null || !e.HasTimestamp) continue;
|
||||
if (!e.Message.StartsWith(ExecutorOutputPrefix, StringComparison.Ordinal)) continue;
|
||||
if (e.Message.IndexOf(BootstrapInstallRunMarker, StringComparison.OrdinalIgnoreCase) < 0
|
||||
&& e.Message.IndexOf(BootstrapInstallRunMarkerAlt, StringComparison.OrdinalIgnoreCase) < 0)
|
||||
continue;
|
||||
|
||||
// First bootstrap install record of this file, offered once — accepted or not.
|
||||
anchored = true;
|
||||
if (CmTraceOffsetCalibrator.TryMeasureOffset(e.LocalTimestamp, deployedUtc, out var offset))
|
||||
{
|
||||
current.Offset = offset;
|
||||
current.AnchorKind = AnchorKindBootstrapStdout;
|
||||
if (bootstrapPolicyId == null) bootstrapPolicyId = currentPolicyId;
|
||||
logger?.Info($"ImeLogEraPreScan: {fileName} bootstrap execution anchored at {offset} (stdout local={e.LocalTimestamp:yyyy-MM-ddTHH:mm:ss.fff}, policy={currentPolicyId ?? "?"})");
|
||||
}
|
||||
else
|
||||
{
|
||||
logger?.Info($"ImeLogEraPreScan: {fileName} bootstrap stdout record rejected by the residual guard (local={e.LocalTimestamp:yyyy-MM-ddTHH:mm:ss.fff}, deployed={deployedUtc:HH:mm:ss}Z)");
|
||||
if (bootstrapPolicyId == null) bootstrapPolicyId = currentPolicyId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ScanServiceFiles(
|
||||
IReadOnlyList<ScanInput> files, DateTime deployedUtc, int maxEntryBytes, CmTraceEraTable table,
|
||||
string? bootstrapPolicyId, AgentLogger? logger)
|
||||
{
|
||||
if (files.Count == 0) return;
|
||||
|
||||
// The leading era: whatever process was writing when the scanned region begins.
|
||||
var current = new CmTraceEra();
|
||||
table.Add(current, isServiceEra: true);
|
||||
var resultOffered = false;
|
||||
|
||||
foreach (var input in files)
|
||||
{
|
||||
var fileName = Path.GetFileName(input.FilePath);
|
||||
var segment = new CmTraceEraSegment(fileName, input.StartOffset, long.MaxValue);
|
||||
current.Segments.Add(segment);
|
||||
|
||||
foreach (var e in ReadEntries(input, maxEntryBytes))
|
||||
{
|
||||
if (e.Message.StartsWith(ServiceStartedPrefix, StringComparison.Ordinal))
|
||||
{
|
||||
segment.EndOffset = e.Offset;
|
||||
var next = new CmTraceEra { StartLocal = e.HasTimestamp ? e.LocalTimestamp : (DateTime?)null };
|
||||
current.EndLocal = next.StartLocal;
|
||||
segment = new CmTraceEraSegment(fileName, e.Offset, long.MaxValue);
|
||||
next.Segments.Add(segment);
|
||||
table.Add(next, isServiceEra: true);
|
||||
current = next;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (resultOffered || bootstrapPolicyId == null || !e.HasTimestamp) continue;
|
||||
if (!e.Message.StartsWith("[PowerShell] User Id = ", StringComparison.Ordinal)) continue;
|
||||
var m = ServicePolicyResult.Match(e.Message);
|
||||
if (!m.Success || !string.Equals(m.Groups["id"].Value, bootstrapPolicyId, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
|
||||
// First result record for the bootstrap policy, offered once.
|
||||
resultOffered = true;
|
||||
if (CmTraceOffsetCalibrator.TryMeasureOffset(e.LocalTimestamp, deployedUtc, out var offset))
|
||||
{
|
||||
current.Offset = offset;
|
||||
current.AnchorKind = AnchorKindBootstrapPolicyResult;
|
||||
logger?.Info($"ImeLogEraPreScan: {fileName} service era anchored at {offset} (policy result local={e.LocalTimestamp:yyyy-MM-ddTHH:mm:ss.fff})");
|
||||
}
|
||||
else
|
||||
{
|
||||
logger?.Info($"ImeLogEraPreScan: {fileName} bootstrap policy result rejected by the residual guard (local={e.LocalTimestamp:yyyy-MM-ddTHH:mm:ss.fff}, deployed={deployedUtc:HH:mm:ss}Z)");
|
||||
}
|
||||
}
|
||||
|
||||
// The era continues into the next (newer) file: close this file's segment at EOF.
|
||||
try { segment.EndOffset = new FileInfo(input.FilePath).Length; } catch { segment.EndOffset = long.MaxValue; }
|
||||
}
|
||||
|
||||
// The last era stays open in its last file.
|
||||
var last = current.Segments[current.Segments.Count - 1];
|
||||
last.EndOffset = long.MaxValue;
|
||||
}
|
||||
|
||||
private sealed class ScannedEntry
|
||||
{
|
||||
public long Offset;
|
||||
public bool HasTimestamp;
|
||||
public DateTime LocalTimestamp;
|
||||
public string Message = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enumerate CMTrace entries with their file offsets. Same multiline assembly as the
|
||||
/// tracker's read loop (an AgentExecutor stdout record spans many lines; the closing tag
|
||||
/// carries the time); oversized or over-long entries are dropped, never partially used.
|
||||
/// </summary>
|
||||
private static IEnumerable<ScannedEntry> ReadEntries(ScanInput input, int maxEntryBytes)
|
||||
{
|
||||
using (var stream = new FileStream(input.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
{
|
||||
if (input.StartOffset > 0 && input.StartOffset < stream.Length)
|
||||
stream.Seek(input.StartOffset, SeekOrigin.Begin);
|
||||
else if (input.StartOffset >= stream.Length)
|
||||
yield break;
|
||||
|
||||
var reader = new BoundedLineReader(stream, maxEntryBytes);
|
||||
StringBuilder? buffer = null;
|
||||
var bufferLines = 0;
|
||||
long entryStart = input.StartOffset;
|
||||
var skipping = false;
|
||||
|
||||
while (true)
|
||||
{
|
||||
var line = reader.ReadLineAsync(System.Threading.CancellationToken.None).GetAwaiter().GetResult();
|
||||
if (line == null) yield break;
|
||||
if (buffer == null) entryStart = reader.LastLineStart;
|
||||
|
||||
if (reader.LastLineTruncated)
|
||||
{
|
||||
buffer = null; bufferLines = 0; skipping = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (skipping)
|
||||
{
|
||||
if (line.StartsWith("<![LOG[", StringComparison.Ordinal)) skipping = false;
|
||||
else
|
||||
{
|
||||
if (line.Contains("]LOG]!>")) skipping = false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (buffer != null)
|
||||
{
|
||||
buffer.Append('\n').Append(line);
|
||||
bufferLines++;
|
||||
if (line.Contains("]LOG]!>"))
|
||||
{
|
||||
line = buffer.ToString();
|
||||
buffer = null; bufferLines = 0;
|
||||
}
|
||||
else if (bufferLines >= MaxEntryLines || buffer.Length >= maxEntryBytes)
|
||||
{
|
||||
buffer = null; bufferLines = 0; skipping = true;
|
||||
continue;
|
||||
}
|
||||
else continue;
|
||||
}
|
||||
else if (line.StartsWith("<![LOG[", StringComparison.Ordinal) && !line.Contains("]LOG]!>"))
|
||||
{
|
||||
buffer = new StringBuilder(line);
|
||||
bufferLines = 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!CmTraceLogParser.TryParseLine(line, out var entry) || entry == null) continue;
|
||||
yield return new ScannedEntry
|
||||
{
|
||||
Offset = entryStart,
|
||||
HasTimestamp = entry.HasTimestamp && !entry.BiasMinutes.HasValue,
|
||||
LocalTimestamp = entry.LocalTimestamp,
|
||||
Message = entry.Message ?? string.Empty,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
-1
@@ -263,6 +263,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// --- Normal processing (single-line or completed multiline) ---
|
||||
CmTraceLogEntry entry;
|
||||
string messageToMatch;
|
||||
_currentEntryOffset = entryStart;
|
||||
if (CmTraceLogParser.TryParseLine(line, out entry))
|
||||
{
|
||||
messageToMatch = entry.Message;
|
||||
@@ -312,6 +313,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// flagged as such.
|
||||
if (hadPreviousObservation && calibrationAnchor != null)
|
||||
CalibrateFrom(_currentSourceFileName, Path.GetFileName(filePath), calibrationAnchor);
|
||||
_currentEntryOffset = -1;
|
||||
}
|
||||
}
|
||||
catch (FileNotFoundException) { }
|
||||
@@ -489,7 +491,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
"imeshutdown", "espphasedetected", "setcurrentapp",
|
||||
"updatestateinstalled", "updatestatedownloading", "updatestateinstalling",
|
||||
"updatestateskipped", "updatestateerror", "updatestatepostponed",
|
||||
"captureexitcode", "capturehresult", "captureappversion",
|
||||
"captureexitcode", "capturehresult", "captureexitcodeclass", "captureappversion",
|
||||
"captureapptypewinget", "captureapptypemsi", "captureattemptnumber",
|
||||
"capturedetectionresult", "esptrackstatus", "policiesdiscovered",
|
||||
"ignorecompletedapp", "updatename", "updatewin32appstate",
|
||||
@@ -509,6 +511,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
LastMatchedSourceOffsetMinutes = null;
|
||||
LastMatchedSourceOffsetOrigin = CmTraceOffsetOrigin.None;
|
||||
LastMatchedMeasuredWriterOffsetMinutes = null;
|
||||
LastMatchedEraAnchorKind = string.Empty;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -518,6 +521,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
LastMatchedSourceLocalTimestamp = entry.HasTimestamp ? entry.LocalTimestamp : (DateTime?)null;
|
||||
LastMatchedSourceOffsetMinutes = offsetMinutes;
|
||||
LastMatchedSourceOffsetOrigin = origin;
|
||||
LastMatchedEraAnchorKind = origin == CmTraceOffsetOrigin.EraAnchored ? _lastEraAnchorKind : string.Empty;
|
||||
|
||||
// Observational: what the calibrator measured for this file, distinct from what
|
||||
// was applied above.
|
||||
@@ -555,7 +559,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// Placed after the staleness gate so a success replayed from a previous
|
||||
// enrollment's log cannot clear a genuine current outage.
|
||||
if (!isStaleReplayLine && string.Equals(pattern.PatternId, "IME-TOKEN-SUCCESS", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
ClearPendingTokenFailure();
|
||||
// Raw user-token observation for the Entra user-affinity detector (2026-09-04).
|
||||
// Deliberately NOT routed through espPhaseDetected: that path deduplicates once
|
||||
// AccountSetup is set, so a FullESP session would never report the token that
|
||||
// followed the real-user desktop.
|
||||
try { OnUserTokenAcquired?.Invoke(LastMatchedLogTimestamp); }
|
||||
catch (Exception ex) { _logger?.Warning($"OnUserTokenAcquired handler threw: {ex.Message}"); }
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
@@ -617,6 +629,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
|
||||
case "imetokenfailure":
|
||||
HandleImeTokenFailure(match.Groups["errorCode"]?.Value, message);
|
||||
// Raw per-line observation (staleness already enforced above via
|
||||
// AppMutatingActions) — the affinity detector counts failures after
|
||||
// the real-user desktop; the grace-window Warning stays separate.
|
||||
try { OnTokenFailureLine?.Invoke(match.Groups["errorCode"]?.Value, LastMatchedLogTimestamp); }
|
||||
catch (Exception ex) { _logger?.Warning($"OnTokenFailureLine handler threw: {ex.Message}"); }
|
||||
break;
|
||||
|
||||
case "imeimpersonation":
|
||||
@@ -698,6 +715,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
_packageStates.GetPackage(_packageStates.CurrentPackageId)?.UpdateHResult(hresultVal);
|
||||
break;
|
||||
|
||||
case "captureexitcodeclass":
|
||||
// Return-code class of the exit code captured just before (IME logs the
|
||||
// number, then "lpExitCode is defined as <class>"). Same current-app
|
||||
// addressing as captureExitCode; last value wins across a Retry loop.
|
||||
var exitCodeClassVal = match.Groups["exitCodeClass"]?.Value;
|
||||
if (!string.IsNullOrEmpty(exitCodeClassVal) && !string.IsNullOrEmpty(_packageStates.CurrentPackageId))
|
||||
_packageStates.GetPackage(_packageStates.CurrentPackageId)?.UpdateExitCodeClass(exitCodeClassVal);
|
||||
break;
|
||||
|
||||
case "captureappversion":
|
||||
var appVersionVal = match.Groups["appVersion"]?.Value;
|
||||
if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(appVersionVal))
|
||||
@@ -941,6 +967,29 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
}
|
||||
}
|
||||
|
||||
// ERA ANCHOR (2026-09-04, session a7140f98): a backlog line whose writer era was
|
||||
// anchored by the bootstrap execution record resolves through that era's offset.
|
||||
// Whole era or nothing — the anchor never crosses an "EMS Agent Started" boundary,
|
||||
// and in-process sibling files (AppWorkload, AppActionProcessor) join by local
|
||||
// time only while the service eras' local ranges are unambiguous. See
|
||||
// ImeLogEraPreScan for why this is the one anchor a backlog line can trust.
|
||||
_lastEraAnchorKind = string.Empty;
|
||||
if (_currentSourceFileName != null && _currentEntryOffset >= 0)
|
||||
{
|
||||
TimeSpan eraOffset;
|
||||
string anchorKind;
|
||||
var resolved = EraTable.TryResolveByOffset(_currentSourceFileName, _currentEntryOffset, out eraOffset, out anchorKind)
|
||||
|| (ImeLogEraPreScan.IsServiceHostedFile(_currentSourceFileName)
|
||||
&& EraTable.TryResolveByLocalTime(entry.LocalTimestamp, out eraOffset, out anchorKind));
|
||||
if (resolved)
|
||||
{
|
||||
origin = CmTraceOffsetOrigin.EraAnchored;
|
||||
offsetMinutes = (int)eraOffset.TotalMinutes;
|
||||
_lastEraAnchorKind = anchorKind;
|
||||
return DateTime.SpecifyKind(entry.LocalTimestamp - eraOffset, DateTimeKind.Utc);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for everything not provably fresh: assume the reader's zone, UNIFORMLY.
|
||||
// Wrong in absolute terms whenever the writer held a different belief, but
|
||||
// self-consistent — both ends of a duration are wrong by the same amount, so derived
|
||||
|
||||
@@ -400,6 +400,27 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
/// <summary>How that offset was arrived at — declared, measured, or neither.</summary>
|
||||
public CmTraceOffsetOrigin LastMatchedSourceOffsetOrigin { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// For <see cref="CmTraceOffsetOrigin.EraAnchored"/>: which anchor established the era's
|
||||
/// offset ("bootstrap-policy-result", "bootstrap-stdout", with "/service-era-transfer"
|
||||
/// when the line came from an in-process sibling file). Empty otherwise.
|
||||
/// </summary>
|
||||
public string LastMatchedEraAnchorKind { get; internal set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Source of the install marker's UTC instant for the backlog era pre-scan
|
||||
/// (<see cref="ImeLogEraPreScan"/>). Defaults to the registry marker; tests inject.
|
||||
/// </summary>
|
||||
internal Func<DateTime?> DeployedUtcProvider { get; set; } = Security.DeploymentMarker.TryReadDeployedUtc;
|
||||
|
||||
/// <summary>Era table built by <see cref="PreScanEras"/> at <see cref="Start"/>; empty until then.</summary>
|
||||
internal CmTraceEraTable EraTable { get; private set; } = new CmTraceEraTable();
|
||||
|
||||
// Byte offset of the entry currently being resolved in the read loop (-1 outside it) —
|
||||
// the key for the era lookup. Set next to _currentSourceFileName.
|
||||
private long _currentEntryOffset = -1;
|
||||
private string _lastEraAnchorKind = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// The offset the calibrator MEASURED for the source file, which is not necessarily the
|
||||
/// one applied.
|
||||
@@ -425,6 +446,21 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// Args: errorCode (may be empty when IME logged none), raw failure line excerpt.
|
||||
// Fired once per distinct errorCode per tracker lifetime (see HandleImeTokenFailure).
|
||||
public Action<string, string> OnImeTokenFailure { get; set; }
|
||||
/// <summary>
|
||||
/// Fires on EVERY IME-TOKEN-SUCCESS line that passes the historic-replay gate, with the
|
||||
/// line's resolved UTC (null when the line carried no timestamp). Unlike
|
||||
/// <see cref="OnEspPhaseChanged"/> (deduplicated once AccountSetup is set) and unlike the
|
||||
/// grace-window model behind <see cref="OnImeTokenFailure"/>, this is the raw observation:
|
||||
/// "Successfully get the token" is IntuneTokenManager acquiring the signed-in user's token
|
||||
/// through WAM, i.e. the only SYSTEM-visible proof of Entra user affinity (2026-09-04).
|
||||
/// </summary>
|
||||
public Action<DateTime?> OnUserTokenAcquired { get; set; }
|
||||
/// <summary>
|
||||
/// Fires on EVERY IME-TOKEN-FAILURE line that passes the historic-replay gate:
|
||||
/// errorCode (may be empty) and the line's resolved UTC. Raw observation — the
|
||||
/// deduplicated Warning stays on <see cref="OnImeTokenFailure"/>.
|
||||
/// </summary>
|
||||
public Action<string, DateTime?> OnTokenFailureLine { get; set; }
|
||||
// Second arg: the [DO TEL] source log line's timestamp when the DO data came from a
|
||||
// log line, null when the DO collector observed the completion live via polling. The
|
||||
// consumer must stamp poll-driven telemetry with the clock — inheriting an unrelated
|
||||
@@ -839,6 +875,44 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
ActivatePatterns(_logPhaseIsCurrentPhase, force: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Build the backlog era table from the files the first pass will read, each from the
|
||||
/// position the pass will start at. Never throws — a failure leaves the table empty and
|
||||
/// every backlog line on the reader-zone fallback, exactly as before.
|
||||
/// </summary>
|
||||
internal void PreScanEras()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(_logFolder)) return;
|
||||
var inputs = new List<ImeLogEraPreScan.ScanInput>();
|
||||
var files = new List<string>();
|
||||
foreach (var filePath in Directory.EnumerateFiles(_logFolder))
|
||||
{
|
||||
if (MatchesLogFilePattern(Path.GetFileName(filePath)))
|
||||
files.Add(filePath);
|
||||
}
|
||||
files.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var filePath in files)
|
||||
{
|
||||
var info = new FileInfo(filePath);
|
||||
if (!info.Exists) continue;
|
||||
inputs.Add(new ImeLogEraPreScan.ScanInput(filePath, _positionTracker.GetSafePosition(filePath, info.Length)));
|
||||
}
|
||||
|
||||
DateTime? deployedUtc = null;
|
||||
try { deployedUtc = DeployedUtcProvider?.Invoke(); }
|
||||
catch (Exception ex) { _logger.Debug($"ImeLogTracker: Deployed marker read failed: {ex.Message}"); }
|
||||
|
||||
EraTable = ImeLogEraPreScan.Build(inputs, deployedUtc, MaxEntryBytes, _logger);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Warning($"ImeLogTracker: era pre-scan failed — backlog stays on the reader-zone fallback: {ex.Message}");
|
||||
EraTable = new CmTraceEraTable();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts the background polling task
|
||||
/// </summary>
|
||||
@@ -851,6 +925,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// exactly where we left off — no re-parsing, no device-phase bleeding.
|
||||
LoadState();
|
||||
|
||||
// Era anchors for the backlog the first pass is about to read (2026-09-04). Runs
|
||||
// before the poll loop so every replayed line already finds its era; read-only on
|
||||
// the position tracker. Replay tooling anchors nothing — its logs did not come from
|
||||
// this device's bootstrap.
|
||||
if (!SimulationMode) PreScanEras();
|
||||
|
||||
_cts = new CancellationTokenSource();
|
||||
var token = _cts.Token;
|
||||
|
||||
@@ -1161,6 +1241,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
ErrorCode = p.ErrorCode,
|
||||
ExitCode = p.ExitCode,
|
||||
HResultFromWin32 = p.HResultFromWin32,
|
||||
ExitCodeClass = p.ExitCodeClass,
|
||||
DoFileSize = p.DoFileSize,
|
||||
DoTotalBytesDownloaded = p.DoTotalBytesDownloaded,
|
||||
DoBytesFromPeers = p.DoBytesFromPeers,
|
||||
@@ -1190,6 +1271,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
p.ProgressPercent, p.BytesDownloaded, p.BytesTotal,
|
||||
errorPatternId: p.ErrorPatternId, errorDetail: p.ErrorDetail, errorCode: p.ErrorCode,
|
||||
exitCode: p.ExitCode, hresultFromWin32: p.HResultFromWin32,
|
||||
exitCodeClass: p.ExitCodeClass,
|
||||
doFileSize: p.DoFileSize, doTotalBytesDownloaded: p.DoTotalBytesDownloaded,
|
||||
doBytesFromPeers: p.DoBytesFromPeers, doPercentPeerCaching: p.DoPercentPeerCaching,
|
||||
doBytesFromLanPeers: p.DoBytesFromLanPeers, doBytesFromGroupPeers: p.DoBytesFromGroupPeers,
|
||||
|
||||
+3
@@ -190,6 +190,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// Installer result codes
|
||||
public string ExitCode { get; set; }
|
||||
public string HResultFromWin32 { get; set; }
|
||||
// Return-code class of the last exit code (null on state files written before the field
|
||||
// existed) - must survive the reboot a SoftReboot/HardReboot app asks for.
|
||||
public string ExitCodeClass { get; set; }
|
||||
|
||||
// Delivery Optimization telemetry
|
||||
public long DoFileSize { get; set; }
|
||||
|
||||
+11
@@ -67,6 +67,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
public event EventHandler<AadPlaceholderUserDetectedEventArgs> PlaceholderUserDetected;
|
||||
public event EventHandler<AadUserJoinedEventArgs> AadUserJoined;
|
||||
|
||||
/// <summary>
|
||||
/// <c>true</c> while a provisioning placeholder (foouser@/autopilot@) is the JoinInfo
|
||||
/// user and no real user has replaced it. On a Hybrid join this stays true through the
|
||||
/// whole user sign-in — the AD sign-in never touches JoinInfo — so consumers report it
|
||||
/// as a fact, never as sign-in evidence (2026-09-04).
|
||||
/// </summary>
|
||||
internal bool PlaceholderObservedWithoutRealUser
|
||||
{
|
||||
get { lock (_stateLock) return _placeholderFired && !_realUserFired; }
|
||||
}
|
||||
|
||||
public AadJoinWatcher(AgentLogger logger)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
|
||||
+2
-2
@@ -234,7 +234,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
try
|
||||
{
|
||||
OnTraceEvent?.Invoke(
|
||||
"desktop_excluded_user",
|
||||
SharedEventTypes.DesktopExcludedUser,
|
||||
$"explorer.exe found but owned by excluded user '{owner}' — not a real user desktop",
|
||||
new Dictionary<string, object> { { "pid", proc.Id }, { "session", proc.SessionId }, { "owner", owner } });
|
||||
}
|
||||
@@ -250,7 +250,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
try
|
||||
{
|
||||
OnTraceEvent?.Invoke(
|
||||
"desktop_real_user_detected",
|
||||
SharedEventTypes.DesktopRealUserDetected,
|
||||
$"Real user desktop detected (explorer.exe PID {proc.Id}, user '[redacted]')",
|
||||
new Dictionary<string, object> { { "pid", proc.Id }, { "session", proc.SessionId }, { "owner", "[redacted]" } });
|
||||
}
|
||||
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Orchestration;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using SharedConstants = AutopilotMonitor.Shared.Constants;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
{
|
||||
/// <summary>
|
||||
/// Single-shot detector for Entra user affinity on Hybrid Azure AD Join devices
|
||||
/// (2026-09-04, session a7140f98). After the real user signs in, IME acquires that user's
|
||||
/// token through WAM and logs "Successfully get the token" (IntuneTokenManager,
|
||||
/// <c>IME-TOKEN-SUCCESS</c>). That line is the only SYSTEM-visible proof that the user
|
||||
/// session carries an Entra identity (PRT); a session whose user never gets one shows only
|
||||
/// "Failed to get AAD token" lines after the desktop.
|
||||
/// <para>
|
||||
/// Contract: <see cref="NotifyRealUserDesktop"/> arms the timer when the device is a Hybrid
|
||||
/// join (probe injected by the host). The first token success stamped after the desktop
|
||||
/// cancels the timer and emits <c>ime_user_token_acquired</c>; the timer emits
|
||||
/// <c>entra_user_affinity_pending</c> with the failure codes observed since the desktop.
|
||||
/// A token that arrives after the timer fired is still posted once — it tells the
|
||||
/// timeline (and the backend rule) that affinity came late rather than never.
|
||||
/// Both emissions happen at most once per agent process — a reboot starts a new process,
|
||||
/// whose repeat is exactly the confidence signal the backend rule counts. Token lines older
|
||||
/// than the desktop (minus a small tolerance for the 30 s desktop poll) belong to the
|
||||
/// device phase and are ignored: they appear in every enrollment.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Not a decision signal. Never influences completion. The JoinInfo placeholder is reported
|
||||
/// as a fact in the payload because it is NOT a login signal on a Hybrid join — the AD
|
||||
/// sign-in never replaces it; only the later Entra device registration does.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
internal sealed class EntraUserAffinityDetector : IDisposable
|
||||
{
|
||||
internal const int DefaultDelayMinutes = 10;
|
||||
internal const string SourceLabel = "EntraUserAffinityDetector";
|
||||
/// <summary>Token lines this much older than the desktop observation still count as post-desktop.</summary>
|
||||
internal static readonly TimeSpan DesktopPollTolerance = TimeSpan.FromMinutes(2);
|
||||
|
||||
private readonly InformationalEventPost _post;
|
||||
private readonly AgentLogger _logger;
|
||||
private readonly Func<bool> _isHybridJoinProbe;
|
||||
private readonly Func<bool>? _placeholderActiveProbe;
|
||||
private readonly Func<DateTime> _utcNow;
|
||||
private readonly TimeSpan _delay;
|
||||
private readonly object _lock = new object();
|
||||
private readonly List<string> _failureCodesSinceDesktop = new List<string>();
|
||||
|
||||
private Timer? _timer;
|
||||
private DateTime? _desktopObservedUtc;
|
||||
private bool _armed;
|
||||
private bool _fired;
|
||||
private bool _tokenAcquiredPosted;
|
||||
private int _failureCountSinceDesktop;
|
||||
private int _disposed;
|
||||
|
||||
internal EntraUserAffinityDetector(
|
||||
InformationalEventPost post,
|
||||
AgentLogger logger,
|
||||
Func<bool> isHybridJoinProbe,
|
||||
Func<bool>? placeholderActiveProbe = null,
|
||||
TimeSpan? delay = null,
|
||||
Func<DateTime>? utcNow = null)
|
||||
{
|
||||
_post = post ?? throw new ArgumentNullException(nameof(post));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_isHybridJoinProbe = isHybridJoinProbe ?? throw new ArgumentNullException(nameof(isHybridJoinProbe));
|
||||
_placeholderActiveProbe = placeholderActiveProbe;
|
||||
_delay = delay ?? TimeSpan.FromMinutes(DefaultDelayMinutes);
|
||||
_utcNow = utcNow ?? (() => DateTime.UtcNow);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The DesktopArrivalDetector resolved explorer.exe under a real (non-placeholder,
|
||||
/// non-system) user. Arms the timer on Hybrid devices; idempotent; no-op after a
|
||||
/// token success or after the timer fired.
|
||||
/// </summary>
|
||||
public void NotifyRealUserDesktop()
|
||||
{
|
||||
bool hybrid;
|
||||
try { hybrid = _isHybridJoinProbe(); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Warning($"EntraUserAffinityDetector: hybrid probe threw — not arming: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
if (_disposed != 0 || _armed || _fired || _tokenAcquiredPosted) return;
|
||||
if (!hybrid)
|
||||
{
|
||||
_logger.Debug("EntraUserAffinityDetector: real-user desktop on a non-Hybrid device — not armed");
|
||||
return;
|
||||
}
|
||||
|
||||
_desktopObservedUtc = _utcNow();
|
||||
_armed = true;
|
||||
_logger.Info(
|
||||
$"EntraUserAffinityDetector: armed at real-user desktop — will emit {SharedConstants.EventTypes.EntraUserAffinityPending} in {_delay.TotalMinutes:F0} min unless IME acquires a user token");
|
||||
_timer = new Timer(OnTimer, null, _delay, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>IME-TOKEN-SUCCESS line observed; <paramref name="lineUtc"/> is the line's resolved time.</summary>
|
||||
public void NotifyUserTokenAcquired(DateTime? lineUtc)
|
||||
{
|
||||
DateTime desktop;
|
||||
double minutesAfterDesktop;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_disposed != 0 || !_armed || _tokenAcquiredPosted) return;
|
||||
desktop = _desktopObservedUtc!.Value;
|
||||
if (!IsAfterDesktop(lineUtc, desktop)) return;
|
||||
|
||||
_tokenAcquiredPosted = true;
|
||||
_timer?.Dispose();
|
||||
_timer = null;
|
||||
minutesAfterDesktop = ((lineUtc ?? _utcNow()) - desktop).TotalMinutes;
|
||||
}
|
||||
|
||||
var data = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["minutesAfterDesktop"] = Math.Max(0, minutesAfterDesktop).ToString("F1", System.Globalization.CultureInfo.InvariantCulture),
|
||||
["tokenFailuresBeforeSuccess"] = _failureCountSinceDesktop.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
["isHybridJoin"] = "true",
|
||||
};
|
||||
|
||||
_post.Emit(
|
||||
eventType: SharedConstants.EventTypes.ImeUserTokenAcquired,
|
||||
source: SourceLabel,
|
||||
message: "Entra user token acquired by IME after the real-user desktop — user affinity established",
|
||||
severity: EventSeverity.Info,
|
||||
immediateUpload: false,
|
||||
data: data,
|
||||
occurredAtUtc: lineUtc);
|
||||
|
||||
_logger.Info($"EntraUserAffinityDetector: user token observed {minutesAfterDesktop:F1} min after desktop — timer cancelled");
|
||||
}
|
||||
|
||||
/// <summary>IME-TOKEN-FAILURE line observed; counted only when stamped after the desktop.</summary>
|
||||
public void NotifyTokenFailureLine(string? errorCode, DateTime? lineUtc)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_disposed != 0 || !_armed || _fired || _tokenAcquiredPosted) return;
|
||||
if (!IsAfterDesktop(lineUtc, _desktopObservedUtc!.Value)) return;
|
||||
|
||||
_failureCountSinceDesktop++;
|
||||
var code = string.IsNullOrWhiteSpace(errorCode) ? "unknown" : errorCode!.Trim();
|
||||
if (!_failureCodesSinceDesktop.Contains(code, StringComparer.OrdinalIgnoreCase))
|
||||
_failureCodesSinceDesktop.Add(code);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
|
||||
lock (_lock)
|
||||
{
|
||||
_timer?.Dispose();
|
||||
_timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Test seams — same lock and state guards as the production paths.
|
||||
internal void TriggerFromTest() => OnTimer(null);
|
||||
internal bool IsArmedForTest { get { lock (_lock) { return _armed; } } }
|
||||
internal bool HasFiredForTest { get { lock (_lock) { return _fired; } } }
|
||||
internal bool TokenAcquiredPostedForTest { get { lock (_lock) { return _tokenAcquiredPosted; } } }
|
||||
|
||||
private static bool IsAfterDesktop(DateTime? lineUtc, DateTime desktopUtc)
|
||||
{
|
||||
// A line without a timestamp cannot be placed — treat it as current (the tracker
|
||||
// only hands us lines it just read), which is after the desktop by construction.
|
||||
if (!lineUtc.HasValue) return true;
|
||||
return lineUtc.Value >= desktopUtc - DesktopPollTolerance;
|
||||
}
|
||||
|
||||
private void OnTimer(object? state)
|
||||
{
|
||||
string codes;
|
||||
int count;
|
||||
double minutesSinceDesktop;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_disposed != 0 || !_armed || _fired || _tokenAcquiredPosted) return;
|
||||
_fired = true;
|
||||
_timer?.Dispose();
|
||||
_timer = null;
|
||||
codes = string.Join(",", _failureCodesSinceDesktop);
|
||||
count = _failureCountSinceDesktop;
|
||||
minutesSinceDesktop = (_utcNow() - _desktopObservedUtc!.Value).TotalMinutes;
|
||||
}
|
||||
|
||||
var placeholderActive = "unknown";
|
||||
try
|
||||
{
|
||||
if (_placeholderActiveProbe != null)
|
||||
placeholderActive = _placeholderActiveProbe() ? "true" : "false";
|
||||
}
|
||||
catch { /* observational */ }
|
||||
|
||||
var data = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["delayMinutes"] = ((int)_delay.TotalMinutes).ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
["reason"] = "timer_fired",
|
||||
["minutesSinceDesktop"] = Math.Max(0, minutesSinceDesktop).ToString("F1", System.Globalization.CultureInfo.InvariantCulture),
|
||||
["tokenFailureCount"] = count.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
["tokenFailureCodes"] = codes,
|
||||
["placeholderActive"] = placeholderActive,
|
||||
["isHybridJoin"] = "true",
|
||||
};
|
||||
|
||||
_post.Emit(
|
||||
eventType: SharedConstants.EventTypes.EntraUserAffinityPending,
|
||||
source: SourceLabel,
|
||||
message: $"Hybrid AAD Join: {(int)_delay.TotalMinutes} min after the real-user desktop IME has not acquired an Entra user token — user affinity pending"
|
||||
+ (count > 0 ? $" ({count} token failure(s): {codes})" : string.Empty),
|
||||
severity: EventSeverity.Warning,
|
||||
immediateUpload: true,
|
||||
data: data);
|
||||
|
||||
_logger.Warning($"EntraUserAffinityDetector: emitted {SharedConstants.EventTypes.EntraUserAffinityPending} (failures={count}, codes={codes})");
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -202,9 +202,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
|
||||
/// <summary>
|
||||
/// True when any AccountSetup subcategory has been tracked (resolved or in progress).
|
||||
/// Presence semantics — see <see cref="ProvisioningStatusTracker.HasAccountSetupActivity"/>
|
||||
/// for why this must stay that way.
|
||||
/// </summary>
|
||||
public bool HasAccountSetupActivity => _provisioningTracker?.HasAccountSetupActivity ?? false;
|
||||
|
||||
/// <summary>
|
||||
/// True once an AccountSetup subcategory has left <c>notStarted</c> — see
|
||||
/// <see cref="ProvisioningStatusTracker.HasAccountSetupProgress"/>. Keep-awake input only.
|
||||
/// </summary>
|
||||
public bool HasAccountSetupProgress => _provisioningTracker?.HasAccountSetupProgress ?? false;
|
||||
|
||||
/// <summary>
|
||||
/// True once WhiteGlove start has been detected (EventID 509 or persisted from prior run).
|
||||
/// Forwarded from ModernDeploymentTracker.
|
||||
|
||||
+21
-1
@@ -36,6 +36,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
internal const int EventId_ProvisioningWillNotLaunch = 360;
|
||||
internal const int EventId_ProvisioningBlocked = 362;
|
||||
internal const int EventId_PinStatus = 376;
|
||||
// Automatic device registration failed at the join / authentication phase (Hybrid Join
|
||||
// affinity diagnosis, 2026-09-04). Not Hello events — they ride the same UDR watcher
|
||||
// because the channel is already armed; surfaced as device_registration_event.
|
||||
internal const int EventId_AutoRegistrationFailedJoin = 304;
|
||||
internal const int EventId_AutoRegistrationFailedAuth = 305;
|
||||
|
||||
internal const int EventId_HelloForBusiness_ProcessingStarted = 3024;
|
||||
internal const int EventId_HelloForBusiness_ProcessingStopped = 6045;
|
||||
@@ -47,6 +52,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
|
||||
private static readonly HashSet<int> TrackedUdrEventIds = new HashSet<int>
|
||||
{
|
||||
EventId_AutoRegistrationFailedJoin,
|
||||
EventId_AutoRegistrationFailedAuth,
|
||||
EventId_NgcKeyRegistered,
|
||||
EventId_NgcKeyRegistrationFailed,
|
||||
EventId_ProvisioningWillLaunch,
|
||||
@@ -547,7 +554,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
var query = new EventLogQuery(
|
||||
UdrEventLogChannel,
|
||||
PathType.LogName,
|
||||
"*[System[(EventID=300 or EventID=301 or EventID=358 or EventID=360 or EventID=362 or EventID=376)]]");
|
||||
"*[System[(EventID=300 or EventID=301 or EventID=304 or EventID=305 or EventID=358 or EventID=360 or EventID=362 or EventID=376)]]");
|
||||
|
||||
_udrWatcher = new EventLogWatcher(query);
|
||||
_udrWatcher.EventRecordWritten += OnUdrEventRecordWritten;
|
||||
@@ -654,6 +661,18 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
message = "Windows Hello PIN status update";
|
||||
break;
|
||||
|
||||
case EventId_AutoRegistrationFailedJoin: // 304
|
||||
case EventId_AutoRegistrationFailedAuth: // 305
|
||||
// OS-side record that the automatic device registration failed (join or
|
||||
// authentication phase). Companion evidence for entra_user_affinity_pending —
|
||||
// no Hello state involved, so no MarkHelloCompleted().
|
||||
eventType = Constants.EventTypes.DeviceRegistrationEvent;
|
||||
severity = EventSeverity.Warning;
|
||||
message = $"User Device Registration: automatic registration failed (event {eventId}, "
|
||||
+ (eventId == EventId_AutoRegistrationFailedJoin ? "join phase)" : "authentication phase)");
|
||||
_logger.Info($"User Device Registration failure event {eventId} observed");
|
||||
break;
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
@@ -691,6 +710,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
// flip state multiple times — keep batched.
|
||||
ImmediateUpload = shouldTriggerHelloCompleted
|
||||
|| eventType == Constants.EventTypes.HelloProvisioningFailed
|
||||
|| eventType == Constants.EventTypes.DeviceRegistrationEvent
|
||||
});
|
||||
|
||||
_logger.Info($"Hello event detected: {eventType} (EventID {eventId}{(isBackfill ? ", backfill" : "")})");
|
||||
|
||||
+52
-17
@@ -10,19 +10,27 @@ using SharedConstants = AutopilotMonitor.Shared.Constants;
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
{
|
||||
/// <summary>
|
||||
/// Single-shot detector for the Hybrid User-Driven completion-gap (2026-05-01 trigger:
|
||||
/// session e58bcfdb-3e68-4f23-a3c2-437429ca9e78). After a Hybrid AAD-Join reboot the
|
||||
/// agent restarts and waits for the user to log in with their real AD/AAD account
|
||||
/// (which replaces the foouser/autopilot placeholder in JoinInfo). When that login is
|
||||
/// overdue the agent today goes silent until the backend 5-h watchdog fires; this
|
||||
/// detector emits a <c>hybrid_login_pending</c> warning event after a short single-shot
|
||||
/// timer so the operator sees an explicit "stuck waiting for AD login" signal in the
|
||||
/// timeline.
|
||||
/// Single-shot detector for the Hybrid User-Driven sign-in gap (2026-05-01 trigger:
|
||||
/// session e58bcfdb-3e68-4f23-a3c2-437429ca9e78). After the Hybrid AAD-Join reboot the
|
||||
/// agent restarts and waits for the user to sign in with their AD account. When nobody
|
||||
/// signs in the agent goes silent until the backend watchdog fires; this detector emits a
|
||||
/// <c>hybrid_login_pending</c> warning after a short single-shot timer so the operator sees
|
||||
/// an explicit "still waiting for the sign-in" signal in the timeline.
|
||||
/// <para>
|
||||
/// Conditions checked at <see cref="Arm"/>: composition root must have already
|
||||
/// confirmed a) post-reboot, b) <c>isHybridJoin == true</c>. The detector itself only
|
||||
/// owns the timer + <see cref="AadJoinWatcher.AadUserJoined"/> cancel-path. No polling.
|
||||
/// No periodicity. Fires at most once per agent process.
|
||||
/// What it measures (rewritten 2026-09-04, session a7140f98): the ABSENCE of a real-user
|
||||
/// desktop. Two cancel paths: the DesktopArrivalDetector resolving explorer.exe under a
|
||||
/// real user (the actual sign-in evidence), and the AadJoinWatcher seeing a real user in
|
||||
/// JoinInfo (the Entra-join flavour, where the OOBE sign-in completes the join). On a
|
||||
/// Hybrid join the AD sign-in never replaces the JoinInfo placeholder — only the later
|
||||
/// Entra device registration does — so the placeholder state is reported as a fact in the
|
||||
/// payload, never as the reason for the warning.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Conditions checked at <see cref="Arm"/> by the composition root: post-reboot,
|
||||
/// <c>isHybridJoin == true</c>, and not a WhiteGlove device (a sealed device legitimately
|
||||
/// waits days for its user; the session status AwaitingUser already describes that).
|
||||
/// The detector owns only the timer and the cancel paths. No polling. Fires at most once
|
||||
/// per agent process.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
internal sealed class HybridLoginPendingDetector : IDisposable
|
||||
@@ -40,6 +48,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
private bool _armed;
|
||||
private bool _fired;
|
||||
private bool _cancelledByRealUser;
|
||||
private bool _cancelledByDesktop;
|
||||
private int _disposed;
|
||||
|
||||
internal HybridLoginPendingDetector(
|
||||
@@ -60,8 +69,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
|
||||
/// <summary>
|
||||
/// Starts the single-shot timer. Idempotent — repeated calls after the first arm
|
||||
/// are no-ops. Has no effect if the watcher already saw a real AAD user (the
|
||||
/// arming was racy and the cancel won), or if the detector already fired.
|
||||
/// are no-ops. Has no effect if a real-user desktop or a real AAD user was already
|
||||
/// observed (the arming was racy and the cancel won), or if the detector already fired.
|
||||
/// </summary>
|
||||
public void Arm()
|
||||
{
|
||||
@@ -69,6 +78,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
{
|
||||
if (_disposed != 0) return;
|
||||
if (_armed || _fired) return;
|
||||
if (_cancelledByDesktop)
|
||||
{
|
||||
_logger.Info("HybridLoginPendingDetector: arm requested but a real-user desktop was already observed — skipped");
|
||||
return;
|
||||
}
|
||||
if (_cancelledByRealUser)
|
||||
{
|
||||
_logger.Info("HybridLoginPendingDetector: arm requested but real AAD user already joined — skipped");
|
||||
@@ -77,12 +91,29 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
|
||||
_armed = true;
|
||||
_logger.Info(
|
||||
$"HybridLoginPendingDetector: armed — will emit hybrid_login_pending in {_delay.TotalMinutes:F0} min if real AAD user has not joined by then");
|
||||
$"HybridLoginPendingDetector: armed — will emit hybrid_login_pending in {_delay.TotalMinutes:F0} min if no real-user desktop appears by then");
|
||||
|
||||
_timer = new Timer(OnTimer, null, _delay, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The DesktopArrivalDetector resolved explorer.exe under a real user — the sign-in
|
||||
/// happened. Cancels a running timer; remembered so a later <see cref="Arm"/> is a no-op.
|
||||
/// </summary>
|
||||
public void NotifyRealUserDesktop()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_cancelledByDesktop = true;
|
||||
if (!_armed || _fired) return;
|
||||
|
||||
_timer?.Dispose();
|
||||
_timer = null;
|
||||
_logger.Info("HybridLoginPendingDetector: cancelled — real-user desktop observed before timeout");
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
|
||||
@@ -106,6 +137,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
|
||||
internal bool IsArmedForTest { get { lock (_lock) { return _armed; } } }
|
||||
internal bool IsCancelledByRealUserForTest { get { lock (_lock) { return _cancelledByRealUser; } } }
|
||||
internal bool IsCancelledByDesktopForTest { get { lock (_lock) { return _cancelledByDesktop; } } }
|
||||
internal bool HasFiredForTest { get { lock (_lock) { return _fired; } } }
|
||||
|
||||
private void OnTimer(object? state) => EmitInternal(reason: "timer_fired");
|
||||
@@ -130,23 +162,26 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
// _armed guard (Codex review 2026-05-01): production is safe because the
|
||||
// timer is only created in Arm(), but explicit guard makes the contract
|
||||
// unambiguous — emission requires a deliberate Arm(), full stop.
|
||||
if (!_armed || _fired || _cancelledByRealUser || _disposed != 0) return;
|
||||
if (!_armed || _fired || _cancelledByRealUser || _cancelledByDesktop || _disposed != 0) return;
|
||||
_fired = true;
|
||||
_timer?.Dispose();
|
||||
_timer = null;
|
||||
}
|
||||
|
||||
var placeholderActive = _watcher.PlaceholderObservedWithoutRealUser ? "true" : "false";
|
||||
var data = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["delayMinutes"] = ((int)_delay.TotalMinutes).ToString(),
|
||||
["reason"] = reason,
|
||||
["isHybridJoin"] = "true", // armed only when composition root verified this
|
||||
["realUserDesktopSeen"] = "false",
|
||||
["placeholderActive"] = placeholderActive,
|
||||
};
|
||||
|
||||
_post.Emit(
|
||||
eventType: SharedConstants.EventTypes.HybridLoginPending,
|
||||
source: SourceLabel,
|
||||
message: $"Hybrid AAD Join: {(int)_delay.TotalMinutes} min after reboot still no real AD user — login overdue (placeholder still active in JoinInfo)",
|
||||
message: $"Hybrid AAD Join: {(int)_delay.TotalMinutes} min after reboot still no real-user desktop — sign-in overdue",
|
||||
severity: EventSeverity.Warning,
|
||||
immediateUpload: true,
|
||||
data: data);
|
||||
|
||||
+41
@@ -209,6 +209,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
|
||||
/// <summary>
|
||||
/// True when any AccountSetup subcategory has been tracked (resolved or in progress).
|
||||
/// <para>
|
||||
/// PRESENCE semantics, deliberately (backlog q8n, 2026-09-04): Windows writes
|
||||
/// <c>AccountSetupCategory.Status</c> with every subcategory <c>notStarted</c> before the
|
||||
/// Device-ESP page exits, so this is true at the Device→Account handoff 62407 already.
|
||||
/// That is load-bearing for completion: about one in five Classic sessions sees only ONE
|
||||
/// Shell-Core 62407 for the whole enrollment (no separate user-ESP page exit), and those
|
||||
/// sessions resolve AccountSetup solely through the user-apps-settled synthesis, which
|
||||
/// needs that single exit to be remembered as the edge. Tightening this to "progress"
|
||||
/// would strand them. Callers that need "the user ESP page has demonstrably started"
|
||||
/// use <see cref="HasAccountSetupProgress"/> instead.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public bool HasAccountSetupActivity
|
||||
{
|
||||
@@ -225,6 +236,36 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True once at least one AccountSetup subcategory has left <c>notStarted</c> — the user
|
||||
/// ESP page (or its background tracking) has demonstrably started working. Unlike
|
||||
/// <see cref="HasAccountSetupActivity"/> this is NOT satisfied by the pre-written
|
||||
/// all-<c>notStarted</c> JSON that precedes the Device-ESP exit (session a2256107: JSON at
|
||||
/// 09:37:42, intermediate 62407 at 09:37:53, first progress at 09:38:25; fleet: progress
|
||||
/// precedes the real user-ESP exit by at least ~1 min). Used by the User-ESP keep-awake
|
||||
/// host to tell the real user-ESP page exit from the Device→Account handoff exit; not a
|
||||
/// completion input.
|
||||
/// </summary>
|
||||
public bool HasAccountSetupProgress
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_stateLock)
|
||||
{
|
||||
if (_lastSubcategoryStates == null)
|
||||
return false;
|
||||
if (!_lastSubcategoryStates.TryGetValue("AccountSetupCategory.Status", out var subs) || subs == null)
|
||||
return false;
|
||||
foreach (var state in subs.Values)
|
||||
{
|
||||
if (!string.Equals(state, "notStarted", StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when DeviceSetup registry JSON contains a SaveWhiteGloveSuccessResult property
|
||||
/// with subcategoryState=succeeded. NOT a WhiteGlove indicator: on Win11 25H2 (build
|
||||
|
||||
+18
-28
@@ -9,6 +9,7 @@ using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Orchestration;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Services;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
@@ -303,7 +304,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
if (TryNormalizeHResult(errorCode, out var hresultValue, out hresultHex))
|
||||
{
|
||||
data["hresult"] = hresultHex;
|
||||
data["hresultSymbol"] = DecodeHResult(hresultValue);
|
||||
data["hresultSymbol"] = ResolveHResultSymbol(hresultValue);
|
||||
}
|
||||
|
||||
var title = string.IsNullOrEmpty(updateTitle) ? "(unknown update)" : updateTitle;
|
||||
@@ -462,36 +463,25 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps common Windows Update HRESULTs to their symbolic name. Not exhaustive — the full
|
||||
/// catalog lives at
|
||||
/// https://learn.microsoft.com/windows/deployment/update/windows-update-error-reference.
|
||||
/// Unknown codes return "WU_E_UNKNOWN" so the raw <c>hresult</c> hex still carries the value.
|
||||
/// Symbolic name of a WU HRESULT from the shared error-code catalog (WU, CBS, Win32 and
|
||||
/// COM families). <c>S_OK</c> for zero, <c>WU_E_UNKNOWN</c> when the catalog has no symbol,
|
||||
/// so the raw <c>hresult</c> hex still carries the value. A catalog load failure is
|
||||
/// swallowed the same way: decoding is decoration and must never cost the event.
|
||||
/// </summary>
|
||||
internal static string DecodeHResult(uint hresult)
|
||||
internal static string ResolveHResultSymbol(uint hresult)
|
||||
=> ResolveHResultSymbol(hresult, code => ErrorCodeCatalog.TryLookup(code));
|
||||
|
||||
internal static string ResolveHResultSymbol(uint hresult, Func<string, ErrorCodeEntry> lookup)
|
||||
{
|
||||
switch (hresult)
|
||||
if (hresult == 0) return "S_OK";
|
||||
try
|
||||
{
|
||||
case 0x00000000: return "S_OK";
|
||||
// WU agent codes (0x8024xxxx)
|
||||
case 0x80240022: return "WU_E_ALL_UPDATES_FAILED";
|
||||
case 0x8024200B: return "WU_E_UH_INSTALLERFAILURE";
|
||||
case 0x80240020: return "WU_E_NO_INTERACTIVE_USER";
|
||||
case 0x80240016: return "WU_E_INSTALL_NOT_ALLOWED";
|
||||
case 0x8024000B: return "WU_E_CALL_CANCELLED";
|
||||
case 0x8024000C: return "WU_E_NOOP";
|
||||
case 0x80240FFF: return "WU_E_UNEXPECTED";
|
||||
case 0x80248007: return "WU_E_DS_NODATA";
|
||||
case 0x8024402C: return "WU_E_PT_WINHTTP_NAME_NOT_RESOLVED";
|
||||
// Generic Win32 / HRESULT
|
||||
case 0x80070005: return "E_ACCESSDENIED";
|
||||
case 0x80070002: return "ERROR_FILE_NOT_FOUND";
|
||||
case 0x80070003: return "ERROR_PATH_NOT_FOUND";
|
||||
case 0x800705B4: return "ERROR_TIMEOUT";
|
||||
// CBS / servicing (LCU install failures)
|
||||
case 0x800F0831: return "CBS_E_STORE_CORRUPTION";
|
||||
case 0x800F0922: return "CBS_E_INSTALLERS_FAILED";
|
||||
case 0x800F0991: return "PSFX_E_MISSING_PAYLOAD_FILE";
|
||||
default: return "WU_E_UNKNOWN";
|
||||
var symbol = lookup("0x" + hresult.ToString("x8", CultureInfo.InvariantCulture))?.Symbol;
|
||||
return string.IsNullOrEmpty(symbol) ? "WU_E_UNKNOWN" : symbol;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "WU_E_UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+88
-1
@@ -65,6 +65,44 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
|
||||
public static DiagnosticsUploadResult SkippedBy(string gate) =>
|
||||
new DiagnosticsUploadResult { Skipped = true, ErrorCode = gate };
|
||||
|
||||
/// <summary>
|
||||
/// Counters of the archive build that produced (or preceded) this result; null when no
|
||||
/// package was built (configuration gate, build exception). Surfaced into the
|
||||
/// <c>diagnostics_uploaded</c> / <c>diagnostics_upload_failed</c> events so a truncated or
|
||||
/// partially failed package is visible without opening the ZIP.
|
||||
/// </summary>
|
||||
public DiagnosticsPackagingStats Packaging { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the packager included, skipped and failed on — as bounded counters only. File paths
|
||||
/// stay inside the ZIP (<c>package-manifest.txt</c>, <c>_TRUNCATED.txt</c>): they can carry
|
||||
/// user names, and a skip list has no upper bound while this payload must stay small no
|
||||
/// matter how many files a cap rejected.
|
||||
/// </summary>
|
||||
public sealed class DiagnosticsPackagingStats
|
||||
{
|
||||
private static readonly IReadOnlyDictionary<string, int> Empty = new Dictionary<string, int>();
|
||||
|
||||
public int IncludedFiles { get; set; }
|
||||
public long IncludedBytes { get; set; }
|
||||
|
||||
/// <summary>Files rejected by a cap or a reparse-point check (the <c>_TRUNCATED.txt</c> list).</summary>
|
||||
public int SkippedFiles { get; set; }
|
||||
|
||||
/// <summary>True when at least one file was skipped — the same condition that writes <c>_TRUNCATED.txt</c>.</summary>
|
||||
public bool Truncated => SkippedFiles > 0;
|
||||
|
||||
/// <summary>Skip count per reason: <c>size</c>, <c>count</c>, <c>total</c>, <c>reparse</c>, <c>resolved-outside-folder</c>.</summary>
|
||||
public IReadOnlyDictionary<string, int> SkippedByReason { get; set; } = Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Packaging problems that are not cap skips, per kind: <c>path-guard</c> (configured path
|
||||
/// refused), <c>no-user-session</c> (user-profile token without a signed-in user),
|
||||
/// <c>folder-rejected</c>, <c>enumerate</c>, <c>open</c>, <c>copy</c>.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, int> ProblemsByKind { get; set; } = Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -134,6 +172,41 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
Skipped.Add(new SkipRecord(path, reason, size));
|
||||
|
||||
public bool HasSkips => Skipped.Count > 0;
|
||||
|
||||
// Non-cap problems (guard refusals, enumeration/open/copy failures) by kind — the
|
||||
// manifest names the files, the event carries only these counts.
|
||||
public Dictionary<string, int> Problems { get; } = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
private readonly HashSet<string> _problemKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Counts one problem of <paramref name="kind"/>. A section is walked once per search
|
||||
/// pattern, so a folder-level failure would otherwise be counted once per pattern —
|
||||
/// pass the folder as <paramref name="dedupeKey"/> to count it once.
|
||||
/// </summary>
|
||||
public void RecordProblem(string kind, string dedupeKey = null)
|
||||
{
|
||||
if (dedupeKey != null && !_problemKeys.Add(kind + "|" + dedupeKey)) return;
|
||||
Problems.TryGetValue(kind, out var n);
|
||||
Problems[kind] = n + 1;
|
||||
}
|
||||
|
||||
public DiagnosticsPackagingStats ToStats()
|
||||
{
|
||||
var byReason = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
foreach (var s in Skipped)
|
||||
{
|
||||
byReason.TryGetValue(s.Reason, out var n);
|
||||
byReason[s.Reason] = n + 1;
|
||||
}
|
||||
return new DiagnosticsPackagingStats
|
||||
{
|
||||
IncludedFiles = FileCount,
|
||||
IncludedBytes = TotalBytes,
|
||||
SkippedFiles = Skipped.Count,
|
||||
SkippedByReason = byReason,
|
||||
ProblemsByKind = new Dictionary<string, int>(Problems, StringComparer.Ordinal),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private readonly struct SkipRecord
|
||||
@@ -262,6 +335,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
var zipFileName = $"AgentDiagnostics-{_configuration.SessionId}-{timestamp}{suffix}.zip";
|
||||
|
||||
var zipBytes = BuildArchiveBytes(enrollmentSucceeded);
|
||||
var packaging = LastPackaging;
|
||||
|
||||
_logger.Info($"Diagnostics package created: {zipFileName} ({zipBytes.Length / 1024} KB)");
|
||||
|
||||
@@ -276,7 +350,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
var errorCode = uploadUrlResponse?.Message ?? "Failed to get diagnostics upload URL from backend";
|
||||
_logger.Warning($"Failed to get diagnostics upload URL from backend — skipping upload: {errorCode}");
|
||||
return new DiagnosticsUploadResult { ErrorCode = errorCode };
|
||||
return new DiagnosticsUploadResult { ErrorCode = errorCode, Packaging = packaging };
|
||||
}
|
||||
|
||||
var sasUrlPrefix = BuildSasUrlPrefix(uploadUrlResponse.UploadUrl);
|
||||
@@ -305,6 +379,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
BlobName = persistedBlobName,
|
||||
Destination = uploadUrlResponse.Destination,
|
||||
SasUrlPrefix = sasUrlPrefix,
|
||||
Packaging = packaging,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -313,6 +388,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
Destination = uploadUrlResponse.Destination,
|
||||
SasUrlPrefix = sasUrlPrefix,
|
||||
ErrorCode = uploadErrorCode,
|
||||
Packaging = packaging,
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -351,6 +427,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
// INSIDE the ZIP (field case: sessions a11102f4 / 3ae7528b, missing evtx undiagnosable).
|
||||
private StringBuilder _manifest;
|
||||
|
||||
/// <summary>Counters of the most recent <see cref="BuildArchiveBytes"/>; null before the first build.</summary>
|
||||
internal DiagnosticsPackagingStats LastPackaging { get; private set; }
|
||||
|
||||
private void ManifestLine(string text)
|
||||
{
|
||||
_manifest?.AppendLine($"[{DateTime.UtcNow:HH:mm:ss.fff}Z] {text}");
|
||||
@@ -391,6 +470,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Diagnostics path blocked by guard: {entry.Path}");
|
||||
ManifestLine($"BLOCKED (path guard): {entry.Path}");
|
||||
tracker.RecordProblem("path-guard");
|
||||
continue;
|
||||
}
|
||||
var expandedPath = UserProfileResolver.ExpandCustomTokens(entry.Path);
|
||||
@@ -398,6 +478,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Diagnostics path skipped (no user session for token): {entry.Path}");
|
||||
ManifestLine($"SKIPPED (no user session for token): {entry.Path}");
|
||||
tracker.RecordProblem("no-user-session");
|
||||
continue;
|
||||
}
|
||||
var folder = Path.GetDirectoryName(expandedPath);
|
||||
@@ -427,6 +508,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
WriteTruncatedMarker(archive, tracker);
|
||||
}
|
||||
|
||||
LastPackaging = tracker.ToStats();
|
||||
return ms.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -498,6 +580,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Built-in diagnostics section skipped (no user session for token): {section.Id}");
|
||||
ManifestLine($"BUILT-IN SKIPPED (no user session for token): {section.Id} '{section.SourceFolder}'");
|
||||
tracker.RecordProblem("no-user-session");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -584,6 +667,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Diagnostics source folder rejected ({folderRejection}): {sourceFolder}");
|
||||
ManifestLine($"FOLDER REJECTED ({folderRejection}): {sourceFolder} (pattern '{searchPattern}')");
|
||||
tracker.RecordProblem("folder-rejected", sourceFolder);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -597,6 +681,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Failed to enumerate log files in {sourceFolder}: {ex.Message}");
|
||||
ManifestLine($"ENUMERATION FAILED: {sourceFolder} (pattern '{searchPattern}'): {ex.Message}");
|
||||
tracker.RecordProblem("enumerate", sourceFolder);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -681,6 +766,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Failed to add log file to diagnostics package: {file} - {ex.Message}");
|
||||
ManifestLine($"FAILED (copy): {file}: {ex.Message}");
|
||||
tracker.RecordProblem("copy");
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -720,6 +806,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
default:
|
||||
_logger.Warning($"Failed to open {file}: {rejection}");
|
||||
ManifestLine($"FAILED (open): {file}: {rejection}");
|
||||
tracker.RecordProblem("open");
|
||||
break;
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -11,6 +11,7 @@ using AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Office;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Transport;
|
||||
using AutopilotMonitor.Agent.V2.Core.Security;
|
||||
using AutopilotMonitor.Agent.V2.Core.SignalAdapters;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
@@ -312,6 +313,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
// later before the detector can fire). When the real-user desktop arrives, Shift+F10 is no
|
||||
// longer possible, so the console watcher is stopped to avoid post-enrollment false positives.
|
||||
ConsoleBypassHost? consoleBypassHost = null;
|
||||
// Captured likewise (assigned right after this host). The real-user desktop is the
|
||||
// sign-in evidence for the Hybrid detectors: it cancels hybrid_login_pending and arms
|
||||
// the Entra user-affinity timer (2026-09-04, session a7140f98).
|
||||
AadJoinHost? aadJoinHostRef = null;
|
||||
var desktopArrivalHost = new DesktopArrivalHost(
|
||||
logger,
|
||||
ingress,
|
||||
@@ -326,6 +331,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
// Shift+F10 works — stop the console watcher (no-op if not created / already stopped).
|
||||
consoleBypassHost?.StopForDesktopArrival();
|
||||
|
||||
aadJoinHostRef?.NotifyRealUserDesktop();
|
||||
|
||||
if (realmJoinHost == null) return;
|
||||
if (UserSidResolver.TryResolveSid(owner, out var sid) && !string.IsNullOrEmpty(sid))
|
||||
{
|
||||
@@ -340,8 +347,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
|
||||
var aadJoinHost = new AadJoinHost(
|
||||
logger, ingress, clock,
|
||||
onRealUserJoined: desktopArrivalHost.RequestResetForRealUserSwitch);
|
||||
onRealUserJoined: desktopArrivalHost.RequestResetForRealUserSwitch,
|
||||
isHybridJoinProbe: EnrollmentRegistryDetector.DetectHybridJoin);
|
||||
hosts.Add(aadJoinHost);
|
||||
aadJoinHostRef = aadJoinHost;
|
||||
|
||||
// RealmJoin support is opt-in per tenant (portal toggle → AnalyzerConfiguration.
|
||||
// EnableRealmJoinWatcher, default off). When disabled, leave realmJoinHost null:
|
||||
@@ -372,7 +381,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
tenantId: tenantId,
|
||||
ingress: ingress,
|
||||
clock: clock,
|
||||
logger: logger));
|
||||
logger: logger,
|
||||
// q8n: release on the user-ESP page exit, i.e. a Shell-Core 62407 that arrives
|
||||
// after the AccountSetup registry left notStarted — never on the handoff exit.
|
||||
accountSetupProgressProbe: () => espAndHelloHost.HasAccountSetupProgress));
|
||||
}
|
||||
|
||||
// OOBE-console / Shift+F10 detection — opt-OUT per tenant (portal toggle →
|
||||
@@ -436,6 +448,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
hosts.Add(imeLogHost);
|
||||
imeLogHostRef = imeLogHost;
|
||||
|
||||
// Entra user affinity (2026-09-04): the raw IME token lines feed the AadJoinHost's
|
||||
// affinity detector. New callbacks — nothing chained before us, so direct assignment.
|
||||
imeLogHost.Tracker.OnUserTokenAcquired = lineUtc => aadJoinHost.NotifyUserTokenAcquired(lineUtc);
|
||||
imeLogHost.Tracker.OnTokenFailureLine = (code, lineUtc) => aadJoinHost.NotifyTokenFailureLine(code, lineUtc);
|
||||
|
||||
// sits-d Cloud-PC fix (2026-08-19): the user-apps-settled AccountSetup synthesis used
|
||||
// to run ONLY on the EspExited edge. On a tenant with a large required-app set the ESP
|
||||
// page exits while apps are still in flight, the single attempt misses, and nothing
|
||||
|
||||
@@ -258,6 +258,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
/// </summary>
|
||||
public bool IsWhiteGlovePart2 => _isWhiteGlovePart2;
|
||||
|
||||
/// <summary>
|
||||
/// <c>true</c> when this device ever resumed a WhiteGlove Part 2 in this session — the
|
||||
/// state folder holds a <c>.part1-<ts>/</c> archive. Unlike
|
||||
/// <see cref="IsWhiteGlovePart2"/> (this start only) it survives later reboots within
|
||||
/// Part 2; see <see cref="StateArchiver.HasPart1Archive"/>.
|
||||
/// </summary>
|
||||
public bool HasWhiteGlovePart1Archive => StateArchiver.HasPart1Archive(_stateDirectory);
|
||||
|
||||
/// <summary>
|
||||
/// <c>true</c> wenn der Start auf einen korrupten State-Segment traf und
|
||||
/// Snapshot + Log-Segmente nach <c>.quarantine/{ts}/</c> bewegt wurden.
|
||||
|
||||
@@ -8,6 +8,13 @@ using AutopilotMonitor.DecisionCore.Engine;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
{
|
||||
/// <summary>
|
||||
/// Hybrid-identity host: the JoinInfo watcher plus the two single-shot detectors that
|
||||
/// describe the user side of a Hybrid Azure AD Join — sign-in overdue
|
||||
/// (<see cref="HybridLoginPendingDetector"/>) and Entra user affinity after the sign-in
|
||||
/// (<see cref="EntraUserAffinityDetector"/>). The composition root feeds it the
|
||||
/// DesktopArrivalDetector's real-user observation and the ImeLogTracker's raw token lines.
|
||||
/// </summary>
|
||||
internal sealed class AadJoinHost : ICollectorHost
|
||||
{
|
||||
public string Name => "AadJoinWatcher";
|
||||
@@ -15,41 +22,87 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
private readonly AadJoinWatcher _watcher;
|
||||
private readonly AadJoinWatcherAdapter _adapter;
|
||||
private readonly HybridLoginPendingDetector _hybridLoginPendingDetector;
|
||||
private readonly EntraUserAffinityDetector _userAffinityDetector;
|
||||
private int _disposed;
|
||||
|
||||
public AadJoinHost(
|
||||
AgentLogger logger,
|
||||
ISignalIngressSink ingress,
|
||||
IClock clock,
|
||||
Action? onRealUserJoined = null)
|
||||
Action? onRealUserJoined = null,
|
||||
Func<bool>? isHybridJoinProbe = null)
|
||||
{
|
||||
_watcher = new AadJoinWatcher(logger);
|
||||
_adapter = new AadJoinWatcherAdapter(_watcher, ingress, clock, onRealUserJoined: onRealUserJoined);
|
||||
var post = new InformationalEventPost(ingress, clock);
|
||||
_hybridLoginPendingDetector = new HybridLoginPendingDetector(
|
||||
watcher: _watcher,
|
||||
post: new InformationalEventPost(ingress, clock),
|
||||
post: post,
|
||||
logger: logger);
|
||||
_userAffinityDetector = new EntraUserAffinityDetector(
|
||||
post: post,
|
||||
logger: logger,
|
||||
isHybridJoinProbe: isHybridJoinProbe ?? (() => false),
|
||||
placeholderActiveProbe: () => _watcher.PlaceholderObservedWithoutRealUser,
|
||||
utcNow: () => clock.UtcNow);
|
||||
}
|
||||
|
||||
public void Start() => _watcher.Start();
|
||||
public void Stop() => _watcher.Stop();
|
||||
|
||||
/// <summary>
|
||||
/// Composition-root entry point for the Hybrid User-Driven completion-gap fix
|
||||
/// (2026-05-01). Only call when both prerequisites hold: a) the prior agent process
|
||||
/// was killed by an OS reboot (<c>previousExitType=reboot_kill</c>), b) the
|
||||
/// Autopilot profile is Hybrid AAD Join (<c>isHybridJoin=true</c>). The detector
|
||||
/// itself enforces single-shot semantics + cancel-on-real-user — repeated calls or
|
||||
/// late calls after a real user joined are safe no-ops.
|
||||
/// Composition-root entry point for the Hybrid User-Driven sign-in-overdue warning
|
||||
/// (2026-05-01, semantics 2026-09-04). Only call when all prerequisites hold: a) the
|
||||
/// prior agent process was killed by an OS reboot (<c>previousExitType=reboot_kill</c>),
|
||||
/// b) the Autopilot profile is Hybrid AAD Join (<c>isHybridJoin=true</c>), c) the device
|
||||
/// is not a WhiteGlove device (neither resuming Part 2 nor carrying a Part-1 archive).
|
||||
/// The detector itself enforces single-shot semantics and both cancel paths —
|
||||
/// repeated calls or late calls after a desktop / real user are safe no-ops.
|
||||
/// </summary>
|
||||
public void ArmHybridLoginPendingDetector() => _hybridLoginPendingDetector.Arm();
|
||||
|
||||
// Test seam — exposes the detector for unit tests in the V2.Core.Tests project.
|
||||
/// <summary>
|
||||
/// The DesktopArrivalDetector resolved explorer.exe under a real user: cancels the
|
||||
/// sign-in-overdue timer and arms the user-affinity timer (Hybrid devices only).
|
||||
/// </summary>
|
||||
public void NotifyRealUserDesktop()
|
||||
{
|
||||
try { _hybridLoginPendingDetector.NotifyRealUserDesktop(); }
|
||||
catch (Exception ex) { LogCallbackFailure("HybridLoginPendingDetector.NotifyRealUserDesktop", ex); }
|
||||
try { _userAffinityDetector.NotifyRealUserDesktop(); }
|
||||
catch (Exception ex) { LogCallbackFailure("EntraUserAffinityDetector.NotifyRealUserDesktop", ex); }
|
||||
}
|
||||
|
||||
/// <summary>ImeLogTracker observed an IME-TOKEN-SUCCESS line (raw, every line).</summary>
|
||||
public void NotifyUserTokenAcquired(DateTime? lineUtc)
|
||||
{
|
||||
try { _userAffinityDetector.NotifyUserTokenAcquired(lineUtc); }
|
||||
catch (Exception ex) { LogCallbackFailure("EntraUserAffinityDetector.NotifyUserTokenAcquired", ex); }
|
||||
}
|
||||
|
||||
/// <summary>ImeLogTracker observed an IME-TOKEN-FAILURE line (raw, every line).</summary>
|
||||
public void NotifyTokenFailureLine(string? errorCode, DateTime? lineUtc)
|
||||
{
|
||||
try { _userAffinityDetector.NotifyTokenFailureLine(errorCode, lineUtc); }
|
||||
catch (Exception ex) { LogCallbackFailure("EntraUserAffinityDetector.NotifyTokenFailureLine", ex); }
|
||||
}
|
||||
|
||||
// Test seams — expose the detectors for unit tests in the V2.Core.Tests project.
|
||||
internal HybridLoginPendingDetector HybridLoginPendingDetectorForTest => _hybridLoginPendingDetector;
|
||||
internal EntraUserAffinityDetector UserAffinityDetectorForTest => _userAffinityDetector;
|
||||
|
||||
private static void LogCallbackFailure(string what, Exception ex)
|
||||
{
|
||||
// Host callbacks are best-effort — a detector fault must never break the caller
|
||||
// (DesktopArrivalDetector poll / ImeLogTracker drain). Swallowed on purpose; the
|
||||
// detectors log their own state transitions.
|
||||
_ = what; _ = ex;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
|
||||
try { _userAffinityDetector.Dispose(); } catch { }
|
||||
try { _hybridLoginPendingDetector.Dispose(); } catch { }
|
||||
try { _adapter.Dispose(); } catch { }
|
||||
try { _watcher.Dispose(); } catch { }
|
||||
|
||||
@@ -55,6 +55,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
/// </summary>
|
||||
public System.Collections.Generic.IReadOnlyCollection<string> StarvedAppsReported => _tracker.StarvedAppsReported;
|
||||
|
||||
/// <summary>
|
||||
/// True once an AccountSetup subcategory has left <c>notStarted</c> — the probe the
|
||||
/// User-ESP keep-awake host uses to tell the real user-ESP page exit from the
|
||||
/// Device→Account handoff exit (see <see cref="EspAndHelloTracker.HasAccountSetupProgress"/>).
|
||||
/// </summary>
|
||||
public bool HasAccountSetupProgress => _tracker.HasAccountSetupProgress;
|
||||
|
||||
/// <summary>L6 — atomic claim for the termination sweep (see EspAndHelloTracker.TryClaimStarvedAppReport).</summary>
|
||||
public bool TryClaimStarvedAppReport(string appId) => _tracker.TryClaimStarvedAppReport(appId);
|
||||
|
||||
|
||||
+51
-9
@@ -22,15 +22,31 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
/// hook <c>GatherRuleExecutorHost</c> uses for phase_change triggers):
|
||||
/// <list type="bullet">
|
||||
/// <item><b>Engage</b> when a signal reports the ESP phase as <c>AccountSetup</c>.</item>
|
||||
/// <item><b>Release</b> on <see cref="DecisionSignalKind.AccountSetupProvisioningComplete"/>
|
||||
/// (User-ESP done), on <see cref="Stop"/> (session teardown), or on the safety-cap timer
|
||||
/// (a backstop in case the completion signal is missed, so a device is never held awake
|
||||
/// for the agent's full max-lifetime).</item>
|
||||
/// <item><b>Release</b> on <see cref="DecisionSignalKind.EspExiting"/> once the AccountSetup
|
||||
/// registry shows progress (the real user-ESP page exit — see below), on
|
||||
/// <see cref="Stop"/> (session teardown), or on the safety-cap timer (a backstop so a
|
||||
/// device is never held awake for the agent's full max-lifetime).</item>
|
||||
/// </list>
|
||||
/// The hold itself is owned by <see cref="KeepAwakeController"/>; the OS also auto-clears it
|
||||
/// on process exit / reboot, so it can never leak.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Why the ESP exit and not <see cref="DecisionSignalKind.AccountSetupProvisioningComplete"/></b>
|
||||
/// (backlog q8n, 2026-09-04): that completion signal is, fleet-wide, almost always the
|
||||
/// user-apps-settled synthesis (Windows no longer writes <c>categorySucceeded</c>), and the
|
||||
/// synthesis builds on the Device→Account handoff 62407 — so it fired a median 3 min before
|
||||
/// the user-ESP page actually closed in 77 % of keep-awake sessions, and a device on battery
|
||||
/// dropped into Modern Standby with the page still up (session a2256107). The page itself is
|
||||
/// the truth: a Shell-Core 62407 that arrives after the AccountSetup registry left
|
||||
/// <c>notStarted</c> is the user-ESP page exit (progress precedes it by ≥ 1 min across the
|
||||
/// fleet), whereas the handoff exit always precedes any progress. Desktop arrival is NOT a
|
||||
/// substitute — explorer.exe already runs under the real user while the page is still up.
|
||||
/// Sessions that only ever see the handoff exit (about one in five) keep the hold until the
|
||||
/// safety cap; that is the advertised behaviour ("awake during User-ESP") erring long, never
|
||||
/// early. The completion guards in <c>EspAndHelloTracker</c> deliberately stay on presence
|
||||
/// semantics — see <c>ProvisioningStatusTracker.HasAccountSetupActivity</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Safety-cap sizing</b>: rather than a fixed product assumption, the cap is derived at
|
||||
/// engage time from the tenant's own ESP policy — the Intune
|
||||
/// <c>SyncFailureTimeout</c> ("show error when installation takes longer than X minutes",
|
||||
@@ -62,8 +78,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
/// </summary>
|
||||
internal const int EspCapMarginMinutes = 30;
|
||||
|
||||
// Release reasons (carried on the keep_awake_released event payload).
|
||||
internal const string ReasonAccountSetupComplete = "account_setup_complete";
|
||||
// Release reasons (carried on the keep_awake_released event payload). "account_setup_complete"
|
||||
// (release on the synthesized completion signal) was retired with q8n — see the class doc.
|
||||
internal const string ReasonUserEspExited = "user_esp_exited";
|
||||
internal const string ReasonHostStop = "host_stop";
|
||||
internal const string ReasonSafetyCap = "safety_cap";
|
||||
|
||||
@@ -83,6 +100,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
private readonly int _fallbackCapMinutes;
|
||||
private readonly TimeSpan? _safetyCapOverride;
|
||||
private readonly Func<int?> _espTimeoutProvider;
|
||||
private readonly Func<bool> _accountSetupProgressProbe;
|
||||
|
||||
private enum HoldState { Idle, Engaging, Engaged, Released }
|
||||
|
||||
@@ -102,7 +120,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
int fallbackCapMinutes = DefaultFallbackCapMinutes,
|
||||
KeepAwakeController? controller = null,
|
||||
TimeSpan? safetyCapOverride = null,
|
||||
Func<int?>? espTimeoutProvider = null)
|
||||
Func<int?>? espTimeoutProvider = null,
|
||||
Func<bool>? accountSetupProgressProbe = null)
|
||||
{
|
||||
if (ingress == null) throw new ArgumentNullException(nameof(ingress));
|
||||
if (clock == null) throw new ArgumentNullException(nameof(clock));
|
||||
@@ -118,6 +137,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
// The ESP SyncFailureTimeout is read at engage time (the ESP policy is present by then).
|
||||
_espTimeoutProvider = espTimeoutProvider
|
||||
?? (() => EspSkipConfigurationProbe.ReadFull(_logger).SyncFailureTimeoutMinutes);
|
||||
// Without a probe no exit can be told apart from the handoff exit — the hold then
|
||||
// lasts until the safety cap (erring long, never early). Production always wires the
|
||||
// EspAndHelloHost probe (DefaultComponentFactory).
|
||||
_accountSetupProgressProbe = accountSetupProgressProbe ?? (() => false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -163,9 +186,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
// (which briefly waits on the keep-awake thread) is dispatched to the ThreadPool.
|
||||
try
|
||||
{
|
||||
if (kind == DecisionSignalKind.AccountSetupProvisioningComplete)
|
||||
if (kind == DecisionSignalKind.EspExiting)
|
||||
{
|
||||
ThreadPool.QueueUserWorkItem(_ => SafeRelease(ReasonAccountSetupComplete, EventSeverity.Info));
|
||||
// Only the user-ESP page exit releases: the Device→Account handoff 62407 arrives
|
||||
// before any AccountSetup subcategory has left notStarted, the real exit after.
|
||||
// Cheap to skip while idle; the probe is a locked dictionary scan.
|
||||
if (IsEngagedOrEngaging() && ProbeAccountSetupProgress())
|
||||
ThreadPool.QueueUserWorkItem(_ => SafeRelease(ReasonUserEspExited, EventSeverity.Info));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -188,6 +215,21 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
catch (Exception ex) { _logger.Error("UserEspKeepAwakeHost: engage failed.", ex); }
|
||||
}
|
||||
|
||||
private bool IsEngagedOrEngaging()
|
||||
{
|
||||
lock (_gate) { return _state == HoldState.Engaging || _state == HoldState.Engaged; }
|
||||
}
|
||||
|
||||
private bool ProbeAccountSetupProgress()
|
||||
{
|
||||
try { return _accountSetupProgressProbe(); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Debug($"UserEspKeepAwakeHost: AccountSetup progress probe threw: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void SafeRelease(string reason, EventSeverity severity)
|
||||
{
|
||||
try { Release(reason, severity, emit: true); }
|
||||
|
||||
@@ -37,6 +37,29 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
/// </summary>
|
||||
public static class StateArchiver
|
||||
{
|
||||
internal const string Part1BucketPrefix = ".part1-";
|
||||
|
||||
/// <summary>
|
||||
/// <c>true</c> when <paramref name="stateDirectory"/> holds at least one archived
|
||||
/// <c>.part1-<ts>/</c> bucket — i.e. this device already went through a WhiteGlove
|
||||
/// Part-1/Part-2 resume in this session. Durable across later reboots, unlike the
|
||||
/// <c>whiteglove.complete</c> marker (cleared on resume) and the orchestrator's
|
||||
/// in-memory Part-2 flag. Used to keep sign-in-overdue warnings off pre-provisioned
|
||||
/// devices that legitimately wait days for their user (2026-09-04).
|
||||
/// </summary>
|
||||
public static bool HasPart1Archive(string stateDirectory)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(stateDirectory) || !Directory.Exists(stateDirectory)) return false;
|
||||
return Directory.GetDirectories(stateDirectory, Part1BucketPrefix + "*").Length > 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reducer-state segment files moved into the <c>.part1-<ts>/</c> bucket on
|
||||
/// archive. <c>event-sequence.json</c> is intentionally NOT in this list — see the
|
||||
@@ -86,7 +109,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
if (!hasAny) return null;
|
||||
|
||||
var stamp = utcNow().ToString("yyyyMMdd'T'HHmmssfff'Z'");
|
||||
var bucket = Path.Combine(stateDirectory, ".part1-" + stamp);
|
||||
var bucket = Path.Combine(stateDirectory, Part1BucketPrefix + stamp);
|
||||
Directory.CreateDirectory(bucket);
|
||||
|
||||
foreach (var name in KnownSegmentFiles)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Security
|
||||
{
|
||||
/// <summary>
|
||||
/// The install-time deployment marker: <c>HKLM\SOFTWARE\AutopilotMonitor\Deployed</c>, an
|
||||
/// ISO-8601 UTC instant written by <c>--install</c> right after the runtime was handed off
|
||||
/// (writer: <c>Program.InstallMode</c> in the runtime project). It is the bootstrap script's
|
||||
/// re-entry lock and — since 2026-09-04 — the one instant the agent knows in UTC that also
|
||||
/// appears in the IME logs: the Intune Management Extension logs the bootstrap script's
|
||||
/// result a few hundred milliseconds later, which anchors the timezone of the pre-agent log
|
||||
/// era (<c>ImeLogEraPreScan</c>). Read-only here; never written from Core.
|
||||
/// </summary>
|
||||
public static class DeploymentMarker
|
||||
{
|
||||
public const string RegistryKeyPath = @"SOFTWARE\AutopilotMonitor";
|
||||
public const string RegistryValueName = "Deployed";
|
||||
|
||||
/// <summary>The marker's UTC instant, or <c>null</c> when absent or unparseable.</summary>
|
||||
public static DateTime? TryReadDeployedUtc()
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var key = Registry.LocalMachine.OpenSubKey(RegistryKeyPath))
|
||||
{
|
||||
var raw = key?.GetValue(RegistryValueName) as string;
|
||||
return Parse(raw);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Pure parse of the marker text (round-trip "O" format); exposed for tests.</summary>
|
||||
public static DateTime? Parse(string? raw)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(raw)) return null;
|
||||
if (!DateTime.TryParse(raw, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed))
|
||||
return null;
|
||||
return parsed.Kind == DateTimeKind.Utc ? parsed : parsed.ToUniversalTime();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -464,6 +464,11 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
if (offsetMinutes.HasValue)
|
||||
data["sourceOffsetMinutes"] = offsetMinutes.Value.ToString(culture);
|
||||
|
||||
// Which era anchor the offset came from — forensics for the era-anchored origin.
|
||||
var anchorKind = _tracker.LastMatchedEraAnchorKind;
|
||||
if (!string.IsNullOrEmpty(anchorKind))
|
||||
data["sourceOffsetAnchor"] = anchorKind;
|
||||
|
||||
// Observational only — what the calibrator measured, which since the 2026-08-20
|
||||
// revert is deliberately NOT what was applied. Kept separate so the two can never
|
||||
// be read as the same thing.
|
||||
@@ -489,6 +494,9 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
// The line anchored itself: read provably fresh, its own distance to the agent
|
||||
// clock (grid-rounded) was applied as the writer's offset. Era-safe per line.
|
||||
case CmTraceOffsetOrigin.LineAnchored: return "line-anchored";
|
||||
// A backlog line resolved through its writer era, anchored by the bootstrap
|
||||
// execution record against the install marker (ImeLogEraPreScan, 2026-09-04).
|
||||
case CmTraceOffsetOrigin.EraAnchored: return "era-anchored";
|
||||
// The line was not provably fresh (backlog, restart catch-up, replay), so this
|
||||
// process's own zone was assumed — correct only if the writer happens to share it.
|
||||
default: return "reader-zone-fallback";
|
||||
@@ -1620,6 +1628,15 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
if (app.AttemptNumber > 0) data["attemptNumber"] = app.AttemptNumber.ToString(culture);
|
||||
if (!string.IsNullOrEmpty(app.DetectionResult)) data["detectionResult"] = app.DetectionResult!;
|
||||
|
||||
// Installer outcome of the last attempt (IME-EXITCODE + IME-EXITCODE-CLASS). The class
|
||||
// is the admin's return-code mapping (Success/SoftReboot/HardReboot/Retry/Failed) and
|
||||
// the only evidence that an app asked for a reboot; the number says which code was
|
||||
// mapped (3010 vs 1641 vs custom). Both are known from the terminal lpExitCode lines
|
||||
// only, so they surface on the terminal events - completed, postponed, skipped and
|
||||
// failed alike - never on progress events.
|
||||
if (!string.IsNullOrEmpty(app.ExitCodeClass)) data["exitCodeClass"] = app.ExitCodeClass!;
|
||||
if (IsCompletedState(newState) && !string.IsNullOrEmpty(app.ExitCode)) data["exitCode"] = app.ExitCode!;
|
||||
|
||||
// Plan §5 Fix 4c — per-app install-lifecycle timing. StartedAt appears on the
|
||||
// first Downloading/Installing/InProgress event; CompletedAt + DurationSeconds
|
||||
// light up on the terminal event. Values are omitted when not yet known so the
|
||||
@@ -1636,7 +1653,6 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
if (!string.IsNullOrEmpty(app.ErrorPatternId)) data["errorPatternId"] = app.ErrorPatternId!;
|
||||
if (!string.IsNullOrEmpty(app.ErrorDetail)) data["errorDetail"] = app.ErrorDetail!;
|
||||
if (!string.IsNullOrEmpty(app.ErrorCode)) data["errorCode"] = app.ErrorCode!;
|
||||
if (!string.IsNullOrEmpty(app.ExitCode)) data["exitCode"] = app.ExitCode!;
|
||||
if (!string.IsNullOrEmpty(app.HResultFromWin32)) data["hresultFromWin32"] = app.HResultFromWin32!;
|
||||
|
||||
// Likely-stuck / detection-failure / install-failure classification: when the
|
||||
|
||||
@@ -4,6 +4,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Telemetry.Signals
|
||||
{
|
||||
|
||||
+1
@@ -4,6 +4,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Telemetry.Transitions
|
||||
{
|
||||
|
||||
+42
-17
@@ -1007,6 +1007,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
if (result != null && result.Success)
|
||||
{
|
||||
_logger.Info($"EnrollmentTerminationHandler: diagnostics uploaded (blob={result.BlobName}).");
|
||||
var data = new Dictionary<string, object>
|
||||
{
|
||||
{ "blobName", result.BlobName ?? string.Empty },
|
||||
// Tells the backend which storage the blob landed in so it can
|
||||
// stamp Session.DiagnosticsBlobDestination and route downloads
|
||||
// even after a future tenant destination switch. Empty when the
|
||||
// backend predates the field (agent falls through harmlessly).
|
||||
{ "destination", result.Destination ?? string.Empty },
|
||||
{ "sasUrlPrefix", result.SasUrlPrefix ?? string.Empty },
|
||||
};
|
||||
AppendPackagingStats(data, result.Packaging);
|
||||
EmitEventSafe(new EnrollmentEvent
|
||||
{
|
||||
SessionId = _configuration.SessionId,
|
||||
@@ -1015,17 +1026,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
Severity = EventSeverity.Info,
|
||||
Source = "EnrollmentTerminationHandler",
|
||||
Phase = EnrollmentPhase.Unknown,
|
||||
Message = $"Diagnostics package uploaded ({result.BlobName}).",
|
||||
Data = new Dictionary<string, object>
|
||||
{
|
||||
{ "blobName", result.BlobName ?? string.Empty },
|
||||
// Tells the backend which storage the blob landed in so it can
|
||||
// stamp Session.DiagnosticsBlobDestination and route downloads
|
||||
// even after a future tenant destination switch. Empty when the
|
||||
// backend predates the field (agent falls through harmlessly).
|
||||
{ "destination", result.Destination ?? string.Empty },
|
||||
{ "sasUrlPrefix", result.SasUrlPrefix ?? string.Empty },
|
||||
},
|
||||
Message = $"Diagnostics package uploaded ({result.BlobName})."
|
||||
+ (result.Packaging != null && result.Packaging.Truncated
|
||||
? $" Truncated: {result.Packaging.SkippedFiles} file(s) skipped by the packaging caps."
|
||||
: string.Empty),
|
||||
Data = data,
|
||||
ImmediateUpload = true,
|
||||
});
|
||||
}
|
||||
@@ -1033,6 +1038,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
{
|
||||
var errorCode = result?.ErrorCode ?? "null-result";
|
||||
_logger.Warning($"EnrollmentTerminationHandler: diagnostics upload failed: {errorCode}.");
|
||||
var data = new Dictionary<string, object>
|
||||
{
|
||||
{ "errorCode", errorCode },
|
||||
{ "blobName", result?.BlobName ?? string.Empty },
|
||||
{ "destination", result?.Destination ?? string.Empty },
|
||||
};
|
||||
AppendPackagingStats(data, result?.Packaging);
|
||||
EmitEventSafe(new EnrollmentEvent
|
||||
{
|
||||
SessionId = _configuration.SessionId,
|
||||
@@ -1042,17 +1054,30 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
Source = "EnrollmentTerminationHandler",
|
||||
Phase = EnrollmentPhase.Unknown,
|
||||
Message = $"Diagnostics upload failed: {errorCode}.",
|
||||
Data = new Dictionary<string, object>
|
||||
{
|
||||
{ "errorCode", errorCode },
|
||||
{ "blobName", result?.BlobName ?? string.Empty },
|
||||
{ "destination", result?.Destination ?? string.Empty },
|
||||
},
|
||||
Data = data,
|
||||
ImmediateUpload = true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the packager's counters to a diagnostics event payload — counts only, never a
|
||||
/// file path (paths live in the ZIP's manifest and may carry user names). Absent when no
|
||||
/// package was built, so consumers treat the keys as optional.
|
||||
/// </summary>
|
||||
private static void AppendPackagingStats(Dictionary<string, object> data, DiagnosticsPackagingStats packaging)
|
||||
{
|
||||
if (packaging == null) return;
|
||||
data["truncated"] = packaging.Truncated;
|
||||
data["includedFiles"] = packaging.IncludedFiles;
|
||||
data["includedBytes"] = packaging.IncludedBytes;
|
||||
data["skippedFiles"] = packaging.SkippedFiles;
|
||||
data["skippedByReason"] = new Dictionary<string, int>(
|
||||
(IDictionary<string, int>)packaging.SkippedByReason ?? new Dictionary<string, int>(), StringComparer.Ordinal);
|
||||
data["problemsByKind"] = new Dictionary<string, int>(
|
||||
(IDictionary<string, int>)packaging.ProblemsByKind ?? new Dictionary<string, int>(), StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
private void WriteEnrollmentCompleteMarker(EnrollmentTerminatedEventArgs args)
|
||||
{
|
||||
// On WhiteGlove Part 1 exit we keep the session alive for Part 2 — DO NOT write the
|
||||
|
||||
+9
-5
@@ -395,12 +395,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
}
|
||||
}
|
||||
|
||||
private static string SerializeBatch(IReadOnlyList<TelemetryItem> items)
|
||||
/// <summary>
|
||||
/// The batch body: a JSON array of <see cref="TelemetryItemDto"/> — the Shared class the
|
||||
/// ingest deserialises — with Newtonsoft defaults (PascalCase, ISO-8601 UTC, Kind by name).
|
||||
/// Internal so <c>TelemetryWireContractTests</c> can freeze the real output as a fixture.
|
||||
/// </summary>
|
||||
internal static string SerializeBatch(IReadOnlyList<TelemetryItem> items)
|
||||
{
|
||||
// Newtonsoft PascalCase default + TelemetryItemKind carries [StringEnumConverter] →
|
||||
// Backend routes by string "Event"/"Signal"/"DecisionTransition". Wire-format
|
||||
// matches Plan §4.x M5 contract (PascalCase, StringEnum, ISO-8601 UTC).
|
||||
return JsonConvert.SerializeObject(items, Formatting.None);
|
||||
var wire = new TelemetryItemDto[items.Count];
|
||||
for (var i = 0; i < items.Count; i++) wire[i] = items[i].ToWire();
|
||||
return JsonConvert.SerializeObject(wire, Formatting.None);
|
||||
}
|
||||
|
||||
private static byte[] CompressWithGzip(string text)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
{
|
||||
@@ -106,6 +107,26 @@ namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
/// <summary>Anzahl der bisher fehlgeschlagenen Upload-Versuche. Wird vom Orchestrator incrementiert.</summary>
|
||||
public int RetryCount { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The wire shape of this item. <see cref="TelemetryItemDto"/> (Shared) is the ONE class both
|
||||
/// ends serialise; this mapping is the only place the agent's validated model meets it.
|
||||
/// <c>TelemetryWireContractTests</c> proves every DTO property is populated here and
|
||||
/// freezes the resulting body under <c>tests/fixtures/telemetry-wire/</c> for the backend.
|
||||
/// </summary>
|
||||
public TelemetryItemDto ToWire() =>
|
||||
new TelemetryItemDto
|
||||
{
|
||||
Kind = Kind.ToString(),
|
||||
PartitionKey = PartitionKey,
|
||||
RowKey = RowKey,
|
||||
TelemetryItemId = TelemetryItemId,
|
||||
SessionTraceOrdinal = SessionTraceOrdinal,
|
||||
PayloadJson = PayloadJson,
|
||||
RequiresImmediateFlush = RequiresImmediateFlush,
|
||||
EnqueuedAtUtc = EnqueuedAtUtc,
|
||||
RetryCount = RetryCount,
|
||||
};
|
||||
|
||||
/// <summary>Copy-with-incremented <see cref="RetryCount"/>. Immutable-Erhalt (§2.3 L.3).</summary>
|
||||
public TelemetryItem WithRetryIncremented() =>
|
||||
new TelemetryItem(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
{
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
#nullable enable
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
{
|
||||
/// <summary>
|
||||
/// Typ eines <see cref="TelemetryItem"/>. Plan §2.7a / L.10.
|
||||
/// <para>
|
||||
/// Drei getrennte Backend-Tabellen:
|
||||
/// <see cref="Event"/> → <c>Events</c>,
|
||||
/// <see cref="Signal"/> → <c>Signals</c>,
|
||||
/// <see cref="DecisionTransition"/> → <c>DecisionTransitions</c>.
|
||||
/// Der generische Transport routet auf Backend-Seite nach <c>Kind</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// String-serialisiert via <see cref="StringEnumConverter"/> — Backend-Routing darf
|
||||
/// nicht von Integer-Ordering abhängen, das bei zukünftigen Erweiterungen bricht
|
||||
/// (L.14 forward-compat).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
[JsonConverter(typeof(StringEnumConverter))]
|
||||
public enum TelemetryItemKind
|
||||
{
|
||||
Event = 0,
|
||||
Signal,
|
||||
DecisionTransition,
|
||||
}
|
||||
}
|
||||
+18
-2
@@ -2,6 +2,7 @@
|
||||
using System;
|
||||
using AutopilotMonitor.DecisionCore.Serialization;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
{
|
||||
@@ -16,10 +17,25 @@ namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
/// </summary>
|
||||
public static class TelemetryItemSerializer
|
||||
{
|
||||
/// <summary>
|
||||
/// DecisionCore settings plus a <see cref="StringEnumConverter"/>: <see cref="TelemetryItem.Kind"/>
|
||||
/// is the only enum on a spool line and has always been written by NAME (<c>"Event"</c>),
|
||||
/// which is also what the wire carries. The enum lives in Shared (no Newtonsoft there), so
|
||||
/// the converter is registered here instead of as an attribute on the type.
|
||||
/// </summary>
|
||||
private static readonly JsonSerializerSettings SpoolSettings = CreateSpoolSettings();
|
||||
|
||||
private static JsonSerializerSettings CreateSpoolSettings()
|
||||
{
|
||||
var settings = DecisionCoreJsonSettings.Create();
|
||||
settings.Converters.Add(new StringEnumConverter());
|
||||
return settings;
|
||||
}
|
||||
|
||||
public static string Serialize(TelemetryItem item)
|
||||
{
|
||||
if (item == null) throw new ArgumentNullException(nameof(item));
|
||||
return JsonConvert.SerializeObject(item, DecisionCoreJsonSettings.Shared);
|
||||
return JsonConvert.SerializeObject(item, SpoolSettings);
|
||||
}
|
||||
|
||||
public static TelemetryItem Deserialize(string line)
|
||||
@@ -28,7 +44,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
|
||||
try
|
||||
{
|
||||
var result = JsonConvert.DeserializeObject<TelemetryItem>(line, DecisionCoreJsonSettings.Shared);
|
||||
var result = JsonConvert.DeserializeObject<TelemetryItem>(line, SpoolSettings);
|
||||
if (result == null)
|
||||
{
|
||||
throw new JsonSerializationException($"TelemetryItem deserialization produced null: {line}");
|
||||
|
||||
@@ -37,8 +37,10 @@ namespace AutopilotMonitor.Agent.V2
|
||||
/// </summary>
|
||||
public static partial class Program
|
||||
{
|
||||
internal const string DeploymentRegistryKey = @"SOFTWARE\AutopilotMonitor";
|
||||
internal const string DeploymentRegistryValue = "Deployed";
|
||||
// Shared with the Core reader (DeploymentMarker) — the marker's UTC instant anchors the
|
||||
// pre-agent IME log era, so writer and reader must agree on key, value and format.
|
||||
internal const string DeploymentRegistryKey = AutopilotMonitor.Agent.V2.Core.Security.DeploymentMarker.RegistryKeyPath;
|
||||
internal const string DeploymentRegistryValue = AutopilotMonitor.Agent.V2.Core.Security.DeploymentMarker.RegistryValueName;
|
||||
internal const string BootstrapConfigFileName = "bootstrap-config.json";
|
||||
internal const string AwaitEnrollmentConfigFileName = "await-enrollment.json";
|
||||
private const string InstalledAgentExeName = "AutopilotMonitor.Agent.exe";
|
||||
|
||||
@@ -494,14 +494,19 @@ namespace AutopilotMonitor.Agent.V2.Runtime
|
||||
{
|
||||
LifecycleEmitters.PostSystemRebootObserved(orchestrator.IngressSink, previousExit, logger);
|
||||
|
||||
// Hybrid User-Driven completion-gap fix (2026-05-01): the reboot is the
|
||||
// expected switch from foouser/autopilot OOBE to the real AD account.
|
||||
// If the user never logs in we go silent until the 5-h backend watchdog;
|
||||
// arm a single-shot 10-min detector that emits hybrid_login_pending
|
||||
// once if the AAD user join is overdue. Cancelled when AadJoinWatcher
|
||||
// sees the real user. Only armed for actual Hybrid devices — non-Hybrid
|
||||
// reboots don't have the placeholder→real-user flow that motivates this.
|
||||
if (!isWhiteGloveResume && EnrollmentRegistryDetector.DetectHybridJoin())
|
||||
// Hybrid User-Driven sign-in gap (2026-05-01, semantics 2026-09-04): after
|
||||
// the Hybrid reboot the user has to sign in with the AD account. If nobody
|
||||
// does, the agent goes silent until the backend watchdog; arm a single-shot
|
||||
// 10-min detector that emits hybrid_login_pending once when no real-user
|
||||
// desktop appeared by then. Cancelled by the DesktopArrivalDetector (the
|
||||
// sign-in evidence) or by the AadJoinWatcher seeing a real user (Entra-join
|
||||
// flavour). Never on WhiteGlove devices: a sealed device legitimately waits
|
||||
// days for its user, and AwaitingUser already describes that — the Part-1
|
||||
// archive check covers reboots inside Part 2 after the resume marker is gone.
|
||||
if (!isWhiteGloveResume
|
||||
&& !orchestrator.IsWhiteGlovePart2
|
||||
&& !orchestrator.HasWhiteGlovePart1Archive
|
||||
&& EnrollmentRegistryDetector.DetectHybridJoin())
|
||||
{
|
||||
try { orchestrator.CollectorSurfaces?.AadJoinHost?.ArmHybridLoginPendingDetector(); }
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -11,9 +11,8 @@ namespace AutopilotMonitor.DecisionCore.Tests.State
|
||||
{
|
||||
/// <summary>
|
||||
/// Every payload-derived string that lands in <see cref="DecisionState"/> is bounded by
|
||||
/// <see cref="FactStringBounds"/> at the reducer boundary. The server-side semantic replay
|
||||
/// (<c>ReducerVerifier</c>) folds device-uploaded payloads through the same engine, so an
|
||||
/// unbounded string there is a per-request memory/CPU amplifier. These tests pin that the
|
||||
/// <see cref="FactStringBounds"/> at the reducer boundary — an unbounded string there is a
|
||||
/// per-signal memory/CPU amplifier in every snapshot persist. These tests pin that the
|
||||
/// bound is applied BEFORE any dedupe comparison (so a forged multi-hundred-KB key neither
|
||||
/// costs a full-length compare nor lands in state) and that real-sized values pass through
|
||||
/// unchanged.
|
||||
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Default-value + round-trip tests for <see cref="AdminConfiguration.EnableIndexDualWrite"/>
|
||||
/// (Plan §M5.d). The flag gates the index-table dual-write rollout — defaulting to false
|
||||
/// keeps pre-M5.d behaviour bit-exact and lets operators flip it on deliberately.
|
||||
/// </summary>
|
||||
public class AdminConfigurationEnableIndexDualWriteTests
|
||||
{
|
||||
[Fact]
|
||||
public void EnableIndexDualWrite_defaults_to_false_on_new_config()
|
||||
{
|
||||
var cfg = new AdminConfiguration();
|
||||
Assert.False(cfg.EnableIndexDualWrite);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnableIndexDualWrite_defaults_to_false_on_CreateDefault()
|
||||
{
|
||||
// CreateDefault() is called when no admin-config row exists yet — if it somehow
|
||||
// enabled dual-write it would break the "default-off" contract immediately.
|
||||
var cfg = AdminConfiguration.CreateDefault();
|
||||
Assert.False(cfg.EnableIndexDualWrite);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnableIndexDualWrite_true_persists_on_the_config()
|
||||
{
|
||||
var cfg = new AdminConfiguration { EnableIndexDualWrite = true };
|
||||
Assert.True(cfg.EnableIndexDualWrite);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -80,7 +80,8 @@ public class AdminIdentityBindingAuthorizationTests
|
||||
{
|
||||
Middleware = new PolicyEnforcementMiddleware(
|
||||
NullLogger<PolicyEnforcementMiddleware>.Instance, globalAdmin, delegatedAdmin,
|
||||
new TenantMemberRoleResolver(tenantAdmins, tenantConfig), tenantConfig),
|
||||
new TenantMemberRoleResolver(tenantAdmins, tenantConfig), tenantConfig,
|
||||
new RecordingDenialReporter()),
|
||||
Repo = repo,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using System.Threading;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
@@ -21,7 +22,7 @@ public class AgentEfficiencyMetricsServiceTests
|
||||
{
|
||||
var repo = new Mock<ISessionRepository>();
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(new List<SessionSummary>(), null));
|
||||
repo
|
||||
.Setup(r => r.GetSessionEventsByTypesAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IReadOnlyCollection<string>>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<int>()))
|
||||
@@ -67,7 +68,7 @@ public class AgentEfficiencyMetricsServiceTests
|
||||
private static void SetupSessions(Mock<ISessionRepository> repo, List<SessionSummary> sessions)
|
||||
{
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(sessions, null));
|
||||
}
|
||||
|
||||
@@ -201,8 +202,8 @@ public class AgentEfficiencyMetricsServiceTests
|
||||
string? capturedTenant = null;
|
||||
IEnumerable<string>? capturedSelect = null;
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?>((t, _, _, _, _, sel) => { capturedTenant = t; capturedSelect = sel; })
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?, CancellationToken>((t, _, _, _, _, sel, _) => { capturedTenant = t; capturedSelect = sel; })
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(new List<SessionSummary>(), null));
|
||||
|
||||
var result = await service.ComputeAsync(days: 45, limit: 100, tenantId: Tenant);
|
||||
@@ -220,7 +221,7 @@ public class AgentEfficiencyMetricsServiceTests
|
||||
var (service, repo) = CreateService();
|
||||
int callCount = 0;
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.Callback(() => callCount++)
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(new List<SessionSummary>(), null));
|
||||
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ namespace AutopilotMonitor.Functions.Tests;
|
||||
/// <summary>
|
||||
/// JSON round-trip tests for <see cref="AnalyzeOnEnrollmentEndEnvelope"/>. The producer
|
||||
/// (<c>AzureQueueAnalyzeOnEnrollmentEndProducer</c>) serializes with Newtonsoft and the
|
||||
/// queue worker (<c>AnalyzeOnEnrollmentEndQueueWorker</c>) deserializes the same shape —
|
||||
/// queue worker (<c>AnalyzeOnEnrollmentEndQueueFunction</c>) deserializes the same shape —
|
||||
/// pinning the contract here keeps the queue from silently breaking when fields are added.
|
||||
/// </summary>
|
||||
public class AnalyzeOnEnrollmentEndEnvelopeSerializationTests
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The middleware-side error-envelope writer: status, content type, Retry-After and the exact body
|
||||
/// (production wire options — camelCase, absent-when-null) for the generic envelope and for a
|
||||
/// specialised <see cref="IApiErrorResponse"/>. Whatever the authentication, policy, rate-limit and
|
||||
/// quota middlewares write flows through here, so this is the one place their body shape is pinned.
|
||||
/// </summary>
|
||||
public class ApiErrorWriterTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Generic_envelope_writes_status_content_type_and_the_three_prefix_keys()
|
||||
{
|
||||
var ctx = NewContext();
|
||||
|
||||
await ApiErrorWriter.WriteAsync(ctx, "cid-42", HttpStatusCode.Unauthorized,
|
||||
Constants.ApiErrorCodes.AuthenticationRequired, "Authentication required.");
|
||||
|
||||
Assert.Equal(401, ctx.Response.StatusCode);
|
||||
Assert.StartsWith("application/json", ctx.Response.ContentType);
|
||||
Assert.False(ctx.Response.Headers.ContainsKey("Retry-After"));
|
||||
Assert.Equal(
|
||||
"{\"error\":\"Authentication required.\",\"code\":\"AuthenticationRequired\",\"correlationId\":\"cid-42\"}",
|
||||
Body(ctx));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Generic_envelope_with_retry_window_sets_the_header_and_mirrors_it_in_the_body()
|
||||
{
|
||||
var ctx = NewContext();
|
||||
|
||||
await ApiErrorWriter.WriteAsync(ctx, "cid-7", HttpStatusCode.TooManyRequests,
|
||||
Constants.ApiErrorCodes.RateLimited, "Rate limit exceeded: 60 requests per minute",
|
||||
retryAfterSeconds: 23);
|
||||
|
||||
Assert.Equal(429, ctx.Response.StatusCode);
|
||||
Assert.Equal("23", ctx.Response.Headers["Retry-After"]);
|
||||
Assert.Equal(
|
||||
"{\"error\":\"Rate limit exceeded: 60 requests per minute\",\"code\":\"RateLimited\",\"correlationId\":\"cid-7\",\"retryAfterSeconds\":23}",
|
||||
Body(ctx));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Generic_envelope_carries_hint_and_operation_only_when_given()
|
||||
{
|
||||
var ctx = NewContext();
|
||||
|
||||
await ApiErrorWriter.WriteAsync(ctx, "cid-9", HttpStatusCode.InternalServerError,
|
||||
Constants.ApiErrorCodes.InternalError, "QueryTable failed.",
|
||||
hint: "Retry with a narrower filter.", operation: "QueryTable");
|
||||
|
||||
Assert.Equal(
|
||||
"{\"error\":\"QueryTable failed.\",\"code\":\"InternalError\",\"correlationId\":\"cid-9\"," +
|
||||
"\"hint\":\"Retry with a narrower filter.\",\"operation\":\"QueryTable\"}",
|
||||
Body(ctx));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Specialised_body_is_stamped_with_the_correlation_id_and_serialized_as_its_runtime_type()
|
||||
{
|
||||
var ctx = NewContext();
|
||||
var body = new DelegatedSlotLimitReachedResponse
|
||||
{
|
||||
Error = "Slot limit reached.",
|
||||
HomeTenantId = "7aa20c11-0002-4b7c-a1d2-52f3aaaa0001",
|
||||
Used = 2,
|
||||
Limit = 2,
|
||||
Required = 1,
|
||||
};
|
||||
|
||||
await ApiErrorWriter.WriteAsync(ctx, "cid-slot", HttpStatusCode.Conflict, body);
|
||||
|
||||
Assert.Equal(409, ctx.Response.StatusCode);
|
||||
Assert.Equal("cid-slot", body.CorrelationId);
|
||||
var json = JsonDocument.Parse(Body(ctx)).RootElement;
|
||||
// Envelope prefix first, then the specialised fields — and nothing of the marker interface.
|
||||
var keys = json.EnumerateObject().Select(p => p.Name).ToArray();
|
||||
Assert.Equal(new[] { "error", "code", "correlationId", "homeTenantId", "used", "limit", "required" }, keys);
|
||||
Assert.Equal("DelegatedSlotLimitReached", json.GetProperty("code").GetString());
|
||||
}
|
||||
|
||||
private static DefaultHttpContext NewContext()
|
||||
{
|
||||
var ctx = new DefaultHttpContext();
|
||||
ctx.Response.Body = new MemoryStream();
|
||||
return ctx;
|
||||
}
|
||||
|
||||
private static string Body(HttpContext ctx)
|
||||
{
|
||||
ctx.Response.Body.Position = 0;
|
||||
using var reader = new StreamReader(ctx.Response.Body);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Text.Json;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
@@ -29,6 +30,33 @@ public class ApiResponseWireParityTests
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
// ---- Error envelope (2026-09, deliberate wire change) ----------------------------------
|
||||
// Non-2xx bodies used to be ~10 anonymous shapes ({ success = false, message }, { error },
|
||||
// { error, message }, { error, code }, …). They are ONE typed envelope now, so these pins fix
|
||||
// the NEW shape exactly rather than proving parity with any single legacy literal.
|
||||
|
||||
[Fact]
|
||||
public void ApiErrorResponse_pins_the_minimal_envelope_shape()
|
||||
{
|
||||
var body = ApiErrorWriter.Build("cid-1", Constants.ApiErrorCodes.NotFound, "Session not found.");
|
||||
|
||||
Assert.Equal(
|
||||
"{\"error\":\"Session not found.\",\"code\":\"NotFound\",\"correlationId\":\"cid-1\"}",
|
||||
JsonSerializer.Serialize(body, WireOptions));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApiErrorResponse_pins_the_full_envelope_shape_and_key_order()
|
||||
{
|
||||
var body = ApiErrorWriter.Build("cid-2", Constants.ApiErrorCodes.ServiceUnavailable,
|
||||
"Authorization service temporarily unavailable.", hint: "Retry.", retryAfterSeconds: 5, operation: "PolicyEnforcement");
|
||||
|
||||
Assert.Equal(
|
||||
"{\"error\":\"Authorization service temporarily unavailable.\",\"code\":\"ServiceUnavailable\"," +
|
||||
"\"correlationId\":\"cid-2\",\"hint\":\"Retry.\",\"retryAfterSeconds\":5,\"operation\":\"PolicyEnforcement\"}",
|
||||
JsonSerializer.Serialize(body, WireOptions));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SuccessMessageResponse_matches_the_canonical_anonymous_shape()
|
||||
{
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Text.Json;
|
||||
using AutopilotMonitor.Functions.Functions.Raw;
|
||||
using AutopilotMonitor.Functions.Middleware;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using Xunit;
|
||||
@@ -6,26 +8,13 @@ namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the <c>POST /api/global/raw/logs</c> KQL-proxy endpoint served by
|
||||
/// <see cref="AutopilotMonitor.Functions.Functions.Raw.AppInsightsQueryFunction"/> — an operator tool
|
||||
/// that forwards an operator-supplied KQL query VERBATIM to the Application Insights REST API. Because
|
||||
/// the query is passed through un-sandboxed and the App Insights workspace can surface secret-bearing
|
||||
/// backend traces, the TRUST BOUNDARY for this endpoint is its authorization gate: only a platform
|
||||
/// Global Admin may call it. These tests pin that gate.
|
||||
///
|
||||
/// SCOPE / WHAT IS AND IS NOT COVERED HERE (deliberate):
|
||||
/// The function's own in-request behavior — appId-not-configured → 503, empty/whitespace query →
|
||||
/// 400 BadRequest, App-Insights-error → 502 BadGateway structured error (innererror message + code +
|
||||
/// SyntaxError/SemanticError hint), happy path → 200 with the raw AI tables JSON — is NOT exercised
|
||||
/// here. The entrypoint <c>Run</c> sits directly on the abstract <c>HttpRequestData</c> /
|
||||
/// <c>HttpResponseData</c> pair (whose <c>HttpResponseData.Cookies</c> returns the abstract
|
||||
/// <c>HttpCookies</c>), reads the body via <c>ReadFromJsonAsync</c> and writes via
|
||||
/// <c>CreateResponse</c>/<c>WriteAsJsonAsync</c> (all of which need a live worker serializer resolved
|
||||
/// from <c>FunctionContext.InstanceServices</c>), and calls Application Insights through a PRIVATE
|
||||
/// STATIC <c>HttpClient</c> + <c>DefaultAzureCredential</c> with no injection seam. Faking that whole
|
||||
/// pipeline + a live Managed Identity is "more setup than the test is worth" — the exact rationale the
|
||||
/// sibling function tests cite (see DeviceBlockFunctionTests / GetAllBlockedDevicesFunctionTests,
|
||||
/// which likewise test the reachable seam instead of the HTTP entrypoint). The authorization gate
|
||||
/// below IS the security-relevant, compilable seam for this endpoint.
|
||||
/// <see cref="AppInsightsQueryFunction"/> — an operator tool that forwards an operator-supplied KQL
|
||||
/// query VERBATIM to one of three telemetry stores (backend / web App Insights, MCP Log Analytics).
|
||||
/// Because the query is passed through un-sandboxed and the stores surface secret-bearing traces and
|
||||
/// portal user telemetry, the TRUST BOUNDARY for this endpoint is its authorization gate: only a
|
||||
/// platform Global Admin may call it. These tests pin that gate, plus the pure pieces of the proxy
|
||||
/// (budget clamp, Kusto body parsing incl. partial results, error extraction). The HTTP entrypoint
|
||||
/// itself (worker serializer, managed identity) is not exercised — the seams are.
|
||||
///
|
||||
/// The gate is asserted through <see cref="EndpointAccessPolicyCatalog.FindPolicy"/> (the single source
|
||||
/// of truth the running middleware consults) and <see cref="AuthenticationMiddleware.SkipsJwtValidation"/>.
|
||||
@@ -34,6 +23,112 @@ public class AppInsightsQueryFunctionTests
|
||||
{
|
||||
private const string LogsRoute = "/api/global/raw/logs";
|
||||
|
||||
// ── Budget: null/0 → default, otherwise clamped into [5, 180] ──
|
||||
[Theory]
|
||||
[InlineData(null, 30)]
|
||||
[InlineData(0, 30)]
|
||||
[InlineData(-7, 30)]
|
||||
[InlineData(1, 5)]
|
||||
[InlineData(30, 30)]
|
||||
[InlineData(120, 120)]
|
||||
[InlineData(180, 180)]
|
||||
[InlineData(600, 180)]
|
||||
public void Budget_is_defaulted_and_clamped(int? requested, int expected)
|
||||
{
|
||||
Assert.Equal(expected, AppInsightsQueryFunction.ClampBudget(requested));
|
||||
}
|
||||
|
||||
// ── Upstream failure → status the caller sees. Query errors are the caller's (400, rendered in full
|
||||
// by the MCP); a missing managed-identity grant (401/403) and store failures (5xx) are 502. ──
|
||||
[Theory]
|
||||
[InlineData(400, System.Net.HttpStatusCode.BadRequest)] // SyntaxError / SemanticError / BadArgumentError
|
||||
[InlineData(404, System.Net.HttpStatusCode.BadRequest)] // unknown app id in the setting: still a config/caller problem, not the store
|
||||
[InlineData(401, System.Net.HttpStatusCode.BadGateway)]
|
||||
[InlineData(403, System.Net.HttpStatusCode.BadGateway)]
|
||||
[InlineData(429, System.Net.HttpStatusCode.BadRequest)]
|
||||
[InlineData(500, System.Net.HttpStatusCode.BadGateway)]
|
||||
[InlineData(503, System.Net.HttpStatusCode.BadGateway)]
|
||||
public void Upstream_failures_map_to_400_for_the_query_and_502_for_grant_or_store(int upstream, System.Net.HttpStatusCode expected)
|
||||
{
|
||||
Assert.Equal(expected, AppInsightsQueryFunction.MapUpstreamFailure((System.Net.HttpStatusCode)upstream));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Hints_name_the_query_problem_or_the_missing_grant()
|
||||
{
|
||||
Assert.Contains("syntax error", AppInsightsQueryFunction.UpstreamHint(System.Net.HttpStatusCode.BadRequest, "SyntaxError", "backend")!);
|
||||
Assert.Contains("getschema", AppInsightsQueryFunction.UpstreamHint(System.Net.HttpStatusCode.BadRequest, "SemanticError", "web")!);
|
||||
Assert.Contains("Log Analytics Reader", AppInsightsQueryFunction.UpstreamHint(System.Net.HttpStatusCode.Forbidden, null, "mcp")!);
|
||||
Assert.Null(AppInsightsQueryFunction.UpstreamHint(System.Net.HttpStatusCode.InternalServerError, "InternalError", "backend"));
|
||||
}
|
||||
|
||||
// ── Kusto body → typed tables; cells forwarded as the JSON the store produced ──
|
||||
[Fact]
|
||||
public void Kusto_body_is_parsed_cell_for_cell_and_complete_results_carry_no_partial()
|
||||
{
|
||||
const string body = """
|
||||
{"tables":[{"name":"PrimaryResult","columns":[{"name":"timestamp","type":"datetime"},{"name":"count_","type":"long"},{"name":"customDimensions","type":"dynamic"},{"name":"note","type":"string"}],
|
||||
"rows":[["2026-09-04T10:00:00Z",42,"{\"TenantId\":\"t1\"}",null]]}]}
|
||||
""";
|
||||
|
||||
var (tables, partial) = AppInsightsQueryFunction.ParseKustoBody(body);
|
||||
|
||||
Assert.Null(partial);
|
||||
var table = Assert.Single(tables);
|
||||
Assert.Equal("PrimaryResult", table.Name);
|
||||
Assert.Equal(new[] { "timestamp", "count_", "customDimensions", "note" }, table.Columns.Select(c => c.Name));
|
||||
Assert.Equal(new[] { "datetime", "long", "dynamic", "string" }, table.Columns.Select(c => c.Type));
|
||||
var row = Assert.Single(table.Rows);
|
||||
Assert.Equal(JsonValueKind.String, row[0].ValueKind);
|
||||
Assert.Equal(42, row[1].GetInt64());
|
||||
// customDimensions stays the JSON STRING App Insights emits — not re-parsed, not re-encoded.
|
||||
Assert.Equal(JsonValueKind.String, row[2].ValueKind);
|
||||
Assert.Equal("{\"TenantId\":\"t1\"}", row[2].GetString());
|
||||
Assert.Equal(JsonValueKind.Null, row[3].ValueKind);
|
||||
// Cloned cells outlive the parsed document.
|
||||
Assert.Equal("42", row[1].GetRawText());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_200_with_a_PartialError_next_to_tables_is_surfaced_not_swallowed()
|
||||
{
|
||||
const string body = """
|
||||
{"tables":[{"name":"PrimaryResult","columns":[{"name":"n","type":"long"}],"rows":[[1]]}],
|
||||
"error":{"code":"PartialError","message":"There were some errors when processing your query.","innererror":{"code":"E_QUERY_RESULT_SET_TOO_LARGE","message":"Query result set has exceeded the internal record count limit 500000."}}}
|
||||
""";
|
||||
|
||||
var (tables, partial) = AppInsightsQueryFunction.ParseKustoBody(body);
|
||||
|
||||
Assert.Single(tables);
|
||||
Assert.Equal("E_QUERY_RESULT_SET_TOO_LARGE: Query result set has exceeded the internal record count limit 500000.", partial);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Empty_or_shapeless_body_yields_no_tables_and_no_partial()
|
||||
{
|
||||
var (tables, partial) = AppInsightsQueryFunction.ParseKustoBody("{}");
|
||||
Assert.Empty(tables);
|
||||
Assert.Null(partial);
|
||||
}
|
||||
|
||||
// ── Error extraction: innererror first, then outer; tolerant of non-JSON ──
|
||||
[Fact]
|
||||
public void Error_extraction_prefers_innererror_and_tolerates_non_json()
|
||||
{
|
||||
var (msg, code) = AppInsightsQueryFunction.ExtractError(
|
||||
"""{"error":{"message":"The request had some invalid properties","code":"BadArgumentError","innererror":{"code":"SyntaxError","message":"Query could not be parsed at 'foo'"}}}""");
|
||||
Assert.Equal("SyntaxError", code);
|
||||
Assert.Equal("Query could not be parsed at 'foo'", msg);
|
||||
|
||||
var (outerMsg, outerCode) = AppInsightsQueryFunction.ExtractError("""{"error":{"message":"Forbidden","code":"InsufficientAccessError"}}""");
|
||||
Assert.Equal("InsufficientAccessError", outerCode);
|
||||
Assert.Equal("Forbidden", outerMsg);
|
||||
|
||||
var (plainMsg, plainCode) = AppInsightsQueryFunction.ExtractError("<html>502 Bad Gateway</html>");
|
||||
Assert.Null(plainCode);
|
||||
Assert.Equal("Telemetry store query failed", plainMsg);
|
||||
}
|
||||
|
||||
// ── Authorization gate: the KQL proxy is Global-Admin-only ──
|
||||
[Fact]
|
||||
public void RawLogs_post_is_registered_as_GlobalAdminOnly()
|
||||
@@ -51,6 +146,8 @@ public class AppInsightsQueryFunctionTests
|
||||
[InlineData("POST", "/api/global/raw/logs")]
|
||||
[InlineData("GET", "/api/global/raw/tables")]
|
||||
[InlineData("GET", "/api/global/raw/tables/TenantConfiguration")]
|
||||
// The MCP's assume-breach probe: its whole value is that a non-GA caller is DENIED here.
|
||||
[InlineData("GET", "/api/global/raw/access-probe")]
|
||||
public void Raw_family_endpoints_are_GlobalAdminOnly_not_global_reader(string method, string path)
|
||||
{
|
||||
var entry = EndpointAccessPolicyCatalog.FindPolicy(method, path);
|
||||
@@ -70,6 +167,14 @@ public class AppInsightsQueryFunctionTests
|
||||
Assert.False(AuthenticationMiddleware.SkipsJwtValidation("POST", LogsRoute));
|
||||
}
|
||||
|
||||
// ── The access probe must sit behind the SAME JWT gate: an anonymous hit is a 401 (no probe
|
||||
// event), only an authenticated non-GA caller reaches the 403 that raises PrivilegedRouteDenied. ──
|
||||
[Fact]
|
||||
public void AccessProbe_requires_jwt_and_is_not_exempt()
|
||||
{
|
||||
Assert.False(AuthenticationMiddleware.SkipsJwtValidation("GET", "/api/global/raw/access-probe"));
|
||||
}
|
||||
|
||||
// ── Verb binding: the KQL proxy is POST-only. A GET to the same path is unregistered and therefore
|
||||
// fail-closed (FindPolicy == null → the middleware denies). Guards against a future GET alias that
|
||||
// would carry the KQL in the query string (and into logs/URLs). ──
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
using System.Security.Claims;
|
||||
using AutopilotMonitor.Functions.Extensions;
|
||||
using AutopilotMonitor.Functions.Middleware;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Application principals — a service principal presenting an app-only token (idtyp=app, typically behind a
|
||||
/// federated credential) — flow through the same role tables as a person under the key
|
||||
/// <c>app:<client-id></c>. These tests pin the four places where that is decided: the classification
|
||||
/// (<see cref="ClaimsPrincipalExtensions.GetUserPrincipalName"/>), the authentication gate
|
||||
/// (<see cref="AuthenticationMiddleware.ValidateApplicationPrincipal"/>: the access_as_application
|
||||
/// permission is mandatory), the roleless-tier deny in the policy middleware (an application is never
|
||||
/// "some authenticated person"), and the caps — Viewer in a tenant, DelegatedReader on managed tenants,
|
||||
/// never a platform role — enforced at resolution rather than only at grant time.
|
||||
/// </summary>
|
||||
public class ApplicationPrincipalTests
|
||||
{
|
||||
private const string TenantA = "11111111-1111-1111-1111-111111111111";
|
||||
private const string TenantB = "22222222-2222-2222-2222-222222222222";
|
||||
private const string AppId = "AAAAAAAA-0000-0000-0000-00000000AAAA";
|
||||
private const string AppOid = "bbbbbbbb-0000-0000-0000-0000bbbbbbbb";
|
||||
private static readonly string AppKey = Constants.PrincipalKeys.ForApplication(AppId);
|
||||
|
||||
private static ClaimsPrincipal AppPrincipal(
|
||||
string tenantId = TenantA, string? appId = AppId, string? oid = AppOid, bool withPermission = true,
|
||||
string appIdClaim = "appid", bool idtyp = true)
|
||||
{
|
||||
var claims = new List<Claim> { new("tid", tenantId) };
|
||||
if (idtyp) claims.Add(new Claim("idtyp", "app"));
|
||||
if (appId != null) claims.Add(new Claim(appIdClaim, appId));
|
||||
if (oid != null) claims.Add(new Claim("oid", oid));
|
||||
if (withPermission) claims.Add(new Claim("roles", Constants.ApplicationPermissions.AccessAsApplication));
|
||||
return new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
|
||||
}
|
||||
|
||||
private static ClaimsPrincipal UserPrincipal(string upn = "alice@contoso.example", string tenantId = TenantA)
|
||||
=> new(new ClaimsIdentity(new[]
|
||||
{
|
||||
new Claim("tid", tenantId), new Claim("upn", upn), new Claim("oid", "cccccccc-0000-0000-0000-0000cccccccc"),
|
||||
new Claim("scp", "access_as_user"),
|
||||
}, "TestAuth"));
|
||||
|
||||
// ── Classification: the principal key ───────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData("appid")]
|
||||
[InlineData("azp")]
|
||||
public void AppOnlyToken_YieldsTheApplicationKey_FromV1AndV2Claims(string claim)
|
||||
{
|
||||
var principal = AppPrincipal(appIdClaim: claim);
|
||||
|
||||
Assert.True(principal.IsApplicationPrincipal());
|
||||
Assert.Equal(AppId.ToLowerInvariant(), principal.GetApplicationId());
|
||||
Assert.Equal($"app:{AppId.ToLowerInvariant()}", principal.GetUserPrincipalName());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TokenWithoutIdtyp_IsNotAnApplication_AndHasNoKey()
|
||||
{
|
||||
// Fail-closed classification: no idtyp ⇒ a person, who then needs a UPN like everyone else.
|
||||
var principal = AppPrincipal(idtyp: false);
|
||||
|
||||
Assert.False(principal.IsApplicationPrincipal());
|
||||
Assert.Null(principal.GetUserPrincipalName());
|
||||
Assert.Null(AdminIdentity.FromPrincipal(principal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserToken_KeepsItsUpn_EvenWhenAnAppIdIsPresent()
|
||||
{
|
||||
var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
|
||||
{
|
||||
new Claim("tid", TenantA), new Claim("upn", "Alice@Contoso.Example"), new Claim("appid", AppId),
|
||||
}, "TestAuth"));
|
||||
|
||||
Assert.Equal("Alice@Contoso.Example", principal.GetUserPrincipalName());
|
||||
Assert.False(principal.IsApplicationPrincipal());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AdminIdentity_OfAnApplication_IsFlagged()
|
||||
{
|
||||
var identity = AdminIdentity.FromPrincipal(AppPrincipal());
|
||||
|
||||
Assert.NotNull(identity);
|
||||
Assert.True(identity!.IsApplication);
|
||||
Assert.Equal(AppKey, identity.Upn);
|
||||
Assert.Equal(AppOid, identity.ObjectId);
|
||||
Assert.False(AdminIdentity.FromPrincipal(UserPrincipal())!.IsApplication);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PrincipalKeys_CannotCollideWithAUpn()
|
||||
{
|
||||
Assert.True(Constants.PrincipalKeys.IsApplication(AppKey));
|
||||
Assert.False(Constants.PrincipalKeys.IsApplication("app@contoso.example"));
|
||||
Assert.Equal(AppId.ToLowerInvariant(), Constants.PrincipalKeys.TryGetApplicationId(AppKey));
|
||||
Assert.Null(Constants.PrincipalKeys.TryGetApplicationId("alice@contoso.example"));
|
||||
}
|
||||
|
||||
// ── Authentication gate ─────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Gate_PassesUserTokens_Untouched()
|
||||
=> Assert.Null(AuthenticationMiddleware.ValidateApplicationPrincipal(UserPrincipal()));
|
||||
|
||||
[Fact]
|
||||
public void Gate_PassesAnAdmissibleAppToken()
|
||||
=> Assert.Null(AuthenticationMiddleware.ValidateApplicationPrincipal(AppPrincipal()));
|
||||
|
||||
[Fact]
|
||||
public void Gate_RejectsAnAppToken_WithoutTheApplicationPermission()
|
||||
{
|
||||
var reason = AuthenticationMiddleware.ValidateApplicationPrincipal(AppPrincipal(withPermission: false));
|
||||
|
||||
Assert.NotNull(reason);
|
||||
Assert.Contains(Constants.ApplicationPermissions.AccessAsApplication, reason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Gate_RejectsAnAppToken_WithoutApplicationIdOrObjectId()
|
||||
{
|
||||
Assert.Contains("application id", AuthenticationMiddleware.ValidateApplicationPrincipal(AppPrincipal(appId: null))!);
|
||||
Assert.Contains("object id", AuthenticationMiddleware.ValidateApplicationPrincipal(AppPrincipal(oid: null))!);
|
||||
}
|
||||
|
||||
// ── Policy middleware: roleless tiers and caps ──────────────────────────────
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
public required PolicyEnforcementMiddleware Middleware { get; init; }
|
||||
public required Mock<IAdminRepository> Repo { get; init; }
|
||||
|
||||
public void MemberRow(string role, bool enabled = true) =>
|
||||
Repo.Setup(r => r.GetTenantMemberAsync(TenantA, AppKey))
|
||||
.ReturnsAsync(new TenantMember { TenantId = TenantA, Upn = AppKey, Role = role, IsEnabled = enabled });
|
||||
}
|
||||
|
||||
private static Harness BuildHarness()
|
||||
{
|
||||
var repo = new Mock<IAdminRepository>();
|
||||
repo.Setup(r => r.GetGlobalRoleAsync(It.IsAny<string>())).ReturnsAsync((string?)null);
|
||||
repo.Setup(r => r.GetTenantMemberAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync((TenantMember?)null);
|
||||
repo.Setup(r => r.GetDelegatedTenantsAsync(It.IsAny<string>())).ReturnsAsync(new List<DelegatedAdminEntry>());
|
||||
repo.Setup(r => r.GetGroupAssignmentsForUpnAsync(It.IsAny<string>())).ReturnsAsync(new List<TenantGroupAssignment>());
|
||||
repo.Setup(r => r.GetIdentityBindingAsync(It.IsAny<string>()))
|
||||
.ReturnsAsync(new AdminIdentityBinding { TenantId = TenantA, ObjectId = AppOid });
|
||||
var configRepo = new Mock<IConfigRepository>();
|
||||
configRepo.Setup(r => r.GetTenantConfigurationAsync(It.IsAny<string>())).ReturnsAsync((TenantConfiguration?)null);
|
||||
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
var bindings = new AdminIdentityBindingService(repo.Object, cache, NullLogger<AdminIdentityBindingService>.Instance);
|
||||
var globalAdmin = new GlobalAdminService(repo.Object, bindings, cache, NullLogger<GlobalAdminService>.Instance);
|
||||
var delegatedAdmin = new DelegatedAdminService(
|
||||
repo.Object, bindings, new StubTenantEntitlementService(TenantEdition.Pro), cache, NullLogger<DelegatedAdminService>.Instance);
|
||||
var tenantAdmins = new TenantAdminsService(repo.Object, cache, NullLogger<TenantAdminsService>.Instance);
|
||||
var tenantConfig = new TenantConfigurationService(configRepo.Object, NullLogger<TenantConfigurationService>.Instance, cache);
|
||||
var mw = new PolicyEnforcementMiddleware(
|
||||
NullLogger<PolicyEnforcementMiddleware>.Instance, globalAdmin, delegatedAdmin,
|
||||
new TenantMemberRoleResolver(tenantAdmins, tenantConfig), tenantConfig, new RecordingDenialReporter());
|
||||
return new Harness { Middleware = mw, Repo = repo };
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("GET", "/api/feedback/status")] // AuthenticatedUser
|
||||
[InlineData("GET", "/api/auth/me")] // AuthenticatedUser
|
||||
[InlineData("POST", "/api/realtime/groups/join")] // AuthenticatedUserWithRole
|
||||
public async Task RolelessTiers_DenyAnApplication_UnlessTheEntryOptsIn(string method, string path)
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.MemberRow(Constants.TenantRoles.Viewer);
|
||||
|
||||
var r = await h.Middleware.DecideAsync(method, path, null, AppPrincipal());
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Equal(403, r.StatusCode);
|
||||
Assert.Equal("ApplicationPrincipalNotAllowed", r.LogReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheMcpFrontDoor_AdmitsAnApplication()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", "/api/auth/mcp", null, AppPrincipal());
|
||||
|
||||
Assert.True(r.Allowed);
|
||||
Assert.Equal(AppKey, r.Context!.UserPrincipalName);
|
||||
Assert.Equal(AppOid, r.Context.ObjectId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MemberRead_AdmitsAnApplicationMember_CappedToViewer()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.MemberRow(Constants.TenantRoles.Admin); // a row edited to Admin still reads as Viewer
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", "/api/sessions", null, AppPrincipal());
|
||||
|
||||
Assert.True(r.Allowed);
|
||||
Assert.Equal(Constants.TenantRoles.Viewer, r.Context!.UserRole);
|
||||
Assert.False(r.Context.IsTenantAdmin);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MemberRead_DeniesAnApplication_WithoutARow()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", "/api/sessions", null, AppPrincipal());
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Equal(403, r.StatusCode);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("POST", "/api/sessions/abc/actions")] // TenantAdminOrOperator
|
||||
[InlineData("PUT", "/api/sessions/abc/annotations/operator")]
|
||||
[InlineData("POST", "/api/config/11111111-1111-1111-1111-111111111111")] // TenantAdminOrGA
|
||||
public async Task WriteTiers_NeverAdmitAnApplication_EvenWithAnAdminRow(string method, string path)
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.MemberRow(Constants.TenantRoles.Admin);
|
||||
|
||||
var r = await h.Middleware.DecideAsync(method, path, null, AppPrincipal());
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Equal(403, r.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlatformRoleRow_IsInert_ForAnApplication()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.Repo.Setup(r => r.GetGlobalRoleAsync(AppKey)).ReturnsAsync(Constants.GlobalRoles.GlobalAdmin);
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", "/api/global/raw/access-probe", null, AppPrincipal());
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Equal(403, r.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DelegatedScope_OfAnApplication_IsCappedToReader()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.Repo.Setup(r => r.GetDelegatedTenantsAsync(AppKey)).ReturnsAsync(new List<DelegatedAdminEntry>
|
||||
{
|
||||
new()
|
||||
{
|
||||
TenantId = TenantB, Role = Constants.DelegatedRoles.DelegatedAdmin, IsEnabled = true,
|
||||
Status = Constants.DelegatedStatus.Active, Source = Constants.DelegatedSource.OperatorGranted,
|
||||
},
|
||||
});
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", $"/api/config/{TenantB}", null, AppPrincipal());
|
||||
|
||||
Assert.True(r.Allowed);
|
||||
Assert.True(r.Context!.IsDelegatedReader);
|
||||
Assert.False(r.Context.IsDelegatedAdmin);
|
||||
}
|
||||
|
||||
// ── Member-role resolver cap ────────────────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(Constants.TenantRoles.Admin)]
|
||||
[InlineData(Constants.TenantRoles.Operator)]
|
||||
[InlineData(Constants.TenantRoles.Viewer)]
|
||||
public async Task Resolver_CapsAnApplicationRow_ToViewer(string rowRole)
|
||||
{
|
||||
var repo = new Mock<IAdminRepository>();
|
||||
repo.Setup(r => r.GetTenantMemberAsync(TenantA, AppKey))
|
||||
.ReturnsAsync(new TenantMember { TenantId = TenantA, Upn = AppKey, Role = rowRole, IsEnabled = true });
|
||||
var sut = Resolver(repo);
|
||||
|
||||
var role = await sut.ResolveAsync(TenantA, AppKey, new[] { Constants.ApplicationPermissions.AccessAsApplication });
|
||||
|
||||
Assert.Equal(Constants.TenantRoles.Viewer, role?.Role);
|
||||
Assert.False(role!.CanManageBootstrapTokens);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolver_NeverDerivesAnApplicationRole_FromClaims()
|
||||
{
|
||||
var repo = new Mock<IAdminRepository>();
|
||||
repo.Setup(r => r.GetTenantMemberAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync((TenantMember?)null);
|
||||
var sut = Resolver(repo, appRolesEnabled: true);
|
||||
|
||||
// Even a (hypothetical) Admin app-role claim on an app token grants nothing without a row.
|
||||
var role = await sut.ResolveAsync(TenantA, AppKey, new[] { Constants.TenantRoles.Admin });
|
||||
|
||||
Assert.Null(role);
|
||||
}
|
||||
|
||||
private static TenantMemberRoleResolver Resolver(Mock<IAdminRepository> repo, bool appRolesEnabled = false)
|
||||
{
|
||||
var configRepo = new Mock<IConfigRepository>();
|
||||
configRepo.Setup(r => r.GetTenantConfigurationAsync(It.IsAny<string>()))
|
||||
.ReturnsAsync(new TenantConfiguration { TenantId = TenantA, EntraAppRolesEnabled = appRolesEnabled });
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
return new TenantMemberRoleResolver(
|
||||
new TenantAdminsService(repo.Object, cache, NullLogger<TenantAdminsService>.Instance),
|
||||
new TenantConfigurationService(configRepo.Object, NullLogger<TenantConfigurationService>.Instance, cache));
|
||||
}
|
||||
|
||||
// ── MCP front door ──────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task McpAccess_ForAnApplicationMember_IsAllMembers_AndNamesTheKey()
|
||||
{
|
||||
var (sut, members) = McpService();
|
||||
members.Verdict = (tid, key, _) => tid == TenantA && key == AppKey ? new MemberRoleInfo { Role = Constants.TenantRoles.Viewer } : null;
|
||||
|
||||
var result = await sut.IsAllowedAsync(AppKey, TenantA, AppOid, new[] { Constants.ApplicationPermissions.AccessAsApplication });
|
||||
|
||||
Assert.True(result.IsAllowed);
|
||||
Assert.Equal("AllMembers", result.AccessGrant);
|
||||
Assert.Equal(AppKey, result.Upn);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task McpAccess_ForAnApplication_WithoutMembership_SaysSo()
|
||||
{
|
||||
var (sut, _) = McpService();
|
||||
|
||||
var result = await sut.IsAllowedAsync(AppKey, TenantA, AppOid);
|
||||
|
||||
Assert.False(result.IsAllowed);
|
||||
Assert.Contains("Service principal", result.Reason);
|
||||
}
|
||||
|
||||
private static (McpUserService Sut, StubTenantMemberRoleResolver Members) McpService()
|
||||
{
|
||||
var adminRepo = new Mock<IAdminRepository>();
|
||||
adminRepo.Setup(x => x.GetMcpUserAsync(It.IsAny<string>())).ReturnsAsync((McpUserEntry?)null);
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
var bindings = new StubAdminIdentityBindingService(bound: true);
|
||||
var globalAdmin = new Mock<GlobalAdminService>(adminRepo.Object, bindings, cache, NullLogger<GlobalAdminService>.Instance) { CallBase = false };
|
||||
globalAdmin.Setup(x => x.GetGlobalRoleAsync(It.IsAny<AdminIdentity?>())).ReturnsAsync((string?)null);
|
||||
var delegatedAdmin = new Mock<DelegatedAdminService>(
|
||||
adminRepo.Object, bindings, new StubTenantEntitlementService(TenantEdition.Pro), cache, NullLogger<DelegatedAdminService>.Instance) { CallBase = false };
|
||||
delegatedAdmin.Setup(x => x.GetScopeAsync(It.IsAny<AdminIdentity?>())).ReturnsAsync(DelegatedScope.Empty);
|
||||
var adminConfig = new Mock<AdminConfigurationService>(Mock.Of<IConfigRepository>(), NullLogger<AdminConfigurationService>.Instance, cache) { CallBase = false };
|
||||
adminConfig.Setup(x => x.GetConfigurationAsync())
|
||||
.ReturnsAsync(new AdminConfiguration { McpAccessPolicy = McpAccessPolicy.AllMembers.ToString() });
|
||||
var members = new StubTenantMemberRoleResolver();
|
||||
var sut = new McpUserService(
|
||||
adminRepo.Object, bindings, cache, NullLogger<McpUserService>.Instance,
|
||||
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, members,
|
||||
new TenantConfigurationService(Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache));
|
||||
return (sut, members);
|
||||
}
|
||||
}
|
||||
@@ -83,7 +83,7 @@ public class AuthFunctionSideEffectTests
|
||||
var mcpUserMock = new Mock<McpUserService>(
|
||||
adminRepo, new StubAdminIdentityBindingService(bound: true), cache, Mock.Of<ILogger<McpUserService>>(),
|
||||
globalAdminMock.Object, delegatedAdminMock.Object, adminConfigService.Object,
|
||||
new TenantMemberRoleResolver(_tenantAdminsMock.Object, _tenantConfigMock.Object))
|
||||
new TenantMemberRoleResolver(_tenantAdminsMock.Object, _tenantConfigMock.Object), _tenantConfigMock.Object)
|
||||
{ CallBase = false };
|
||||
|
||||
_metricsRepoMock = new Mock<IMetricsRepository>();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user